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