Fix in search sheet_id with many args
[odoo/odoo.git] / addons / hr_timesheet_sheet / hr_timesheet_sheet.py
1 ##############################################################################
2 #
3 # Copyright (c) 2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # $Id: hr_timesheet.py 5490 2007-01-29 16:05:51Z pinky $
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 import time
31 from osv import fields
32 from osv import osv
33 import netsvc
34
35 from mx import DateTime
36
37
38 class one2many_mod2(fields.one2many):
39         def get(self, cr, obj, ids, name, user=None, offset=0, context={}, values={}):
40                 res = {}
41                 for id in ids:
42                         res[id] = []
43
44                 res5 = obj.read(cr, user, ids, ['date_current', 'user_id'], context)
45                 res6 = {}
46                 for r in res5:
47                         res6[r['id']] = (r['date_current'], r['user_id'][0])
48
49                 ids2 = []
50                 for id in ids:
51                         dom = []
52                         if id in res6:
53                                 dom = [('name', '>=', res6[id][0] + ' 00:00:00'),
54                                                 ('name', '<=', res6[id][0] + ' 23:59:59'),
55                                                 ('employee_id.user_id', '=', res6[id][1])]
56                         ids2.extend(obj.pool.get(self._obj).search(cr, user,
57                                 dom, limit=self._limit))
58
59                 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2,
60                                 [self._fields_id], context=context, load='_classic_write'):
61                         if r[self._fields_id]:
62                                 res.setdefault(r[self._fields_id][0], []).append(r['id'])
63
64                 return res
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)
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):
99                 field_name = name.strip('_day')
100                 cr.execute('SELECT sheet.id, day.' + field_name +' \
101                                 FROM hr_timesheet_sheet_sheet AS sheet \
102                                 LEFT JOIN hr_timesheet_sheet_sheet_day AS day \
103                                         ON (sheet.id = day.sheet_id \
104                                                 AND day.name = sheet.date_current) \
105                                 WHERE sheet.id in (' + ','.join([str(x) for x in ids]) + ')')
106                 return dict(cr.fetchall())
107
108         def _total(self, cr, uid, ids, name, args, context):
109                 cr.execute('SELECT s.id, COALESCE(SUM(d.' + name + '),0) \
110                                 FROM hr_timesheet_sheet_sheet s \
111                                         LEFT JOIN hr_timesheet_sheet_sheet_day d \
112                                                 ON (s.id = d.sheet_id) \
113                                 WHERE s.id in ('+ ','.join(map(str, ids)) + ') \
114                                 GROUP BY s.id')
115                 return dict(cr.fetchall())
116
117         def _state_attendance(self, cr, uid, ids, name, args, context):
118                 result = {}
119                 link_emp = {}
120                 emp_ids = []
121                 emp_obj = self.pool.get('hr.employee')
122
123                 for sheet in self.browse(cr, uid, ids, context):
124                         result[sheet.id] = 'none'
125                         emp_ids2 = emp_obj.search(cr, uid,
126                                         [('user_id', '=', sheet.user_id.id)])
127                         if emp_ids2:
128                                 link_emp[emp_ids2[0]] = sheet.id
129                                 emp_ids.append(emp_ids2[0])
130                 for emp in emp_obj.browse(cr, uid, emp_ids, context=context):
131                         if emp.id in link_emp:
132                                 sheet_id = link_emp[emp.id]
133                                 result[sheet_id] = emp.state
134                 return result
135
136         def button_confirm(self, cr, uid, ids, context):
137                 for sheet in self.browse(cr, uid, ids, context):
138                         di = sheet.user_id.company_id.timesheet_max_difference
139                         if (abs(sheet.total_difference) < di) or not di:
140                                 wf_service = netsvc.LocalService("workflow")
141                                 wf_service.trg_validate(uid, 'hr_timesheet_sheet.sheet', sheet.id, 'confirm', cr)
142                         else:
143                                 raise osv.except_osv('Warning !', 'Please verify that the total difference of the sheet is lower than %.2f !' %(di,))
144                 return True
145
146         def date_today(self, cr, uid, ids, context):
147                 for sheet in self.browse(cr, uid, ids, context):
148                         if DateTime.now() <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
149                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
150                         elif DateTime.now() >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
151                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
152                         else:
153                                 self.write(cr, uid, [sheet.id], {'date_current': time.strftime('%Y-%m-%d')})
154                 return True
155
156         def date_previous(self, cr, uid, ids, context):
157                 for sheet in self.browse(cr, uid, ids, context):
158                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
159                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
160                         else:
161                                 self.write(cr, uid, [sheet.id], {
162                                         'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=-1)).strftime('%Y-%m-%d'),
163                                 })
164                 return True
165
166         def date_next(self, cr, uid, ids, context):
167                 for sheet in self.browse(cr, uid, ids, context):
168                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
169                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
170                         else:
171                                 self.write(cr, uid, [sheet.id], {
172                                         'date_current': (DateTime.strptime(sheet.date_current, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d'),
173                                 })
174                 return True
175
176         def button_dummy(self, cr, uid, ids, context):
177                 for sheet in self.browse(cr, uid, ids, context):
178                         if DateTime.strptime(sheet.date_current, '%Y-%m-%d') <= DateTime.strptime(sheet.date_from, '%Y-%m-%d'):
179                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_from,})
180                         elif DateTime.strptime(sheet.date_current, '%Y-%m-%d') >= DateTime.strptime(sheet.date_to, '%Y-%m-%d'):
181                                 self.write(cr, uid, [sheet.id], {'date_current': sheet.date_to,})
182                 return True
183
184         def sign_in(self, cr, uid, ids, context):
185                 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
186                         raise osv.except_osv('Error !', 'You can not sign in from an other date than today')
187                 emp_obj = self.pool.get('hr.employee')
188                 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
189                 context['sheet_id']=ids[0]
190                 success = emp_obj.sign_in(cr, uid, emp_id, context=context)
191                 return True
192
193         def sign_out(self, cr, uid, ids, context):
194                 if not self.browse(cr, uid, ids, context)[0].date_current == time.strftime('%Y-%m-%d'):
195                         raise osv.except_osv('Error !', 'You can not sign out from an other date than today')
196                 emp_obj = self.pool.get('hr.employee')
197                 emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)])
198                 context['sheet_id']=ids[0]
199                 success = emp_obj.sign_out(cr, uid, emp_id, context=context)
200                 return True
201
202         _columns = {
203                 'name': fields.char('Description', size=64, select=1),
204                 'user_id': fields.many2one('res.users', 'User', required=True, select=1),
205                 'date_from': fields.date('Date from', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
206                 'date_to': fields.date('Date to', required=True, select=1, readonly=True, states={'new':[('readonly', False)]}),
207                 'date_current': fields.date('Current date', required=True),
208                 'timesheet_ids' : one2many_mod('hr.analytic.timesheet', 'sheet_id',
209                         'Timesheet lines', domain=[('date', '=', time.strftime('%Y-%m-%d'))],
210                         readonly=True, states={
211                                 'draft': [('readonly', False)],
212                                 'new': [('readonly', False)]}
213                         ),
214                 'attendances_ids' : one2many_mod2('hr.attendance', 'sheet_id', 'Attendances', readonly=True, states={'draft':[('readonly',False)],'new':[('readonly',False)]}),
215                 'state' : fields.selection([('new', 'New'),('draft','Draft'),('confirm','Confirmed'),('done','Done')], 'state', select=True, required=True, readonly=True),
216                 'state_attendance' : fields.function(_state_attendance, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present'),('none','No employee defined')], string='Current state'),
217                 'total_attendance_day': fields.function(_total_day, method=True, string='Total Attendance'),
218                 'total_timesheet_day': fields.function(_total_day, method=True, string='Total Timesheet'),
219                 'total_difference_day': fields.function(_total_day, method=True, string='Difference'),
220                 'total_attendance': fields.function(_total, method=True, string='Total Attendance'),
221                 'total_timesheet': fields.function(_total, method=True, string='Total Timesheet'),
222                 'total_difference': fields.function(_total, method=True, string='Difference'),
223                 'period_ids': fields.one2many('hr_timesheet_sheet.sheet.day', 'sheet_id', 'Period', readonly=True),
224                 'account_ids': fields.one2many('hr_timesheet_sheet.sheet.account', 'sheet_id', 'Analytic accounts', readonly=True),
225         }
226
227         def _default_date_from(self,cr, uid, context={}):
228                 user = self.pool.get('res.users').browse(cr, uid, uid, context)
229                 r = user.company_id and user.company_id.timesheet_range or 'month'
230                 if r=='month':
231                         return time.strftime('%Y-%m-01')
232                 elif r=='week':
233                         return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d')
234                 elif r=='year':
235                         return time.strftime('%Y-01-01')
236                 return time.strftime('%Y-%m-%d')
237
238         def _default_date_to(self,cr, uid, context={}):
239                 user = self.pool.get('res.users').browse(cr, uid, uid, context)
240                 r = user.company_id and user.company_id.timesheet_range or 'month'
241                 if r=='month':
242                         return (DateTime.now() + DateTime.RelativeDateTime(months=+1,day=1,days=-1)).strftime('%Y-%m-%d')
243                 elif r=='week':
244                         return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d')
245                 elif r=='year':
246                         return time.strftime('%Y-12-31')
247                 return time.strftime('%Y-%m-%d')
248
249         _defaults = {
250                 'user_id': lambda self,cr,uid,c: uid,
251                 'date_from' : _default_date_from,
252                 'date_current' : lambda *a: time.strftime('%Y-%m-%d'),
253                 'date_to' : _default_date_to,
254                 'state': lambda *a: 'new',
255         }
256
257         def _sheet_date(self, cr, uid, ids):
258                 for sheet in self.browse(cr, uid, ids):
259                         cr.execute('SELECT id \
260                                         FROM hr_timesheet_sheet_sheet \
261                                         WHERE (date_from < %s and %s < date_to) \
262                                                 AND user_id=%d \
263                                                 AND id <> %d', (sheet.date_to, sheet.date_from,
264                                                         sheet.user_id.id, sheet.id))
265                         if cr.fetchall():
266                                 return False
267                 return True
268
269         _constraints = [
270                 (_sheet_date, 'You can not have 2 timesheets that overlaps !', ['date_from','date_to'])
271         ]
272
273         def action_set_to_draft(self, cr, uid, ids, *args):
274                 self.write(cr, uid, ids, {'state': 'draft'})
275                 wf_service = netsvc.LocalService('workflow')
276                 for id in ids:
277                         wf_service.trg_create(uid, self._name, id, cr)
278                 return True
279
280         def name_get(self, cr, uid, ids, context={}):
281                 if not len(ids):
282                         return []
283                 return [(r['id'], r['date_from'] + ' - ' + r['date_to']) \
284                                 for r in self.read(cr, uid, ids, ['date_from', 'date_to'],
285                                         context, load='_classic_write')]
286
287 hr_timesheet_sheet()
288
289
290 class hr_timesheet_line(osv.osv):
291         _inherit = "hr.analytic.timesheet"
292
293         def _get_default_date(self, cr, uid, context={}):
294                 if 'date' in context:
295                         return context['date']
296                 return time.strftime('%Y-%m-%d')
297
298         def _sheet(self, cursor, user, ids, name, args, context):
299                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
300
301                 cursor.execute('SELECT l.id, COALESCE(MAX(s.id), 0) \
302                                 FROM hr_timesheet_sheet_sheet s \
303                                         LEFT JOIN (hr_analytic_timesheet l \
304                                                 LEFT JOIN account_analytic_line al \
305                                                         ON (l.line_id = al.id)) \
306                                                 ON (s.date_to >= al.date \
307                                                         AND s.date_from <= al.date \
308                                                         AND s.user_id = al.user_id) \
309                                 WHERE l.id in (' + ','.join([str(x) for x in ids]) + ') \
310                                 GROUP BY l.id')
311                 res = dict(cursor.fetchall())
312                 sheet_names = {}
313                 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
314                                 context=context):
315                         sheet_names[sheet_id] = name
316
317                 for line_id in ids:
318                         sheet_id = res.get(line_id, False)
319                         if sheet_id:
320                                 res[line_id] = (sheet_id, sheet_names[sheet_id])
321                         else:
322                                 res[line_id] = False
323                 return res
324
325         def _sheet_search(self, cursor, user, obj, name, args):
326                 if not len(args):
327                         return []
328                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
329
330                 i = 0
331                 while i < len(args):
332                         fargs = args[i][0].split('.', 1)
333                         if len(fargs) > 1:
334                                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
335                                         [(fargs[1], args[i][1], args[i][2])]))
336                                 i += 1
337                                 continue
338                         if isinstance(args[i][2], basestring):
339                                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
340                                                 args[i][1])
341                                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
342                         i += 1
343                 qu1, qu2 = [], []
344                 for x in args:
345                         if x[1] != 'in':
346                                 if (x[2] is False) and (x[1] == '='):
347                                         qu1.append('(s.id IS NULL)')
348                                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
349                                         qu1.append('(s.id IS NOT NULL)')
350                                 else:
351                                         qu1.append('(s.id %s %s)' % (x[1], '%d'))
352                                         qu2.append(x[2])
353                         elif x[1] == 'in':
354                                 if len(x[2]) > 0:
355                                         qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
356                                         qu2 += x[2]
357                                 else:
358                                         qu1.append('(False)')
359                 if len(qu1):
360                         qu1 = ' WHERE ' + ' AND '.join(qu1)
361                 else:
362                         qu1 = ''
363                 cursor.execute('SELECT l.id \
364                                 FROM hr_timesheet_sheet_sheet s \
365                                         LEFT JOIN (hr_analytic_timesheet l \
366                                                 LEFT JOIN account_analytic_line al \
367                                                         ON (l.line_id = al.id)) \
368                                                 ON (s.date_to >= al.date \
369                                                         AND s.date_from <= al.date \
370                                                         AND s.user_id = al.user_id)' + \
371                                 qu1, qu2)
372                 res = cursor.fetchall()
373                 if not len(res):
374                         return [('id', '=', '0')]
375                 return [('id', 'in', [x[0] for x in res])]
376
377         _columns = {
378                 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
379                         type='many2one', relation='hr_timesheet_sheet.sheet',
380                         fnct_search=_sheet_search),
381         }
382         _defaults = {
383                 'date': _get_default_date,
384         }
385
386         def create(self, cr, uid, vals, *args, **kwargs):
387                 if 'sheet_id' in vals:
388                         ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
389                         if not ts.state in ('draft', 'new'):
390                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
391                 return super(hr_timesheet_line,self).create(cr, uid, vals, *args, **kwargs)
392
393         def unlink(self, cr, uid, ids, *args, **kwargs):
394                 self._check(cr, uid, ids)
395                 return super(hr_timesheet_line,self).unlink(cr, uid, ids,*args, **kwargs)
396
397         def write(self, cr, uid, ids, *args, **kwargs):
398                 self._check(cr, uid, ids)
399                 return super(hr_timesheet_line,self).write(cr, uid, ids,*args, **kwargs)
400
401         def _check(self, cr, uid, ids):
402                 for att in self.browse(cr, uid, ids):
403                         if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
404                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
405                 return True
406
407 hr_timesheet_line()
408
409 class hr_attendance(osv.osv):
410         _inherit = "hr.attendance"
411
412         def _get_default_date(self, cr, uid, context={}):
413                 if 'name' in context:
414                         return context['name'] + time.strftime(' %H:%M:%S')
415                 return time.strftime('%Y-%m-%d %H:%M:%S')
416
417         def _sheet(self, cursor, user, ids, name, args, context):
418                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
419
420                 cursor.execute('SELECT a.id, COALESCE(MAX(s.id), 0) \
421                                 FROM hr_timesheet_sheet_sheet s \
422                                         LEFT JOIN (hr_attendance a \
423                                                 LEFT JOIN hr_employee e \
424                                                         ON (a.employee_id = e.id)) \
425                                                 ON (s.date_to >= a.name \
426                                                         AND s.date_from <= a.name \
427                                                         AND s.user_id = e.user_id) \
428                                 WHERE a.id in (' + ','.join([str(x) for x in ids]) + ') \
429                                 GROUP BY a.id')
430                 res = dict(cursor.fetchall())
431                 sheet_names = {}
432                 for sheet_id, name in sheet_obj.name_get(cursor, user, res.values(),
433                                 context=context):
434                         sheet_names[sheet_id] = name
435
436                 for line_id in ids:
437                         sheet_id = res.get(line_id, False)
438                         if sheet_id:
439                                 res[line_id] = (sheet_id, sheet_names[sheet_id])
440                         else:
441                                 res[line_id] = False
442                 return res
443
444         def _sheet_search(self, cursor, user, obj, name, args):
445                 if not len(args):
446                         return []
447                 sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
448
449                 i = 0
450                 while i < len(args):
451                         fargs = args[i][0].split('.', 1)
452                         if len(fargs) > 1:
453                                 args[i] = (fargs[0], 'in', sheet_obj.search(cursor, user,
454                                         [(fargs[1], args[i][1], args[i][2])]))
455                                 i += 1
456                                 continue
457                         if isinstance(args[i][2], basestring):
458                                 res_ids = sheet_obj.name_search(cursor, user, args[i][2], [],
459                                                 args[i][1])
460                                 args[i] = (args[i][0], 'in', [x[0] for x in res_ids])
461                         i += 1
462                 qu1, qu2 = [], []
463                 for x in args:
464                         if x[1] != 'in':
465                                 if (x[2] is False) and (x[1] == '='):
466                                         qu1.append('(s.id IS NULL)')
467                                 elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='):
468                                         qu1.append('(s.id IS NOT NULL)')
469                                 else:
470                                         qu1.append('(s.id %s %s)' % (x[1], '%d'))
471                                         qu2.append(x[2])
472                         elif x[1] == 'in':
473                                 if len(x[2]) > 0:
474                                         qu1.append('(s.id in (%s))' % (','.join(['%d'] * len(x[2]))))
475                                         qu2 += x[2]
476                                 else:
477                                         qu1.append('(False)')
478                 if len(qu1):
479                         qu1 = ' WHERE ' + ' AND '.join(qu1)
480                 else:
481                         qu1 = ''
482                 cursor.execute('SELECT a.id\
483                                 FROM hr_timesheet_sheet_sheet s \
484                                         LEFT JOIN (hr_attendance a \
485                                                 LEFT JOIN hr_employee e \
486                                                         ON (a.employee_id = e.id)) \
487                                                 ON (s.date_to >= a.name \
488                                                         AND s.date_from <= a.name \
489                                                         AND s.user_id = e.user_id) ' + \
490                                 qu1, qu2)
491                 res = cursor.fetchall()
492                 if not len(res):
493                         return [('id', '=', '0')]
494                 return [('id', 'in', [x[0] for x in res])]
495
496         _columns = {
497                 'sheet_id': fields.function(_sheet, method=True, string='Sheet',
498                         type='many2one', relation='hr_timesheet_sheet.sheet',
499                         fnct_search=_sheet_search),
500         }
501         _defaults = {
502                 'name': _get_default_date,
503         }
504
505         def create(self, cr, uid, vals, context={}):
506                 if 'sheet_id' in context:
507                         vals['sheet_id']=context['sheet_id']
508                 if 'sheet_id' in vals:
509                         ts = self.pool.get('hr_timesheet_sheet.sheet').browse(cr, uid, vals['sheet_id'])
510                         if ts.state not in ('draft', 'new'):
511                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
512                 return super(hr_attendance,self).create(cr, uid, vals, context=context)
513
514         def unlink(self, cr, uid, ids, *args, **kwargs):
515                 self._check(cr, uid, ids)
516                 return super(hr_attendance,self).unlink(cr, uid, ids,*args, **kwargs)
517
518         def write(self, cr, uid, ids, vals, context={}):
519                 if 'sheet_id' in context:
520                         vals['sheet_id']=context['sheet_id']
521                 self._check(cr, uid, ids)
522                 return super(hr_attendance,self).write(cr, uid, ids, vals, context=context)
523
524         def _check(self, cr, uid, ids):
525                 for att in self.browse(cr, uid, ids):
526                         if att.sheet_id and att.sheet_id.state not in ('draft', 'new'):
527                                 raise osv.except_osv('Error !', 'You can not modify an entry in a confirmed timesheet !')
528                 return True
529
530 hr_attendance()
531
532 class hr_timesheet_sheet_sheet_day(osv.osv):
533         _name = "hr_timesheet_sheet.sheet.day"
534         _description = "Timesheets by period"
535         _auto = False
536         _order='name'
537         _columns = {
538                 'name': fields.date('Date', readonly=True),
539                 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True, select="1"),
540                 'total_timesheet': fields.float('Project Timesheet', readonly=True),
541                 'total_attendance': fields.float('Attendance', readonly=True),
542                 'total_difference': fields.float('Difference', readonly=True),
543         }
544
545         def init(self, cr):
546                 cr.execute("""create or replace view hr_timesheet_sheet_sheet_day as
547                         SELECT
548                                 id,
549                                 name,
550                                 sheet_id,
551                                 total_timesheet,
552                                 total_attendance,
553                                 (total_attendance - total_timesheet) AS total_difference
554                         FROM
555                                 ((
556                                         SELECT
557                                                 MAX(id) as id,
558                                                 name,
559                                                 sheet_id,
560                                                 SUM(total_timesheet) as total_timesheet,
561                                                 CASE WHEN SUM(total_attendance) < 0
562                                                         THEN (SUM(total_attendance) +
563                                                                 CASE WHEN current_date <> name
564                                                                         THEN 1440
565                                                                         ELSE (EXTRACT(hour FROM current_time) * 60) + EXTRACT(minute FROM current_time)
566                                                                 END
567                                                                 )
568                                                         ELSE SUM(total_attendance)
569                                                 END /60  as total_attendance
570                                         FROM
571                                                 ((
572                                                         select
573                                                                 min(hrt.id) as id,
574                                                                 l.date::date as name,
575                                                                 s.id as sheet_id,
576                                                                 sum(l.unit_amount) as total_timesheet,
577                                                                 0.0 as total_attendance
578                                                         from
579                                                                 hr_analytic_timesheet hrt
580                                                                 left join (account_analytic_line l
581                                                                         LEFT JOIN hr_timesheet_sheet_sheet s
582                                                                         ON (s.date_to >= l.date
583                                                                                 AND s.date_from <= l.date
584                                                                                 AND s.user_id = l.user_id))
585                                                                         on (l.id = hrt.line_id)
586                                                         group by l.date::date, s.id
587                                                 ) union (
588                                                         select
589                                                                 -min(a.id) as id,
590                                                                 a.name::date as name,
591                                                                 s.id as sheet_id,
592                                                                 0.0 as total_timesheet,
593                                                                 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
594                                                         from
595                                                                 hr_attendance a
596                                                                 LEFT JOIN (hr_timesheet_sheet_sheet s
597                                                                         LEFT JOIN hr_employee e
598                                                                         ON (s.user_id = e.user_id))
599                                                                 ON (a.employee_id = e.id
600                                                                         AND s.date_to >= a.name
601                                                                         AND s.date_from <= a.name)
602                                                         WHERE action in ('sign_in', 'sign_out')
603                                                         group by a.name::date, s.id
604                                                 )) AS foo
605                                                 GROUP BY name, sheet_id
606                                 )) AS bar""")
607
608 hr_timesheet_sheet_sheet_day()
609
610
611 class hr_timesheet_sheet_sheet_account(osv.osv):
612         _name = "hr_timesheet_sheet.sheet.account"
613         _description = "Timesheets by period"
614         _auto = False
615         _order='name'
616         _columns = {
617                 'name': fields.many2one('account.analytic.account', 'Analytic Account', readonly=True),
618                 'sheet_id': fields.many2one('hr_timesheet_sheet.sheet', 'Sheet', readonly=True),
619                 'total': fields.float('Total Time', digits=(16,2), readonly=True),
620                 'invoice_rate': fields.many2one('hr_timesheet_invoice.factor', 'Invoice rate', readonly=True),
621         }
622
623         def init(self, cr):
624                 cr.execute("""create or replace view hr_timesheet_sheet_sheet_account as (
625                         select
626                                 min(hrt.id) as id,
627                                 l.account_id as name,
628                                 s.id as sheet_id,
629                                 sum(l.unit_amount) as total,
630                                 l.to_invoice as invoice_rate
631                         from
632                                 hr_analytic_timesheet hrt
633                                 left join (account_analytic_line l
634                                         LEFT JOIN hr_timesheet_sheet_sheet s
635                                                 ON (s.date_to >= l.date
636                                                         AND s.date_from <= l.date
637                                                         AND s.user_id = l.user_id))
638                                         on (l.id = hrt.line_id)
639                         group by l.account_id, s.id, l.to_invoice
640                 )""")
641
642 hr_timesheet_sheet_sheet_account()
643
644
645 class res_company(osv.osv):
646         _inherit = 'res.company'
647         _columns = {
648                 'timesheet_range': fields.selection([('day','Day'),('week','Week'),('month','Month'),('year','Year')], 'Timeshet range'),
649                 'timesheet_max_difference': fields.float('Timesheet allowed difference', help="Allowed difference between the sign in/out and the timesheet computation for one sheet. Set this to 0 if you do not want any control."),
650         }
651         _defaults = {
652                 'timesheet_range': lambda *args: 'month',
653                 'timesheet_max_difference': lambda *args: 0.0
654         }
655
656 res_company()