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