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 ##############################################################################
25 from osv import fields, osv
26 from mx import DateTime
27 from tools.translate import _
29 class one2many_mod2(fields.one2many):
30 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
35 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
38 res6[r['id']] = (r['date_current'], r['user_id'][0])
44 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
45 ('name', '<=', res6[id][0] + ' 23:59:59'),
46 ('employee_id.user_id', '=', res6[id][1])]
47 ids2.extend(obj.pool.get(self._obj).search(cr, user,
48 dom, limit=self._limit))
50 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
51 [self._fields_id], context=context, load='_classic_write'):
52 if r[self._fields_id]:
53 res.setdefault(r[self._fields_id][0], []).append(r['id'])
57 def set(self, cr, obj, id, field, values, user=None, context=None):
60 context = context.copy()
61 context['sheet_id'] = id
62 return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user,
66 class one2many_mod(fields.one2many):
67 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
72 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
75 res6[r['id']] = (r['date_current'], r['user_id'][0])
81 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
82 ids2.extend(obj.pool.get(self._obj).search(cr, user,
83 dom, limit=self._limit))
85 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
86 [self._fields_id], context=context, load='_classic_write'):
87 if r[self._fields_id]:
88 res.setdefault(r[self._fields_id][0], []).append(r['id'])
92 class hr_timesheet_sheet(osv.osv):
93 _name = "hr_timesheet_sheet.sheet"
94 _table = 'hr_timesheet_sheet_sheet'
96 _description="Timesheet"
98 def _total_day(self, cr, uid, ids, name, args, context=None):
102 cr.execute('SELECT sheet.id, day.total_attendance, day.total_timesheet, day.total_difference\
103 FROM hr_timesheet_sheet_sheet AS sheet \
104 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
105 ON (sheet.id = day.sheet_id \
106 AND day.name = sheet.date_current) \
107 WHERE sheet.id IN %s',(tuple(ids),))
108 for record in cr.fetchall():
110 res[record[0]]['total_attendance_day'] = record[1]
111 res[record[0]]['total_timesheet_day'] = record[2]
112 res[record[0]]['total_difference_day'] = record[3]
115 def _total(self, cr, uid, ids, name, args, context=None):
119 cr.execute('SELECT s.id, COALESCE(SUM(d.total_attendance),0), COALESCE(SUM(d.total_timesheet),0), COALESCE(SUM(d.total_difference),0) \
120 FROM hr_timesheet_sheet_sheet s \
121 LEFT JOIN hr_timesheet_sheet_sheet_day d \
122 ON (s.id = d.sheet_id) \
123 WHERE s.id IN %s GROUP BY s.id',(tuple(ids),))
124 for record in cr.fetchall():
126 res[record[0]]['total_attendance'] = record[1]
127 res[record[0]]['total_timesheet'] = record[2]
128 res[record[0]]['total_difference'] = record[3]
131 def _state_attendance(self, cr, uid, ids, name, args, context=None):
132 emp_obj = self.pool.get('hr.employee')
139 for sheet in self.browse(cr, uid, ids, context=context):
140 result[sheet.id] = 'none'
141 emp_ids2 = emp_obj.search(cr, uid,
142 [('user_id', '=', sheet.user_id.id)], context=context)
144 link_emp[emp_ids2[0]] = sheet.id
145 emp_ids.append(emp_ids2[0])
146 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
147 if emp.id in link_emp:
148 sheet_id = link_emp[emp.id]
149 result[sheet_id] = emp.state
152 def check_employee_attendance_state(self, cr, uid, sheet_id, context=None):
153 ids_signin = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_in')])
154 ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')])
156 if len(ids_signin) != len(ids_signout):
157 raise osv.except_osv(('Warning !'),_('The timesheet cannot be validated as it does not contain equal no. of sign ins and sign outs!'))
160 def copy(self, cr, uid, ids, *args, **argv):
161 raise osv.except_osv(_('Error !'), _('You cannot duplicate a timesheet !'))
163 def button_confirm(self, cr, uid, ids, context=None):
166 for sheet in self.browse(cr, uid, ids, context=context):
167 self.check_employee_attendance_state(cr, uid, sheet.id, context)
168 di = sheet.user_id.company_id.timesheet_max_difference
169 if (abs(sheet.total_difference) < di) or not di:
170 wf_service = netsvc.LocalService("workflow")
171 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
173 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
176 def date_today(self, cr, uid, ids, context=None):
179 for sheet in self.browse(cr, uid, ids, context=context):
180 if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
181 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
182 elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
183 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
185 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')}, context=context)
188 def date_previous(self, cr, uid, ids, context=None):
191 for sheet in self.browse(cr, uid, ids, context=context):
192 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
193 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
195 self.write(cr, uid, [sheet.id], {
196 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
200 def date_next(self, cr, uid, ids, context=None):
203 for sheet in self.browse(cr, uid, ids, context=context):
204 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
205 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
207 self.write(cr, uid, [sheet.id], {
208 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
212 def button_dummy(self, cr, uid, ids, context=None):
215 for sheet in self.browse(cr, uid, ids, context=context):
216 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
217 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
218 elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
219 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
222 def sign_in(self, cr, uid, ids, context=None):
223 emp_obj = self.pool.get('hr.employee')
226 if not self.browse(cr, uid, ids, context=context)[0].date_current == time.strftime('%Y-%m-%d'):
227 raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
228 emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
229 context['sheet_id']=ids[0]
230 success = emp_obj.attendance_action_change(cr, uid, emp_ids, type='sign_in', context=context,)
233 def sign_out(self, cr, uid, ids, context=None):
234 emp_obj = self.pool.get('hr.employee')
237 if not self.browse(cr, uid, ids, context=context)[0].date_current == time.strftime('%Y-%m-%d'):
238 raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
239 emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)])
240 context['sheet_id']=ids[0]
241 success = emp_obj.attendance_action_change(cr, uid, emp_ids, type='sign_out', context=context,)
245 'name': fields.char('Description', size=64, select=1,
246 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
247 'user_id': fields.many2one('res.users', 'User', required=True, select=1,
248 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
249 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
250 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
251 'date_current': fields.date('Current date', required=True),
252 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
253 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
254 readonly=True, states={
255 'draft': [('readonly', False)],
256 'new': [('readonly', False)]}
258 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
259 'state' : fields.selection([
262 ('confirm','Confirmed'),
263 ('done','Done')], 'State', select=True, required=True, readonly=True,
264 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
265 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
266 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
267 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
268 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance', multi="_total_day"),
269 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet', multi="_total_day"),
270 'total_difference_day': fields.function(_total_day, method=True, string='Difference', multi="_total_day"),
271 'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total_sheet"),
272 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total_sheet"),
273 'total_difference': fields.function(_total, method=True, string='Difference', multi="_total_sheet"),
274 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
275 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
276 'company_id': fields.many2one('res.company', 'Company'),
277 'department_id':fields.many2one('hr.department','Department'),
280 def _default_date_from(self,cr, uid, context=None):
283 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
284 r = user.company_id and user.company_id.timesheet_range or 'month'
286 return time.strftime('%Y-%m-01')
288 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
290 return time.strftime('%Y-01-01')
291 return time.strftime('%Y-%m-%d')
293 def _default_date_to(self,cr, uid, context=None):
294 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
295 r = user.company_id and user.company_id.timesheet_range or 'month'
297 return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
299 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
301 return time.strftime('%Y-12-31')
302 return time.strftime('%Y-%m-%d')
305 'user_id': lambda self,cr,uid,c: uid,
306 'date_from' : _default_date_from,
307 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
308 'date_to' : _default_date_to,
310 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
313 def _sheet_date(self, cr, uid, ids):
314 for sheet in self.browse(cr, uid, ids):
315 cr.execute('SELECT id \
316 FROM hr_timesheet_sheet_sheet \
317 WHERE (date_from < %s and %s < date_to) \
319 AND id <> %s', (sheet.date_to, sheet.date_from,
320 sheet.user_id.id, sheet.id))
325 def _date_current_check(self, cr, uid, ids):
326 for sheet in self.browse(cr, uid, ids):
327 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
333 (_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']),
334 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
337 def action_set_to_draft(self, cr, uid, ids, *args):
338 self.write(cr, uid, ids, {'state': 'draft'})
339 wf_service = netsvc.LocalService('workflow')
341 wf_service.trg_create(uid, self._name, id, cr)
344 def name_get(self, cr, uid, ids, context=None):
349 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
350 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
351 context=context, load='_classic_write')]
353 def unlink(self, cr, uid, ids, context=None):
356 sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
358 if sheet['state'] in ('confirm', 'done'):
359 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
360 elif sheet['total_attendance'] <> 0.00:
361 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
362 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
367 class hr_timesheet_line(osv.osv):
368 _inherit = "hr.analytic.timesheet"
370 def _get_default_date(self, cr, uid, context=None):
373 if 'date' in context:
374 return context['date']
375 return time.strftime('%Y-%m-%d')
377 def _sheet(self, cursor, user, ids, name, args, context=None):
378 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
381 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
382 FROM hr_timesheet_sheet_sheet s \
383 LEFT JOIN (hr_analytic_timesheet l \
384 LEFT JOIN account_analytic_line al \
385 ON (l.line_id = al.id)) \
386 ON (s.date_to >= al.date \
387 AND s.date_from <= al.date \
388 AND s.user_id = al.user_id) \
389 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
390 res = dict(cursor.fetchall())
392 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
394 sheet_names[sheet_id] = name
396 for line_id in {}.fromkeys(ids):
397 sheet_id = res.get(line_id, False)
399 res[line_id] = (sheet_id, sheet_names[sheet_id])
404 def _sheet_search(self, cursor, user, obj, name, args, context=None):
409 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
413 fargs = args[i][0].split('.', 1)
415 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
416 [(fargs[1], args[i][1], args[i][2])], context=context))
419 if isinstance(args[i][2], basestring):
420 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
422 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
427 if (x[2] is False) and (x[1] == '='):
428 qu1.append('(s.id IS NULL)')
429 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
430 qu1.append('(s.id IS NOT NULL)')
432 qu1.append('(s.id %s %s)' % (x[1], '%s'))
436 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
439 qu1.append('(False)')
441 qu1 = ' WHERE ' + ' AND '.join(qu1)
444 cursor.execute('SELECT l.id \
445 FROM hr_timesheet_sheet_sheet s \
446 LEFT JOIN (hr_analytic_timesheet l \
447 LEFT JOIN account_analytic_line al \
448 ON (l.line_id = al.id)) \
449 ON (s.date_to >= al.date \
450 AND s.date_from <= al.date \
451 AND s.user_id = al.user_id)' + \
453 res = cursor.fetchall()
455 return [('id', '=', '0')]
456 return [('id', 'in', [x[0] for x in res])]
459 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
460 type='many2one', relation='hr_timesheet_sheet.sheet',
461 fnct_search=_sheet_search),
464 'date': _get_default_date,
467 def create(self, cr, uid, vals, *args, **kwargs):
468 if vals.get('sheet_id', False):
469 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
470 if not ts.state in ('draft', 'new'):
471 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
472 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
474 def unlink(self, cr, uid, ids, *args, **kwargs):
475 self._check(cr, uid, ids)
476 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
478 def write(self, cr, uid, ids, *args, **kwargs):
479 self._check(cr, uid, ids)
480 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
482 def _check(self, cr, uid, ids):
483 for att in self.browse(cr, uid, ids):
484 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
485 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
490 class hr_attendance(osv.osv):
491 _inherit = "hr.attendance"
493 def _get_default_date(self, cr, uid, context=None):
496 if 'name' in context:
497 return context['name'] + time.strftime(' %H:%M:%S')
498 return time.strftime('%Y-%m-%d %H:%M:%S')
500 def _sheet(self, cursor, user, ids, name, args, context=None):
503 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
504 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
505 FROM hr_timesheet_sheet_sheet s \
506 LEFT JOIN (hr_attendance a \
507 LEFT JOIN hr_employee e \
508 LEFT JOIN resource_resource r \
509 ON (e.resource_id = r.id) \
510 ON (a.employee_id = e.id)) \
511 ON (s.date_to >= date_trunc('day',a.name) \
512 AND s.date_from <= a.name \
513 AND s.user_id = r.user_id) \
514 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
515 res = dict(cursor.fetchall())
517 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
519 sheet_names[sheet_id] = name
520 for line_id in {}.fromkeys(ids):
521 sheet_id = res.get(line_id, False)
523 res[line_id] = (sheet_id, sheet_names[sheet_id])
528 def _sheet_search(self, cursor, user, obj, name, args, context=None):
532 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
537 fargs = args[i][0].split('.', 1)
539 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
540 [(fargs[1], args[i][1], args[i][2])], context=context))
543 if isinstance(args[i][2], basestring):
544 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
546 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
551 if (x[2] is False) and (x[1] == '='):
552 qu1.append('(s.id IS NULL)')
553 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
554 qu1.append('(s.id IS NOT NULL)')
556 qu1.append('(s.id %s %s)' % (x[1], '%s'))
560 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
563 qu1.append('(False)')
565 qu1 = ' WHERE ' + ' AND '.join(qu1)
568 cursor.execute('SELECT a.id\
569 FROM hr_timesheet_sheet_sheet s \
570 LEFT JOIN (hr_attendance a \
571 LEFT JOIN hr_employee e \
572 ON (a.employee_id = e.id)) \
573 LEFT JOIN resource_resource r \
574 ON (e.resource_id = r.id) \
575 ON (s.date_to >= date_trunc(\'day\',a.name) \
576 AND s.date_from <= a.name \
577 AND s.user_id = r.user_id) ' + \
579 res = cursor.fetchall()
581 return [('id', '=', '0')]
582 return [('id', 'in', [x[0] for x in res])]
585 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
586 type='many2one', relation='hr_timesheet_sheet.sheet',
587 fnct_search=_sheet_search),
590 'name': _get_default_date,
593 def create(self, cr, uid, vals, context=None):
596 if 'sheet_id' in context:
597 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
598 if ts.state not in ('draft', 'new'):
599 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
600 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
601 if 'sheet_id' in context:
602 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
603 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
604 'date outside the current timesheet dates!'))
607 def unlink(self, cr, uid, ids, *args, **kwargs):
608 self._check(cr, uid, ids)
609 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
611 def write(self, cr, uid, ids, vals, context=None):
614 self._check(cr, uid, ids)
615 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
616 if 'sheet_id' in context:
617 for attendance in self.browse(cr, uid, ids, context=context):
618 if context['sheet_id'] != attendance.sheet_id.id:
619 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
620 'date outside the current timesheet dates!'))
623 def _check(self, cr, uid, ids):
624 for att in self.browse(cr, uid, ids):
625 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
626 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
631 class hr_timesheet_sheet_sheet_day(osv.osv):
632 _name = "hr_timesheet_sheet.sheet.day"
633 _description = "Timesheets by Period"
637 'name': fields.date('Date', readonly=True),
638 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
639 'total_timesheet': fields.float('Project Timesheet', readonly=True),
640 'total_attendance': fields.float('Attendance', readonly=True),
641 'total_difference': fields.float('Difference', readonly=True),
645 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
652 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
659 SUM(total_timesheet) as total_timesheet,
660 CASE WHEN SUM(total_attendance) < 0
661 THEN (SUM(total_attendance) +
662 CASE WHEN current_date <> name
664 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
667 ELSE SUM(total_attendance)
668 END /60 as total_attendance
673 l.date::date as name,
675 sum(l.unit_amount) as total_timesheet,
676 0.0 as total_attendance
678 hr_analytic_timesheet hrt
679 left join (account_analytic_line l
680 LEFT JOIN hr_timesheet_sheet_sheet s
681 ON (s.date_to >= l.date
682 AND s.date_from <= l.date
683 AND s.user_id = l.user_id))
684 on (l.id = hrt.line_id)
685 group by l.date::date, s.id
689 a.name::date as name,
691 0.0 as total_timesheet,
692 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
695 LEFT JOIN (hr_timesheet_sheet_sheet s
696 LEFT JOIN resource_resource r
697 LEFT JOIN hr_employee e
698 ON (e.resource_id = r.id)
699 ON (s.user_id = r.user_id))
700 ON (a.employee_id = e.id
701 AND s.date_to >= date_trunc('day',a.name)
702 AND s.date_from <= a.name)
703 WHERE action in ('sign_in', 'sign_out')
704 group by a.name::date, s.id
706 GROUP BY name, sheet_id
709 hr_timesheet_sheet_sheet_day()
712 class hr_timesheet_sheet_sheet_account(osv.osv):
713 _name = "hr_timesheet_sheet.sheet.account"
714 _description = "Timesheets by Period"
718 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
719 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
720 'total': fields.float('Total Time', digits=(16,2), readonly=True),
721 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
725 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
728 l.account_id as name,
730 sum(l.unit_amount) as total,
731 l.to_invoice as invoice_rate
733 hr_analytic_timesheet hrt
734 left join (account_analytic_line l
735 LEFT JOIN hr_timesheet_sheet_sheet s
736 ON (s.date_to >= l.date
737 AND s.date_from <= l.date
738 AND s.user_id = l.user_id))
739 on (l.id = hrt.line_id)
740 group by l.account_id, s.id, l.to_invoice
743 hr_timesheet_sheet_sheet_account()
747 class res_company(osv.osv):
748 _inherit = 'res.company'
750 'timesheet_range': fields.selection(
751 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
752 'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
753 help="Allowed difference in hours between the sign in/out and the timesheet " \
754 "computation for one sheet. Set this to 0 if you do not want any control."),
757 'timesheet_range': lambda *args: 'week',
758 'timesheet_max_difference': lambda *args: 0.0
763 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: