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 _
31 class one2many_mod2(fields.one2many):
32 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
37 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
40 res6[r['id']] = (r['date_current'], r['user_id'][0])
46 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
47 ('name', '<=', res6[id][0] + ' 23:59:59'),
48 ('employee_id.user_id', '=', res6[id][1])]
49 ids2.extend(obj.pool.get(self._obj).search(cr, user,
50 dom, limit=self._limit))
52 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
53 [self._fields_id], context=context, load='_classic_write'):
54 if r[self._fields_id]:
55 res.setdefault(r[self._fields_id][0], []).append(r['id'])
59 def set(self, cr, obj, id, field, values, user=None, context=None):
62 context = context.copy()
63 context['sheet_id'] = id
64 return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user,
68 class one2many_mod(fields.one2many):
69 def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
74 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
77 res6[r['id']] = (r['date_current'], r['user_id'][0])
83 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
84 ids2.extend(obj.pool.get(self._obj).search(cr, user,
85 dom, limit=self._limit))
87 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
88 [self._fields_id], context=context, load='_classic_write'):
89 if r[self._fields_id]:
90 res.setdefault(r[self._fields_id][0], []).append(r['id'])
94 class hr_timesheet_sheet(osv.osv):
95 _name = "hr_timesheet_sheet.sheet"
96 _table = 'hr_timesheet_sheet_sheet'
99 def _total_day(self, cr, uid, ids, name, args, context):
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 =ANY(%s)',(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):
116 cr.execute('SELECT s.id, COALESCE(SUM(d.total_attendance),0), COALESCE(SUM(d.total_timesheet),0), COALESCE(SUM(d.total_difference),0) \
117 FROM hr_timesheet_sheet_sheet s \
118 LEFT JOIN hr_timesheet_sheet_sheet_day d \
119 ON (s.id = d.sheet_id) \
120 WHERE s.id =ANY(%s) GROUP BY s.id',(ids,))
121 for record in cr.fetchall():
123 res[record[0]]['total_attendance'] = record[1]
124 res[record[0]]['total_timesheet'] = record[2]
125 res[record[0]]['total_difference'] = record[3]
128 def _state_attendance(self, cr, uid, ids, name, args, context):
132 emp_obj = self.pool.get('hr.employee')
134 for sheet in self.browse(cr, uid, ids, context):
135 result[sheet.id] = 'none'
136 emp_ids2 = emp_obj.search(cr, uid,
137 [('user_id', '=', sheet.user_id.id)])
139 link_emp[emp_ids2[0]] = sheet.id
140 emp_ids.append(emp_ids2[0])
141 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
142 if emp.id in link_emp:
143 sheet_id = link_emp[emp.id]
144 result[sheet_id] = emp.state
147 def copy(self, cr, uid, ids, *args, **argv):
148 raise osv.except_osv(_('Error !'), _('You can not duplicate a timesheet !'))
150 def button_confirm(self, cr, uid, ids, context):
151 for sheet in self.browse(cr, uid, ids, context):
152 di = sheet.user_id.company_id.timesheet_max_difference
153 if (abs(sheet.total_difference) < di) or not di:
154 wf_service = netsvc.LocalService("workflow")
155 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
157 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
160 def date_today(self, cr, uid, ids, context):
161 for sheet in self.browse(cr, uid, ids, context):
162 if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
163 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
164 elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
165 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
167 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
170 def date_previous(self, cr, uid, ids, context):
171 for sheet in self.browse(cr, uid, ids, context):
172 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
173 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
175 self.write(cr, uid, [sheet.id], {
176 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
180 def date_next(self, cr, uid, ids, context):
181 for sheet in self.browse(cr, uid, ids, context):
182 if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
183 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
185 self.write(cr, uid, [sheet.id], {
186 'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
190 def button_dummy(self, cr, uid, ids, context):
191 for sheet in self.browse(cr, uid, ids, 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,})
194 elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
195 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
198 def sign_in(self, cr, uid, ids, context):
199 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
200 raise osv.except_osv(_('Error !'), _('You can not sign in from an other date than today'))
201 emp_obj = self.pool.get('hr.employee')
202 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
203 context['sheet_id']=ids[0]
204 success = emp_obj.attendance_action_change(cr, uid, emp_id, type='sign_in', context=context,)
207 def sign_out(self, cr, uid, ids, context):
208 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
209 raise osv.except_osv(_('Error !'), _('You can not sign out from an other date than today'))
210 emp_obj = self.pool.get('hr.employee')
211 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
212 context['sheet_id']=ids[0]
213 success = emp_obj.attendance_action_change(cr, uid, emp_id, type='sign_out', context=context,)
217 'name': fields.char('Description', size=64, select=1,
218 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
219 'user_id': fields.many2one('res.users', 'User', required=True, select=1,
220 states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
221 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
222 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
223 'date_current': fields.date('Current date', required=True),
224 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
225 'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
226 readonly=True, states={
227 'draft': [('readonly', False)],
228 'new': [('readonly', False)]}
230 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
231 'state' : fields.selection([
234 ('confirm','Confirmed'),
235 ('done','Done')], 'State', select=True, required=True, readonly=True,
236 help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
237 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
238 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
239 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
240 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance', multi="_total_day"),
241 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet', multi="_total_day"),
242 'total_difference_day': fields.function(_total_day, method=True, string='Difference', multi="_total_day"),
243 'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total_sheet"),
244 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total_sheet"),
245 'total_difference': fields.function(_total, method=True, string='Difference', multi="_total_sheet"),
246 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
247 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
248 'company_id': fields.many2one('res.company', 'Company'),
249 'department_id':fields.many2one('hr.department','Department'),
252 def _default_date_from(self,cr, uid, context={}):
253 user = self.pool.get('res.users').browse(cr, uid, uid, context)
254 r = user.company_id and user.company_id.timesheet_range or 'month'
256 return time.strftime('%Y-%m-01')
258 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
260 return time.strftime('%Y-01-01')
261 return time.strftime('%Y-%m-%d')
263 def _default_date_to(self,cr, uid, context={}):
264 user = self.pool.get('res.users').browse(cr, uid, uid, context)
265 r = user.company_id and user.company_id.timesheet_range or 'month'
267 return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
269 return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
271 return time.strftime('%Y-12-31')
272 return time.strftime('%Y-%m-%d')
275 'user_id': lambda self,cr,uid,c: uid,
276 'date_from' : _default_date_from,
277 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
278 'date_to' : _default_date_to,
279 'state': lambda *a: 'new',
280 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
283 def _sheet_date(self, cr, uid, ids):
284 for sheet in self.browse(cr, uid, ids):
285 cr.execute('SELECT id \
286 FROM hr_timesheet_sheet_sheet \
287 WHERE (date_from < %s and %s < date_to) \
289 AND id <> %s', (sheet.date_to, sheet.date_from,
290 sheet.user_id.id, sheet.id))
295 def _date_current_check(self, cr, uid, ids):
296 for sheet in self.browse(cr, uid, ids):
297 if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
303 (_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']),
304 (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
307 def action_set_to_draft(self, cr, uid, ids, *args):
308 self.write(cr, uid, ids, {'state': 'draft'})
309 wf_service = netsvc.LocalService('workflow')
311 wf_service.trg_create(uid, self._name, id, cr)
314 def name_get(self, cr, uid, ids, context={}):
317 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
318 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
319 context, load='_classic_write')]
321 def unlink(self, cr, uid, ids, context=None):
322 sheets = self.read(cr, uid, ids, ['state','total_attendance'])
324 if sheet['state'] in ('confirm', 'done'):
325 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
326 elif sheet['total_attendance'] <> 0.00:
327 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
328 return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
333 class hr_timesheet_line(osv.osv):
334 _inherit = "hr.analytic.timesheet"
336 def _get_default_date(self, cr, uid, context={}):
337 if 'date' in context:
338 return context['date']
339 return time.strftime('%Y-%m-%d')
341 def _sheet(self, cursor, user, ids, name, args, context):
342 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
344 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
345 FROM hr_timesheet_sheet_sheet s \
346 LEFT JOIN (hr_analytic_timesheet l \
347 LEFT JOIN account_analytic_line al \
348 ON (l.line_id = al.id)) \
349 ON (s.date_to >= al.date \
350 AND s.date_from <= al.date \
351 AND s.user_id = al.user_id) \
352 WHERE l.id =ANY(%s) GROUP BY l.id',(ids,))
353 res = dict(cursor.fetchall())
355 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
357 sheet_names[sheet_id] = name
359 for line_id in {}.fromkeys(ids):
360 sheet_id = res.get(line_id, False)
362 res[line_id] = (sheet_id, sheet_names[sheet_id])
367 def _sheet_search(self, cursor, user, obj, name, args, context=None):
370 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
374 fargs = args[i][0].split('.', 1)
376 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
377 [(fargs[1], args[i][1], args[i][2])]))
380 if isinstance(args[i][2], basestring):
381 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
383 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
388 if (x[2] is False) and (x[1] == '='):
389 qu1.append('(s.id IS NULL)')
390 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
391 qu1.append('(s.id IS NOT NULL)')
393 qu1.append('(s.id %s %s)' % (x[1], '%s'))
397 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
400 qu1.append('(False)')
402 qu1 = ' WHERE ' + ' AND '.join(qu1)
405 cursor.execute('SELECT l.id \
406 FROM hr_timesheet_sheet_sheet s \
407 LEFT JOIN (hr_analytic_timesheet l \
408 LEFT JOIN account_analytic_line al \
409 ON (l.line_id = al.id)) \
410 ON (s.date_to >= al.date \
411 AND s.date_from <= al.date \
412 AND s.user_id = al.user_id)' + \
414 res = cursor.fetchall()
416 return [('id', '=', '0')]
417 return [('id', 'in', [x[0] for x in res])]
420 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
421 type='many2one', relation='hr_timesheet_sheet.sheet',
422 fnct_search=_sheet_search),
425 'date': _get_default_date,
428 def create(self, cr, uid, vals, *args, **kwargs):
429 if vals.get('sheet_id', False):
430 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
431 if not ts.state in ('draft', 'new'):
432 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
433 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
435 def unlink(self, cr, uid, ids, *args, **kwargs):
436 self._check(cr, uid, ids)
437 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
439 def write(self, cr, uid, ids, *args, **kwargs):
440 self._check(cr, uid, ids)
441 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
443 def _check(self, cr, uid, ids):
444 for att in self.browse(cr, uid, ids):
445 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
446 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
451 class hr_attendance(osv.osv):
452 _inherit = "hr.attendance"
454 def _get_default_date(self, cr, uid, context={}):
455 if 'name' in context:
456 return context['name'] + time.strftime(' %H:%M:%S')
457 return time.strftime('%Y-%m-%d %H:%M:%S')
459 def _sheet(self, cursor, user, ids, name, args, context):
460 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
461 cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
462 FROM hr_timesheet_sheet_sheet s \
463 LEFT JOIN (hr_attendance a \
464 LEFT JOIN hr_employee e \
465 LEFT JOIN resource_resource r \
466 ON (e.resource_id = r.id) \
467 ON (a.employee_id = e.id)) \
468 ON (s.date_to >= date_trunc('day',a.name) \
469 AND s.date_from <= a.name \
470 AND s.user_id = r.user_id) \
471 WHERE a.id =ANY(%s) GROUP BY a.id",(ids,))
472 res = dict(cursor.fetchall())
474 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
476 sheet_names[sheet_id] = name
477 for line_id in {}.fromkeys(ids):
478 sheet_id = res.get(line_id, False)
480 res[line_id] = (sheet_id, sheet_names[sheet_id])
485 def _sheet_search(self, cursor, user, obj, name, args, context=None):
488 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
492 fargs = args[i][0].split('.', 1)
494 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
495 [(fargs[1], args[i][1], args[i][2])]))
498 if isinstance(args[i][2], basestring):
499 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
501 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
506 if (x[2] is False) and (x[1] == '='):
507 qu1.append('(s.id IS NULL)')
508 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
509 qu1.append('(s.id IS NOT NULL)')
511 qu1.append('(s.id %s %s)' % (x[1], '%s'))
515 qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
518 qu1.append('(False)')
520 qu1 = ' WHERE ' + ' AND '.join(qu1)
523 cursor.execute('SELECT a.id\
524 FROM hr_timesheet_sheet_sheet s \
525 LEFT JOIN (hr_attendance a \
526 LEFT JOIN hr_employee e \
527 ON (a.employee_id = e.id)) \
528 LEFT JOIN resource_resource r \
529 ON (e.resource_id = r.id) \
530 ON (s.date_to >= date_trunc(\'day\',a.name) \
531 AND s.date_from <= a.name \
532 AND s.user_id = r.user_id) ' + \
534 res = cursor.fetchall()
536 return [('id', '=', '0')]
537 return [('id', 'in', [x[0] for x in res])]
540 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
541 type='many2one', relation='hr_timesheet_sheet.sheet',
542 fnct_search=_sheet_search),
545 'name': _get_default_date,
548 def create(self, cr, uid, vals, context={}):
549 if 'sheet_id' in context:
550 ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'])
551 if ts.state not in ('draft', 'new'):
552 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
553 res = super(hr_attendance,self).create(cr, uid, vals, context=context)
554 if 'sheet_id' in context:
555 if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
556 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
557 'date outside the current timesheet dates!'))
560 def unlink(self, cr, uid, ids, *args, **kwargs):
561 self._check(cr, uid, ids)
562 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
564 def write(self, cr, uid, ids, vals, context={}):
565 self._check(cr, uid, ids)
566 res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
567 if 'sheet_id' in context:
568 for attendance in self.browse(cr, uid, ids, context=context):
569 if context['sheet_id'] != attendance.sheet_id.id:
570 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
571 'date outside the current timesheet dates!'))
574 def _check(self, cr, uid, ids):
575 for att in self.browse(cr, uid, ids):
576 if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
577 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
582 class hr_timesheet_sheet_sheet_day(osv.osv):
583 _name = "hr_timesheet_sheet.sheet.day"
584 _description = "Timesheets by Period"
588 'name': fields.date('Date', readonly=True),
589 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
590 'total_timesheet': fields.float('Project Timesheet', readonly=True),
591 'total_attendance': fields.float('Attendance', readonly=True),
592 'total_difference': fields.float('Difference', readonly=True),
596 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
603 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
610 SUM(total_timesheet) as total_timesheet,
611 CASE WHEN SUM(total_attendance) < 0
612 THEN (SUM(total_attendance) +
613 CASE WHEN current_date <> name
615 ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
618 ELSE SUM(total_attendance)
619 END /60 as total_attendance
624 l.date::date as name,
626 sum(l.unit_amount) as total_timesheet,
627 0.0 as total_attendance
629 hr_analytic_timesheet hrt
630 left join (account_analytic_line l
631 LEFT JOIN hr_timesheet_sheet_sheet s
632 ON (s.date_to >= l.date
633 AND s.date_from <= l.date
634 AND s.user_id = l.user_id))
635 on (l.id = hrt.line_id)
636 group by l.date::date, s.id
640 a.name::date as name,
642 0.0 as total_timesheet,
643 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
646 LEFT JOIN (hr_timesheet_sheet_sheet s
647 LEFT JOIN resource_resource r
648 LEFT JOIN hr_employee e
649 ON (e.resource_id = r.id)
650 ON (s.user_id = r.user_id))
651 ON (a.employee_id = e.id
652 AND s.date_to >= date_trunc('day',a.name)
653 AND s.date_from <= a.name)
654 WHERE action in ('sign_in', 'sign_out')
655 group by a.name::date, s.id
657 GROUP BY name, sheet_id
660 hr_timesheet_sheet_sheet_day()
663 class hr_timesheet_sheet_sheet_account(osv.osv):
664 _name = "hr_timesheet_sheet.sheet.account"
665 _description = "Timesheets by Period"
669 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
670 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
671 'total': fields.float('Total Time', digits=(16,2), readonly=True),
672 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
676 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
679 l.account_id as name,
681 sum(l.unit_amount) as total,
682 l.to_invoice as invoice_rate
684 hr_analytic_timesheet hrt
685 left join (account_analytic_line l
686 LEFT JOIN hr_timesheet_sheet_sheet s
687 ON (s.date_to >= l.date
688 AND s.date_from <= l.date
689 AND s.user_id = l.user_id))
690 on (l.id = hrt.line_id)
691 group by l.account_id, s.id, l.to_invoice
694 hr_timesheet_sheet_sheet_account()
698 class res_company(osv.osv):
699 _inherit = 'res.company'
701 'timesheet_range': fields.selection(
702 [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range'),
703 'timesheet_max_difference': fields.float('Timesheet allowed difference',
704 help="Allowed difference between the sign in/out and the timesheet " \
705 "computation for one sheet. Set this to 0 if you do not want any control."),
708 'timesheet_range': lambda *args: 'month',
709 'timesheet_max_difference': lambda *args: 0.0
714 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: