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