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