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