Improved:
[odoo/odoo.git] / addons / hr_timesheet_sheet / hr_timesheet_sheet.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 import time
32 from osv import fields
33 from osv import osv
34 import netsvc
35
36 from mx import DateTime
37 from tools.translate import _
38
39
40 class one2many_mod2(fields.one2many):
41     def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
42         res = {}
43         for id in ids:
44             res[id] = []
45
46         res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
47         res6 = {}
48         for r in res5:
49             res6[r['id']] = (r['date_current'], r['user_id'][0])
50
51         ids2 = []
52         for id in ids:
53             dom = []
54             if id in res6:
55                 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
56                         ('name', '<=', res6[id][0] + ' 23:59:59'),
57                         ('employee_id.user_id', '=', res6[id][1])]
58             ids2.extend(obj.pool.get(self._obj).search(cr, user,
59                 dom, limit=self._limit))
60
61         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
62                 [self._fields_id], context=context, load='_classic_write'):
63             if r[self._fields_id]:
64                 res.setdefault(r[self._fields_id][0], []).append(r['id'])
65
66         return res
67
68     def set(self, cr, obj, id, field, values, user=None, context=None):
69         if context is None:
70             context = {}
71         context = context.copy()
72         context['sheet_id'] = id
73         return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user,
74                 context=context)
75
76
77 class one2many_mod(fields.one2many):
78     def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
79         res = {}
80         for id in ids:
81             res[id] = []
82
83         res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
84         res6 = {}
85         for r in res5:
86             res6[r['id']] = (r['date_current'], r['user_id'][0])
87
88         ids2 = []
89         for id in ids:
90             dom = []
91             if id in res6:
92                 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
93             ids2.extend(obj.pool.get(self._obj).search(cr, user,
94                 dom, limit=self._limit))
95
96         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
97                 [self._fields_id], context=context, load='_classic_write'):
98             if r[self._fields_id]:
99                 res.setdefault(r[self._fields_id][0], []).append(r['id'])
100
101         return res
102
103 class hr_timesheet_sheet(osv.osv):
104     _name = "hr_timesheet_sheet.sheet"
105     _table = 'hr_timesheet_sheet_sheet'
106     _order = "id desc"
107
108     def _total_day(self, cr, uid, ids, name, args, context):
109         field_name = name.strip('_day')
110         cr.execute('SELECT sheet.id, day.' + field_name +' \
111                 FROM hr_timesheet_sheet_sheet AS sheet \
112                 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
113                     ON (sheet.id = day.sheet_id \
114                         AND day.name = sheet.date_current) \
115                 WHERE sheet.id in (' + ','.join([str(x) for x in ids]) + ')')
116         return dict(cr.fetchall())
117
118     def _total(self, cr, uid, ids, name, args, context):
119         cr.execute('SELECT s.id, COALESCE(SUM(d.' + name + '),0) \
120                 FROM hr_timesheet_sheet_sheet s \
121                     LEFT JOIN hr_timesheet_sheet_sheet_day d \
122                         ON (s.id = d.sheet_id) \
123                 WHERE s.id in ('+ ','.join(map(str, ids)) + ') \
124                 GROUP BY s.id')
125         return dict(cr.fetchall())
126
127     def _state_attendance(self, cr, uid, ids, name, args, context):
128         result = {}
129         link_emp = {}
130         emp_ids = []
131         emp_obj = self.pool.get('hr.employee')
132
133         for sheet in self.browse(cr, uid, ids, context):
134             result[sheet.id] = 'none'
135             emp_ids2 = emp_obj.search(cr, uid,
136                     [('user_id', '=', sheet.user_id.id)])
137             if emp_ids2:
138                 link_emp[emp_ids2[0]] = sheet.id
139                 emp_ids.append(emp_ids2[0])
140         for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
141             if emp.id in link_emp:
142                 sheet_id = link_emp[emp.id]
143                 result[sheet_id] = emp.state
144         return result
145
146     def button_confirm(self, cr, uid, ids, context):
147         for sheet in self.browse(cr, uid, ids, context):
148             di = sheet.user_id.company_id.timesheet_max_difference
149             if (abs(sheet.total_difference) < di) or not di:
150                 wf_service = netsvc.LocalService("workflow")
151                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
152             else:
153                 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
154         return True
155
156     def date_today(self, cr, uid, ids, context):
157         for sheet in self.browse(cr, uid, ids, context):
158             if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
159                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
160             elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
161                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
162             else:
163                 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
164         return True
165
166     def date_previous(self, cr, uid, ids, context):
167         for sheet in self.browse(cr, uid, ids, context):
168             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
169                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
170             else:
171                 self.write(cr, uid, [sheet.id], {
172                     'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
173                 })
174         return True
175
176     def date_next(self, cr, uid, ids, context):
177         for sheet in self.browse(cr, uid, ids, context):
178             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
179                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
180             else:
181                 self.write(cr, uid, [sheet.id], {
182                     'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
183                 })
184         return True
185
186     def button_dummy(self, cr, uid, ids, context):
187         for sheet in self.browse(cr, uid, ids, context):
188             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
189                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
190             elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
191                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
192         return True
193
194     def sign_in(self, cr, uid, ids, context):
195         if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
196             raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
197         emp_obj = self.pool.get('hr.employee')
198         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
199         context['sheet_id']=ids[0]
200         success = emp_obj.sign_in(cr, uid, emp_id, context=context)
201         return True
202
203     def sign_out(self, cr, uid, ids, context):
204         if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
205             raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
206         emp_obj = self.pool.get('hr.employee')
207         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
208         context['sheet_id']=ids[0]
209         success = emp_obj.sign_out(cr, uid, emp_id, context=context)
210         return True
211
212     _columns = {
213         'name': fields.char('Description', size=64, select=1),
214         'user_id': fields.many2one('res.users', 'User', required=True, select=1),
215         'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
216         'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
217         'date_current': fields.date('Current date', required=True),
218         'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
219             'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
220             readonly=True, states={
221                 'draft': [('readonly', False)],
222                 'new': [('readonly', False)]}
223             ),
224         'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
225         'state' : fields.selection([('new', 'New'),('draft','Draft'),('confirm','Confirmed'),('done','Done')], 'Status', select=True, required=True, readonly=True),
226         'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
227         'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance'),
228         'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet'),
229         'total_difference_day': fields.function(_total_day, method=True, string='Difference'),
230         'total_attendance': fields.function(_total, method=True, string='Total Attendance'),
231         'total_timesheet': fields.function(_total, method=True, string='Total Timesheet'),
232         'total_difference': fields.function(_total, method=True, string='Difference'),
233         'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
234         'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
235     }
236
237     def _default_date_from(self,cr, uid, context={}):
238         user = self.pool.get('res.users').browse(cr, uid, uid, context)
239         r = user.company_id and user.company_id.timesheet_range or 'month'
240         if r=='month':
241             return time.strftime('%Y-%m-01')
242         elif r=='week':
243             return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
244         elif r=='year':
245             return time.strftime('%Y-01-01')
246         return time.strftime('%Y-%m-%d')
247
248     def _default_date_to(self,cr, uid, context={}):
249         user = self.pool.get('res.users').browse(cr, uid, uid, context)
250         r = user.company_id and user.company_id.timesheet_range or 'month'
251         if r=='month':
252             return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
253         elif r=='week':
254             return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
255         elif r=='year':
256             return time.strftime('%Y-12-31')
257         return time.strftime('%Y-%m-%d')
258
259     _defaults = {
260         'user_id': lambda self,cr,uid,c: uid,
261         'date_from' : _default_date_from,
262         'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
263         'date_to' : _default_date_to,
264         'state': lambda *a: 'new',
265     }
266
267     def _sheet_date(self, cr, uid, ids):
268         for sheet in self.browse(cr, uid, ids):
269             cr.execute('SELECT id \
270                     FROM hr_timesheet_sheet_sheet \
271                     WHERE (date_from < %s and %s < date_to) \
272                         AND user_id=%d \
273                         AND id <> %d', (sheet.date_to, sheet.date_from,
274                             sheet.user_id.id, sheet.id))
275             if cr.fetchall():
276                 return False
277         return True
278
279     def _date_current_check(self, cr, uid, ids):
280         for sheet in self.browse(cr, uid, ids):
281             if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
282                 return False
283         return True
284
285
286     _constraints = [
287         (_sheet_date, 'You can not have 2 timesheets that overlaps !', ['date_from','date_to']),
288         (_date_current_check, 'You must select a Current date wich is in the timesheet dates !', ['date_current']),
289     ]
290
291     def action_set_to_draft(self, cr, uid, ids, *args):
292         self.write(cr, uid, ids, {'state': 'draft'})
293         wf_service = netsvc.LocalService('workflow')
294         for id in ids:
295             wf_service.trg_create(uid, self._name, id, cr)
296         return True
297
298     def name_get(self, cr, uid, ids, context={}):
299         if not len(ids):
300             return []
301         return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
302                 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
303                     context, load='_classic_write')]
304
305 hr_timesheet_sheet()
306
307
308 class hr_timesheet_line(osv.osv):
309     _inherit = "hr.analytic.timesheet"
310
311     def _get_default_date(self, cr, uid, context={}):
312         if 'date' in context:
313             return context['date']
314         return time.strftime('%Y-%m-%d')
315
316     def _sheet(self, cursor, user, ids, name, args, context):
317         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
318
319         cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
320                 FROM hr_timesheet_sheet_sheet s \
321                     LEFT JOIN (hr_analytic_timesheet l \
322                         LEFT JOIN account_analytic_line al \
323                             ON (l.line_id = al.id)) \
324                         ON (s.date_to >= al.date \
325                             AND s.date_from <= al.date \
326                             AND s.user_id = al.user_id) \
327                 WHERE l.id in (' + ','.join([str(x) for x in ids]) + ') \
328                 GROUP BY l.id')
329         res = dict(cursor.fetchall())
330         sheet_names = {}
331         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
332                 context=context):
333             sheet_names[sheet_id] = name
334
335         for line_id in {}.fromkeys(ids):
336             sheet_id = res.get(line_id, False)
337             if sheet_id:
338                 res[line_id] = (sheet_id, sheet_names[sheet_id])
339             else:
340                 res[line_id] = False
341         return res
342
343     def _sheet_search(self, cursor, user, obj, name, args):
344         if not len(args):
345             return []
346         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
347
348         i = 0
349         while i < len(args):
350             fargs = args[i][0].split('.', 1)
351             if len(fargs) > 1:
352                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
353                     [(fargs[1], args[i][1], args[i][2])]))
354                 i += 1
355                 continue
356             if isinstance(args[i][2], basestring):
357                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
358                         args[i][1])
359                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
360             i += 1
361         qu1, qu2 = [], []
362         for x in args:
363             if x[1] != 'in':
364                 if (x[2] is False) and (x[1] == '='):
365                     qu1.append('(s.id IS NULL)')
366                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
367                     qu1.append('(s.id IS NOT NULL)')
368                 else:
369                     qu1.append('(s.id %s %s)' % (x[1], '%d'))
370                     qu2.append(x[2])
371             elif x[1] == 'in':
372                 if len(x[2]) > 0:
373                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
374                     qu2 += x[2]
375                 else:
376                     qu1.append('(False)')
377         if len(qu1):
378             qu1 = ' WHERE ' + ' AND '.join(qu1)
379         else:
380             qu1 = ''
381         cursor.execute('SELECT l.id \
382                 FROM hr_timesheet_sheet_sheet s \
383                     LEFT JOIN (hr_analytic_timesheet l \
384                         LEFT JOIN account_analytic_line al \
385                             ON (l.line_id = al.id)) \
386                         ON (s.date_to >= al.date \
387                             AND s.date_from <= al.date \
388                             AND s.user_id = al.user_id)' + \
389                 qu1, qu2)
390         res = cursor.fetchall()
391         if not len(res):
392             return [('id', '=', '0')]
393         return [('id', 'in', [x[0] for x in res])]
394
395     _columns = {
396         'sheet_id': fields.function(_sheet, method=True, string='Sheet',
397             type='many2one', relation='hr_timesheet_sheet.sheet',
398             fnct_search=_sheet_search),
399     }
400     _defaults = {
401         'date': _get_default_date,
402     }
403
404     def create(self, cr, uid, vals, *args, **kwargs):
405         if 'sheet_id' in vals:
406             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
407             if not ts.state in ('draft', 'new'):
408                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
409         return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
410
411     def unlink(self, cr, uid, ids, *args, **kwargs):
412         self._check(cr, uid, ids)
413         return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
414
415     def write(self, cr, uid, ids, *args, **kwargs):
416         self._check(cr, uid, ids)
417         return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
418
419     def _check(self, cr, uid, ids):
420         for att in self.browse(cr, uid, ids):
421             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
422                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
423         return True
424
425 hr_timesheet_line()
426
427 class hr_attendance(osv.osv):
428     _inherit = "hr.attendance"
429
430     def _get_default_date(self, cr, uid, context={}):
431         if 'name' in context:
432             return context['name'] + time.strftime(' %H:%M:%S')
433         return time.strftime('%Y-%m-%d %H:%M:%S')
434
435     def _sheet(self, cursor, user, ids, name, args, context):
436         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
437
438         cursor.execute('SELECT a.id, COALESCE(MAX(s.id), 0) \
439                 FROM hr_timesheet_sheet_sheet s \
440                     LEFT JOIN (hr_attendance a \
441                         LEFT JOIN hr_employee e \
442                             ON (a.employee_id = e.id)) \
443                         ON (s.date_to >= a.name \
444                             AND s.date_from <= a.name \
445                             AND s.user_id = e.user_id) \
446                 WHERE a.id in (' + ','.join([str(x) for x in ids]) + ') \
447                 GROUP BY a.id')
448         res = dict(cursor.fetchall())
449         sheet_names = {}
450         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
451                 context=context):
452             sheet_names[sheet_id] = name
453
454         for line_id in {}.fromkeys(ids):
455             sheet_id = res.get(line_id, False)
456             if sheet_id:
457                 res[line_id] = (sheet_id, sheet_names[sheet_id])
458             else:
459                 res[line_id] = False
460         return res
461
462     def _sheet_search(self, cursor, user, obj, name, args):
463         if not len(args):
464             return []
465         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
466
467         i = 0
468         while i < len(args):
469             fargs = args[i][0].split('.', 1)
470             if len(fargs) > 1:
471                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
472                     [(fargs[1], args[i][1], args[i][2])]))
473                 i += 1
474                 continue
475             if isinstance(args[i][2], basestring):
476                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
477                         args[i][1])
478                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
479             i += 1
480         qu1, qu2 = [], []
481         for x in args:
482             if x[1] != 'in':
483                 if (x[2] is False) and (x[1] == '='):
484                     qu1.append('(s.id IS NULL)')
485                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
486                     qu1.append('(s.id IS NOT NULL)')
487                 else:
488                     qu1.append('(s.id %s %s)' % (x[1], '%d'))
489                     qu2.append(x[2])
490             elif x[1] == 'in':
491                 if len(x[2]) > 0:
492                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
493                     qu2 += x[2]
494                 else:
495                     qu1.append('(False)')
496         if len(qu1):
497             qu1 = ' WHERE ' + ' AND '.join(qu1)
498         else:
499             qu1 = ''
500         cursor.execute('SELECT a.id\
501                 FROM hr_timesheet_sheet_sheet s \
502                     LEFT JOIN (hr_attendance a \
503                         LEFT JOIN hr_employee e \
504                             ON (a.employee_id = e.id)) \
505                         ON (s.date_to >= a.name \
506                             AND s.date_from <= a.name \
507                             AND s.user_id = e.user_id) ' + \
508                 qu1, qu2)
509         res = cursor.fetchall()
510         if not len(res):
511             return [('id', '=', '0')]
512         return [('id', 'in', [x[0] for x in res])]
513
514     _columns = {
515         'sheet_id': fields.function(_sheet, method=True, string='Sheet',
516             type='many2one', relation='hr_timesheet_sheet.sheet',
517             fnct_search=_sheet_search),
518     }
519     _defaults = {
520         'name': _get_default_date,
521     }
522
523     def create(self, cr, uid, vals, context={}):
524         if 'sheet_id' in context:
525             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'])
526             if ts.state not in ('draft', 'new'):
527                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
528         res = super(hr_attendance,self).create(cr, uid, vals, context=context)
529         if 'sheet_id' in context:
530             if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
531                 raise osv.except_osv(_('UserError'), _('You can not enter an attendance ' \
532                         'date outside the current timesheet dates!'))
533         return res
534
535     def unlink(self, cr, uid, ids, *args, **kwargs):
536         self._check(cr, uid, ids)
537         return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
538
539     def write(self, cr, uid, ids, vals, context={}):
540         self._check(cr, uid, ids)
541         res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
542         if 'sheet_id' in context:
543             for attendance in self.browse(cr, uid, ids, context=context):
544                 if context['sheet_id'] != attendance.sheet_id.id:
545                     raise osv.except_osv(_('UserError'), _('You can not enter an attendance ' \
546                             'date outside the current timesheet dates!'))
547         return res
548
549     def _check(self, cr, uid, ids):
550         for att in self.browse(cr, uid, ids):
551             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
552                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
553         return True
554
555 hr_attendance()
556
557 class hr_timesheet_sheet_sheet_day(osv.osv):
558     _name = "hr_timesheet_sheet.sheet.day"
559     _description = "Timesheets by period"
560     _auto = False
561     _order='name'
562     _columns = {
563         'name': fields.date('Date', readonly=True),
564         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
565         'total_timesheet': fields.float('Project Timesheet', readonly=True),
566         'total_attendance': fields.float('Attendance', readonly=True),
567         'total_difference': fields.float('Difference', readonly=True),
568     }
569
570     def init(self, cr):
571         cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
572             SELECT
573                 id,
574                 name,
575                 sheet_id,
576                 total_timesheet,
577                 total_attendance,
578                 (total_attendance - total_timesheet) AS total_difference
579             FROM
580                 ((
581                     SELECT
582                         MAX(id) as id,
583                         name,
584                         sheet_id,
585                         SUM(total_timesheet) as total_timesheet,
586                         CASE WHEN SUM(total_attendance) < 0
587                             THEN (SUM(total_attendance) +
588                                 CASE WHEN current_date <> name
589                                     THEN 1440
590                                     ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
591                                 END
592                                 )
593                             ELSE SUM(total_attendance)
594                         END /60  as total_attendance
595                     FROM
596                         ((
597                             select
598                                 min(hrt.id) as id,
599                                 l.date::date as name,
600                                 s.id as sheet_id,
601                                 sum(l.unit_amount) as total_timesheet,
602                                 0.0 as total_attendance
603                             from
604                                 hr_analytic_timesheet hrt
605                                 left join (account_analytic_line l
606                                     LEFT JOIN hr_timesheet_sheet_sheet s
607                                     ON (s.date_to >= l.date
608                                         AND s.date_from <= l.date
609                                         AND s.user_id = l.user_id))
610                                     on (l.id = hrt.line_id)
611                             group by l.date::date, s.id
612                         ) union (
613                             select
614                                 -min(a.id) as id,
615                                 a.name::date as name,
616                                 s.id as sheet_id,
617                                 0.0 as total_timesheet,
618                                 SUM(((EXTRACT(hour FROM a.name) * 60) + EXTRACT(minute FROM a.name)) * (CASE WHEN a.action = 'sign_in' THEN -1 ELSE 1 END)) as total_attendance
619                             from
620                                 hr_attendance a
621                                 LEFT JOIN (hr_timesheet_sheet_sheet s
622                                     LEFT JOIN hr_employee e
623                                     ON (s.user_id = e.user_id))
624                                 ON (a.employee_id = e.id
625                                     AND s.date_to >= a.name
626                                     AND s.date_from <= a.name)
627                             WHERE action in ('sign_in', 'sign_out')
628                             group by a.name::date, s.id
629                         )) AS foo
630                         GROUP BY name, sheet_id
631                 )) AS bar""")
632
633 hr_timesheet_sheet_sheet_day()
634
635
636 class hr_timesheet_sheet_sheet_account(osv.osv):
637     _name = "hr_timesheet_sheet.sheet.account"
638     _description = "Timesheets by period"
639     _auto = False
640     _order='name'
641     _columns = {
642         'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
643         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
644         'total': fields.float('Total Time', digits=(16,2), readonly=True),
645         'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
646     }
647
648     def init(self, cr):
649         cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
650             select
651                 min(hrt.id) as id,
652                 l.account_id as name,
653                 s.id as sheet_id,
654                 sum(l.unit_amount) as total,
655                 l.to_invoice as invoice_rate
656             from
657                 hr_analytic_timesheet hrt
658                 left join (account_analytic_line l
659                     LEFT JOIN hr_timesheet_sheet_sheet s
660                         ON (s.date_to >= l.date
661                             AND s.date_from <= l.date
662                             AND s.user_id = l.user_id))
663                     on (l.id = hrt.line_id)
664             group by l.account_id, s.id, l.to_invoice
665         )""")
666
667 hr_timesheet_sheet_sheet_account()
668
669
670
671 class res_company(osv.osv):
672     _inherit = 'res.company'
673     _columns = {
674         'timesheet_range': fields.selection(
675             [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range',
676             required=True),
677         'timesheet_max_difference': fields.float('Timesheet allowed difference',
678             help="Allowed difference between the sign in/out and the timesheet " \
679                  "computation for one sheet. Set this to 0 if you do not want any control."),
680     }
681     _defaults = {
682         'timesheet_range': lambda *args: 'month',
683         'timesheet_max_difference': lambda *args: 0.0
684     }
685
686 res_company()
687
688 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
689