1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
26 from osv import fields, osv
27 from tools.translate import _
30 class one2many_mod2(fields.one2many):
31 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
39 # {idn: (date_current, user_id), ...
40 # 1: ('2010-08-15', 1)}
41 res6 = dict([(rec['id'], (rec['date_current'], rec['user_id'][0]))
43 in obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)])
46 # '&', '&', ('name', '>=', '2011-03-01'), ('name', '<=', '2011-03-01'), ('employee_id.user_id', '=', 1),
47 # '&', '&', ('name', '>=', '2011-02-01'), ('name', '<=', '2011-02-01'), ('employee_id.user_id', '=', 1)]
49 for c, id in enumerate(ids):
55 dom.append(('name', '>=', res6[id][0]))
56 dom.append(('name', '<=', res6[id][0]))
57 dom.append(('employee_id.user_id', '=', res6[id][1]))
59 ids2 = obj.pool.get(self._obj).search(cr, user, dom, limit=self._limit)
65 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
66 if r[self._fields_id]:
67 res[r[self._fields_id][0]].append(r['id'])
71 def set(self, cr, obj, id, field, values, user=None, context=None):
75 context = context.copy()
76 context['sheet_id'] = id
77 return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user, context=context)
80 class one2many_mod(fields.one2many):
81 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
89 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
92 res6[r['id']] = (r['date_current'], r['user_id'][0])
98 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
99 ids2.extend(obj.pool.get(self._obj).search(cr, user,
100 dom, limit=self._limit))
104 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
105 [self._fields_id], context=context, load='_classic_write'):
106 if r[self._fields_id]:
107 res[r[self._fields_id][0]].append(r['id'])
111 class hr_timesheet_sheet(osv.osv):
112 _name = "hr_timesheet_sheet.sheet"
113 _table = 'hr_timesheet_sheet_sheet'
115 _description="Timesheet"
117 def _total_day(self, cr, uid, ids, name, args, context=None):
119 cr.execute('SELECT sheet.id, day.total_attendance, day.total_timesheet, day.total_difference\
120 FROM hr_timesheet_sheet_sheet AS sheet \
121 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
122 ON (sheet.id = day.sheet_id \
123 AND day.name = sheet.date_current) \
124 WHERE sheet.id IN %s',(tuple(ids),))
125 for record in cr.fetchall():
127 res[record[0]]['total_attendance_day'] = record[1]
128 res[record[0]]['total_timesheet_day'] = record[2]
129 res[record[0]]['total_difference_day'] = record[3]
132 def _total(self, cr, uid, ids, name, args, context=None):
134 cr.execute('SELECT s.id, COALESCE(SUM(d.total_attendance),0), COALESCE(SUM(d.total_timesheet),0), COALESCE(SUM(d.total_difference),0) \
135 FROM hr_timesheet_sheet_sheet s \
136 LEFT JOIN hr_timesheet_sheet_sheet_day d \
137 ON (s.id = d.sheet_id) \
138 WHERE s.id IN %s GROUP BY s.id',(tuple(ids),))
139 for record in cr.fetchall():
141 res[record[0]]['total_attendance'] = record[1]
142 res[record[0]]['total_timesheet'] = record[2]
143 res[record[0]]['total_difference'] = record[3]
146 def _state_attendance(self, cr, uid, ids, name, args, context=None):
147 emp_obj = self.pool.get('hr.employee')
152 for sheet in self.browse(cr, uid, ids, context=context):
153 result[sheet.id] = 'none'
154 emp_ids2 = emp_obj.search(cr, uid,
155 [('user_id', '=', sheet.user_id.id)], context=context)
157 link_emp[emp_ids2[0]] = sheet.id
158 emp_ids.append(emp_ids2[0])
159 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
160 if emp.id in link_emp:
161 sheet_id = link_emp[emp.id]
162 result[sheet_id] = emp.state
165 def check_employee_attendance_state(self, cr, uid, sheet_id, context=None):
166 ids_signin = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_in')])
167 ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')])
169 if len(ids_signin) != len(ids_signout):
170 raise osv.except_osv(('Warning !'),_('The timesheet cannot be validated as it does not contain equal no. of sign ins and sign outs!'))
173 def copy(self, cr, uid, ids, *args, **argv):
174 raise osv.except_osv(_('Error !'), _('You cannot duplicate a timesheet !'))
176 def create(self, cr, uid, vals, *args, **argv):
177 if 'employee_id' in vals:
178 if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id:
179 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any user defined !'))
180 return super(hr_timesheet_sheet, self).create(cr, uid, vals, *args, **argv)
182 def write(self, cr, uid, ids, vals, *args, **argv):
183 if 'employee_id' in vals:
184 new_user_id = self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id.id or False
186 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any user defined !'))
187 if not self._sheet_date(cr, uid, ids, forced_user_id=new_user_id):
188 raise osv.except_osv(_('Error !'), _('You can not have 2 timesheets that overlaps !\nPlease use the menu \'My Current Timesheet\' to avoid this problem.'))
189 return super(hr_timesheet_sheet, self).write(cr, uid, ids, vals, *args, **argv)
191 def button_confirm(self, cr, uid, ids, context=None):
192 for sheet in self.browse(cr, uid, ids, context=context):
193 self.check_employee_attendance_state(cr, uid, sheet.id, context)
194 di = sheet.user_id.company_id.timesheet_max_difference
195 if (abs(sheet.total_difference) < di) or not di:
196 wf_service = netsvc.LocalService("workflow")
197 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
199 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
202 def date_today(self, cr, uid, ids, context=None):
203 for sheet in self.browse(cr, uid, ids, context=context):
204 if datetime.today() <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
205 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
206 elif datetime.now() >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
207 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
209 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')}, context=context)
212 def date_previous(self, cr, uid, ids, context=None):
213 for sheet in self.browse(cr, uid, ids, context=context):
214 if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
215 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
217 self.write(cr, uid, [sheet.id], {
218 'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=-1)).strftime('%Y-%m-%d'),
222 def date_next(self, cr, uid, ids, context=None):
223 for sheet in self.browse(cr, uid, ids, context=context):
224 if datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
225 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
227 self.write(cr, uid, [sheet.id], {
228 'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=1)).strftime('%Y-%m-%d'),
232 def button_dummy(self, cr, uid, ids, context=None):
233 for sheet in self.browse(cr, uid, ids, context=context):
234 if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
235 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
236 elif datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
237 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
240 def sign(self, cr, uid, ids, typ, context=None):
241 emp_obj = self.pool.get('hr.employee')
242 sheet = self.browse(cr, uid, ids, context=context)[0]
245 if not sheet.date_current == time.strftime('%Y-%m-%d'):
246 raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
247 emp_id = sheet.employee_id.id
248 context['sheet_id']=ids[0]
249 emp_obj.attendance_action_change(cr, uid, [emp_id], type=typ, context=context,)
252 def sign_in(self, cr, uid, ids, context=None):
253 return self.sign(cr,uid,ids,'sign_in',context=None)
255 def sign_out(self, cr, uid, ids, context=None):
256 return self.sign(cr,uid,ids,'sign_out',context=None)
259 'name': fields.char('Description', size=64, select=1,
260 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
261 'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
262 '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)]}),
263 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
264 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
265 'date_current': fields.date('Current date', required=True, select=1),
266 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
267 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
268 readonly=True, states={
269 'draft': [('readonly', False)],
270 'new': [('readonly', False)]}
272 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True,),
273 'state' : fields.selection([
276 ('confirm','Confirmed'),
277 ('done','Done')], 'State', select=True, required=True, readonly=True,
278 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
279 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
280 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
281 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
282 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance', multi="_total_day"),
283 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet', multi="_total_day"),
284 'total_difference_day': fields.function(_total_day, method=True, string='Difference', multi="_total_day"),
285 'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total_sheet"),
286 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total_sheet"),
287 'total_difference': fields.function(_total, method=True, string='Difference', multi="_total_sheet"),
288 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
289 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
290 'company_id': fields.many2one('res.company', 'Company'),
291 'department_id':fields.many2one('hr.department','Department'),
294 def _default_date_from(self,cr, uid, context=None):
295 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
296 r = user.company_id and user.company_id.timesheet_range or 'month'
298 return time.strftime('%Y-%m-01')
300 return (datetime.today() + relativedelta(weekday=0, weeks=-1)).strftime('%Y-%m-%d')
302 return time.strftime('%Y-01-01')
303 return time.strftime('%Y-%m-%d')
305 def _default_date_to(self,cr, uid, context=None):
306 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
307 r = user.company_id and user.company_id.timesheet_range or 'month'
309 return (datetime.today() + relativedelta(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
311 return (datetime.today() + relativedelta(weekday=6)).strftime('%Y-%m-%d')
313 return time.strftime('%Y-12-31')
314 return time.strftime('%Y-%m-%d')
316 def _default_employee(self,cr, uid, context=None):
317 emp_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=',uid)], context=context)
318 return emp_ids and emp_ids[0] or False
321 'date_from' : _default_date_from,
322 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
323 'date_to' : _default_date_to,
325 'employee_id': _default_employee,
326 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
329 def _sheet_date(self, cr, uid, ids, forced_user_id=False, context=None):
330 for sheet in self.browse(cr, uid, ids, context=context):
331 new_user_id = forced_user_id or sheet.user_id and sheet.user_id.id
333 cr.execute('SELECT id \
334 FROM hr_timesheet_sheet_sheet \
335 WHERE (date_from < %s and %s < date_to) \
337 AND id <> %s',(sheet.date_to, sheet.date_from, new_user_id, sheet.id))
342 def _date_current_check(self, cr, uid, ids, context=None):
343 for sheet in self.browse(cr, uid, ids, context=context):
344 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
350 (_sheet_date, 'You can not have 2 timesheets that overlaps !\nPlease use the menu \'My Current Timesheet\' to avoid this problem.', ['date_from','date_to']),
351 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
354 def action_set_to_draft(self, cr, uid, ids, *args):
355 self.write(cr, uid, ids, {'state': 'draft'})
356 wf_service = netsvc.LocalService('workflow')
358 wf_service.trg_create(uid, self._name, id, cr)
361 def name_get(self, cr, uid, ids, context=None):
364 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
365 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
366 context=context, load='_classic_write')]
368 def unlink(self, cr, uid, ids, context=None):
369 sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
371 if sheet['state'] in ('confirm', 'done'):
372 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
373 elif sheet['total_attendance'] <> 0.00:
374 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
375 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
380 class hr_timesheet_line(osv.osv):
381 _inherit = "hr.analytic.timesheet"
383 def _get_default_date(self, cr, uid, context=None):
386 if 'date' in context:
387 return context['date']
388 return time.strftime('%Y-%m-%d')
390 def _sheet(self, cursor, user, ids, name, args, context=None):
391 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
392 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
393 FROM hr_timesheet_sheet_sheet s \
394 LEFT JOIN (hr_analytic_timesheet l \
395 LEFT JOIN account_analytic_line al \
396 ON (l.line_id = al.id)) \
397 ON (s.date_to >= al.date \
398 AND s.date_from <= al.date \
399 AND s.user_id = al.user_id) \
400 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
401 res = dict(cursor.fetchall())
403 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
405 sheet_names[sheet_id] = name
407 for line_id in {}.fromkeys(ids):
408 sheet_id = res.get(line_id, False)
410 res[line_id] = (sheet_id, sheet_names[sheet_id])
415 def _sheet_search(self, cursor, user, obj, name, args, context=None):
418 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
422 fargs = args[i][0].split('.', 1)
424 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
425 [(fargs[1], args[i][1], args[i][2])], context=context))
428 if isinstance(args[i][2], basestring):
429 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
431 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
436 if (x[2] is False) and (x[1] == '='):
437 qu1.append('(s.id IS NULL)')
438 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
439 qu1.append('(s.id IS NOT NULL)')
441 qu1.append('(s.id %s %s)' % (x[1], '%s'))
445 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
448 qu1.append('(False)')
450 qu1 = ' WHERE ' + ' AND '.join(qu1)
453 cursor.execute('SELECT l.id \
454 FROM hr_timesheet_sheet_sheet s \
455 LEFT JOIN (hr_analytic_timesheet l \
456 LEFT JOIN account_analytic_line al \
457 ON (l.line_id = al.id)) \
458 ON (s.date_to >= al.date \
459 AND s.date_from <= al.date \
460 AND s.user_id = al.user_id)' + \
462 res = cursor.fetchall()
464 return [('id', '=', '0')]
465 return [('id', 'in', [x[0] for x in res])]
468 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
469 type='many2one', relation='hr_timesheet_sheet.sheet',
470 fnct_search=_sheet_search),
473 'date': _get_default_date,
476 def create(self, cr, uid, vals, *args, **kwargs):
477 if vals.get('sheet_id', False):
478 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
479 if not ts.state in ('draft', 'new'):
480 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
481 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
483 def unlink(self, cr, uid, ids, *args, **kwargs):
484 self._check(cr, uid, ids)
485 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
487 def write(self, cr, uid, ids, *args, **kwargs):
488 self._check(cr, uid, ids)
489 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
491 def _check(self, cr, uid, ids):
492 for att in self.browse(cr, uid, ids):
493 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
494 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
499 class hr_attendance(osv.osv):
500 _inherit = "hr.attendance"
502 def _get_default_date(self, cr, uid, context=None):
505 if 'name' in context:
506 return context['name'] + time.strftime(' %H:%M:%S')
507 return time.strftime('%Y-%m-%d %H:%M:%S')
509 def _sheet(self, cursor, user, ids, name, args, context=None):
510 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
511 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
512 FROM hr_timesheet_sheet_sheet s \
513 LEFT JOIN (hr_attendance a \
514 LEFT JOIN hr_employee e \
515 LEFT JOIN resource_resource r \
516 ON (e.resource_id = r.id) \
517 ON (a.employee_id = e.id)) \
518 ON (s.date_to >= date_trunc('day',a.name) \
519 AND s.date_from <= a.name \
520 AND s.user_id = r.user_id) \
521 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
522 res = dict(cursor.fetchall())
524 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
526 sheet_names[sheet_id] = name
527 for line_id in {}.fromkeys(ids):
528 sheet_id = res.get(line_id, False)
530 res[line_id] = (sheet_id, sheet_names[sheet_id])
535 def _sheet_search(self, cursor, user, obj, name, args, context=None):
539 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
542 fargs = args[i][0].split('.', 1)
544 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
545 [(fargs[1], args[i][1], args[i][2])], context=context))
548 if isinstance(args[i][2], basestring):
549 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
551 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
556 if (x[2] is False) and (x[1] == '='):
557 qu1.append('(s.id IS NULL)')
558 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
559 qu1.append('(s.id IS NOT NULL)')
561 qu1.append('(s.id %s %s)' % (x[1], '%s'))
565 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
568 qu1.append('(False)')
570 qu1 = ' WHERE ' + ' AND '.join(qu1)
573 cursor.execute('SELECT a.id\
574 FROM hr_timesheet_sheet_sheet s \
575 LEFT JOIN (hr_attendance a \
576 LEFT JOIN hr_employee e \
577 ON (a.employee_id = e.id)) \
578 LEFT JOIN resource_resource r \
579 ON (e.resource_id = r.id) \
580 ON (s.date_to >= date_trunc(\'day\',a.name) \
581 AND s.date_from <= a.name \
582 AND s.user_id = r.user_id) ' + \
584 res = cursor.fetchall()
586 return [('id', '=', '0')]
587 return [('id', 'in', [x[0] for x in res])]
590 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
591 type='many2one', relation='hr_timesheet_sheet.sheet',
592 fnct_search=_sheet_search),
595 'name': _get_default_date,
598 def create(self, cr, uid, vals, context=None):
601 if 'sheet_id' in context:
602 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
603 if ts.state not in ('draft', 'new'):
604 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
605 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
606 if 'sheet_id' in context:
607 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
608 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
609 'date outside the current timesheet dates!'))
612 def unlink(self, cr, uid, ids, *args, **kwargs):
613 self._check(cr, uid, ids)
614 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
616 def write(self, cr, uid, ids, vals, context=None):
619 self._check(cr, uid, ids)
620 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
621 if 'sheet_id' in context:
622 for attendance in self.browse(cr, uid, ids, context=context):
623 if context['sheet_id'] != attendance.sheet_id.id:
624 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
625 'date outside the current timesheet dates!'))
628 def _check(self, cr, uid, ids):
629 for att in self.browse(cr, uid, ids):
630 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
631 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
636 class hr_timesheet_sheet_sheet_day(osv.osv):
637 _name = "hr_timesheet_sheet.sheet.day"
638 _description = "Timesheets by Period"
642 'name': fields.date('Date', readonly=True),
643 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
644 'total_timesheet': fields.float('Total Timesheet', readonly=True),
645 'total_attendance': fields.float('Attendance', readonly=True),
646 'total_difference': fields.float('Difference', readonly=True),
650 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
657 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
664 SUM(total_timesheet) as total_timesheet,
665 CASE WHEN SUM(total_attendance) < 0
666 THEN (SUM(total_attendance) +
667 CASE WHEN current_date <> name
669 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
672 ELSE SUM(total_attendance)
673 END /60 as total_attendance
678 l.date::date as name,
680 sum(l.unit_amount) as total_timesheet,
681 0.0 as total_attendance
683 hr_analytic_timesheet hrt
684 left join (account_analytic_line l
685 LEFT JOIN hr_timesheet_sheet_sheet s
686 ON (s.date_to >= l.date
687 AND s.date_from <= l.date
688 AND s.user_id = l.user_id))
689 on (l.id = hrt.line_id)
690 group by l.date::date, s.id
694 a.name::date as name,
696 0.0 as total_timesheet,
697 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
700 LEFT JOIN (hr_timesheet_sheet_sheet s
701 LEFT JOIN resource_resource r
702 LEFT JOIN hr_employee e
703 ON (e.resource_id = r.id)
704 ON (s.user_id = r.user_id))
705 ON (a.employee_id = e.id
706 AND s.date_to >= date_trunc('day',a.name)
707 AND s.date_from <= a.name)
708 WHERE action in ('sign_in', 'sign_out')
709 group by a.name::date, s.id
711 GROUP BY name, sheet_id
714 hr_timesheet_sheet_sheet_day()
717 class hr_timesheet_sheet_sheet_account(osv.osv):
718 _name = "hr_timesheet_sheet.sheet.account"
719 _description = "Timesheets by Period"
723 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
724 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
725 'total': fields.float('Total Time', digits=(16,2), readonly=True),
726 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
730 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
733 l.account_id as name,
735 sum(l.unit_amount) as total,
736 l.to_invoice as invoice_rate
738 hr_analytic_timesheet hrt
739 left join (account_analytic_line l
740 LEFT JOIN hr_timesheet_sheet_sheet s
741 ON (s.date_to >= l.date
742 AND s.date_from <= l.date
743 AND s.user_id = l.user_id))
744 on (l.id = hrt.line_id)
745 group by l.account_id, s.id, l.to_invoice
748 hr_timesheet_sheet_sheet_account()
752 class res_company(osv.osv):
753 _inherit = 'res.company'
755 'timesheet_range': fields.selection(
756 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
757 'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
758 help="Allowed difference in hours between the sign in/out and the timesheet " \
759 "computation for one sheet. Set this to 0 if you do not want any control."),
762 'timesheet_range': lambda *args: 'week',
763 'timesheet_max_difference': lambda *args: 0.0
768 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: