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