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