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 osv import fields
27 from mx import DateTime
28 from tools.translate import _
30 class one2many_mod2(fields.one2many):
31 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
36 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
39 res6[r['id']] = (r['date_current'], r['user_id'][0])
45 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
46 ('name', '<=', res6[id][0] + ' 23:59:59'),
47 ('employee_id.user_id', '=', res6[id][1])]
48 ids2.extend(obj.pool.get(self._obj).search(cr, user,
49 dom, limit=self._limit))
51 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
52 [self._fields_id], context=context, load='_classic_write'):
53 if r[self._fields_id]:
54 res.setdefault(r[self._fields_id][0], []).append(r['id'])
58 def set(self, cr, obj, id, field, values, user=None, context=None):
61 context = context.copy()
62 context['sheet_id'] = id
63 return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user,
67 class one2many_mod(fields.one2many):
68 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
73 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
76 res6[r['id']] = (r['date_current'], r['user_id'][0])
82 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
83 ids2.extend(obj.pool.get(self._obj).search(cr, user,
84 dom, limit=self._limit))
86 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
87 [self._fields_id], context=context, load='_classic_write'):
88 if r[self._fields_id]:
89 res.setdefault(r[self._fields_id][0], []).append(r['id'])
93 class hr_timesheet_sheet(osv.osv):
94 _name = "hr_timesheet_sheet.sheet"
95 _table = 'hr_timesheet_sheet_sheet'
98 def _total_day(self, cr, uid, ids, name, args, context=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)])
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 copy(self, cr, uid, ids, *args, **argv):
153 raise osv.except_osv(_('Error !'), _('You can not duplicate a timesheet !'))
155 def button_confirm(self, cr, uid, ids, context=None):
158 for sheet in self.browse(cr, uid, ids, context=context):
159 di = sheet.user_id.company_id.timesheet_max_difference
160 if (abs(sheet.total_difference) < di) or not di:
161 wf_service = netsvc.LocalService("workflow")
162 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
164 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
167 def date_today(self, cr, uid, ids, context=None):
170 for sheet in self.browse(cr, uid, ids, context=context):
171 if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
172 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
173 elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
174 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
176 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
179 def date_previous(self, cr, uid, ids, context=None):
182 for sheet in self.browse(cr, uid, ids, context=context):
183 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
184 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
186 self.write(cr, uid, [sheet.id], {
187 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
191 def date_next(self, cr, uid, ids, context=None):
194 for sheet in self.browse(cr, uid, ids, context=context):
195 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
196 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
198 self.write(cr, uid, [sheet.id], {
199 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
203 def button_dummy(self, cr, uid, ids, context=None):
206 for sheet in self.browse(cr, uid, ids, context=context):
207 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
208 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
209 elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
210 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
213 def sign_in(self, cr, uid, ids, context=None):
214 emp_obj = self.pool.get('hr.employee')
217 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
218 raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
219 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
220 context['sheet_id']=ids[0]
221 success = emp_obj.attendance_action_change(cr, uid, emp_id, type='sign_in', context=context,)
224 def sign_out(self, cr, uid, ids, context=None):
225 emp_obj = self.pool.get('hr.employee')
228 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
229 raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
230 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
231 context['sheet_id']=ids[0]
232 success = emp_obj.attendance_action_change(cr, uid, emp_id, type='sign_out', context=context,)
236 'name': fields.char('Description', size=64, select=1,
237 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
238 'user_id': fields.many2one('res.users', 'User', required=True, select=1,
239 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
240 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
241 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
242 'date_current': fields.date('Current date', required=True),
243 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
244 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
245 readonly=True, states={
246 'draft': [('readonly', False)],
247 'new': [('readonly', False)]}
249 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
250 'state' : fields.selection([
253 ('confirm','Confirmed'),
254 ('done','Done')], 'State', select=True, required=True, readonly=True,
255 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
256 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
257 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
258 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
259 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance', multi="_total_day"),
260 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet', multi="_total_day"),
261 'total_difference_day': fields.function(_total_day, method=True, string='Difference', multi="_total_day"),
262 'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total_sheet"),
263 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total_sheet"),
264 'total_difference': fields.function(_total, method=True, string='Difference', multi="_total_sheet"),
265 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
266 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
267 'company_id': fields.many2one('res.company', 'Company'),
268 'department_id':fields.many2one('hr.department','Department'),
271 def _default_date_from(self,cr, uid, context={}):
272 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
273 r = user.company_id and user.company_id.timesheet_range or 'month'
275 return time.strftime('%Y-%m-01')
277 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
279 return time.strftime('%Y-01-01')
280 return time.strftime('%Y-%m-%d')
282 def _default_date_to(self,cr, uid, context={}):
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 (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
288 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
290 return time.strftime('%Y-12-31')
291 return time.strftime('%Y-%m-%d')
294 'user_id': lambda self,cr,uid,c: uid,
295 'date_from' : _default_date_from,
296 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
297 'date_to' : _default_date_to,
299 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
302 def _sheet_date(self, cr, uid, ids):
303 for sheet in self.browse(cr, uid, ids):
304 cr.execute('SELECT id \
305 FROM hr_timesheet_sheet_sheet \
306 WHERE (date_from < %s and %s < date_to) \
308 AND id <> %s', (sheet.date_to, sheet.date_from,
309 sheet.user_id.id, sheet.id))
314 def _date_current_check(self, cr, uid, ids):
315 for sheet in self.browse(cr, uid, ids):
316 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
322 (_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']),
323 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
326 def action_set_to_draft(self, cr, uid, ids, *args):
327 self.write(cr, uid, ids, {'state': 'draft'})
328 wf_service = netsvc.LocalService('workflow')
330 wf_service.trg_create(uid, self._name, id, cr)
333 def name_get(self, cr, uid, ids, context={}):
336 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
337 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
338 context, load='_classic_write')]
340 def unlink(self, cr, uid, ids, context=None):
343 sheets = self.read(cr, uid, ids, ['state','total_attendance'])
345 if sheet['state'] in ('confirm', 'done'):
346 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
347 elif sheet['total_attendance'] <> 0.00:
348 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
349 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
354 class hr_timesheet_line(osv.osv):
355 _inherit = "hr.analytic.timesheet"
357 def _get_default_date(self, cr, uid, context={}):
358 if 'date' in context:
359 return context['date']
360 return time.strftime('%Y-%m-%d')
362 def _sheet(self, cursor, user, ids, name, args, context):
363 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
365 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
366 FROM hr_timesheet_sheet_sheet s \
367 LEFT JOIN (hr_analytic_timesheet l \
368 LEFT JOIN account_analytic_line al \
369 ON (l.line_id = al.id)) \
370 ON (s.date_to >= al.date \
371 AND s.date_from <= al.date \
372 AND s.user_id = al.user_id) \
373 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
374 res = dict(cursor.fetchall())
376 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
378 sheet_names[sheet_id] = name
380 for line_id in {}.fromkeys(ids):
381 sheet_id = res.get(line_id, False)
383 res[line_id] = (sheet_id, sheet_names[sheet_id])
388 def _sheet_search(self, cursor, user, obj, name, args, context=None):
391 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
395 fargs = args[i][0].split('.', 1)
397 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
398 [(fargs[1], args[i][1], args[i][2])]))
401 if isinstance(args[i][2], basestring):
402 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
404 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
409 if (x[2] is False) and (x[1] == '='):
410 qu1.append('(s.id IS NULL)')
411 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
412 qu1.append('(s.id IS NOT NULL)')
414 qu1.append('(s.id %s %s)' % (x[1], '%s'))
418 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
421 qu1.append('(False)')
423 qu1 = ' WHERE ' + ' AND '.join(qu1)
426 cursor.execute('SELECT l.id \
427 FROM hr_timesheet_sheet_sheet s \
428 LEFT JOIN (hr_analytic_timesheet l \
429 LEFT JOIN account_analytic_line al \
430 ON (l.line_id = al.id)) \
431 ON (s.date_to >= al.date \
432 AND s.date_from <= al.date \
433 AND s.user_id = al.user_id)' + \
435 res = cursor.fetchall()
437 return [('id', '=', '0')]
438 return [('id', 'in', [x[0] for x in res])]
441 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
442 type='many2one', relation='hr_timesheet_sheet.sheet',
443 fnct_search=_sheet_search),
446 'date': _get_default_date,
449 def create(self, cr, uid, vals, *args, **kwargs):
450 if vals.get('sheet_id', False):
451 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
452 if not ts.state in ('draft', 'new'):
453 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
454 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
456 def unlink(self, cr, uid, ids, *args, **kwargs):
457 self._check(cr, uid, ids)
458 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
460 def write(self, cr, uid, ids, *args, **kwargs):
461 self._check(cr, uid, ids)
462 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
464 def _check(self, cr, uid, ids):
465 for att in self.browse(cr, uid, ids):
466 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
467 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
472 class hr_attendance(osv.osv):
473 _inherit = "hr.attendance"
475 def _get_default_date(self, cr, uid, context={}):
476 if 'name' in context:
477 return context['name'] + time.strftime(' %H:%M:%S')
478 return time.strftime('%Y-%m-%d %H:%M:%S')
480 def _sheet(self, cursor, user, ids, name, args, context):
481 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
482 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
483 FROM hr_timesheet_sheet_sheet s \
484 LEFT JOIN (hr_attendance a \
485 LEFT JOIN hr_employee e \
486 LEFT JOIN resource_resource r \
487 ON (e.resource_id = r.id) \
488 ON (a.employee_id = e.id)) \
489 ON (s.date_to >= date_trunc('day',a.name) \
490 AND s.date_from <= a.name \
491 AND s.user_id = r.user_id) \
492 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
493 res = dict(cursor.fetchall())
495 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
497 sheet_names[sheet_id] = name
498 for line_id in {}.fromkeys(ids):
499 sheet_id = res.get(line_id, False)
501 res[line_id] = (sheet_id, sheet_names[sheet_id])
506 def _sheet_search(self, cursor, user, obj, name, args, context=None):
509 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
513 fargs = args[i][0].split('.', 1)
515 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
516 [(fargs[1], args[i][1], args[i][2])]))
519 if isinstance(args[i][2], basestring):
520 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
522 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
527 if (x[2] is False) and (x[1] == '='):
528 qu1.append('(s.id IS NULL)')
529 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
530 qu1.append('(s.id IS NOT NULL)')
532 qu1.append('(s.id %s %s)' % (x[1], '%s'))
536 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
539 qu1.append('(False)')
541 qu1 = ' WHERE ' + ' AND '.join(qu1)
544 cursor.execute('SELECT a.id\
545 FROM hr_timesheet_sheet_sheet s \
546 LEFT JOIN (hr_attendance a \
547 LEFT JOIN hr_employee e \
548 ON (a.employee_id = e.id)) \
549 LEFT JOIN resource_resource r \
550 ON (e.resource_id = r.id) \
551 ON (s.date_to >= date_trunc(\'day\',a.name) \
552 AND s.date_from <= a.name \
553 AND s.user_id = r.user_id) ' + \
555 res = cursor.fetchall()
557 return [('id', '=', '0')]
558 return [('id', 'in', [x[0] for x in res])]
561 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
562 type='many2one', relation='hr_timesheet_sheet.sheet',
563 fnct_search=_sheet_search),
566 'name': _get_default_date,
569 def create(self, cr, uid, vals, context=None):
572 if 'sheet_id' in context:
573 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'])
574 if ts.state not in ('draft', 'new'):
575 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
576 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
577 if 'sheet_id' in context:
578 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
579 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
580 'date outside the current timesheet dates!'))
583 def unlink(self, cr, uid, ids, *args, **kwargs):
584 self._check(cr, uid, ids)
585 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
587 def write(self, cr, uid, ids, vals, context={}):
590 self._check(cr, uid, ids)
591 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
592 if 'sheet_id' in context:
593 for attendance in self.browse(cr, uid, ids, context=context):
594 if context['sheet_id'] != attendance.sheet_id.id:
595 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
596 'date outside the current timesheet dates!'))
599 def _check(self, cr, uid, ids):
600 for att in self.browse(cr, uid, ids):
601 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
602 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
607 class hr_timesheet_sheet_sheet_day(osv.osv):
608 _name = "hr_timesheet_sheet.sheet.day"
609 _description = "Timesheets by Period"
613 'name': fields.date('Date', readonly=True),
614 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
615 'total_timesheet': fields.float('Project Timesheet', readonly=True),
616 'total_attendance': fields.float('Attendance', readonly=True),
617 'total_difference': fields.float('Difference', readonly=True),
621 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
628 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
635 SUM(total_timesheet) as total_timesheet,
636 CASE WHEN SUM(total_attendance) < 0
637 THEN (SUM(total_attendance) +
638 CASE WHEN current_date <> name
640 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
643 ELSE SUM(total_attendance)
644 END /60 as total_attendance
649 l.date::date as name,
651 sum(l.unit_amount) as total_timesheet,
652 0.0 as total_attendance
654 hr_analytic_timesheet hrt
655 left join (account_analytic_line l
656 LEFT JOIN hr_timesheet_sheet_sheet s
657 ON (s.date_to >= l.date
658 AND s.date_from <= l.date
659 AND s.user_id = l.user_id))
660 on (l.id = hrt.line_id)
661 group by l.date::date, s.id
665 a.name::date as name,
667 0.0 as total_timesheet,
668 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
671 LEFT JOIN (hr_timesheet_sheet_sheet s
672 LEFT JOIN resource_resource r
673 LEFT JOIN hr_employee e
674 ON (e.resource_id = r.id)
675 ON (s.user_id = r.user_id))
676 ON (a.employee_id = e.id
677 AND s.date_to >= date_trunc('day',a.name)
678 AND s.date_from <= a.name)
679 WHERE action in ('sign_in', 'sign_out')
680 group by a.name::date, s.id
682 GROUP BY name, sheet_id
685 hr_timesheet_sheet_sheet_day()
688 class hr_timesheet_sheet_sheet_account(osv.osv):
689 _name = "hr_timesheet_sheet.sheet.account"
690 _description = "Timesheets by Period"
694 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
695 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
696 'total': fields.float('Total Time', digits=(16,2), readonly=True),
697 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
701 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
704 l.account_id as name,
706 sum(l.unit_amount) as total,
707 l.to_invoice as invoice_rate
709 hr_analytic_timesheet hrt
710 left join (account_analytic_line l
711 LEFT JOIN hr_timesheet_sheet_sheet s
712 ON (s.date_to >= l.date
713 AND s.date_from <= l.date
714 AND s.user_id = l.user_id))
715 on (l.id = hrt.line_id)
716 group by l.account_id, s.id, l.to_invoice
719 hr_timesheet_sheet_sheet_account()
723 class res_company(osv.osv):
724 _inherit = 'res.company'
726 'timesheet_range': fields.selection(
727 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
728 'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
729 help="Allowed difference in hours between the sign in/out and the timesheet " \
730 "computation for one sheet. Set this to 0 if you do not want any control."),
733 'timesheet_range': lambda *args: 'month',
734 'timesheet_max_difference': lambda *args: 0.0
739 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: