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