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