minor change
[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-2008 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 button_confirm(self, cr, uid, ids, context):
139         for sheet in self.browse(cr, uid, ids, context):
140             di = sheet.user_id.company_id.timesheet_max_difference
141             if (abs(sheet.total_difference) < di) or not di:
142                 wf_service = netsvc.LocalService("workflow")
143                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
144             else:
145                 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
146         return True
147
148     def date_today(self, cr, uid, ids, context):
149         for sheet in self.browse(cr, uid, ids, context):
150             if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
151                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
152             elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
153                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
154             else:
155                 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
156         return True
157
158     def date_previous(self, cr, uid, ids, context):
159         for sheet in self.browse(cr, uid, ids, context):
160             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
161                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
162             else:
163                 self.write(cr, uid, [sheet.id], {
164                     'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
165                 })
166         return True
167
168     def date_next(self, cr, uid, ids, context):
169         for sheet in self.browse(cr, uid, ids, context):
170             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
171                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
172             else:
173                 self.write(cr, uid, [sheet.id], {
174                     'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
175                 })
176         return True
177
178     def button_dummy(self, cr, uid, ids, context):
179         for sheet in self.browse(cr, uid, ids, context):
180             if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
181                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
182             elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
183                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
184         return True
185
186     def sign_in(self, cr, uid, ids, context):
187         if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
188             raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
189         emp_obj = self.pool.get('hr.employee')
190         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
191         context['sheet_id']=ids[0]
192         success = emp_obj.sign_in(cr, uid, emp_id, context=context)
193         return True
194
195     def sign_out(self, cr, uid, ids, context):
196         if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
197             raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
198         emp_obj = self.pool.get('hr.employee')
199         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
200         context['sheet_id']=ids[0]
201         success = emp_obj.sign_out(cr, uid, emp_id, context=context)
202         return True
203
204     _columns = {
205         'name': fields.char('Description', size=64, select=1),
206         'user_id': fields.many2one('res.users', 'User', required=True, select=1),
207         'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
208         'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
209         'date_current': fields.date('Current date', required=True),
210         'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
211             'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
212             readonly=True, states={
213                 'draft': [('readonly', False)],
214                 'new': [('readonly', False)]}
215             ),
216         'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
217         'state' : fields.selection([('new', 'New'),('draft','Draft'),('confirm','Confirmed'),('done','Done')], 'Status', select=True, required=True, readonly=True),
218         'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
219         'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance'),
220         'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet'),
221         'total_difference_day': fields.function(_total_day, method=True, string='Difference'),
222         'total_attendance': fields.function(_total, method=True, string='Total Attendance'),
223         'total_timesheet': fields.function(_total, method=True, string='Total Timesheet'),
224         'total_difference': fields.function(_total, method=True, string='Difference'),
225         'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
226         'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
227     }
228
229     def _default_date_from(self,cr, uid, context={}):
230         user = self.pool.get('res.users').browse(cr, uid, uid, context)
231         r = user.company_id and user.company_id.timesheet_range or 'month'
232         if r=='month':
233             return time.strftime('%Y-%m-01')
234         elif r=='week':
235             return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
236         elif r=='year':
237             return time.strftime('%Y-01-01')
238         return time.strftime('%Y-%m-%d')
239
240     def _default_date_to(self,cr, uid, context={}):
241         user = self.pool.get('res.users').browse(cr, uid, uid, context)
242         r = user.company_id and user.company_id.timesheet_range or 'month'
243         if r=='month':
244             return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
245         elif r=='week':
246             return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
247         elif r=='year':
248             return time.strftime('%Y-12-31')
249         return time.strftime('%Y-%m-%d')
250
251     _defaults = {
252         'user_id': lambda self,cr,uid,c: uid,
253         'date_from' : _default_date_from,
254         'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
255         'date_to' : _default_date_to,
256         'state': lambda *a: 'new',
257     }
258
259     def _sheet_date(self, cr, uid, ids):
260         for sheet in self.browse(cr, uid, ids):
261             cr.execute('SELECT id \
262                     FROM hr_timesheet_sheet_sheet \
263                     WHERE (date_from < %s and %s < date_to) \
264                         AND user_id=%d \
265                         AND id <> %d', (sheet.date_to, sheet.date_from,
266                             sheet.user_id.id, sheet.id))
267             if cr.fetchall():
268                 return False
269         return True
270
271     def _date_current_check(self, cr, uid, ids):
272         for sheet in self.browse(cr, uid, ids):
273             if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
274                 return False
275         return True
276
277
278     _constraints = [
279         (_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']),
280         (_date_current_check, 'You must select a Current date wich is in the timesheet dates !', ['date_current']),
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
663 class res_company(osv.osv):
664     _inherit = 'res.company'
665     _columns = {
666         'timesheet_range': fields.selection(
667             [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range',
668             required=True),
669         'timesheet_max_difference': fields.float('Timesheet allowed difference',
670             help="Allowed difference between the sign in/out and the timesheet " \
671                  "computation for one sheet. Set this to 0 if you do not want any control."),
672     }
673     _defaults = {
674         'timesheet_range': lambda *args: 'month',
675         'timesheet_max_difference': lambda *args: 0.0
676     }
677
678 res_company()
679
680 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
681