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 if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
181 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any product defined !'))
182 if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
183 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any analytic journal defined !'))
184 return super(hr_timesheet_sheet, self).create(cr, uid, vals, *args, **argv)
186 def write(self, cr, uid, ids, vals, *args, **argv):
187 if 'employee_id' in vals:
188 new_user_id = self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id.id or False
190 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any user defined !'))
191 if not self._sheet_date(cr, uid, ids, forced_user_id=new_user_id):
192 raise osv.except_osv(_('Error !'), _('You can not have 2 timesheets that overlaps !\nPlease use the menu \'My Current Timesheet\' to avoid this problem.'))
193 if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
194 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any product defined !'))
195 if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
196 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any analytic journal defined !'))
197 return super(hr_timesheet_sheet, self).write(cr, uid, ids, vals, *args, **argv)
199 def button_confirm(self, cr, uid, ids, context=None):
200 for sheet in self.browse(cr, uid, ids, context=context):
201 self.check_employee_attendance_state(cr, uid, sheet.id, context)
202 di = sheet.user_id.company_id.timesheet_max_difference
203 if (abs(sheet.total_difference) < di) or not di:
204 wf_service = netsvc.LocalService("workflow")
205 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
207 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
210 def date_today(self, cr, uid, ids, context=None):
211 for sheet in self.browse(cr, uid, ids, context=context):
212 if datetime.today() <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
213 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
214 elif datetime.now() >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
215 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
217 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')}, context=context)
220 def date_previous(self, cr, uid, ids, context=None):
221 for sheet in self.browse(cr, uid, ids, context=context):
222 if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
223 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
225 self.write(cr, uid, [sheet.id], {
226 'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=-1)).strftime('%Y-%m-%d'),
230 def date_next(self, cr, uid, ids, context=None):
231 for sheet in self.browse(cr, uid, ids, context=context):
232 if datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
233 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
235 self.write(cr, uid, [sheet.id], {
236 'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=1)).strftime('%Y-%m-%d'),
240 def button_dummy(self, cr, uid, ids, context=None):
241 for sheet in self.browse(cr, uid, ids, context=context):
242 if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
243 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
244 elif datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
245 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
248 def sign(self, cr, uid, ids, typ, context=None):
249 emp_obj = self.pool.get('hr.employee')
250 sheet = self.browse(cr, uid, ids, context=context)[0]
253 if not sheet.date_current == time.strftime('%Y-%m-%d'):
254 raise osv.except_osv(_('Error !'), _('You cannot sign in/sign out from an other date than today'))
255 emp_id = sheet.employee_id.id
256 context['sheet_id']=ids[0]
257 emp_obj.attendance_action_change(cr, uid, [emp_id], type=typ, context=context,)
260 def sign_in(self, cr, uid, ids, context=None):
261 return self.sign(cr,uid,ids,'sign_in',context=None)
263 def sign_out(self, cr, uid, ids, context=None):
264 return self.sign(cr,uid,ids,'sign_out',context=None)
267 'name': fields.char('Description', size=64, select=1,
268 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
269 'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
270 '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)]}),
271 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
272 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
273 'date_current': fields.date('Current date', required=True, select=1),
274 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
275 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
276 readonly=True, states={
277 'draft': [('readonly', False)],
278 'new': [('readonly', False)]}
280 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances'),
281 'state' : fields.selection([
284 ('confirm','Confirmed'),
285 ('done','Done')], 'State', select=True, required=True, readonly=True,
286 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
287 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
288 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
289 'state_attendance' : fields.function(_state_attendance, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
290 'total_attendance_day': fields.function(_total_day, string='Total Attendance', multi="_total_day"),
291 'total_timesheet_day': fields.function(_total_day, string='Total Timesheet', multi="_total_day"),
292 'total_difference_day': fields.function(_total_day, string='Difference', multi="_total_day"),
293 'total_attendance': fields.function(_total, string='Total Attendance', multi="_total_sheet"),
294 'total_timesheet': fields.function(_total, string='Total Timesheet', multi="_total_sheet"),
295 'total_difference': fields.function(_total, string='Difference', multi="_total_sheet"),
296 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
297 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
298 'company_id': fields.many2one('res.company', 'Company'),
299 'department_id':fields.many2one('hr.department','Department'),
302 def _default_date_from(self,cr, uid, context=None):
303 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
304 r = user.company_id and user.company_id.timesheet_range or 'month'
306 return time.strftime('%Y-%m-01')
308 return (datetime.today() + relativedelta(weekday=0, weeks=-1)).strftime('%Y-%m-%d')
310 return time.strftime('%Y-01-01')
311 return time.strftime('%Y-%m-%d')
313 def _default_date_to(self,cr, uid, context=None):
314 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
315 r = user.company_id and user.company_id.timesheet_range or 'month'
317 return (datetime.today() + relativedelta(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
319 return (datetime.today() + relativedelta(weekday=6)).strftime('%Y-%m-%d')
321 return time.strftime('%Y-12-31')
322 return time.strftime('%Y-%m-%d')
324 def _default_employee(self,cr, uid, context=None):
325 emp_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=',uid)], context=context)
326 return emp_ids and emp_ids[0] or False
329 'date_from' : _default_date_from,
330 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
331 'date_to' : _default_date_to,
333 'employee_id': _default_employee,
334 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
337 def _sheet_date(self, cr, uid, ids, forced_user_id=False, context=None):
338 for sheet in self.browse(cr, uid, ids, context=context):
339 new_user_id = forced_user_id or sheet.user_id and sheet.user_id.id
341 cr.execute('SELECT id \
342 FROM hr_timesheet_sheet_sheet \
343 WHERE (date_from < %s and %s < date_to) \
345 AND id <> %s',(sheet.date_to, sheet.date_from, new_user_id, sheet.id))
350 def _date_current_check(self, cr, uid, ids, context=None):
351 for sheet in self.browse(cr, uid, ids, context=context):
352 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
358 (_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']),
359 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
362 def action_set_to_draft(self, cr, uid, ids, *args):
363 self.write(cr, uid, ids, {'state': 'draft'})
364 wf_service = netsvc.LocalService('workflow')
366 wf_service.trg_create(uid, self._name, id, cr)
369 def name_get(self, cr, uid, ids, context=None):
372 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
373 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
374 context=context, load='_classic_write')]
376 def unlink(self, cr, uid, ids, context=None):
377 sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
379 if sheet['state'] in ('confirm', 'done'):
380 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
381 elif sheet['total_attendance'] <> 0.00:
382 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
383 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
388 class hr_timesheet_line(osv.osv):
389 _inherit = "hr.analytic.timesheet"
391 def _get_default_date(self, cr, uid, context=None):
394 if 'date' in context:
395 return context['date']
396 return time.strftime('%Y-%m-%d')
398 def _sheet(self, cursor, user, ids, name, args, context=None):
399 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
400 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
401 FROM hr_timesheet_sheet_sheet s \
402 LEFT JOIN (hr_analytic_timesheet l \
403 LEFT JOIN account_analytic_line al \
404 ON (l.line_id = al.id)) \
405 ON (s.date_to >= al.date \
406 AND s.date_from <= al.date \
407 AND s.user_id = al.user_id) \
408 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
409 res = dict(cursor.fetchall())
411 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
413 sheet_names[sheet_id] = name
415 for line_id in {}.fromkeys(ids):
416 sheet_id = res.get(line_id, False)
418 res[line_id] = (sheet_id, sheet_names[sheet_id])
423 def _sheet_search(self, cursor, user, obj, name, args, context=None):
426 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
430 fargs = args[i][0].split('.', 1)
432 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
433 [(fargs[1], args[i][1], args[i][2])], context=context))
436 if isinstance(args[i][2], basestring):
437 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
439 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
444 if (x[2] is False) and (x[1] == '='):
445 qu1.append('(s.id IS NULL)')
446 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
447 qu1.append('(s.id IS NOT NULL)')
449 qu1.append('(s.id %s %s)' % (x[1], '%s'))
453 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
456 qu1.append('(False)')
458 qu1 = ' WHERE ' + ' AND '.join(qu1)
461 cursor.execute('SELECT l.id \
462 FROM hr_timesheet_sheet_sheet s \
463 LEFT JOIN (hr_analytic_timesheet l \
464 LEFT JOIN account_analytic_line al \
465 ON (l.line_id = al.id)) \
466 ON (s.date_to >= al.date \
467 AND s.date_from <= al.date \
468 AND s.user_id = al.user_id)' + \
470 res = cursor.fetchall()
472 return [('id', '=', '0')]
473 return [('id', 'in', [x[0] for x in res])]
476 'sheet_id': fields.function(_sheet, string='Sheet',
477 type='many2one', relation='hr_timesheet_sheet.sheet',
478 fnct_search=_sheet_search),
481 'date': _get_default_date,
484 def _check_sheet_state(self, cr, uid, ids, context=None):
487 for timesheet_line in self.browse(cr, uid, ids, context=context):
488 if timesheet_line.sheet_id and timesheet_line.sheet_id.state not in ('draft', 'new'):
493 (_check_sheet_state, 'You can not modify an entry in a Confirmed/Done timesheet !.', ['state']),
496 def unlink(self, cr, uid, ids, *args, **kwargs):
497 if isinstance(ids, (int, long)):
499 self._check(cr, uid, ids)
500 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
502 def _check(self, cr, uid, ids):
503 for att in self.browse(cr, uid, ids):
504 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
505 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
510 class hr_attendance(osv.osv):
511 _inherit = "hr.attendance"
513 def _get_default_date(self, cr, uid, context=None):
516 if 'name' in context:
517 return context['name'] + time.strftime(' %H:%M:%S')
518 return time.strftime('%Y-%m-%d %H:%M:%S')
520 def _sheet(self, cursor, user, ids, name, args, context=None):
521 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
522 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
523 FROM hr_timesheet_sheet_sheet s \
524 LEFT JOIN (hr_attendance a \
525 LEFT JOIN hr_employee e \
526 LEFT JOIN resource_resource r \
527 ON (e.resource_id = r.id) \
528 ON (a.employee_id = e.id)) \
529 ON (s.date_to >= date_trunc('day',a.name) \
530 AND s.date_from <= a.name \
531 AND s.user_id = r.user_id) \
532 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
533 res = dict(cursor.fetchall())
535 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
537 sheet_names[sheet_id] = name
538 for line_id in {}.fromkeys(ids):
539 sheet_id = res.get(line_id, False)
541 res[line_id] = (sheet_id, sheet_names[sheet_id])
546 def _sheet_search(self, cursor, user, obj, name, args, context=None):
550 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
553 fargs = args[i][0].split('.', 1)
555 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
556 [(fargs[1], args[i][1], args[i][2])], context=context))
559 if isinstance(args[i][2], basestring):
560 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
562 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
567 if (x[2] is False) and (x[1] == '='):
568 qu1.append('(s.id IS NULL)')
569 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
570 qu1.append('(s.id IS NOT NULL)')
572 qu1.append('(s.id %s %s)' % (x[1], '%s'))
576 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
579 qu1.append('(False)')
581 qu1 = ' WHERE ' + ' AND '.join(qu1)
584 cursor.execute('SELECT a.id\
585 FROM hr_timesheet_sheet_sheet s \
586 LEFT JOIN (hr_attendance a \
587 LEFT JOIN hr_employee e \
588 ON (a.employee_id = e.id)) \
589 LEFT JOIN resource_resource r \
590 ON (e.resource_id = r.id) \
591 ON (s.date_to >= date_trunc(\'day\',a.name) \
592 AND s.date_from <= a.name \
593 AND s.user_id = r.user_id) ' + \
595 res = cursor.fetchall()
597 return [('id', '=', '0')]
598 return [('id', 'in', [x[0] for x in res])]
601 'sheet_id': fields.function(_sheet, string='Sheet',
602 type='many2one', relation='hr_timesheet_sheet.sheet',
603 fnct_search=_sheet_search),
606 'name': _get_default_date,
609 def create(self, cr, uid, vals, context=None):
612 if 'sheet_id' in context:
613 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
614 if ts.state not in ('draft', 'new'):
615 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
616 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
617 if 'sheet_id' in context:
618 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
619 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
620 'date outside the current timesheet dates!'))
623 def unlink(self, cr, uid, ids, *args, **kwargs):
624 if isinstance(ids, (int, long)):
626 self._check(cr, uid, ids)
627 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
629 def write(self, cr, uid, ids, vals, context=None):
632 if isinstance(ids, (int, long)):
634 self._check(cr, uid, ids)
635 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
636 if 'sheet_id' in context:
637 for attendance in self.browse(cr, uid, ids, context=context):
638 if context['sheet_id'] != attendance.sheet_id.id:
639 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
640 'date outside the current timesheet dates!'))
643 def _check(self, cr, uid, ids):
644 for att in self.browse(cr, uid, ids):
645 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
646 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
651 class hr_timesheet_sheet_sheet_day(osv.osv):
652 _name = "hr_timesheet_sheet.sheet.day"
653 _description = "Timesheets by Period"
657 'name': fields.date('Date', readonly=True),
658 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
659 'total_timesheet': fields.float('Total Timesheet', readonly=True),
660 'total_attendance': fields.float('Attendance', readonly=True),
661 'total_difference': fields.float('Difference', readonly=True),
665 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
672 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
679 SUM(total_timesheet) as total_timesheet,
680 CASE WHEN SUM(total_attendance) < 0
681 THEN (SUM(total_attendance) +
682 CASE WHEN current_date <> name
684 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
687 ELSE SUM(total_attendance)
688 END /60 as total_attendance
693 l.date::date as name,
695 sum(l.unit_amount) as total_timesheet,
696 0.0 as total_attendance
698 hr_analytic_timesheet hrt
699 left join (account_analytic_line l
700 LEFT JOIN hr_timesheet_sheet_sheet s
701 ON (s.date_to >= l.date
702 AND s.date_from <= l.date
703 AND s.user_id = l.user_id))
704 on (l.id = hrt.line_id)
705 group by l.date::date, s.id
709 a.name::date as name,
711 0.0 as total_timesheet,
712 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
715 LEFT JOIN (hr_timesheet_sheet_sheet s
716 LEFT JOIN resource_resource r
717 LEFT JOIN hr_employee e
718 ON (e.resource_id = r.id)
719 ON (s.user_id = r.user_id))
720 ON (a.employee_id = e.id
721 AND s.date_to >= date_trunc('day',a.name)
722 AND s.date_from <= a.name)
723 WHERE action in ('sign_in', 'sign_out')
724 group by a.name::date, s.id
726 GROUP BY name, sheet_id
729 hr_timesheet_sheet_sheet_day()
732 class hr_timesheet_sheet_sheet_account(osv.osv):
733 _name = "hr_timesheet_sheet.sheet.account"
734 _description = "Timesheets by Period"
738 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
739 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
740 'total': fields.float('Total Time', digits=(16,2), readonly=True),
741 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
745 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
748 l.account_id as name,
750 sum(l.unit_amount) as total,
751 l.to_invoice as invoice_rate
753 hr_analytic_timesheet hrt
754 left join (account_analytic_line l
755 LEFT JOIN hr_timesheet_sheet_sheet s
756 ON (s.date_to >= l.date
757 AND s.date_from <= l.date
758 AND s.user_id = l.user_id))
759 on (l.id = hrt.line_id)
760 group by l.account_id, s.id, l.to_invoice
763 hr_timesheet_sheet_sheet_account()
767 class res_company(osv.osv):
768 _inherit = 'res.company'
770 'timesheet_range': fields.selection(
771 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
772 'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
773 help="Allowed difference in hours between the sign in/out and the timesheet " \
774 "computation for one sheet. Set this to 0 if you do not want any control."),
777 'timesheet_range': lambda *args: 'week',
778 'timesheet_max_difference': lambda *args: 0.0
783 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: