[IMP]Removed assigned grades.
[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
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26
27 class hr_action_reason(osv.osv):
28     _name = "hr.action.reason"
29     _description = "Action Reason"
30     _columns = {
31         'name': fields.char('Reason', size=64, required=True, help='Specifies the reason for Signing In/Signing Out.'),
32         'action_type': fields.selection([('sign_in', 'Sign in'), ('sign_out', 'Sign out')], "Action Type"),
33     }
34     _defaults = {
35         'action_type': 'sign_in',
36     }
37
38
39 def _employee_get(obj, cr, uid, context=None):
40     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
41     return ids and ids[0] or False
42
43 class hr_attendance(osv.osv):
44     _name = "hr.attendance"
45     _description = "Attendance"
46
47     def _day_compute(self, cr, uid, ids, fieldnames, args, context=None):
48         res = dict.fromkeys(ids, '')
49         for obj in self.browse(cr, uid, ids, context=context):
50             res[obj.id] = time.strftime('%Y-%m-%d', time.strptime(obj.name, '%Y-%m-%d %H:%M:%S'))
51         return res
52
53     _columns = {
54         'name': fields.datetime('Date', required=True, select=1),
55         'action': fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'), ('action','Action')], 'Action', required=True),
56         '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.'),
57         'employee_id': fields.many2one('hr.employee', "Employee", required=True, select=True),
58         'day': fields.function(_day_compute, type='char', string='Day', store=True, select=1, size=32),
59     }
60     _defaults = {
61         '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
62         'employee_id': _employee_get,
63     }
64
65     def _altern_si_so(self, cr, uid, ids, context=None):
66         """ Alternance sign_in/sign_out check.
67             Previous (if exists) must be of opposite action.
68             Next (if exists) must be of opposite action.
69         """
70         for att in self.browse(cr, uid, ids, context=context):
71             # search and browse for first previous and first next records
72             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')
73             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')
74             prev_atts = self.browse(cr, uid, prev_att_ids, context=context)
75             next_atts = self.browse(cr, uid, next_add_ids, context=context)
76             # check for alternance, return False if at least one condition is not satisfied
77             if prev_atts and prev_atts[0].action == att.action: # previous exists and is same action
78                 return False
79             if next_atts and next_atts[0].action == att.action: # next exists and is same action
80                 return False
81             if (not prev_atts) and (not next_atts) and att.action != 'sign_in': # first attendance must be sign_in
82                 return False
83         return True
84
85     _constraints = [(_altern_si_so, 'Error ! Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
86     _order = 'name desc'
87
88
89 class hr_employee(osv.osv):
90     _inherit = "hr.employee"
91     _description = "Employee"
92
93     def _state(self, cr, uid, ids, name, args, context=None):
94         result = {}
95         if not ids:
96             return result
97         for id in ids:
98             result[id] = 'absent'
99         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
100                 FROM ( \
101                     SELECT MAX(name) AS name, employee_id \
102                     FROM hr_attendance \
103                     WHERE action in (\'sign_in\', \'sign_out\') \
104                     GROUP BY employee_id \
105                 ) AS foo \
106                 LEFT JOIN hr_attendance \
107                     ON (hr_attendance.employee_id = foo.employee_id \
108                         AND hr_attendance.name = foo.name) \
109                 WHERE hr_attendance.employee_id IN %s',(tuple(ids),))
110         for res in cr.fetchall():
111             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
112         return result
113     
114     def _last_sign(self, cr, uid, ids, name, args, context=None):
115         result = {}
116         if not ids:
117             return result
118         for id in ids:
119             result[id] = False
120             cr.execute("""select max(name) as name
121                         from hr_attendance
122                         where action in ('sign_in', 'sign_out') and employee_id = %s""",(id,))
123             for res in cr.fetchall():
124                 result[id] = res[0]
125         return result
126
127     def _attendance_access(self, cr, uid, ids, name, args, context=None):
128         # this function field use to hide attendance button to singin/singout from menu
129         group = self.pool.get('ir.model.data').get_object(cr, uid, 'base', 'group_hr_attendance')
130         visible = False
131         if uid in [user.id for user in group.users]:
132             visible = True
133         return dict([(x, visible) for x in ids])
134
135     _columns = {
136        'state': fields.function(_state, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
137        'last_sign': fields.function(_last_sign, type='datetime', string='Last Sign'),
138        'attendance_access': fields.function(_attendance_access, string='Attendance Access', type='boolean'),
139     }
140
141     def _action_check(self, cr, uid, emp_id, dt=False, context=None):
142         cr.execute('SELECT MAX(name) FROM hr_attendance WHERE employee_id=%s', (emp_id,))
143         res = cr.fetchone()
144         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
145
146     def attendance_action_change(self, cr, uid, ids, context=None):
147         if context is None:
148             context = {}
149         action_date = context.get('action_date', False)
150         action = context.get('action', False)
151         hr_attendance = self.pool.get('hr.attendance')
152         warning_sign = {'sign_in': _('Sign In'), 'sign_out': _('Sign Out')}
153         for employee in self.browse(cr, uid, ids, context=context):
154             if not action:
155                 if employee.state == 'present': action = 'sign_out'
156                 if employee.state == 'absent': action = 'sign_in'
157
158             if not self._action_check(cr, uid, employee.id, action_date, context):
159                 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],))
160
161             vals = {'action': action, 'employee_id': employee.id}
162             if action_date:
163                 vals['name'] = action_date
164             hr_attendance.create(cr, uid, vals, context=context)
165         return True
166
167
168 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: