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