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