add encoding comment and vim comment
[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')], 'State', 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 state'),
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     _constraints = [
280         (_sheet_date, 'You can not have 2 timesheets that overlaps !', ['date_from','date_to'])
281     ]
282
283     def action_set_to_draft(self, cr, uid, ids, *args):
284         self.write(cr, uid, ids, {'state': 'draft'})
285         wf_service = netsvc.LocalService('workflow')
286         for id in ids:
287             wf_service.trg_create(uid, self._name, id, cr)
288         return True
289
290     def name_get(self, cr, uid, ids, context={}):
291         if not len(ids):
292             return []
293         return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
294                 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
295                     context, load='_classic_write')]
296
297 hr_timesheet_sheet()
298
299
300 class hr_timesheet_line(osv.osv):
301     _inherit = "hr.analytic.timesheet"
302
303     def _get_default_date(self, cr, uid, context={}):
304         if 'date' in context:
305             return context['date']
306         return time.strftime('%Y-%m-%d')
307
308     def _sheet(self, cursor, user, ids, name, args, context):
309         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
310
311         cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
312                 FROM hr_timesheet_sheet_sheet s \
313                     LEFT JOIN (hr_analytic_timesheet l \
314                         LEFT JOIN account_analytic_line al \
315                             ON (l.line_id = al.id)) \
316                         ON (s.date_to >= al.date \
317                             AND s.date_from <= al.date \
318                             AND s.user_id = al.user_id) \
319                 WHERE l.id in (' + ','.join([str(x) for x in ids]) + ') \
320                 GROUP BY l.id')
321         res = dict(cursor.fetchall())
322         sheet_names = {}
323         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
324                 context=context):
325             sheet_names[sheet_id] = name
326
327         for line_id in {}.fromkeys(ids):
328             sheet_id = res.get(line_id, False)
329             if sheet_id:
330                 res[line_id] = (sheet_id, sheet_names[sheet_id])
331             else:
332                 res[line_id] = False
333         return res
334
335     def _sheet_search(self, cursor, user, obj, name, args):
336         if not len(args):
337             return []
338         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
339
340         i = 0
341         while i < len(args):
342             fargs = args[i][0].split('.', 1)
343             if len(fargs) > 1:
344                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
345                     [(fargs[1], args[i][1], args[i][2])]))
346                 i += 1
347                 continue
348             if isinstance(args[i][2], basestring):
349                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
350                         args[i][1])
351                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
352             i += 1
353         qu1, qu2 = [], []
354         for x in args:
355             if x[1] != 'in':
356                 if (x[2] is False) and (x[1] == '='):
357                     qu1.append('(s.id IS NULL)')
358                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
359                     qu1.append('(s.id IS NOT NULL)')
360                 else:
361                     qu1.append('(s.id %s %s)' % (x[1], '%d'))
362                     qu2.append(x[2])
363             elif x[1] == 'in':
364                 if len(x[2]) > 0:
365                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
366                     qu2 += x[2]
367                 else:
368                     qu1.append('(False)')
369         if len(qu1):
370             qu1 = ' WHERE ' + ' AND '.join(qu1)
371         else:
372             qu1 = ''
373         cursor.execute('SELECT l.id \
374                 FROM hr_timesheet_sheet_sheet s \
375                     LEFT JOIN (hr_analytic_timesheet l \
376                         LEFT JOIN account_analytic_line al \
377                             ON (l.line_id = al.id)) \
378                         ON (s.date_to >= al.date \
379                             AND s.date_from <= al.date \
380                             AND s.user_id = al.user_id)' + \
381                 qu1, qu2)
382         res = cursor.fetchall()
383         if not len(res):
384             return [('id', '=', '0')]
385         return [('id', 'in', [x[0] for x in res])]
386
387     _columns = {
388         'sheet_id': fields.function(_sheet, method=True, string='Sheet',
389             type='many2one', relation='hr_timesheet_sheet.sheet',
390             fnct_search=_sheet_search),
391     }
392     _defaults = {
393         'date': _get_default_date,
394     }
395
396     def create(self, cr, uid, vals, *args, **kwargs):
397         if 'sheet_id' in vals:
398             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
399             if not ts.state in ('draft', 'new'):
400                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
401         return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
402
403     def unlink(self, cr, uid, ids, *args, **kwargs):
404         self._check(cr, uid, ids)
405         return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
406
407     def write(self, cr, uid, ids, *args, **kwargs):
408         self._check(cr, uid, ids)
409         return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
410
411     def _check(self, cr, uid, ids):
412         for att in self.browse(cr, uid, ids):
413             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
414                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
415         return True
416
417 hr_timesheet_line()
418
419 class hr_attendance(osv.osv):
420     _inherit = "hr.attendance"
421
422     def _get_default_date(self, cr, uid, context={}):
423         if 'name' in context:
424             return context['name'] + time.strftime(' %H:%M:%S')
425         return time.strftime('%Y-%m-%d %H:%M:%S')
426
427     def _sheet(self, cursor, user, ids, name, args, context):
428         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
429
430         cursor.execute('SELECT a.id, COALESCE(MAX(s.id), 0) \
431                 FROM hr_timesheet_sheet_sheet s \
432                     LEFT JOIN (hr_attendance a \
433                         LEFT JOIN hr_employee e \
434                             ON (a.employee_id = e.id)) \
435                         ON (s.date_to >= a.name \
436                             AND s.date_from <= a.name \
437                             AND s.user_id = e.user_id) \
438                 WHERE a.id in (' + ','.join([str(x) for x in ids]) + ') \
439                 GROUP BY a.id')
440         res = dict(cursor.fetchall())
441         sheet_names = {}
442         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
443                 context=context):
444             sheet_names[sheet_id] = name
445
446         for line_id in {}.fromkeys(ids):
447             sheet_id = res.get(line_id, False)
448             if sheet_id:
449                 res[line_id] = (sheet_id, sheet_names[sheet_id])
450             else:
451                 res[line_id] = False
452         return res
453
454     def _sheet_search(self, cursor, user, obj, name, args):
455         if not len(args):
456             return []
457         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
458
459         i = 0
460         while i < len(args):
461             fargs = args[i][0].split('.', 1)
462             if len(fargs) > 1:
463                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
464                     [(fargs[1], args[i][1], args[i][2])]))
465                 i += 1
466                 continue
467             if isinstance(args[i][2], basestring):
468                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
469                         args[i][1])
470                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
471             i += 1
472         qu1, qu2 = [], []
473         for x in args:
474             if x[1] != 'in':
475                 if (x[2] is False) and (x[1] == '='):
476                     qu1.append('(s.id IS NULL)')
477                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
478                     qu1.append('(s.id IS NOT NULL)')
479                 else:
480                     qu1.append('(s.id %s %s)' % (x[1], '%d'))
481                     qu2.append(x[2])
482             elif x[1] == 'in':
483                 if len(x[2]) > 0:
484                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
485                     qu2 += x[2]
486                 else:
487                     qu1.append('(False)')
488         if len(qu1):
489             qu1 = ' WHERE ' + ' AND '.join(qu1)
490         else:
491             qu1 = ''
492         cursor.execute('SELECT a.id\
493                 FROM hr_timesheet_sheet_sheet s \
494                     LEFT JOIN (hr_attendance a \
495                         LEFT JOIN hr_employee e \
496                             ON (a.employee_id = e.id)) \
497                         ON (s.date_to >= a.name \
498                             AND s.date_from <= a.name \
499                             AND s.user_id = e.user_id) ' + \
500                 qu1, qu2)
501         res = cursor.fetchall()
502         if not len(res):
503             return [('id', '=', '0')]
504         return [('id', 'in', [x[0] for x in res])]
505
506     _columns = {
507         'sheet_id': fields.function(_sheet, method=True, string='Sheet',
508             type='many2one', relation='hr_timesheet_sheet.sheet',
509             fnct_search=_sheet_search),
510     }
511     _defaults = {
512         'name': _get_default_date,
513     }
514
515     def create(self, cr, uid, vals, context={}):
516         if 'sheet_id' in context:
517             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'])
518             if ts.state not in ('draft', 'new'):
519                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
520         res = super(hr_attendance,self).create(cr, uid, vals, context=context)
521         if 'sheet_id' in context:
522             if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
523                 raise osv.except_osv(_('UserError'), _('You can not enter an attendance ' \
524                         'date outside the current timesheet dates!'))
525         return res
526
527     def unlink(self, cr, uid, ids, *args, **kwargs):
528         self._check(cr, uid, ids)
529         return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
530
531     def write(self, cr, uid, ids, vals, context={}):
532         self._check(cr, uid, ids)
533         res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
534         if 'sheet_id' in context:
535             for attendance in self.browse(cr, uid, ids, context=context):
536                 if context['sheet_id'] != attendance.sheet_id.id:
537                     raise osv.except_osv(_('UserError'), _('You can not enter an attendance ' \
538                             'date outside the current timesheet dates!'))
539         return res
540
541     def _check(self, cr, uid, ids):
542         for att in self.browse(cr, uid, ids):
543             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
544                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
545         return True
546
547 hr_attendance()
548
549 class hr_timesheet_sheet_sheet_day(osv.osv):
550     _name = "hr_timesheet_sheet.sheet.day"
551     _description = "Timesheets by period"
552     _auto = False
553     _order='name'
554     _columns = {
555         'name': fields.date('Date', readonly=True),
556         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
557         'total_timesheet': fields.float('Project Timesheet', readonly=True),
558         'total_attendance': fields.float('Attendance', readonly=True),
559         'total_difference': fields.float('Difference', readonly=True),
560     }
561
562     def init(self, cr):
563         cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
564             SELECT
565                 id,
566                 name,
567                 sheet_id,
568                 total_timesheet,
569                 total_attendance,
570                 (total_attendance - total_timesheet) AS total_difference
571             FROM
572                 ((
573                     SELECT
574                         MAX(id) as id,
575                         name,
576                         sheet_id,
577                         SUM(total_timesheet) as total_timesheet,
578                         CASE WHEN SUM(total_attendance) < 0
579                             THEN (SUM(total_attendance) +
580                                 CASE WHEN current_date <> name
581                                     THEN 1440
582                                     ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
583                                 END
584                                 )
585                             ELSE SUM(total_attendance)
586                         END /60  as total_attendance
587                     FROM
588                         ((
589                             select
590                                 min(hrt.id) as id,
591                                 l.date::date as name,
592                                 s.id as sheet_id,
593                                 sum(l.unit_amount) as total_timesheet,
594                                 0.0 as total_attendance
595                             from
596                                 hr_analytic_timesheet hrt
597                                 left join (account_analytic_line l
598                                     LEFT JOIN hr_timesheet_sheet_sheet s
599                                     ON (s.date_to >= l.date
600                                         AND s.date_from <= l.date
601                                         AND s.user_id = l.user_id))
602                                     on (l.id = hrt.line_id)
603                             group by l.date::date, s.id
604                         ) union (
605                             select
606                                 -min(a.id) as id,
607                                 a.name::date as name,
608                                 s.id as sheet_id,
609                                 0.0 as total_timesheet,
610                                 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
611                             from
612                                 hr_attendance a
613                                 LEFT JOIN (hr_timesheet_sheet_sheet s
614                                     LEFT JOIN hr_employee e
615                                     ON (s.user_id = e.user_id))
616                                 ON (a.employee_id = e.id
617                                     AND s.date_to >= a.name
618                                     AND s.date_from <= a.name)
619                             WHERE action in ('sign_in', 'sign_out')
620                             group by a.name::date, s.id
621                         )) AS foo
622                         GROUP BY name, sheet_id
623                 )) AS bar""")
624
625 hr_timesheet_sheet_sheet_day()
626
627
628 class hr_timesheet_sheet_sheet_account(osv.osv):
629     _name = "hr_timesheet_sheet.sheet.account"
630     _description = "Timesheets by period"
631     _auto = False
632     _order='name'
633     _columns = {
634         'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
635         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
636         'total': fields.float('Total Time', digits=(16,2), readonly=True),
637         'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
638     }
639
640     def init(self, cr):
641         cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
642             select
643                 min(hrt.id) as id,
644                 l.account_id as name,
645                 s.id as sheet_id,
646                 sum(l.unit_amount) as total,
647                 l.to_invoice as invoice_rate
648             from
649                 hr_analytic_timesheet hrt
650                 left join (account_analytic_line l
651                     LEFT JOIN hr_timesheet_sheet_sheet s
652                         ON (s.date_to >= l.date
653                             AND s.date_from <= l.date
654                             AND s.user_id = l.user_id))
655                     on (l.id = hrt.line_id)
656             group by l.account_id, s.id, l.to_invoice
657         )""")
658
659 hr_timesheet_sheet_sheet_account()
660
661
662 class res_company(osv.osv):
663     _inherit = 'res.company'
664     _columns = {
665         'timesheet_range': fields.selection([('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range'),
666         'timesheet_max_difference': fields.float('Timesheet allowed difference', help="Allowed difference between the sign in/out and the timesheet computation for one sheet. Set this to 0 if you do not want any control."),
667     }
668     _defaults = {
669         'timesheet_range': lambda *args: 'month',
670         'timesheet_max_difference': lambda *args: 0.0
671     }
672
673 res_company()
674
675 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
676