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