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