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