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