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])
326 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
327 type='many2one', relation='hr_timesheet_sheet.sheet'),
330 'date': _get_default_date,
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)
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)
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)
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 !')
356 class hr_attendance(osv.osv):
357 _inherit = "hr.attendance"
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')
364 def _sheet(self, cursor, user, ids, name, args, context):
365 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
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]) + ') \
377 res = dict(cursor.fetchall())
379 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
381 sheet_names[sheet_id] = name
384 sheet_id = res.get(line_id, False)
386 res[line_id] = (sheet_id, sheet_names[sheet_id])
392 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
393 type='many2one', relation='hr_timesheet_sheet.sheet'),
396 'name': _get_default_date,
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)
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)
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)
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 !')
426 class hr_timesheet_sheet_sheet_day(osv.osv):
427 _name = "hr_timesheet_sheet.sheet.day"
428 _description = "Timesheets by period"
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),
440 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
447 (total_attendance - total_timesheet) AS total_difference
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
459 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
462 ELSE SUM(total_attendance)
463 END /60 as total_attendance
468 l.date::date as name,
470 sum(l.unit_amount) as total_timesheet,
471 0.0 as total_attendance
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
484 a.name::date as name,
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
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
499 GROUP BY name, sheet_id
502 hr_timesheet_sheet_sheet_day()
505 class hr_timesheet_sheet_sheet_account(osv.osv):
506 _name = "hr_timesheet_sheet.sheet.account"
507 _description = "Timesheets by period"
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),
518 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
521 l.account_id as name,
523 sum(l.unit_amount) as total,
524 l.to_invoice as invoice_rate
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
536 hr_timesheet_sheet_sheet_account()
539 class res_company(osv.osv):
540 _inherit = 'res.company'
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."),
546 'timesheet_range': lambda *args: 'month',
547 'timesheet_max_difference': lambda *args: 0.0