4887d41a52c1ff1ce1a7a0379d5b34db2cc839e8
[odoo/odoo.git] / addons / hr_attendance / hr_attendance.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 datetime import datetime
24
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27
28
29 class hr_action_reason(osv.osv):
30     _name = "hr.action.reason"
31     _description = "Action Reason"
32     _columns = {
33         'name': fields.char('Reason', required=True, help='Specifies the reason for Signing In/Signing Out.'),
34         'action_type': fields.selection([('sign_in', 'Sign in'), ('sign_out', 'Sign out')], "Action Type"),
35     }
36     _defaults = {
37         'action_type': 'sign_in',
38     }
39
40
41 def _employee_get(obj, cr, uid, context=None):
42     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
43     return ids and ids[0] or False
44
45
46 class hr_attendance(osv.osv):
47     _name = "hr.attendance"
48     _description = "Attendance"
49
50     def _worked_hours_compute(self, cr, uid, ids, fieldnames, args, context=None):
51         """For each hr.attendance record of action sign-in: assign 0.
52         For each hr.attendance record of action sign-out: assign number of hours since last sign-in.
53         """
54         res = {}
55         for obj in self.browse(cr, uid, ids, context=context):
56             if obj.action == 'sign_in':
57                 res[obj.id] = 0
58             elif obj.action == 'sign_out':
59                 # Get the associated sign-in
60                 last_signin_id = self.search(cr, uid, [
61                     ('employee_id', '=', obj.employee_id.id),
62                     ('name', '<', obj.name), ('action', '=', 'sign_in')
63                 ], limit=1, order='name DESC')
64                 if last_signin_id:
65                     last_signin = self.browse(cr, uid, last_signin_id, context=context)[0]
66
67                     # Compute time elapsed between sign-in and sign-out
68                     last_signin_datetime = datetime.strptime(last_signin.name, '%Y-%m-%d %H:%M:%S')
69                     signout_datetime = datetime.strptime(obj.name, '%Y-%m-%d %H:%M:%S')
70                     workedhours_datetime = (signout_datetime - last_signin_datetime)
71                     res[obj.id] = ((workedhours_datetime.seconds) / 60) / 60
72                 else:
73                     res[obj.id] = False
74         return res
75
76     _columns = {
77         'name': fields.datetime('Date', required=True, select=1),
78         'action': fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'), ('action','Action')], 'Action', required=True),
79         'action_desc': fields.many2one("hr.action.reason", "Action Reason", domain="[('action_type', '=', action)]", help='Specifies the reason for Signing In/Signing Out in case of extra hours.'),
80         'employee_id': fields.many2one('hr.employee', "Employee", required=True, select=True),
81         'worked_hours': fields.function(_worked_hours_compute, type='float', string='Worked Hours', store=True),
82     }
83     _defaults = {
84         'name': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), #please don't remove the lambda, if you remove it then the current time will not change
85         'employee_id': _employee_get,
86     }
87
88     def _altern_si_so(self, cr, uid, ids, context=None):
89         """ Alternance sign_in/sign_out check.
90             Previous (if exists) must be of opposite action.
91             Next (if exists) must be of opposite action.
92         """
93         for att in self.browse(cr, uid, ids, context=context):
94             # search and browse for first previous and first next records
95             prev_att_ids = self.search(cr, uid, [('employee_id', '=', att.employee_id.id), ('name', '<', att.name), ('action', 'in', ('sign_in', 'sign_out'))], limit=1, order='name DESC')
96             next_add_ids = self.search(cr, uid, [('employee_id', '=', att.employee_id.id), ('name', '>', att.name), ('action', 'in', ('sign_in', 'sign_out'))], limit=1, order='name ASC')
97             prev_atts = self.browse(cr, uid, prev_att_ids, context=context)
98             next_atts = self.browse(cr, uid, next_add_ids, context=context)
99             # check for alternance, return False if at least one condition is not satisfied
100             if prev_atts and prev_atts[0].action == att.action: # previous exists and is same action
101                 return False
102             if next_atts and next_atts[0].action == att.action: # next exists and is same action
103                 return False
104             if (not prev_atts) and (not next_atts) and att.action != 'sign_in': # first attendance must be sign_in
105                 return False
106         return True
107
108     _constraints = [(_altern_si_so, 'Error ! Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
109     _order = 'name desc'
110
111
112 class hr_employee(osv.osv):
113     _inherit = "hr.employee"
114     _description = "Employee"
115
116     def _state(self, cr, uid, ids, name, args, context=None):
117         result = {}
118         if not ids:
119             return result
120         for id in ids:
121             result[id] = 'absent'
122         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
123                 FROM ( \
124                     SELECT MAX(name) AS name, employee_id \
125                     FROM hr_attendance \
126                     WHERE action in (\'sign_in\', \'sign_out\') \
127                     GROUP BY employee_id \
128                 ) AS foo \
129                 LEFT JOIN hr_attendance \
130                     ON (hr_attendance.employee_id = foo.employee_id \
131                         AND hr_attendance.name = foo.name) \
132                 WHERE hr_attendance.employee_id IN %s',(tuple(ids),))
133         for res in cr.fetchall():
134             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
135         return result
136
137     def _last_sign(self, cr, uid, ids, name, args, context=None):
138         result = {}
139         if not ids:
140             return result
141         for id in ids:
142             result[id] = False
143             cr.execute("""select max(name) as name
144                         from hr_attendance
145                         where action in ('sign_in', 'sign_out') and employee_id = %s""",(id,))
146             for res in cr.fetchall():
147                 result[id] = res[0]
148         return result
149
150     def _attendance_access(self, cr, uid, ids, name, args, context=None):
151         # this function field use to hide attendance button to singin/singout from menu
152         group = self.pool.get('ir.model.data').get_object(cr, uid, 'base', 'group_hr_attendance')
153         visible = False
154         if uid in [user.id for user in group.users]:
155             visible = True
156         return dict([(x, visible) for x in ids])
157
158     _columns = {
159        'state': fields.function(_state, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
160        'last_sign': fields.function(_last_sign, type='datetime', string='Last Sign'),
161        'attendance_access': fields.function(_attendance_access, string='Attendance Access', type='boolean'),
162     }
163
164     def _action_check(self, cr, uid, emp_id, dt=False, context=None):
165         cr.execute('SELECT MAX(name) FROM hr_attendance WHERE employee_id=%s', (emp_id,))
166         res = cr.fetchone()
167         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
168
169     def attendance_action_change(self, cr, uid, ids, context=None):
170         if context is None:
171             context = {}
172         action_date = context.get('action_date', False)
173         action = context.get('action', False)
174         hr_attendance = self.pool.get('hr.attendance')
175         warning_sign = {'sign_in': _('Sign In'), 'sign_out': _('Sign Out')}
176         for employee in self.browse(cr, uid, ids, context=context):
177             if not action:
178                 if employee.state == 'present': action = 'sign_out'
179                 if employee.state == 'absent': action = 'sign_in'
180
181             if not self._action_check(cr, uid, employee.id, action_date, context):
182                 raise osv.except_osv(_('Warning'), _('You tried to %s with a date anterior to another event !\nTry to contact the HR Manager to correct attendances.')%(warning_sign[action],))
183
184             vals = {'action': action, 'employee_id': employee.id}
185             if action_date:
186                 vals['name'] = action_date
187             hr_attendance.create(cr, uid, vals, context=context)
188         return True
189
190
191 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: