16f3530c1e9f85733f665df7d8af1125c84c4201
[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 osv import fields, osv
25 from 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 hr_action_reason()
39
40 def _employee_get(obj, cr, uid, context=None):
41     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
42     return ids and ids[0] or False
43
44 class hr_attendance(osv.osv):
45     _name = "hr.attendance"
46     _description = "Attendance"
47
48     def _day_compute(self, cr, uid, ids, fieldnames, args, context=None):
49         res = dict.fromkeys(ids, '')
50         for obj in self.browse(cr, uid, ids, context=context):
51             res[obj.id] = time.strftime('%Y-%m-%d', time.strptime(obj.name, '%Y-%m-%d %H:%M:%S'))
52         return res
53
54     _columns = {
55         'name': fields.datetime('Date', required=True, select=1),
56         'action': fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'), ('action','Action')], 'Action', required=True),
57         '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.'),
58         'employee_id': fields.many2one('hr.employee', "Employee's Name", required=True, select=True),
59         'day': fields.function(_day_compute, type='char', string='Day', store=True, select=1, size=32),
60     }
61     _defaults = {
62         '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
63         'employee_id': _employee_get,
64     }
65
66     def _altern_si_so(self, cr, uid, ids, context=None):
67         """ Alternance sign_in/sign_out check.
68             Previous (if exists) must be of opposite action.
69             Next (if exists) must be of opposite action.
70         """
71         for att in self.browse(cr, uid, ids, context=context):
72             # search and browse for first previous and first next records
73             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')
74             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')
75             prev_atts = self.browse(cr, uid, prev_att_ids, context=context)
76             next_atts = self.browse(cr, uid, next_add_ids, context=context)
77             # check for alternance, return False if at least one condition is not satisfied
78             if prev_atts and prev_atts[0].action == att.action: # previous exists and is same action
79                 return False
80             if next_atts and next_atts[0].action == att.action: # next exists and is same action
81                 return False
82             if (not prev_atts) and (not next_atts) and att.action != 'sign_in': # first attendance must be sign_in
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
89 hr_attendance()
90
91 class hr_employee(osv.osv):
92     _inherit = "hr.employee"
93     _description = "Employee"
94
95     def _state(self, cr, uid, ids, name, args, context=None):
96         result = {}
97         if not ids:
98             return result
99         for id in ids:
100             result[id] = 'absent'
101         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
102                 FROM ( \
103                     SELECT MAX(name) AS name, employee_id \
104                     FROM hr_attendance \
105                     WHERE action in (\'sign_in\', \'sign_out\') \
106                     GROUP BY employee_id \
107                 ) AS foo \
108                 LEFT JOIN hr_attendance \
109                     ON (hr_attendance.employee_id = foo.employee_id \
110                         AND hr_attendance.name = foo.name) \
111                 WHERE hr_attendance.employee_id IN %s',(tuple(ids),))
112         for res in cr.fetchall():
113             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
114         return result
115
116     _columns = {
117        'state': fields.function(_state, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
118     }
119
120     def _action_check(self, cr, uid, emp_id, dt=False, context=None):
121         cr.execute('SELECT MAX(name) FROM hr_attendance WHERE employee_id=%s', (emp_id,))
122         res = cr.fetchone()
123         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
124
125     def attendance_action_change(self, cr, uid, ids, type='action', context=None, dt=False, *args):
126         obj_attendance = self.pool.get('hr.attendance')
127         id = False
128         warning_sign = 'sign'
129         res = {}
130
131         #Special case when button calls this method: type=context
132         if isinstance(type, dict):
133             type = type.get('type','action')
134         if type == 'sign_in':
135             warning_sign = "Sign In"
136         elif type == 'sign_out':
137             warning_sign = "Sign Out"
138         for emp in self.read(cr, uid, ids, ['id'], context=context):
139             if not self._action_check(cr, uid, emp['id'], dt, context):
140                 raise osv.except_osv(_('Warning !'), _('You tried to %s with a date anterior to another event !\nTry to contact the administrator to correct attendances.')%(warning_sign,))
141
142             res = {'action': type, 'employee_id': emp['id']}
143             if dt:
144                 res['name'] = dt
145         id = obj_attendance.create(cr, uid, res, context=context)
146
147         if type != 'action':
148             return id
149         return True
150
151 hr_employee()
152
153 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: