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