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