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'
97 def _total_day(self, cr, uid, ids, name, args, context=None):
101 cr.execute('SELECT sheet.id, day.total_attendance, day.total_timesheet, day.total_difference\
102 FROM hr_timesheet_sheet_sheet AS sheet \
103 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
104 ON (sheet.id = day.sheet_id \
105 AND day.name = sheet.date_current) \
106 WHERE sheet.id IN %s',(tuple(ids),))
107 for record in cr.fetchall():
109 res[record[0]]['total_attendance_day'] = record[1]
110 res[record[0]]['total_timesheet_day'] = record[2]
111 res[record[0]]['total_difference_day'] = record[3]
114 def _total(self, cr, uid, ids, name, args, context=None):
118 cr.execute('SELECT s.id, COALESCE(SUM(d.total_attendance),0), COALESCE(SUM(d.total_timesheet),0), COALESCE(SUM(d.total_difference),0) \
119 FROM hr_timesheet_sheet_sheet s \
120 LEFT JOIN hr_timesheet_sheet_sheet_day d \
121 ON (s.id = d.sheet_id) \
122 WHERE s.id IN %s GROUP BY s.id',(tuple(ids),))
123 for record in cr.fetchall():
125 res[record[0]]['total_attendance'] = record[1]
126 res[record[0]]['total_timesheet'] = record[2]
127 res[record[0]]['total_difference'] = record[3]
130 def _state_attendance(self, cr, uid, ids, name, args, context=None):
131 emp_obj = self.pool.get('hr.employee')
138 for sheet in self.browse(cr, uid, ids, context=context):
139 result[sheet.id] = 'none'
140 emp_ids2 = emp_obj.search(cr, uid,
141 [('user_id', '=', sheet.user_id.id)], context=context)
143 link_emp[emp_ids2[0]] = sheet.id
144 emp_ids.append(emp_ids2[0])
145 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
146 if emp.id in link_emp:
147 sheet_id = link_emp[emp.id]
148 result[sheet_id] = emp.state
151 def check_employee_attendance_state(self, cr, uid, sheet_id, context=None):
152 ids_signin = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_in')])
153 ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')])
155 if len(ids_signin) != len(ids_signout):
156 raise osv.except_osv(('Warning !'),_('The timesheet cannot be validated as it does not contain equal no. of sign ins and sign outs!'))
159 def copy(self, cr, uid, ids, *args, **argv):
160 raise osv.except_osv(_('Error !'), _('You cannot duplicate a timesheet !'))
162 def button_confirm(self, cr, uid, ids, context=None):
165 for sheet in self.browse(cr, uid, ids, context=context):
166 self.check_employee_attendance_state(cr, uid, sheet.id, context)
167 di = sheet.user_id.company_id.timesheet_max_difference
168 if (abs(sheet.total_difference) < di) or not di:
169 wf_service = netsvc.LocalService("workflow")
170 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
172 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
175 def date_today(self, cr, uid, ids, context=None):
178 for sheet in self.browse(cr, uid, ids, context=context):
179 if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
180 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
181 elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
182 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
184 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')}, context=context)
187 def date_previous(self, cr, uid, ids, context=None):
190 for sheet in self.browse(cr, uid, ids, context=context):
191 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
192 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
194 self.write(cr, uid, [sheet.id], {
195 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
199 def date_next(self, cr, uid, ids, context=None):
202 for sheet in self.browse(cr, uid, ids, context=context):
203 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
204 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
206 self.write(cr, uid, [sheet.id], {
207 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
211 def button_dummy(self, cr, uid, ids, context=None):
214 for sheet in self.browse(cr, uid, ids, context=context):
215 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
216 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
217 elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
218 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
221 def sign_in(self, cr, uid, ids, context=None):
222 emp_obj = self.pool.get('hr.employee')
225 if not self.browse(cr, uid, ids, context=context)[0].date_current == time.strftime('%Y-%m-%d'):
226 raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
227 emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
228 context['sheet_id']=ids[0]
229 success = emp_obj.attendance_action_change(cr, uid, emp_ids, type='sign_in', context=context,)
232 def sign_out(self, cr, uid, ids, context=None):
233 emp_obj = self.pool.get('hr.employee')
236 if not self.browse(cr, uid, ids, context=context)[0].date_current == time.strftime('%Y-%m-%d'):
237 raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
238 emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)])
239 context['sheet_id']=ids[0]
240 success = emp_obj.attendance_action_change(cr, uid, emp_ids, type='sign_out', context=context,)
244 'name': fields.char('Description', size=64, select=1,
245 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
246 'user_id': fields.many2one('res.users', 'User', required=True, select=1,
247 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
248 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
249 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
250 'date_current': fields.date('Current date', required=True),
251 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
252 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
253 readonly=True, states={
254 'draft': [('readonly', False)],
255 'new': [('readonly', False)]}
257 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
258 'state' : fields.selection([
261 ('confirm','Confirmed'),
262 ('done','Done')], 'State', select=True, required=True, readonly=True,
263 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
264 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
265 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
266 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
267 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance', multi="_total_day"),
268 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet', multi="_total_day"),
269 'total_difference_day': fields.function(_total_day, method=True, string='Difference', multi="_total_day"),
270 'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total_sheet"),
271 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total_sheet"),
272 'total_difference': fields.function(_total, method=True, string='Difference', multi="_total_sheet"),
273 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
274 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
275 'company_id': fields.many2one('res.company', 'Company'),
276 'department_id':fields.many2one('hr.department','Department'),
279 def _default_date_from(self,cr, uid, context=None):
282 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
283 r = user.company_id and user.company_id.timesheet_range or 'month'
285 return time.strftime('%Y-%m-01')
287 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
289 return time.strftime('%Y-01-01')
290 return time.strftime('%Y-%m-%d')
292 def _default_date_to(self,cr, uid, context=None):
293 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
294 r = user.company_id and user.company_id.timesheet_range or 'month'
296 return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
298 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
300 return time.strftime('%Y-12-31')
301 return time.strftime('%Y-%m-%d')
304 'user_id': lambda self,cr,uid,c: uid,
305 'date_from' : _default_date_from,
306 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
307 'date_to' : _default_date_to,
309 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
312 def _sheet_date(self, cr, uid, ids):
313 for sheet in self.browse(cr, uid, ids):
314 cr.execute('SELECT id \
315 FROM hr_timesheet_sheet_sheet \
316 WHERE (date_from < %s and %s < date_to) \
318 AND id <> %s', (sheet.date_to, sheet.date_from,
319 sheet.user_id.id, sheet.id))
324 def _date_current_check(self, cr, uid, ids):
325 for sheet in self.browse(cr, uid, ids):
326 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
332 (_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']),
333 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
336 def action_set_to_draft(self, cr, uid, ids, *args):
337 self.write(cr, uid, ids, {'state': 'draft'})
338 wf_service = netsvc.LocalService('workflow')
340 wf_service.trg_create(uid, self._name, id, cr)
343 def name_get(self, cr, uid, ids, context=None):
348 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
349 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
350 context=context, load='_classic_write')]
352 def unlink(self, cr, uid, ids, context=None):
355 sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
357 if sheet['state'] in ('confirm', 'done'):
358 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
359 elif sheet['total_attendance'] <> 0.00:
360 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
361 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
366 class hr_timesheet_line(osv.osv):
367 _inherit = "hr.analytic.timesheet"
369 def _get_default_date(self, cr, uid, context=None):
372 if 'date' in context:
373 return context['date']
374 return time.strftime('%Y-%m-%d')
376 def _sheet(self, cursor, user, ids, name, args, context=None):
377 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
380 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
381 FROM hr_timesheet_sheet_sheet s \
382 LEFT JOIN (hr_analytic_timesheet l \
383 LEFT JOIN account_analytic_line al \
384 ON (l.line_id = al.id)) \
385 ON (s.date_to >= al.date \
386 AND s.date_from <= al.date \
387 AND s.user_id = al.user_id) \
388 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
389 res = dict(cursor.fetchall())
391 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
393 sheet_names[sheet_id] = name
395 for line_id in {}.fromkeys(ids):
396 sheet_id = res.get(line_id, False)
398 res[line_id] = (sheet_id, sheet_names[sheet_id])
403 def _sheet_search(self, cursor, user, obj, name, args, context=None):
408 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
412 fargs = args[i][0].split('.', 1)
414 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
415 [(fargs[1], args[i][1], args[i][2])], context=context))
418 if isinstance(args[i][2], basestring):
419 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
421 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
426 if (x[2] is False) and (x[1] == '='):
427 qu1.append('(s.id IS NULL)')
428 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
429 qu1.append('(s.id IS NOT NULL)')
431 qu1.append('(s.id %s %s)' % (x[1], '%s'))
435 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
438 qu1.append('(False)')
440 qu1 = ' WHERE ' + ' AND '.join(qu1)
443 cursor.execute('SELECT l.id \
444 FROM hr_timesheet_sheet_sheet s \
445 LEFT JOIN (hr_analytic_timesheet l \
446 LEFT JOIN account_analytic_line al \
447 ON (l.line_id = al.id)) \
448 ON (s.date_to >= al.date \
449 AND s.date_from <= al.date \
450 AND s.user_id = al.user_id)' + \
452 res = cursor.fetchall()
454 return [('id', '=', '0')]
455 return [('id', 'in', [x[0] for x in res])]
458 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
459 type='many2one', relation='hr_timesheet_sheet.sheet',
460 fnct_search=_sheet_search),
463 'date': _get_default_date,
466 def create(self, cr, uid, vals, *args, **kwargs):
467 if vals.get('sheet_id', False):
468 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
469 if not ts.state in ('draft', 'new'):
470 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
471 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
473 def unlink(self, cr, uid, ids, *args, **kwargs):
474 self._check(cr, uid, ids)
475 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
477 def write(self, cr, uid, ids, *args, **kwargs):
478 self._check(cr, uid, ids)
479 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
481 def _check(self, cr, uid, ids):
482 for att in self.browse(cr, uid, ids):
483 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
484 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
489 class hr_attendance(osv.osv):
490 _inherit = "hr.attendance"
492 def _get_default_date(self, cr, uid, context=None):
495 if 'name' in context:
496 return context['name'] + time.strftime(' %H:%M:%S')
497 return time.strftime('%Y-%m-%d %H:%M:%S')
499 def _sheet(self, cursor, user, ids, name, args, context=None):
502 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
503 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
504 FROM hr_timesheet_sheet_sheet s \
505 LEFT JOIN (hr_attendance a \
506 LEFT JOIN hr_employee e \
507 LEFT JOIN resource_resource r \
508 ON (e.resource_id = r.id) \
509 ON (a.employee_id = e.id)) \
510 ON (s.date_to >= date_trunc('day',a.name) \
511 AND s.date_from <= a.name \
512 AND s.user_id = r.user_id) \
513 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
514 res = dict(cursor.fetchall())
516 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
518 sheet_names[sheet_id] = name
519 for line_id in {}.fromkeys(ids):
520 sheet_id = res.get(line_id, False)
522 res[line_id] = (sheet_id, sheet_names[sheet_id])
527 def _sheet_search(self, cursor, user, obj, name, args, context=None):
531 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
536 fargs = args[i][0].split('.', 1)
538 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
539 [(fargs[1], args[i][1], args[i][2])], context=context))
542 if isinstance(args[i][2], basestring):
543 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
545 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
550 if (x[2] is False) and (x[1] == '='):
551 qu1.append('(s.id IS NULL)')
552 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
553 qu1.append('(s.id IS NOT NULL)')
555 qu1.append('(s.id %s %s)' % (x[1], '%s'))
559 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
562 qu1.append('(False)')
564 qu1 = ' WHERE ' + ' AND '.join(qu1)
567 cursor.execute('SELECT a.id\
568 FROM hr_timesheet_sheet_sheet s \
569 LEFT JOIN (hr_attendance a \
570 LEFT JOIN hr_employee e \
571 ON (a.employee_id = e.id)) \
572 LEFT JOIN resource_resource r \
573 ON (e.resource_id = r.id) \
574 ON (s.date_to >= date_trunc(\'day\',a.name) \
575 AND s.date_from <= a.name \
576 AND s.user_id = r.user_id) ' + \
578 res = cursor.fetchall()
580 return [('id', '=', '0')]
581 return [('id', 'in', [x[0] for x in res])]
584 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
585 type='many2one', relation='hr_timesheet_sheet.sheet',
586 fnct_search=_sheet_search),
589 'name': _get_default_date,
592 def create(self, cr, uid, vals, context=None):
595 if 'sheet_id' in context:
596 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
597 if ts.state not in ('draft', 'new'):
598 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
599 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
600 if 'sheet_id' in context:
601 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
602 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
603 'date outside the current timesheet dates!'))
606 def unlink(self, cr, uid, ids, *args, **kwargs):
607 self._check(cr, uid, ids)
608 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
610 def write(self, cr, uid, ids, vals, context=None):
613 self._check(cr, uid, ids)
614 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
615 if 'sheet_id' in context:
616 for attendance in self.browse(cr, uid, ids, context=context):
617 if context['sheet_id'] != attendance.sheet_id.id:
618 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
619 'date outside the current timesheet dates!'))
622 def _check(self, cr, uid, ids):
623 for att in self.browse(cr, uid, ids):
624 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
625 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
630 class hr_timesheet_sheet_sheet_day(osv.osv):
631 _name = "hr_timesheet_sheet.sheet.day"
632 _description = "Timesheets by Period"
636 'name': fields.date('Date', readonly=True),
637 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
638 'total_timesheet': fields.float('Project Timesheet', readonly=True),
639 'total_attendance': fields.float('Attendance', readonly=True),
640 'total_difference': fields.float('Difference', readonly=True),
644 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
651 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
658 SUM(total_timesheet) as total_timesheet,
659 CASE WHEN SUM(total_attendance) < 0
660 THEN (SUM(total_attendance) +
661 CASE WHEN current_date <> name
663 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
666 ELSE SUM(total_attendance)
667 END /60 as total_attendance
672 l.date::date as name,
674 sum(l.unit_amount) as total_timesheet,
675 0.0 as total_attendance
677 hr_analytic_timesheet hrt
678 left join (account_analytic_line l
679 LEFT JOIN hr_timesheet_sheet_sheet s
680 ON (s.date_to >= l.date
681 AND s.date_from <= l.date
682 AND s.user_id = l.user_id))
683 on (l.id = hrt.line_id)
684 group by l.date::date, s.id
688 a.name::date as name,
690 0.0 as total_timesheet,
691 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
694 LEFT JOIN (hr_timesheet_sheet_sheet s
695 LEFT JOIN resource_resource r
696 LEFT JOIN hr_employee e
697 ON (e.resource_id = r.id)
698 ON (s.user_id = r.user_id))
699 ON (a.employee_id = e.id
700 AND s.date_to >= date_trunc('day',a.name)
701 AND s.date_from <= a.name)
702 WHERE action in ('sign_in', 'sign_out')
703 group by a.name::date, s.id
705 GROUP BY name, sheet_id
708 hr_timesheet_sheet_sheet_day()
711 class hr_timesheet_sheet_sheet_account(osv.osv):
712 _name = "hr_timesheet_sheet.sheet.account"
713 _description = "Timesheets by Period"
717 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
718 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
719 'total': fields.float('Total Time', digits=(16,2), readonly=True),
720 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
724 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
727 l.account_id as name,
729 sum(l.unit_amount) as total,
730 l.to_invoice as invoice_rate
732 hr_analytic_timesheet hrt
733 left join (account_analytic_line l
734 LEFT JOIN hr_timesheet_sheet_sheet s
735 ON (s.date_to >= l.date
736 AND s.date_from <= l.date
737 AND s.user_id = l.user_id))
738 on (l.id = hrt.line_id)
739 group by l.account_id, s.id, l.to_invoice
742 hr_timesheet_sheet_sheet_account()
746 class res_company(osv.osv):
747 _inherit = 'res.company'
749 'timesheet_range': fields.selection(
750 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
751 'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
752 help="Allowed difference in hours between the sign in/out and the timesheet " \
753 "computation for one sheet. Set this to 0 if you do not want any control."),
756 'timesheet_range': lambda *args: 'week',
757 'timesheet_max_difference': lambda *args: 0.0
762 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: