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