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