Fix sheet function on attendance
[odoo/odoo.git] / addons / hr_timesheet_sheet / hr_timesheet_sheet.py
1 ##############################################################################
2 #
3 # Copyright (c) 2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # $Id: hr_timesheet.py 5490 2007-01-29 16:05:51Z pinky $
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 import time
31 from osv import fields
32 from osv import osv
33 import netsvc
34
35 from mx import DateTime
36
37
38 class one2many_mod2(fields.one2many):
39         def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
40                 res = {}
41                 for id in ids:
42                         res[id] = []
43
44                 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
45                 res6 = {}
46                 for r in res5:
47                         res6[r['id']] = (r['date_current'], r['user_id'][0])
48
49                 ids2 = []
50                 for id in ids:
51                         dom = []
52                         if id in res6:
53                                 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
54                                                 ('name', '<=', res6[id][0] + ' 23:59:59'),
55                                                 ('employee_id.user_id', '=', res6[id][1])]
56                         ids2.extend(obj.pool.get(self._obj).search(cr, user,
57                                 dom, limit=self._limit))
58
59                 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
60                                 [self._fields_id], context=context, load='_classic_write'):
61                         if r[self._fields_id]:
62                                 res.setdefault(r[self._fields_id][0], []).append(r['id'])
63
64                 return res
65
66
67 class one2many_mod(fields.one2many):
68         def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
69                 res = {}
70                 for id in ids:
71                         res[id] = []
72
73                 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
74                 res6 = {}
75                 for r in res5:
76                         res6[r['id']] = (r['date_current'], r['user_id'][0])
77
78                 ids2 = []
79                 for id in ids:
80                         dom = []
81                         if id in res6:
82                                 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
83                         ids2.extend(obj.pool.get(self._obj).search(cr, user,
84                                 dom, limit=self._limit))
85
86                 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
87                                 [self._fields_id], context=context, load='_classic_write'):
88                         if r[self._fields_id]:
89                                 res.setdefault(r[self._fields_id][0], []).append(r['id'])
90
91                 return res
92
93 class hr_timesheet_sheet(osv.osv):
94         _name = "hr_timesheet_sheet.sheet"
95         _table = 'hr_timesheet_sheet_sheet'
96         _order = "id desc"
97
98         def _total_day(self, cr, uid, ids, name, args, context):
99                 field_name = name.strip('_day')
100                 cr.execute('SELECT sheet.id, day.' + field_name +' \
101                                 FROM hr_timesheet_sheet_sheet AS sheet \
102                                 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
103                                         ON (sheet.id = day.sheet_id \
104                                                 AND day.name = sheet.date_current) \
105                                 WHERE sheet.id in (' + ','.join([str(x) for x in ids]) + ')')
106                 return dict(cr.fetchall())
107
108         def _total(self, cr, uid, ids, name, args, context):
109                 cr.execute('SELECT s.id, COALESCE(SUM(d.' + name + '),0) \
110                                 FROM hr_timesheet_sheet_sheet s \
111                                         LEFT JOIN hr_timesheet_sheet_sheet_day d \
112                                                 ON (s.id = d.sheet_id) \
113                                 WHERE s.id in ('+ ','.join(map(str, ids)) + ') \
114                                 GROUP BY s.id')
115                 return dict(cr.fetchall())
116
117         def _state_attendance(self, cr, uid, ids, name, args, context):
118                 result = {}
119                 link_emp = {}
120                 emp_ids = []
121                 emp_obj = self.pool.get('hr.employee')
122
123                 for sheet in self.browse(cr, uid, ids, context):
124                         result[sheet.id] = 'none'
125                         emp_ids2 = emp_obj.search(cr, uid,
126                                         [('user_id', '=', sheet.user_id.id)])
127                         if emp_ids2:
128                                 link_emp[emp_ids2[0]] = sheet.id
129                                 emp_ids.append(emp_ids2[0])
130                 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
131                         if emp.id in link_emp:
132                                 sheet_id = link_emp[emp.id]
133                                 result[sheet_id] = emp.state
134                 return result
135
136         def button_confirm(self, cr, uid, ids, context):
137                 for sheet in self.browse(cr, uid, ids, context):
138                         di = sheet.user_id.company_id.timesheet_max_difference
139                         if (abs(sheet.total_difference) < di) or not di:
140                                 wf_service = netsvc.LocalService("workflow")
141                                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
142                         else:
143                                 raise osv.except_osv('Warning !', 'Please verify that the total difference of the sheet is lower than %.2f !' %(di,))
144                 return True
145
146         def date_today(self, cr, uid, ids, context):
147                 for sheet in self.browse(cr, uid, ids, context):
148                         if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
149                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
150                         elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
151                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
152                         else:
153                                 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
154                 return True
155
156         def date_previous(self, cr, uid, ids, context):
157                 for sheet in self.browse(cr, uid, ids, context):
158                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
159                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
160                         else:
161                                 self.write(cr, uid, [sheet.id], {
162                                         'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
163                                 })
164                 return True
165
166         def date_next(self, cr, uid, ids, context):
167                 for sheet in self.browse(cr, uid, ids, context):
168                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
169                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
170                         else:
171                                 self.write(cr, uid, [sheet.id], {
172                                         'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
173                                 })
174                 return True
175
176         def button_dummy(self, cr, uid, ids, context):
177                 for sheet in self.browse(cr, uid, ids, context):
178                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
179                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
180                         elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
181                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
182                 return True
183
184         def sign_in(self, cr, uid, ids, context):
185                 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
186                         raise osv.except_osv('Error !', 'You can not sign in from an other date than today')
187                 emp_obj = self.pool.get('hr.employee')
188                 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
189                 context['sheet_id']=ids[0]
190                 success = emp_obj.sign_in(cr, uid, emp_id, context=context)
191                 return True
192
193         def sign_out(self, cr, uid, ids, context):
194                 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
195                         raise osv.except_osv('Error !', 'You can not sign out from an other date than today')
196                 emp_obj = self.pool.get('hr.employee')
197                 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
198                 context['sheet_id']=ids[0]
199                 success = emp_obj.sign_out(cr, uid, emp_id, context=context)
200                 return True
201
202         _columns = {
203                 'name': fields.char('Description', size=64, select=1),
204                 'user_id': fields.many2one('res.users', 'User', required=True, select=1),
205                 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
206                 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
207                 'date_current': fields.date('Current date', required=True),
208                 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
209                         'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
210                         readonly=True, states={
211                                 'draft': [('readonly', False)],
212                                 'new': [('readonly', False)]}
213                         ),
214                 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
215                 'state' : fields.selection([('new', 'New'),('draft','Draft'),('confirm','Confirmed'),('done','Done')], 'state', select=True, required=True, readonly=True),
216                 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current state'),
217                 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance'),
218                 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet'),
219                 'total_difference_day': fields.function(_total_day, method=True, string='Difference'),
220                 'total_attendance': fields.function(_total, method=True, string='Total Attendance'),
221                 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet'),
222                 'total_difference': fields.function(_total, method=True, string='Difference'),
223                 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
224                 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
225         }
226
227         def _default_date_from(self,cr, uid, context={}):
228                 user = self.pool.get('res.users').browse(cr, uid, uid, context)
229                 r = user.company_id and user.company_id.timesheet_range or 'month'
230                 if r=='month':
231                         return time.strftime('%Y-%m-01')
232                 elif r=='week':
233                         return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
234                 elif r=='year':
235                         return time.strftime('%Y-01-01')
236                 return time.strftime('%Y-%m-%d')
237
238         def _default_date_to(self,cr, uid, context={}):
239                 user = self.pool.get('res.users').browse(cr, uid, uid, context)
240                 r = user.company_id and user.company_id.timesheet_range or 'month'
241                 if r=='month':
242                         return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
243                 elif r=='week':
244                         return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
245                 elif r=='year':
246                         return time.strftime('%Y-12-31')
247                 return time.strftime('%Y-%m-%d')
248
249         _defaults = {
250                 'user_id': lambda self,cr,uid,c: uid,
251                 'date_from' : _default_date_from,
252                 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
253                 'date_to' : _default_date_to,
254                 'state': lambda *a: 'new',
255         }
256
257         def _sheet_date(self, cr, uid, ids):
258                 for sheet in self.browse(cr, uid, ids):
259                         cr.execute('SELECT id \
260                                         FROM hr_timesheet_sheet_sheet \
261                                         WHERE (date_from < %s and %s < date_to) \
262                                                 AND user_id=%d \
263                                                 AND id <> %d', (sheet.date_to, sheet.date_from,
264                                                         sheet.user_id.id, sheet.id))
265                         if cr.fetchall():
266                                 return False
267                 return True
268
269         _constraints = [
270                 (_sheet_date, 'You can not have 2 timesheets that overlaps !', ['date_from','date_to'])
271         ]
272
273         def action_set_to_draft(self, cr, uid, ids, *args):
274                 self.write(cr, uid, ids, {'state': 'draft'})
275                 wf_service = netsvc.LocalService('workflow')
276                 for id in ids:
277                         wf_service.trg_create(uid, self._name, id, cr)
278                 return True
279
280         def name_get(self, cr, uid, ids, context={}):
281                 if not len(ids):
282                         return []
283                 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
284                                 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
285                                         context, load='_classic_write')]
286
287 hr_timesheet_sheet()
288
289
290 class hr_timesheet_line(osv.osv):
291         _inherit = "hr.analytic.timesheet"
292
293         def _get_default_date(self, cr, uid, context={}):
294                 if 'date' in context:
295                         return context['date']
296                 return time.strftime('%Y-%m-%d')
297
298         def _sheet(self, cursor, user, ids, name, args, context):
299                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
300
301                 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
302                                 FROM hr_timesheet_sheet_sheet s \
303                                         LEFT JOIN (hr_analytic_timesheet l \
304                                                 LEFT JOIN account_analytic_line al \
305                                                         ON (l.line_id = al.id)) \
306                                                 ON (s.date_to >= al.date \
307                                                         AND s.date_from <= al.date \
308                                                         AND s.user_id = al.user_id) \
309                                 WHERE l.id in (' + ','.join([str(x) for x in ids]) + ') \
310                                 GROUP BY l.id')
311                 res = dict(cursor.fetchall())
312                 sheet_names = {}
313                 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
314                                 context=context):
315                         sheet_names[sheet_id] = name
316
317                 for line_id in ids:
318                         sheet_id = res.get(line_id, False)
319                         if sheet_id:
320                                 res[line_id] = (sheet_id, sheet_names[sheet_id])
321                         else:
322                                 res[line_id] = False
323                 return res
324
325         _columns = {
326                 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
327                         type='many2one', relation='hr_timesheet_sheet.sheet'),
328         }
329         _defaults = {
330                 'date': _get_default_date,
331         }
332
333         def create(self, cr, uid, vals, *args, **kwargs):
334                 if 'sheet_id' in vals:
335                         ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
336                         if not ts.state in ('draft', 'new'):
337                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
338                 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
339
340         def unlink(self, cr, uid, ids, *args, **kwargs):
341                 self._check(cr, uid, ids)
342                 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
343
344         def write(self, cr, uid, ids, *args, **kwargs):
345                 self._check(cr, uid, ids)
346                 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
347
348         def _check(self, cr, uid, ids):
349                 for att in self.browse(cr, uid, ids):
350                         if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
351                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
352                 return True
353
354 hr_timesheet_line()
355
356 class hr_attendance(osv.osv):
357         _inherit = "hr.attendance"
358
359         def _get_default_date(self, cr, uid, context={}):
360                 if 'name' in context:
361                         return context['name'] + time.strftime(' %H:%M:%S')
362                 return time.strftime('%Y-%m-%d %H:%M:%S')
363
364         def _sheet(self, cursor, user, ids, name, args, context):
365                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
366
367                 cursor.execute('SELECT a.id, COALESCE(MAX(s.id), 0) \
368                                 FROM hr_timesheet_sheet_sheet s \
369                                         LEFT JOIN (hr_attendance a \
370                                                 LEFT JOIN hr_employee e \
371                                                         ON (a.employee_id = e.id)) \
372                                                 ON (s.date_to >= a.name \
373                                                         AND s.date_from <= a.name \
374                                                         AND s.user_id = e.user_id) \
375                                 WHERE a.id in (' + ','.join([str(x) for x in ids]) + ') \
376                                 GROUP BY a.id')
377                 res = dict(cursor.fetchall())
378                 sheet_names = {}
379                 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
380                                 context=context):
381                         sheet_names[sheet_id] = name
382
383                 for line_id in ids:
384                         sheet_id = res.get(line_id, False)
385                         if sheet_id:
386                                 res[line_id] = (sheet_id, sheet_names[sheet_id])
387                         else:
388                                 res[line_id] = False
389                 return res
390
391         _columns = {
392                 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
393                         type='many2one', relation='hr_timesheet_sheet.sheet'),
394         }
395         _defaults = {
396                 'name': _get_default_date,
397         }
398
399         def create(self, cr, uid, vals, context={}):
400                 if 'sheet_id' in context:
401                         vals['sheet_id']=context['sheet_id']
402                 if 'sheet_id' in vals:
403                         ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
404                         if ts.state not in ('draft', 'new'):
405                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
406                 return super(hr_attendance,self).create(cr, uid, vals, context=context)
407
408         def unlink(self, cr, uid, ids, *args, **kwargs):
409                 self._check(cr, uid, ids)
410                 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
411
412         def write(self, cr, uid, ids, vals, context={}):
413                 if 'sheet_id' in context:
414                         vals['sheet_id']=context['sheet_id']
415                 self._check(cr, uid, ids)
416                 return super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
417
418         def _check(self, cr, uid, ids):
419                 for att in self.browse(cr, uid, ids):
420                         if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
421                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
422                 return True
423
424 hr_attendance()
425
426 class hr_timesheet_sheet_sheet_day(osv.osv):
427         _name = "hr_timesheet_sheet.sheet.day"
428         _description = "Timesheets by period"
429         _auto = False
430         _order='name'
431         _columns = {
432                 'name': fields.date('Date', readonly=True),
433                 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
434                 'total_timesheet': fields.float('Project Timesheet', readonly=True),
435                 'total_attendance': fields.float('Attendance', readonly=True),
436                 'total_difference': fields.float('Difference', readonly=True),
437         }
438
439         def init(self, cr):
440                 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
441                         SELECT
442                                 id,
443                                 name,
444                                 sheet_id,
445                                 total_timesheet,
446                                 total_attendance,
447                                 (total_attendance - total_timesheet) AS total_difference
448                         FROM
449                                 ((
450                                         SELECT
451                                                 MAX(id) as id,
452                                                 name,
453                                                 sheet_id,
454                                                 SUM(total_timesheet) as total_timesheet,
455                                                 CASE WHEN SUM(total_attendance) < 0
456                                                         THEN (SUM(total_attendance) +
457                                                                 CASE WHEN current_date <> name
458                                                                         THEN 1440
459                                                                         ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
460                                                                 END
461                                                                 )
462                                                         ELSE SUM(total_attendance)
463                                                 END /60  as total_attendance
464                                         FROM
465                                                 ((
466                                                         select
467                                                                 min(hrt.id) as id,
468                                                                 l.date::date as name,
469                                                                 s.id as sheet_id,
470                                                                 sum(l.unit_amount) as total_timesheet,
471                                                                 0.0 as total_attendance
472                                                         from
473                                                                 hr_analytic_timesheet hrt
474                                                                 left join (account_analytic_line l
475                                                                         LEFT JOIN hr_timesheet_sheet_sheet s
476                                                                         ON (s.date_to >= l.date
477                                                                                 AND s.date_from <= l.date
478                                                                                 AND s.user_id = l.user_id))
479                                                                         on (l.id = hrt.line_id)
480                                                         group by l.date::date, s.id
481                                                 ) union (
482                                                         select
483                                                                 -min(a.id) as id,
484                                                                 a.name::date as name,
485                                                                 s.id as sheet_id,
486                                                                 0.0 as total_timesheet,
487                                                                 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
488                                                         from
489                                                                 hr_attendance a
490                                                                 LEFT JOIN (hr_timesheet_sheet_sheet s
491                                                                         LEFT JOIN hr_employee e
492                                                                         ON (s.user_id = e.user_id))
493                                                                 ON (a.employee_id = e.id
494                                                                         AND s.date_to >= a.name
495                                                                         AND s.date_from <= a.name)
496                                                         WHERE action in ('sign_in', 'sign_out')
497                                                         group by a.name::date, s.id
498                                                 )) AS foo
499                                                 GROUP BY name, sheet_id
500                                 )) AS bar""")
501
502 hr_timesheet_sheet_sheet_day()
503
504
505 class hr_timesheet_sheet_sheet_account(osv.osv):
506         _name = "hr_timesheet_sheet.sheet.account"
507         _description = "Timesheets by period"
508         _auto = False
509         _order='name'
510         _columns = {
511                 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
512                 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
513                 'total': fields.float('Total Time', digits=(16,2), readonly=True),
514                 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
515         }
516
517         def init(self, cr):
518                 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
519                         select
520                                 min(hrt.id) as id,
521                                 l.account_id as name,
522                                 s.id as sheet_id,
523                                 sum(l.unit_amount) as total,
524                                 l.to_invoice as invoice_rate
525                         from
526                                 hr_analytic_timesheet hrt
527                                 left join (account_analytic_line l
528                                         LEFT JOIN hr_timesheet_sheet_sheet s
529                                                 ON (s.date_to >= l.date
530                                                         AND s.date_from <= l.date
531                                                         AND s.user_id = l.user_id))
532                                         on (l.id = hrt.line_id)
533                         group by l.account_id, s.id, l.to_invoice
534                 )""")
535
536 hr_timesheet_sheet_sheet_account()
537
538
539 class res_company(osv.osv):
540         _inherit = 'res.company'
541         _columns = {
542                 'timesheet_range': fields.selection([('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range'),
543                 'timesheet_max_difference': fields.float('Timesheet allowed difference', help="Allowed difference between the sign in/out and the timesheet computation for one sheet. Set this to 0 if you do not want any control."),
544         }
545         _defaults = {
546                 'timesheet_range': lambda *args: 'month',
547                 'timesheet_max_difference': lambda *args: 0.0
548         }
549
550 res_company()