merge pso branch
[odoo/odoo.git] / addons / hr_attendance / hr_attendance.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 from mx import DateTime
32 import time
33
34 from osv import fields, osv
35 from tools.translate import _
36
37 class hr_action_reason(osv.osv):
38     _name = "hr.action.reason"
39     _description = "Action reason"
40     _columns = {
41         'name' : fields.char('Reason', size=64, required=True),
42         'action_type' : fields.selection([('sign_in', 'Sign in'), ('sign_out', 'Sign out')], "Action's type"),
43     }
44     _defaults = {
45         'action_type' : lambda *a: 'sign_in',
46     }
47 hr_action_reason()
48
49 def _employee_get(obj,cr,uid,context={}):
50     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
51     if ids:
52         return ids[0]
53     return False
54
55 class hr_attendance(osv.osv):
56     _name = "hr.attendance"
57     _description = "Attendance"
58     _columns = {
59         'name' : fields.datetime('Date', required=True),
60         'action' : fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'),('action','Action')], 'Action', required=True),
61         'action_desc' : fields.many2one("hr.action.reason", "Action reason", domain="[('action_type', '=', action)]"),
62         'employee_id' : fields.many2one('hr.employee', 'Employee', required=True, select=True),
63     }
64     _defaults = {
65         'name' : lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
66         'employee_id' : _employee_get,
67     }
68     
69     def _altern_si_so(self, cr, uid, ids):
70         for id in ids:
71             sql = '''
72             select action, name
73             from hr_attendance as att
74             where employee_id = (select employee_id from hr_attendance where id=%s)
75             and action in ('sign_in','sign_out')
76             and name <= (select name from hr_attendance where id=%s)
77             order by name desc
78             limit 2
79             ''' % (id, id)
80             cr.execute(sql)
81             atts = cr.fetchall()
82             if not ((len(atts)==1 and atts[0][0] == 'sign_in') or (atts[0][0] != atts[1][0] and atts[0][1] != atts[1][1])):
83                 return False
84         return True
85     
86     _constraints = [(_altern_si_so, 'Error: Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
87     _order = 'name desc'
88 hr_attendance()
89
90 class hr_employee(osv.osv):
91     _inherit = "hr.employee"
92     _description = "Employee"
93     
94     def _state(self, cr, uid, ids, name, args, context={}):
95         result = {}
96         for id in ids:
97             result[id] = 'absent'
98         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
99                 FROM ( \
100                     SELECT MAX(name) AS name, employee_id \
101                     FROM hr_attendance \
102                     WHERE action in (\'sign_in\', \'sign_out\') \
103                     GROUP BY employee_id \
104                 ) AS foo \
105                 LEFT JOIN hr_attendance \
106                     ON (hr_attendance.employee_id = foo.employee_id \
107                         AND hr_attendance.name = foo.name) \
108                 WHERE hr_attendance.employee_id \
109                     in (' + ','.join([str(x) for x in ids]) + ')')
110         for res in cr.fetchall():
111             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
112         return result
113     
114     _columns = {
115        'state': fields.function(_state, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
116      }
117     
118     def sign_change(self, cr, uid, ids, context={}, dt=False):
119         for emp in self.browse(cr, uid, ids):
120             if not self._action_check(cr, uid, emp.id, dt, context):
121                 raise osv.except_osv(_('Warning'), _('You tried to sign with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
122             res = {'action':'action', 'employee_id':emp.id}
123             if dt:
124                 res['name'] = dt
125             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
126         return True
127
128     def sign_out(self, cr, uid, ids, context={}, dt=False, *args):
129         id = False
130         for emp in self.browse(cr, uid, ids):
131             if not self._action_check(cr, uid, emp.id, dt, context):
132                 raise osv.except_osv(_('Warning'), _('You tried to sign out with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
133             res = {'action':'sign_out', 'employee_id':emp.id}
134             if dt:
135                 res['name'] = dt
136             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
137             id = att_id
138         return id
139
140     def _action_check(self, cr, uid, emp_id, dt=False,context={}):
141         cr.execute('select max(name) from hr_attendance where employee_id=%d', (emp_id,))
142         res = cr.fetchone()
143         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
144
145     def sign_in(self, cr, uid, ids, context={}, dt=False, *args):
146         id = False
147         for emp in self.browse(cr, uid, ids):
148             if not self._action_check(cr, uid, emp.id, dt, context):
149                 raise osv.except_osv(_('Warning'), _('You tried to sign in with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
150             res = {'action':'sign_in', 'employee_id':emp.id}
151             if dt:
152                 res['name'] = dt
153             id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
154         return id
155     
156 hr_employee()
157     
158 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: