[FIX] widgets client action handler: one action per widget
[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 osv import fields, osv
27 from tools.translate import _
28 import netsvc
29
30 class one2many_mod2(fields.one2many):
31     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
32         if context is None:
33             context = {}
34
35         if values is None:
36             values = {}
37
38         # dict:
39         # {idn: (date_current, user_id), ...
40         #  1: ('2010-08-15', 1)}
41         res6 = dict([(rec['id'], (rec['date_current'], rec['user_id'][0]))
42                         for rec
43                             in obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)])
44
45         # eg: ['|', '|',
46         #       '&', '&', ('name', '>=', '2011-03-01'), ('name', '<=', '2011-03-01'), ('employee_id.user_id', '=', 1),
47         #       '&', '&', ('name', '>=', '2011-02-01'), ('name', '<=', '2011-02-01'), ('employee_id.user_id', '=', 1)]
48         dom = []
49         for c, id in enumerate(ids):
50             if id in res6:
51                 if c: # skip first
52                     dom.insert(0 ,'|')
53                 dom.append('&')
54                 dom.append('&')
55                 dom.append(('name', '>=', res6[id][0]))
56                 dom.append(('name', '<=', res6[id][0]))
57                 dom.append(('employee_id.user_id', '=', res6[id][1]))
58
59         ids2 = obj.pool.get(self._obj).search(cr, user, dom, limit=self._limit)
60
61         res = {}
62         for i in ids:
63             res[i] = []
64
65         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
66             if r[self._fields_id]:
67                 res[r[self._fields_id][0]].append(r['id'])
68
69         return res
70
71     def set(self, cr, obj, id, field, values, user=None, context=None):
72         if context is None:
73             context = {}
74
75         context = context.copy()
76         context['sheet_id'] = id
77         return super(one2many_mod2, self).set(cr, obj, id, field, values, user=user, context=context)
78
79
80 class one2many_mod(fields.one2many):
81     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
82         if context is None:
83             context = {}
84
85         if values is None:
86             values = {}
87
88
89         res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context=context)
90         res6 = {}
91         for r in res5:
92             res6[r['id']] = (r['date_current'], r['user_id'][0])
93
94         ids2 = []
95         for id in ids:
96             dom = []
97             if id in res6:
98                 dom = [('date', '=', res6[id][0]), ('user_id', '=', res6[id][1])]
99             ids2.extend(obj.pool.get(self._obj).search(cr, user,
100                 dom, limit=self._limit))
101         res = {}
102         for i in ids:
103             res[i] = []
104         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
105                 [self._fields_id], context=context, load='_classic_write'):
106             if r[self._fields_id]:
107                 res[r[self._fields_id][0]].append(r['id'])
108
109         return res
110
111 class hr_timesheet_sheet(osv.osv):
112     _name = "hr_timesheet_sheet.sheet"
113     _table = 'hr_timesheet_sheet_sheet'
114     _order = "id desc"
115     _description="Timesheet"
116
117     def _total_day(self, cr, uid, ids, name, args, context=None):
118         res = {}
119         cr.execute('SELECT sheet.id, day.total_attendance, day.total_timesheet, day.total_difference\
120                 FROM hr_timesheet_sheet_sheet AS sheet \
121                 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
122                     ON (sheet.id = day.sheet_id \
123                         AND day.name = sheet.date_current) \
124                 WHERE sheet.id IN %s',(tuple(ids),))
125         for record in cr.fetchall():
126             res[record[0]] = {}
127             res[record[0]]['total_attendance_day'] = record[1]
128             res[record[0]]['total_timesheet_day'] = record[2]
129             res[record[0]]['total_difference_day'] = record[3]
130         return res
131
132     def _total(self, cr, uid, ids, name, args, context=None):
133         res = {}
134         cr.execute('SELECT s.id, COALESCE(SUM(d.total_attendance),0), COALESCE(SUM(d.total_timesheet),0), COALESCE(SUM(d.total_difference),0) \
135                 FROM hr_timesheet_sheet_sheet s \
136                     LEFT JOIN hr_timesheet_sheet_sheet_day d \
137                         ON (s.id = d.sheet_id) \
138                 WHERE s.id IN %s GROUP BY s.id',(tuple(ids),))
139         for record in cr.fetchall():
140             res[record[0]] = {}
141             res[record[0]]['total_attendance'] = record[1]
142             res[record[0]]['total_timesheet'] = record[2]
143             res[record[0]]['total_difference'] = record[3]
144         return res
145
146     def _state_attendance(self, cr, uid, ids, name, args, context=None):
147         emp_obj = self.pool.get('hr.employee')
148         result = {}
149         link_emp = {}
150         emp_ids = []
151
152         for sheet in self.browse(cr, uid, ids, context=context):
153             result[sheet.id] = 'none'
154             emp_ids2 = emp_obj.search(cr, uid,
155                     [('user_id', '=', sheet.user_id.id)], context=context)
156             if emp_ids2:
157                 link_emp[emp_ids2[0]] = sheet.id
158                 emp_ids.append(emp_ids2[0])
159         for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
160             if emp.id in link_emp:
161                 sheet_id = link_emp[emp.id]
162                 result[sheet_id] = emp.state
163         return result
164
165     def check_employee_attendance_state(self, cr, uid, sheet_id, context=None):
166         ids_signin = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_in')])
167         ids_signout = self.pool.get('hr.attendance').search(cr,uid,[('sheet_id', '=', sheet_id),('action','=','sign_out')])
168
169         if len(ids_signin) != len(ids_signout):
170             raise osv.except_osv(('Warning !'),_('The timesheet cannot be validated as it does not contain equal no. of sign ins and sign outs!'))
171         return True
172
173     def copy(self, cr, uid, ids, *args, **argv):
174         raise osv.except_osv(_('Error !'), _('You cannot duplicate a timesheet !'))
175
176     def create(self, cr, uid, vals, *args, **argv):
177         if 'employee_id' in vals:
178             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id:
179                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any user defined !'))
180             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
181                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any product defined !'))
182             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
183                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any analytic journal defined !'))
184         return super(hr_timesheet_sheet, self).create(cr, uid, vals, *args, **argv)
185
186     def write(self, cr, uid, ids, vals, *args, **argv):
187         if 'employee_id' in vals:
188             new_user_id = self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).user_id.id or False
189             if not new_user_id:
190                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any user defined !'))
191             if not self._sheet_date(cr, uid, ids, forced_user_id=new_user_id):
192                 raise osv.except_osv(_('Error !'), _('You can not have 2 timesheets that overlaps !\nPlease use the menu \'My Current Timesheet\' to avoid this problem.'))
193             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).product_id:
194                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any product defined !'))
195             if not self.pool.get('hr.employee').browse(cr, uid, vals['employee_id']).journal_id:
196                 raise osv.except_osv(_('Error !'), _('You cannot create a timesheet for an employee that does not have any analytic journal defined !'))
197         return super(hr_timesheet_sheet, self).write(cr, uid, ids, vals, *args, **argv)
198
199     def button_confirm(self, cr, uid, ids, context=None):
200         for sheet in self.browse(cr, uid, ids, context=context):
201             self.check_employee_attendance_state(cr, uid, sheet.id, context)
202             di = sheet.user_id.company_id.timesheet_max_difference
203             if (abs(sheet.total_difference) < di) or not di:
204                 wf_service = netsvc.LocalService("workflow")
205                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
206             else:
207                 raise osv.except_osv(_('Warning !'), _('Please verify that the total difference of the sheet is lower than %.2f !') %(di,))
208         return True
209
210     def date_today(self, cr, uid, ids, context=None):
211         for sheet in self.browse(cr, uid, ids, context=context):
212             if datetime.today() <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
213                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
214             elif datetime.now() >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
215                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
216             else:
217                 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')}, context=context)
218         return True
219
220     def date_previous(self, cr, uid, ids, context=None):
221         for sheet in self.browse(cr, uid, ids, context=context):
222             if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
223                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
224             else:
225                 self.write(cr, uid, [sheet.id], {
226                     'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=-1)).strftime('%Y-%m-%d'),
227                 }, context=context)
228         return True
229
230     def date_next(self, cr, uid, ids, context=None):
231         for sheet in self.browse(cr, uid, ids, context=context):
232             if datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
233                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
234             else:
235                 self.write(cr, uid, [sheet.id], {
236                     'date_current': (datetime.strptime(sheet.date_current, '%Y-%m-%d') + relativedelta(days=1)).strftime('%Y-%m-%d'),
237                 }, context=context)
238         return True
239
240     def button_dummy(self, cr, uid, ids, context=None):
241         for sheet in self.browse(cr, uid, ids, context=context):
242             if datetime.strptime(sheet.date_current, '%Y-%m-%d') <= datetime.strptime(sheet.date_from, '%Y-%m-%d'):
243                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,}, context=context)
244             elif datetime.strptime(sheet.date_current, '%Y-%m-%d') >= datetime.strptime(sheet.date_to, '%Y-%m-%d'):
245                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,}, context=context)
246         return True
247
248     def sign(self, cr, uid, ids, typ, context=None):
249         emp_obj = self.pool.get('hr.employee')
250         sheet = self.browse(cr, uid, ids, context=context)[0]
251         if context is None:
252             context = {}
253         if not sheet.date_current == time.strftime('%Y-%m-%d'):
254             raise osv.except_osv(_('Error !'), _('You cannot sign in/sign out from an other date than today'))
255         emp_id = sheet.employee_id.id
256         context['sheet_id']=ids[0]
257         emp_obj.attendance_action_change(cr, uid, [emp_id], type=typ, context=context,)
258         return True
259
260     def sign_in(self, cr, uid, ids, context=None):
261         return self.sign(cr,uid,ids,'sign_in',context=None)
262
263     def sign_out(self, cr, uid, ids, context=None):
264         return self.sign(cr,uid,ids,'sign_out',context=None)
265
266     _columns = {
267         'name': fields.char('Description', size=64, select=1,
268                             states={'confirm':[('readonly', True)], 'done':[('readonly', True)]}),
269         'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
270         '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)]}),
271         'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
272         'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
273         'date_current': fields.date('Current date', required=True, select=1),
274         'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
275             'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
276             readonly=True, states={
277                 'draft': [('readonly', False)],
278                 'new': [('readonly', False)]}
279             ),
280         'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances'),
281         'state' : fields.selection([
282             ('new', 'New'),
283             ('draft','Draft'),
284             ('confirm','Confirmed'),
285             ('done','Done')], 'State', select=True, required=True, readonly=True,
286             help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed timesheet. \
287                 \n* The \'Confirmed\' state is used for to confirm the timesheet by user. \
288                 \n* The \'Done\' state is used when users timesheet is accepted by his/her senior.'),
289         'state_attendance' : fields.function(_state_attendance, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current Status'),
290         'total_attendance_day': fields.function(_total_day, string='Total Attendance', multi="_total_day"),
291         'total_timesheet_day': fields.function(_total_day, string='Total Timesheet', multi="_total_day"),
292         'total_difference_day': fields.function(_total_day, string='Difference', multi="_total_day"),
293         'total_attendance': fields.function(_total, string='Total Attendance', multi="_total_sheet"),
294         'total_timesheet': fields.function(_total, string='Total Timesheet', multi="_total_sheet"),
295         'total_difference': fields.function(_total, string='Difference', multi="_total_sheet"),
296         'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
297         'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
298         'company_id': fields.many2one('res.company', 'Company'),
299         'department_id':fields.many2one('hr.department','Department'),
300     }
301
302     def _default_date_from(self,cr, uid, context=None):
303         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
304         r = user.company_id and user.company_id.timesheet_range or 'month'
305         if r=='month':
306             return time.strftime('%Y-%m-01')
307         elif r=='week':
308             return (datetime.today() + relativedelta(weekday=0, weeks=-1)).strftime('%Y-%m-%d')
309         elif r=='year':
310             return time.strftime('%Y-01-01')
311         return time.strftime('%Y-%m-%d')
312
313     def _default_date_to(self,cr, uid, context=None):
314         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
315         r = user.company_id and user.company_id.timesheet_range or 'month'
316         if r=='month':
317             return (datetime.today() + relativedelta(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
318         elif r=='week':
319             return (datetime.today() + relativedelta(weekday=6)).strftime('%Y-%m-%d')
320         elif r=='year':
321             return time.strftime('%Y-12-31')
322         return time.strftime('%Y-%m-%d')
323
324     def _default_employee(self,cr, uid, context=None):
325         emp_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id','=',uid)], context=context)
326         return emp_ids and emp_ids[0] or False
327
328     _defaults = {
329         'date_from' : _default_date_from,
330         'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
331         'date_to' : _default_date_to,
332         'state': 'new',
333         'employee_id': _default_employee,
334         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr_timesheet_sheet.sheet', context=c)
335     }
336
337     def _sheet_date(self, cr, uid, ids, forced_user_id=False, context=None):
338         for sheet in self.browse(cr, uid, ids, context=context):
339             new_user_id = forced_user_id or sheet.user_id and sheet.user_id.id
340             if new_user_id:
341                 cr.execute('SELECT id \
342                     FROM hr_timesheet_sheet_sheet \
343                     WHERE (date_from < %s and %s < date_to) \
344                         AND user_id=%s \
345                         AND id <> %s',(sheet.date_to, sheet.date_from, new_user_id, sheet.id))
346                 if cr.fetchall():
347                     return False
348         return True
349
350     def _date_current_check(self, cr, uid, ids, context=None):
351         for sheet in self.browse(cr, uid, ids, context=context):
352             if sheet.date_current < sheet.date_from or sheet.date_current > sheet.date_to:
353                 return False
354         return True
355
356
357     _constraints = [
358         (_sheet_date, 'You can not have 2 timesheets that overlaps !\nPlease use the menu \'My Current Timesheet\' to avoid this problem.', ['date_from','date_to']),
359         (_date_current_check, 'You must select a Current date which is in the timesheet dates !', ['date_current']),
360     ]
361
362     def action_set_to_draft(self, cr, uid, ids, *args):
363         self.write(cr, uid, ids, {'state': 'draft'})
364         wf_service = netsvc.LocalService('workflow')
365         for id in ids:
366             wf_service.trg_create(uid, self._name, id, cr)
367         return True
368
369     def name_get(self, cr, uid, ids, context=None):
370         if not len(ids):
371             return []
372         return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
373                 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
374                     context=context, load='_classic_write')]
375
376     def unlink(self, cr, uid, ids, context=None):
377         sheets = self.read(cr, uid, ids, ['state','total_attendance'], context=context)
378         for sheet in sheets:
379             if sheet['state'] in ('confirm', 'done'):
380                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which are already confirmed !'))
381             elif sheet['total_attendance'] <> 0.00:
382                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Sheet(s) which have attendance entries encoded !'))
383         return super(hr_timesheet_sheet, self).unlink(cr, uid, ids, context=context)
384
385 hr_timesheet_sheet()
386
387
388 class hr_timesheet_line(osv.osv):
389     _inherit = "hr.analytic.timesheet"
390
391     def _get_default_date(self, cr, uid, context=None):
392         if context is None:
393             context = {}
394         if 'date' in context:
395             return context['date']
396         return time.strftime('%Y-%m-%d')
397
398     def _sheet(self, cursor, user, ids, name, args, context=None):
399         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
400         cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
401                 FROM hr_timesheet_sheet_sheet s \
402                     LEFT JOIN (hr_analytic_timesheet l \
403                         LEFT JOIN account_analytic_line al \
404                             ON (l.line_id = al.id)) \
405                         ON (s.date_to >= al.date \
406                             AND s.date_from <= al.date \
407                             AND s.user_id = al.user_id) \
408                 WHERE l.id IN %s GROUP BY l.id',(tuple(ids),))
409         res = dict(cursor.fetchall())
410         sheet_names = {}
411         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
412                 context=context):
413             sheet_names[sheet_id] = name
414
415         for line_id in {}.fromkeys(ids):
416             sheet_id = res.get(line_id, False)
417             if sheet_id:
418                 res[line_id] = (sheet_id, sheet_names[sheet_id])
419             else:
420                 res[line_id] = False
421         return res
422
423     def _sheet_search(self, cursor, user, obj, name, args, context=None):
424         if not len(args):
425             return []
426         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
427
428         i = 0
429         while i < len(args):
430             fargs = args[i][0].split('.', 1)
431             if len(fargs) > 1:
432                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
433                     [(fargs[1], args[i][1], args[i][2])], context=context))
434                 i += 1
435                 continue
436             if isinstance(args[i][2], basestring):
437                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
438                         args[i][1])
439                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
440             i += 1
441         qu1, qu2 = [], []
442         for x in args:
443             if x[1] != 'in':
444                 if (x[2] is False) and (x[1] == '='):
445                     qu1.append('(s.id IS NULL)')
446                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
447                     qu1.append('(s.id IS NOT NULL)')
448                 else:
449                     qu1.append('(s.id %s %s)' % (x[1], '%s'))
450                     qu2.append(x[2])
451             elif x[1] == 'in':
452                 if len(x[2]) > 0:
453                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
454                     qu2 += x[2]
455                 else:
456                     qu1.append('(False)')
457         if len(qu1):
458             qu1 = ' WHERE ' + ' AND '.join(qu1)
459         else:
460             qu1 = ''
461         cursor.execute('SELECT l.id \
462                 FROM hr_timesheet_sheet_sheet s \
463                     LEFT JOIN (hr_analytic_timesheet l \
464                         LEFT JOIN account_analytic_line al \
465                             ON (l.line_id = al.id)) \
466                         ON (s.date_to >= al.date \
467                             AND s.date_from <= al.date \
468                             AND s.user_id = al.user_id)' + \
469                 qu1, qu2)
470         res = cursor.fetchall()
471         if not len(res):
472             return [('id', '=', '0')]
473         return [('id', 'in', [x[0] for x in res])]
474
475     _columns = {
476         'sheet_id': fields.function(_sheet, string='Sheet',
477             type='many2one', relation='hr_timesheet_sheet.sheet',
478             fnct_search=_sheet_search),
479     }
480     _defaults = {
481         'date': _get_default_date,
482     }
483
484     def _check_sheet_state(self, cr, uid, ids, context=None):
485         if context is None:
486             context = {}
487         for timesheet_line in self.browse(cr, uid, ids, context=context):
488             if timesheet_line.sheet_id and timesheet_line.sheet_id.state not in ('draft', 'new'):
489                 return False
490         return True
491
492     _constraints = [
493         (_check_sheet_state, 'You can not modify an entry in a Confirmed/Done timesheet !.', ['state']),
494     ]
495
496     def unlink(self, cr, uid, ids, *args, **kwargs):
497         if isinstance(ids, (int, long)):
498             ids = [ids]
499         self._check(cr, uid, ids)
500         return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
501
502     def _check(self, cr, uid, ids):
503         for att in self.browse(cr, uid, ids):
504             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
505                 raise osv.except_osv(_('Error !'), _('You can not modify an entry in a confirmed timesheet !'))
506         return True
507
508 hr_timesheet_line()
509
510 class hr_attendance(osv.osv):
511     _inherit = "hr.attendance"
512
513     def _get_default_date(self, cr, uid, context=None):
514         if context is None:
515             context = {}
516         if 'name' in context:
517             return context['name'] + time.strftime(' %H:%M:%S')
518         return time.strftime('%Y-%m-%d %H:%M:%S')
519
520     def _sheet(self, cursor, user, ids, name, args, context=None):
521         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
522         cursor.execute("SELECT a.id, COALESCE(MAX(s.id), 0) \
523                 FROM hr_timesheet_sheet_sheet s \
524                     LEFT JOIN (hr_attendance a \
525                         LEFT JOIN hr_employee e \
526                             LEFT JOIN resource_resource r \
527                                 ON (e.resource_id = r.id) \
528                             ON (a.employee_id = e.id)) \
529                         ON (s.date_to >= date_trunc('day',a.name) \
530                             AND s.date_from <= a.name \
531                             AND s.user_id = r.user_id) \
532                 WHERE a.id IN %s GROUP BY a.id",(tuple(ids),))
533         res = dict(cursor.fetchall())
534         sheet_names = {}
535         for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
536                 context=context):
537             sheet_names[sheet_id] = name
538         for line_id in {}.fromkeys(ids):
539             sheet_id = res.get(line_id, False)
540             if sheet_id:
541                 res[line_id] = (sheet_id, sheet_names[sheet_id])
542             else:
543                 res[line_id] = False
544         return res
545
546     def _sheet_search(self, cursor, user, obj, name, args, context=None):
547         if not len(args):
548             return []
549
550         sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
551         i = 0
552         while i < len(args):
553             fargs = args[i][0].split('.', 1)
554             if len(fargs) > 1:
555                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
556                     [(fargs[1], args[i][1], args[i][2])], context=context))
557                 i += 1
558                 continue
559             if isinstance(args[i][2], basestring):
560                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
561                         args[i][1])
562                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
563             i += 1
564         qu1, qu2 = [], []
565         for x in args:
566             if x[1] != 'in':
567                 if (x[2] is False) and (x[1] == '='):
568                     qu1.append('(s.id IS NULL)')
569                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
570                     qu1.append('(s.id IS NOT NULL)')
571                 else:
572                     qu1.append('(s.id %s %s)' % (x[1], '%s'))
573                     qu2.append(x[2])
574             elif x[1] == 'in':
575                 if len(x[2]) > 0:
576                     qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
577                     qu2 += x[2]
578                 else:
579                     qu1.append('(False)')
580         if len(qu1):
581             qu1 = ' WHERE ' + ' AND '.join(qu1)
582         else:
583             qu1 = ''
584         cursor.execute('SELECT a.id\
585                 FROM hr_timesheet_sheet_sheet s \
586                     LEFT JOIN (hr_attendance a \
587                         LEFT JOIN hr_employee e \
588                             ON (a.employee_id = e.id)) \
589                                 LEFT JOIN resource_resource r \
590                                     ON (e.resource_id = r.id) \
591                         ON (s.date_to >= date_trunc(\'day\',a.name) \
592                             AND s.date_from <= a.name \
593                             AND s.user_id = r.user_id) ' + \
594                 qu1, qu2)
595         res = cursor.fetchall()
596         if not len(res):
597             return [('id', '=', '0')]
598         return [('id', 'in', [x[0] for x in res])]
599
600     _columns = {
601         'sheet_id': fields.function(_sheet, string='Sheet',
602             type='many2one', relation='hr_timesheet_sheet.sheet',
603             fnct_search=_sheet_search),
604     }
605     _defaults = {
606         'name': _get_default_date,
607     }
608
609     def create(self, cr, uid, vals, context=None):
610         if context is None:
611             context = {}
612         if 'sheet_id' in context:
613             ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, context['sheet_id'], context=context)
614             if ts.state not in ('draft', 'new'):
615                 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
616         res = super(hr_attendance,self).create(cr, uid, vals, context=context)
617         if 'sheet_id' in context:
618             if context['sheet_id'] != self.browse(cr, uid, res, context=context).sheet_id.id:
619                 raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
620                         'date outside the current timesheet dates!'))
621         return res
622
623     def unlink(self, cr, uid, ids, *args, **kwargs):
624         if isinstance(ids, (int, long)):
625             ids = [ids]
626         self._check(cr, uid, ids)
627         return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
628
629     def write(self, cr, uid, ids, vals, context=None):
630         if context is None:
631             context = {}
632         if isinstance(ids, (int, long)):
633             ids = [ids]
634         self._check(cr, uid, ids)
635         res = super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
636         if 'sheet_id' in context:
637             for attendance in self.browse(cr, uid, ids, context=context):
638                 if context['sheet_id'] != attendance.sheet_id.id:
639                     raise osv.except_osv(_('UserError'), _('You cannot enter an attendance ' \
640                             'date outside the current timesheet dates!'))
641         return res
642
643     def _check(self, cr, uid, ids):
644         for att in self.browse(cr, uid, ids):
645             if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
646                 raise osv.except_osv(_('Error !'), _('You cannot modify an entry in a confirmed timesheet !'))
647         return True
648
649 hr_attendance()
650
651 class hr_timesheet_sheet_sheet_day(osv.osv):
652     _name = "hr_timesheet_sheet.sheet.day"
653     _description = "Timesheets by Period"
654     _auto = False
655     _order='name'
656     _columns = {
657         'name': fields.date('Date', readonly=True),
658         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
659         'total_timesheet': fields.float('Total Timesheet', readonly=True),
660         'total_attendance': fields.float('Attendance', readonly=True),
661         'total_difference': fields.float('Difference', readonly=True),
662     }
663
664     def init(self, cr):
665         cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
666             SELECT
667                 id,
668                 name,
669                 sheet_id,
670                 total_timesheet,
671                 total_attendance,
672                 cast(round(cast(total_attendance - total_timesheet as Numeric),2) as Double Precision) AS total_difference
673             FROM
674                 ((
675                     SELECT
676                         MAX(id) as id,
677                         name,
678                         sheet_id,
679                         SUM(total_timesheet) as total_timesheet,
680                         CASE WHEN SUM(total_attendance) < 0
681                             THEN (SUM(total_attendance) +
682                                 CASE WHEN current_date <> name
683                                     THEN 1440
684                                     ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
685                                 END
686                                 )
687                             ELSE SUM(total_attendance)
688                         END /60  as total_attendance
689                     FROM
690                         ((
691                             select
692                                 min(hrt.id) as id,
693                                 l.date::date as name,
694                                 s.id as sheet_id,
695                                 sum(l.unit_amount) as total_timesheet,
696                                 0.0 as total_attendance
697                             from
698                                 hr_analytic_timesheet hrt
699                                 left join (account_analytic_line l
700                                     LEFT JOIN hr_timesheet_sheet_sheet s
701                                     ON (s.date_to >= l.date
702                                         AND s.date_from <= l.date
703                                         AND s.user_id = l.user_id))
704                                     on (l.id = hrt.line_id)
705                             group by l.date::date, s.id
706                         ) union (
707                             select
708                                 -min(a.id) as id,
709                                 a.name::date as name,
710                                 s.id as sheet_id,
711                                 0.0 as total_timesheet,
712                                 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
713                             from
714                                 hr_attendance a
715                                 LEFT JOIN (hr_timesheet_sheet_sheet s
716                                     LEFT JOIN resource_resource r
717                                         LEFT JOIN hr_employee e
718                                         ON (e.resource_id = r.id)
719                                     ON (s.user_id = r.user_id))
720                                 ON (a.employee_id = e.id
721                                     AND s.date_to >= date_trunc('day',a.name)
722                                     AND s.date_from <= a.name)
723                             WHERE action in ('sign_in', 'sign_out')
724                             group by a.name::date, s.id
725                         )) AS foo
726                         GROUP BY name, sheet_id
727                 )) AS bar""")
728
729 hr_timesheet_sheet_sheet_day()
730
731
732 class hr_timesheet_sheet_sheet_account(osv.osv):
733     _name = "hr_timesheet_sheet.sheet.account"
734     _description = "Timesheets by Period"
735     _auto = False
736     _order='name'
737     _columns = {
738         'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
739         'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
740         'total': fields.float('Total Time', digits=(16,2), readonly=True),
741         'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
742         }
743
744     def init(self, cr):
745         cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
746             select
747                 min(hrt.id) as id,
748                 l.account_id as name,
749                 s.id as sheet_id,
750                 sum(l.unit_amount) as total,
751                 l.to_invoice as invoice_rate
752             from
753                 hr_analytic_timesheet hrt
754                 left join (account_analytic_line l
755                     LEFT JOIN hr_timesheet_sheet_sheet s
756                         ON (s.date_to >= l.date
757                             AND s.date_from <= l.date
758                             AND s.user_id = l.user_id))
759                     on (l.id = hrt.line_id)
760             group by l.account_id, s.id, l.to_invoice
761         )""")
762
763 hr_timesheet_sheet_sheet_account()
764
765
766
767 class res_company(osv.osv):
768     _inherit = 'res.company'
769     _columns = {
770         'timesheet_range': fields.selection(
771             [('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timesheet range'),
772         'timesheet_max_difference': fields.float('Timesheet allowed difference(Hours)',
773             help="Allowed difference in hours between the sign in/out and the timesheet " \
774                  "computation for one sheet. Set this to 0 if you do not want any control."),
775     }
776     _defaults = {
777         'timesheet_range': lambda *args: 'week',
778         'timesheet_max_difference': lambda *args: 0.0
779     }
780
781 res_company()
782
783 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
784