An employee should receive a mail.message in inbox when an manager refuse a timesheet.
[odoo/odoo.git] / addons / hr_timesheet_sheet / hr_timesheet_sheet.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 import time
23 from datetime import datetime, timedelta
24 from dateutil.relativedelta import relativedelta
25
26 from osv import fields, osv
27 from tools.translate import _
28 import netsvc
29
30 class hr_timesheet_sheet(osv.osv):
31     _name = "hr_timesheet_sheet.sheet"
32     _inherit = "mail.thread"
33     _table = 'hr_timesheet_sheet_sheet'
34     _order = "id desc"
35     _description="Timesheet"
36
37     def _total(self, cr, uid, ids, name, args, context=None):
38         """ Compute the attendances, analytic lines timesheets and differences between them
39             for all the days of a timesheet and the current day
40         """
41
42         res = {}
43         for sheet in self.browse(cr, uid, ids, context=context or {}):
44             res.setdefault(sheet.id, {
45                 'total_attendance': 0.0,
46                 'total_timesheet': 0.0,
47                 'total_difference': 0.0,
48             })
49             for period in sheet.period_ids:
50                 res[sheet.id]['total_attendance'] += period.total_attendance
51                 res[sheet.id]['total_timesheet'] += period.total_timesheet
52                 res[sheet.id]['total_difference'] += period.total_attendance - period.total_timesheet
53         return res
54
55     def check_employee_attendance_state(self, cr, uid, sheet_id, context=None):
56         ids_signin = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_in')])
57         ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')])
58
59         if len(ids_signin) != len(ids_signout):
60             raise osv.except_osv(('Warning!'),_('The timesheet cannot be validated as it does not contain an equal number of sign ins and sign outs.'))
61         return True
62
63     def copy(self, cr, uid, ids, *args, **argv):
64         raise osv.except_osv(_('Error!'), _('You cannot duplicate a timesheet.'))
65
66     def create(self, cr, uid, vals, *args, **argv):
67         if 'employee_id' in vals:
68             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id:
69                 raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must assign it to a user.'))
70             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
71                 raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link the employee to a product, like \'Consultant\'.'))
72             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
73                 raise osv.except_osv(_('Configuration Error!'), _('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.'))
74         return super(hr_timesheet_sheet, self).create(cr, uid, vals, *args, **argv)
75
76     def write(self, cr, uid, ids, vals, *args, **argv):
77         if 'employee_id' in vals:
78             new_user_id = self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id.id or False
79             if not new_user_id:
80                 raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must assign it to a user.'))
81             if not self._sheet_date(cr, uid, ids, forced_user_id=new_user_id):
82                 raise osv.except_osv(_('Error!'), _('You cannot have 2 timesheets that overlap!\nYou should use the menu \'My Timesheet\' to avoid this problem.'))
83             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
84                 raise osv.except_osv(_('Error!'), _('In order to create a timesheet for this employee, you must link the employee to a product.'))
85             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
86                 raise osv.except_osv(_('Configuration Error!'), _('In order to create a timesheet for this employee, you must assign an analytic journal to the employee, like \'Timesheet Journal\'.'))
87         return super(hr_timesheet_sheet, self).write(cr, uid, ids, vals, *args, **argv)
88
89     def button_confirm(self, cr, uid, ids, context=None):
90         for sheet in self.browse(cr, uid, ids, context=context):
91             if sheet.employee_id and sheet.employee_id.parent_id and sheet.employee_id.parent_id.user_id:
92                 self.message_subscribe_users(cr, uid, [sheet.id], user_ids=[sheet.employee_id.parent_id.user_id.id], context=context)
93             self.check_employee_attendance_state(cr, uid, sheet.id, context=context)
94             di = sheet.user_id.company_id.timesheet_max_difference
95             if (abs(sheet.total_difference) < di) or not di:
96                 wf_service = netsvc.LocalService("workflow")
97                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
98                 self.confirm_send_note(cr, uid, ids, context=context)
99             else:
100                 raise osv.except_osv(_('Warning!'), _('Please verify that the total difference of the sheet is lower than %.2f.') %(di,))
101         return True
102
103     def button_cancel(self, cr, uid, ids, context=None):
104         for sheet in self.browse(cr, uid, ids, context=context):
105             if sheet.employee_id and sheet.employee_id.user_id:
106                 self.message_subscribe_users(cr, uid, [sheet.id], user_ids=[sheet.employee_id.user_id.id], context=context)
107             wf_service = netsvc.LocalService("workflow")
108             wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'cancel', cr)
109             self.cancel_send_note(cr, uid, ids, context=context)
110         return True
111
112     def attendance_action_change(self, cr, uid, ids, context=None):
113         hr_employee = self.pool.get('hr.employee')
114         employee_ids = []
115         for sheet in self.browse(cr, uid, ids, context=context):
116             if sheet.employee_id.id not in employee_ids: employee_ids.append(sheet.employee_id.id)
117         return hr_employee.attendance_action_change(cr, uid, employee_ids, context=context)
118
119     _columns = {
120         'name': fields.char('Note', size=64, select=1,
121                             states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
122         'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
123         'user_id': fields.related('employee_id', 'user_id', type="many2one", relation="res.users", store=True, string="User", required=False, readonly=True),#fields.many2one('res.users', 'User', required=True, select=1, states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
124         'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
125         'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
126         'timesheet_ids' : fields.one2many('hr.analytic.timesheet', 'sheet_id',
127             'Timesheet lines',
128             readonly=True, states={
129                 'draft': [('readonly', False)],
130                 'new': [('readonly', False)]}
131             ),
132         'attendances_ids' : fields.one2many('hr.attendance', 'sheet_id', 'Attendances'),
133         'state' : fields.selection([
134             ('new', 'New'),
135             ('draft','Open'),
136             ('confirm','Waiting Approval'),
137             ('done','Approved')], 'Status', select=True, required=True, readonly=True,
138             help=' * The \'Draft\' status is used when a user is encoding a new and unconfirmed timesheet. \
139                 \n* The \'Confirmed\' status is used for to confirm the timesheet by user. \
140                 \n* The \'Done\' status is used when users timesheet is accepted by his/her senior.'),
141         'state_attendance' : fields.related('employee_id', 'state', type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Current Status', readonly=True),
142         'total_attendance': fields.function(_total, method=True, string='Total Attendance', multi="_total"),
143         'total_timesheet': fields.function(_total, method=True, string='Total Timesheet', multi="_total"),
144         'total_difference': fields.function(_total, method=True, string='Difference', multi="_total"),
145         'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
146         'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
147         'company_id': fields.many2one('res.company', 'Company'),
148         'department_id':fields.many2one('hr.department','Department'),
149     }
150
151     def _default_date_from(self, cr, uid, context=None):
152         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
153         r = user.company_id and user.company_id.timesheet_range or 'month'
154         if r=='month':
155             return time.strftime('%Y-%m-01')
156         elif r=='week':
157             return (datetime.today() + relativedelta(weekday=0, days=-6)).strftime('%Y-%m-%d')
158         elif r=='year':
159             return time.strftime('%Y-01-01')
160         return time.strftime('%Y-%m-%d')
161
162     def _default_date_to(self, cr, uid, context=None):
163         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
164         r = user.company_id and user.company_id.timesheet_range or 'month'
165         if r=='month':
166             return (datetime.today() + relativedelta(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
167         elif r=='week':
168             return (datetime.today() + relativedelta(weekday=6)).strftime('%Y-%m-%d')
169         elif r=='year':
170             return time.strftime('%Y-12-31')
171         return time.strftime('%Y-%m-%d')
172
173     def _default_employee(self, cr, uid, context=None):
174         emp_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=',uid)], context=context)
175         return emp_ids and emp_ids[0] or False
176
177     _defaults = {
178         'date_from' : _default_date_from,
179         'date_to' : _default_date_to,
180         'state': 'new',
181         'employee_id': _default_employee,
182         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c),
183         'user_id': _default_employee
184     }
185
186     def _sheet_date(self, cr, uid, ids, forced_user_id=False, context=None):
187         for sheet in self.browse(cr, uid, ids, context=context):
188             new_user_id = forced_user_id or sheet.user_id and sheet.user_id.id
189             if new_user_id:
190                 cr.execute('SELECT id \
191                     FROM hr_timesheet_sheet_sheet \
192                     WHERE (date_from <= %s and %s <= date_to) \
193                         AND user_id=%s \
194                         AND id <> %s',(sheet.date_to, sheet.date_from, new_user_id, sheet.id))
195                 if cr.fetchall():
196                     return False
197         return True
198
199
200     _constraints = [
201         (_sheet_date, 'You cannot have 2 timesheets that overlap!\nPlease use the menu \'My Current Timesheet\' to avoid this problem.', ['date_from','date_to']),
202     ]
203
204     def action_set_to_draft(self, cr, uid, ids, *args):
205         self.write(cr, uid, ids, {'state': 'draft'})
206         wf_service = netsvc.LocalService('workflow')
207         for id in ids:
208             wf_service.trg_create(uid, self._name, id, cr)
209         return True
210
211     def name_get(self, cr, uid, ids, context=None):
212         if not ids:
213             return []
214         if isinstance(ids, (long, int)):
215             ids = [ids]
216         return [(r['id'], _('Week ')+datetime.strptime(r['date_from'], '%Y-%m-%d').strftime('%U')) \
217                 for r in self.read(cr, uid, ids, ['date_from'],
218                     context=context, load='_classic_write')]
219
220     def unlink(self, cr, uid, ids, context=None):
221         sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
222         for sheet in sheets:
223             if sheet['state'] in ('confirm', 'done'):
224                 raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a timesheet which is already confirmed.'))
225             elif sheet['total_attendance'] <> 0.00:
226                 raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a timesheet which have attendance entries.'))
227         return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
228
229     def onchange_employee_id(self, cr, uid, ids, employee_id, context=None):
230         department_id =  False
231         if employee_id:
232             department_id = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context).department_id.id
233         return {'value': {'department_id': department_id}}
234
235     # ------------------------------------------------
236     # OpenChatter methods and notifications
237     # ------------------------------------------------
238     
239     def _needaction_domain_get(self, cr, uid, ids, context=None):
240         emp_obj = self.pool.get('hr.employee')
241         empids = emp_obj.search(cr, uid, [('parent_id.user_id', '=', uid)], context=context)
242         dom = ['&', ('state', '=', 'confirm'), ('employee_id', 'in', empids)]
243         return dom
244
245     def confirm_send_note(self, cr, uid, ids, context=None):
246         for obj in self.browse(cr, uid, ids, context=context):
247             self.message_post(cr, uid, [obj.id], body=_("Timesheet has been submitted by %s.") % (obj.employee_id.name), subtype="hr_timesheet_sheet.mt_submit_timesheet", context=context)
248
249     def cancel_send_note(self, cr, uid, ids, context=None):
250         user_name = self.pool.get("res.users").browse(cr, uid, uid, context=context).name
251         for obj in self.browse(cr, uid, ids, context=context):
252             self.message_post(cr, uid, [obj.id], body=_("Timesheet has been refused by %s.") % (user_name), subtype="hr_timesheet_sheet.mt_refuse_timesheet", context=context)
253
254 hr_timesheet_sheet()
255
256 class account_analytic_line(osv.osv):
257     _inherit = "account.analytic.line"
258
259     def _get_default_date(self, cr, uid, context=None):
260         if context is None:
261             context = {}
262         #get the default date (should be: today)
263         res = super(account_analytic_line, self)._get_default_date(cr, uid, context=context)
264         #if we got the dates from and to from the timesheet and if the default date is in between, we use the default
265         #but if the default isn't included in those dates, we use the date start of the timesheet as default
266         if context.get('timesheet_date_from') and context.get('timesheet_date_to'):
267             if context['timesheet_date_from'] <= res <= context['timesheet_date_to']:
268                 return res
269             return context.get('timesheet_date_from')
270         #if we don't get the dates from the timesheet, we return the default value from super()
271         return res
272
273
274 class hr_timesheet_line(osv.osv):
275     _inherit = "hr.analytic.timesheet"
276
277     def _sheet(self, cursor, user, ids, name, args, context=None):
278         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
279         res = {}.fromkeys(ids, False)
280         for ts_line in self.browse(cursor, user, ids, context=context):
281             sheet_ids = sheet_obj.search(cursor, user,
282                 [('date_to', '>=', ts_line.date), ('date_from', '<=', ts_line.date),
283                  ('employee_id.user_id', '=', ts_line.user_id.id)],
284                 context=context)
285             if sheet_ids:
286             # [0] because only one sheet possible for an employee between 2 dates
287                 res[ts_line.id] = sheet_obj.name_get(cursor, user, sheet_ids, context=context)[0]
288         return res
289
290     def _get_hr_timesheet_sheet(self, cr, uid, ids, context=None):
291         ts_line_ids = []
292         for ts in self.browse(cr, uid, ids, context=context):
293             cr.execute("""
294                     SELECT l.id
295                         FROM hr_analytic_timesheet l
296                     INNER JOIN account_analytic_line al
297                         ON (l.line_id = al.id)
298                     WHERE %(date_to)s >= al.date
299                         AND %(date_from)s <= al.date
300                         AND %(user_id)s = al.user_id
301                     GROUP BY l.id""", {'date_from': ts.date_from,
302                                         'date_to': ts.date_to,
303                                         'user_id': ts.employee_id.user_id.id,})
304             ts_line_ids.extend([row[0] for row in cr.fetchall()])
305         return ts_line_ids
306
307     def _get_account_analytic_line(self, cr, uid, ids, context=None):
308         ts_line_ids = self.pool.get('hr.analytic.timesheet').search(cr, uid, [('line_id', 'in', ids)])
309         return ts_line_ids
310
311     _columns = {
312         'sheet_id': fields.function(_sheet, string='Sheet',
313             type='many2one', relation='hr_timesheet_sheet.sheet', ondelete="cascade",
314             store={
315                     'hr_timesheet_sheet.sheet': (_get_hr_timesheet_sheet, ['employee_id', 'date_from', 'date_to'], 10),
316                     'account.analytic.line': (_get_account_analytic_line, ['user_id', 'date'], 10),
317                     'hr.analytic.timesheet': (lambda self,cr,uid,ids,context=None: ids, None, 10),
318                   },
319             ),
320     }
321
322     def _check_sheet_state(self, cr, uid, ids, context=None):
323         if context is None:
324             context = {}
325         for timesheet_line in self.browse(cr, uid, ids, context=context):
326             if timesheet_line.sheet_id and timesheet_line.sheet_id.state not in ('draft', 'new'):
327                 return False
328         return True
329
330     _constraints = [
331         (_check_sheet_state, 'You cannot modify an entry in a Confirmed/Done timesheet !', ['state']),
332     ]
333
334     def unlink(self, cr, uid, ids, *args, **kwargs):
335         if isinstance(ids, (int, long)):
336             ids = [ids]
337         self._check(cr, uid, ids)
338         return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
339
340     def _check(self, cr, uid, ids):
341         for att in self.browse(cr, uid, ids):
342             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
343                 raise osv.except_osv(_('Error!'), _('You cannot modify an entry in a confirmed timesheet.'))
344         return True
345
346     def multi_on_change_account_id(self, cr, uid, ids, account_ids, context=None):
347         return dict([(el, self.on_change_account_id(cr, uid, ids, el, context.get('user_id', uid))) for el in account_ids])
348
349
350 hr_timesheet_line()
351
352 class hr_attendance(osv.osv):
353     _inherit = "hr.attendance"
354
355     def _get_default_date(self, cr, uid, context=None):
356         if context is None:
357             context = {}
358         if 'name' in context:
359             return context['name'] + time.strftime(' %H:%M:%S')
360         return time.strftime('%Y-%m-%d %H:%M:%S')
361
362     def _get_hr_timesheet_sheet(self, cr, uid, ids, context=None):
363         attendance_ids = []
364         for ts in self.browse(cr, uid, ids, context=context):
365             cr.execute("""
366                         SELECT a.id
367                           FROM hr_attendance a
368                          INNER JOIN hr_employee e
369                                INNER JOIN resource_resource r
370                                        ON (e.resource_id = r.id)
371                             ON (a.employee_id = e.id)
372                         WHERE %(date_to)s >= date_trunc('day', a.name)
373                               AND %(date_from)s <= a.name
374                               AND %(user_id)s = r.user_id
375                          GROUP BY a.id""", {'date_from': ts.date_from,
376                                             'date_to': ts.date_to,
377                                             'user_id': ts.employee_id.user_id.id,})
378             attendance_ids.extend([row[0] for row in cr.fetchall()])
379         return attendance_ids
380
381     def _sheet(self, cursor, user, ids, name, args, context=None):
382         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
383         res = {}.fromkeys(ids, False)
384         for attendance in self.browse(cursor, user, ids, context=context):
385             date_to = datetime.strftime(datetime.strptime(attendance.name[0:10], '%Y-%m-%d'), '%Y-%m-%d %H:%M:%S')
386             sheet_ids = sheet_obj.search(cursor, user,
387                 [('date_to', '>=', date_to), ('date_from', '<=', attendance.name),
388                  ('employee_id', '=', attendance.employee_id.id)],
389                 context=context)
390             if sheet_ids:
391                 # [0] because only one sheet possible for an employee between 2 dates
392                 res[attendance.id] = sheet_obj.name_get(cursor, user, sheet_ids, context=context)[0]
393         return res
394
395     _columns = {
396         'sheet_id': fields.function(_sheet, string='Sheet',
397             type='many2one', relation='hr_timesheet_sheet.sheet',
398             store={
399                       'hr_timesheet_sheet.sheet': (_get_hr_timesheet_sheet, ['employee_id', 'date_from', 'date_to'], 10),
400                       'hr.attendance': (lambda self,cr,uid,ids,context=None: ids, ['employee_id', 'name', 'day'], 10),
401                   },
402             )
403     }
404     _defaults = {
405         'name': _get_default_date,
406     }
407
408     def create(self, cr, uid, vals, context=None):
409         if context is None:
410             context = {}
411         if 'sheet_id' in context:
412             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
413             if ts.state not in ('draft', 'new'):
414                 raise osv.except_osv(_('Error!'), _('You cannot modify an entry in a confirmed timesheet.'))
415         res = super(hr_attendance,self).create(cr, uid, vals, context=context)
416         if 'sheet_id' in context:
417             if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
418                 raise osv.except_osv(_('User Error!'), _('You cannot enter an attendance ' \
419                         'date outside the current timesheet dates.'))
420         return res
421
422     def unlink(self, cr, uid, ids, *args, **kwargs):
423         if isinstance(ids, (int, long)):
424             ids = [ids]
425         self._check(cr, uid, ids)
426         return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
427
428     def write(self, cr, uid, ids, vals, context=None):
429         if context is None:
430             context = {}
431         if isinstance(ids, (int, long)):
432             ids = [ids]
433         self._check(cr, uid, ids)
434         res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
435         if 'sheet_id' in context:
436             for attendance in self.browse(cr, uid, ids, context=context):
437                 if context['sheet_id'] != attendance.sheet_id.id:
438                     raise osv.except_osv(_('User Error!'), _('You cannot enter an attendance ' \
439                             'date outside the current timesheet dates.'))
440         return res
441
442     def _check(self, cr, uid, ids):
443         for att in self.browse(cr, uid, ids):
444             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
445                 raise osv.except_osv(_('Error!'), _('You cannot modify an entry in a confirmed timesheet'))
446         return True
447
448 hr_attendance()
449
450 class hr_timesheet_sheet_sheet_day(osv.osv):
451     _name = "hr_timesheet_sheet.sheet.day"
452     _description = "Timesheets by Period"
453     _auto = False
454     _order='name'
455     _columns = {
456         'name': fields.date('Date', readonly=True),
457         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
458         'total_timesheet': fields.float('Total Timesheet', readonly=True),
459         'total_attendance': fields.float('Attendance', readonly=True),
460         'total_difference': fields.float('Difference', readonly=True),
461     }
462
463     def init(self, cr):
464         cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
465             SELECT
466                 id,
467                 name,
468                 sheet_id,
469                 total_timesheet,
470                 total_attendance,
471                 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
472             FROM
473                 ((
474                     SELECT
475                         MAX(id) as id,
476                         name,
477                         sheet_id,
478                         SUM(total_timesheet) as total_timesheet,
479                         CASE WHEN SUM(total_attendance) < 0
480                             THEN (SUM(total_attendance) +
481                                 CASE WHEN current_date <> name
482                                     THEN 1440
483                                     ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
484                                 END
485                                 )
486                             ELSE SUM(total_attendance)
487                         END /60  as total_attendance
488                     FROM
489                         ((
490                             select
491                                 min(hrt.id) as id,
492                                 l.date::date as name,
493                                 s.id as sheet_id,
494                                 sum(l.unit_amount) as total_timesheet,
495                                 0.0 as total_attendance
496                             from
497                                 hr_analytic_timesheet hrt
498                                 left join (account_analytic_line l
499                                     LEFT JOIN hr_timesheet_sheet_sheet s
500                                     ON (s.date_to >= l.date
501                                         AND s.date_from <= l.date
502                                         AND s.user_id = l.user_id))
503                                     on (l.id = hrt.line_id)
504                             group by l.date::date, s.id
505                         ) union (
506                             select
507                                 -min(a.id) as id,
508                                 a.name::date as name,
509                                 s.id as sheet_id,
510                                 0.0 as total_timesheet,
511                                 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
512                             from
513                                 hr_attendance a
514                                 LEFT JOIN (hr_timesheet_sheet_sheet s
515                                     LEFT JOIN resource_resource r
516                                         LEFT JOIN hr_employee e
517                                         ON (e.resource_id = r.id)
518                                     ON (s.user_id = r.user_id))
519                                 ON (a.employee_id = e.id
520                                     AND s.date_to >= date_trunc('day',a.name)
521                                     AND s.date_from <= a.name)
522                             WHERE action in ('sign_in', 'sign_out')
523                             group by a.name::date, s.id
524                         )) AS foo
525                         GROUP BY name, sheet_id
526                 )) AS bar""")
527
528 hr_timesheet_sheet_sheet_day()
529
530
531 class hr_timesheet_sheet_sheet_account(osv.osv):
532     _name = "hr_timesheet_sheet.sheet.account"
533     _description = "Timesheets by Period"
534     _auto = False
535     _order='name'
536     _columns = {
537         'name': fields.many2one('account.analytic.account', 'Project / Analytic Account', readonly=True),
538         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
539         'total': fields.float('Total Time', digits=(16,2), readonly=True),
540         'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
541         }
542
543     def init(self, cr):
544         cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
545             select
546                 min(hrt.id) as id,
547                 l.account_id as name,
548                 s.id as sheet_id,
549                 sum(l.unit_amount) as total,
550                 l.to_invoice as invoice_rate
551             from
552                 hr_analytic_timesheet hrt
553                 left join (account_analytic_line l
554                     LEFT JOIN hr_timesheet_sheet_sheet s
555                         ON (s.date_to >= l.date
556                             AND s.date_from <= l.date
557                             AND s.user_id = l.user_id))
558                     on (l.id = hrt.line_id)
559             group by l.account_id, s.id, l.to_invoice
560         )""")
561
562 hr_timesheet_sheet_sheet_account()
563
564
565
566 class res_company(osv.osv):
567     _inherit = 'res.company'
568     _columns = {
569         'timesheet_range': fields.selection(
570             [('day','Day'),('week','Week'),('month','Month')], 'Timesheet range',
571             help="Periodicity on which you validate your timesheets."),
572         'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
573             help="Allowed difference in hours between the sign in/out and the timesheet " \
574                  "computation for one sheet. Set this to 0 if you do not want any control."),
575     }
576     _defaults = {
577         'timesheet_range': lambda *args: 'week',
578         'timesheet_max_difference': lambda *args: 0.0
579     }
580
581 res_company()
582
583 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
584