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