1 ##############################################################################
3 # Copyright (c) 2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 # $Id: hr_timesheet.py 5490 2007-01-29 16:05:51Z pinky $
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
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.
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.
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.
28 ##############################################################################
31 from osv import fields
35 from mx import DateTime
38 class one2many_mod2(fields.one2many):
39 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
44 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
47 res6[r['id']] = (r['date_current'], r['user_id'][0])
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))
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'])
67 class one2many_mod(fields.one2many):
68 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
73 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
76 res6[r['id']] = (r['date_current'], r['user_id'][0])
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))
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'])
93 class hr_timesheet_sheet(osv.osv):
94 _name = "hr_timesheet_sheet.sheet"
95 _table = 'hr_timesheet_sheet_sheet'
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())
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)) + ') \
115 return dict(cr.fetchall())
117 def _state_attendance(self, cr, uid, ids, name, args, context):
121 emp_obj = self.pool.get('hr.employee')
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)])
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
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)
143 raise osv.except_osv('Warning !', 'Please verify that the total difference of the sheet is lower than %.2f !' %(di,))
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,})
153 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
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,})
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'),
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,})
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'),
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,})
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)
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)
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)]}
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),
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'
231 return time.strftime('%Y-%m-01')
233 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
235 return time.strftime('%Y-01-01')
236 return time.strftime('%Y-%m-%d')
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'
242 return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
244 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
246 return time.strftime('%Y-12-31')
247 return time.strftime('%Y-%m-%d')
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',
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) \
263 AND id <> %d', (sheet.date_to, sheet.date_from,
264 sheet.user_id.id, sheet.id))
270 (_sheet_date, 'You can not have 2 timesheets that overlaps !', ['date_from','date_to'])
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')
277 wf_service.trg_create(uid, self._name, id, cr)
280 def name_get(self, cr, uid, ids, context={}):
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')]
290 class hr_timesheet_line(osv.osv):
291 _inherit = "hr.analytic.timesheet"
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')
298 def _sheet(self, cursor, user, ids, name, args, context):
299 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
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]) + ') \
311 res = dict(cursor.fetchall())
313 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
315 sheet_names[sheet_id] = name
318 sheet_id = res.get(line_id, False)
320 res[line_id] = (sheet_id, sheet_names[sheet_id])
325 def _sheet_search(self, cursor, user, obj, name, args):
328 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
332 fargs = args[i][0].split('.', 1)
334 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
335 [(fargs[1], args[i][1], args[i][2])]))
338 if isinstance(args[i][2], basestring):
339 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
341 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
346 if (x[2] is False) and (x[1] == '='):
347 qu1.append('(s.id IS NULL)')
348 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
349 qu1.append('(s.id IS NOT NULL)')
351 qu1.append('(s.id %s %s)' % (x[1], '%d'))
355 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
358 qu1.append('(False)')
360 qu1 = ' WHERE ' + ' AND '.join(qu1)
363 cursor.execute('SELECT l.id \
364 FROM hr_timesheet_sheet_sheet s \
365 LEFT JOIN (hr_analytic_timesheet l \
366 LEFT JOIN account_analytic_line al \
367 ON (l.line_id = al.id)) \
368 ON (s.date_to >= al.date \
369 AND s.date_from <= al.date \
370 AND s.user_id = al.user_id)' + \
372 res = cursor.fetchall()
374 return [('id', '=', '0')]
375 return [('id', 'in', [x[0] for x in res])]
378 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
379 type='many2one', relation='hr_timesheet_sheet.sheet',
380 fnct_search=_sheet_search),
383 'date': _get_default_date,
386 def create(self, cr, uid, vals, *args, **kwargs):
387 if 'sheet_id' in vals:
388 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
389 if not ts.state in ('draft', 'new'):
390 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
391 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
393 def unlink(self, cr, uid, ids, *args, **kwargs):
394 self._check(cr, uid, ids)
395 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
397 def write(self, cr, uid, ids, *args, **kwargs):
398 self._check(cr, uid, ids)
399 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
401 def _check(self, cr, uid, ids):
402 for att in self.browse(cr, uid, ids):
403 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
404 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
409 class hr_attendance(osv.osv):
410 _inherit = "hr.attendance"
412 def _get_default_date(self, cr, uid, context={}):
413 if 'name' in context:
414 return context['name'] + time.strftime(' %H:%M:%S')
415 return time.strftime('%Y-%m-%d %H:%M:%S')
417 def _sheet(self, cursor, user, ids, name, args, context):
418 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
420 cursor.execute('SELECT a.id, COALESCE(MAX(s.id), 0) \
421 FROM hr_timesheet_sheet_sheet s \
422 LEFT JOIN (hr_attendance a \
423 LEFT JOIN hr_employee e \
424 ON (a.employee_id = e.id)) \
425 ON (s.date_to >= a.name \
426 AND s.date_from <= a.name \
427 AND s.user_id = e.user_id) \
428 WHERE a.id in (' + ','.join([str(x) for x in ids]) + ') \
430 res = dict(cursor.fetchall())
432 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
434 sheet_names[sheet_id] = name
437 sheet_id = res.get(line_id, False)
439 res[line_id] = (sheet_id, sheet_names[sheet_id])
444 def _sheet_search(self, cursor, user, obj, name, args):
447 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
451 fargs = args[i][0].split('.', 1)
453 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
454 [(fargs[1], args[i][1], args[i][2])]))
457 if isinstance(args[i][2], basestring):
458 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
460 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
465 if (x[2] is False) and (x[1] == '='):
466 qu1.append('(s.id IS NULL)')
467 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
468 qu1.append('(s.id IS NOT NULL)')
470 qu1.append('(s.id %s %s)' % (x[1], '%d'))
474 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
477 qu1.append('(False)')
479 qu1 = ' WHERE ' + ' AND '.join(qu1)
482 cursor.execute('SELECT a.id\
483 FROM hr_timesheet_sheet_sheet s \
484 LEFT JOIN (hr_attendance a \
485 LEFT JOIN hr_employee e \
486 ON (a.employee_id = e.id)) \
487 ON (s.date_to >= a.name \
488 AND s.date_from <= a.name \
489 AND s.user_id = e.user_id) ' + \
491 res = cursor.fetchall()
493 return [('id', '=', '0')]
494 return [('id', 'in', [x[0] for x in res])]
497 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
498 type='many2one', relation='hr_timesheet_sheet.sheet',
499 fnct_search=_sheet_search),
502 'name': _get_default_date,
505 def create(self, cr, uid, vals, context={}):
506 if 'sheet_id' in context:
507 vals['sheet_id']=context['sheet_id']
508 if 'sheet_id' in vals:
509 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
510 if ts.state not in ('draft', 'new'):
511 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
512 return super(hr_attendance,self).create(cr, uid, vals, context=context)
514 def unlink(self, cr, uid, ids, *args, **kwargs):
515 self._check(cr, uid, ids)
516 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
518 def write(self, cr, uid, ids, vals, context={}):
519 if 'sheet_id' in context:
520 vals['sheet_id']=context['sheet_id']
521 self._check(cr, uid, ids)
522 return super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
524 def _check(self, cr, uid, ids):
525 for att in self.browse(cr, uid, ids):
526 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
527 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
532 class hr_timesheet_sheet_sheet_day(osv.osv):
533 _name = "hr_timesheet_sheet.sheet.day"
534 _description = "Timesheets by period"
538 'name': fields.date('Date', readonly=True),
539 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
540 'total_timesheet': fields.float('Project Timesheet', readonly=True),
541 'total_attendance': fields.float('Attendance', readonly=True),
542 'total_difference': fields.float('Difference', readonly=True),
546 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
553 (total_attendance - total_timesheet) AS total_difference
560 SUM(total_timesheet) as total_timesheet,
561 CASE WHEN SUM(total_attendance) < 0
562 THEN (SUM(total_attendance) +
563 CASE WHEN current_date <> name
565 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
568 ELSE SUM(total_attendance)
569 END /60 as total_attendance
574 l.date::date as name,
576 sum(l.unit_amount) as total_timesheet,
577 0.0 as total_attendance
579 hr_analytic_timesheet hrt
580 left join (account_analytic_line l
581 LEFT JOIN hr_timesheet_sheet_sheet s
582 ON (s.date_to >= l.date
583 AND s.date_from <= l.date
584 AND s.user_id = l.user_id))
585 on (l.id = hrt.line_id)
586 group by l.date::date, s.id
590 a.name::date as name,
592 0.0 as total_timesheet,
593 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
596 LEFT JOIN (hr_timesheet_sheet_sheet s
597 LEFT JOIN hr_employee e
598 ON (s.user_id = e.user_id))
599 ON (a.employee_id = e.id
600 AND s.date_to >= a.name
601 AND s.date_from <= a.name)
602 WHERE action in ('sign_in', 'sign_out')
603 group by a.name::date, s.id
605 GROUP BY name, sheet_id
608 hr_timesheet_sheet_sheet_day()
611 class hr_timesheet_sheet_sheet_account(osv.osv):
612 _name = "hr_timesheet_sheet.sheet.account"
613 _description = "Timesheets by period"
617 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
618 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
619 'total': fields.float('Total Time', digits=(16,2), readonly=True),
620 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
624 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
627 l.account_id as name,
629 sum(l.unit_amount) as total,
630 l.to_invoice as invoice_rate
632 hr_analytic_timesheet hrt
633 left join (account_analytic_line l
634 LEFT JOIN hr_timesheet_sheet_sheet s
635 ON (s.date_to >= l.date
636 AND s.date_from <= l.date
637 AND s.user_id = l.user_id))
638 on (l.id = hrt.line_id)
639 group by l.account_id, s.id, l.to_invoice
642 hr_timesheet_sheet_sheet_account()
645 class res_company(osv.osv):
646 _inherit = 'res.company'
648 'timesheet_range': fields.selection([('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range'),
649 '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."),
652 'timesheet_range': lambda *args: 'month',
653 'timesheet_max_difference': lambda *args: 0.0