[IMP] Clean hr_* module (Still need to done)
[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's type"),
33     }
34     _defaults = {
35         'action_type': 'sign_in',
36     }
37 hr_action_reason()
38
39 def _employee_get(obj, cr, uid, context=None):
40     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)])
41     if ids:
42         return ids[0]
43     return False
44
45 class hr_attendance(osv.osv):
46     _name = "hr.attendance"
47     _description = "Attendance"
48
49     def _day_compute(self, cr, uid, ids, fieldnames, args, context=None):
50         res = dict.fromkeys(ids, '')
51         for obj in self.browse(cr, uid, ids, context=context):
52             res[obj.id] = time.strftime('%Y-%m-%d', time.strptime(obj.name, '%Y-%m-%d %H:%M:%S'))
53         return res
54
55     _columns = {
56         'name': fields.datetime('Date', required=True, select=1),
57         'action': fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'), ('action','Action')], 'Action', required=True),
58         '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.'),
59         'employee_id': fields.many2one('hr.employee', "Employee's Name", required=True, select=True),
60         'day': fields.function(_day_compute, method=True, type='char', string='Day', store=True, select=1, size=32),
61     }
62     _defaults = {
63         'name': time.strftime('%Y-%m-%d %H:%M:%S'),
64         'employee_id': _employee_get,
65     }
66
67     def _altern_si_so(self, cr, uid, ids):
68         for id in ids:
69             sql = '''
70             select action, name
71             from hr_attendance as att
72             where employee_id = (select employee_id from hr_attendance where id=%s)
73             and action in ('sign_in','sign_out')
74             and name <= (select name from hr_attendance where id=%s)
75             order by name desc
76             limit 2 '''
77             cr.execute(sql,(id,id))
78             atts = cr.fetchall()
79             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])):
80                 return False
81         return True
82
83     _constraints = [(_altern_si_so, 'Error: Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
84     _order = 'name desc'
85 hr_attendance()
86
87 class hr_employee(osv.osv):
88     _inherit = "hr.employee"
89     _description = "Employee"
90
91     def _state(self, cr, uid, ids, name, args, context=None):
92         result = {}
93         for id in ids:
94             result[id] = 'absent'
95         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
96                 FROM ( \
97                     SELECT MAX(name) AS name, employee_id \
98                     FROM hr_attendance \
99                     WHERE action in (\'sign_in\', \'sign_out\') \
100                     GROUP BY employee_id \
101                 ) AS foo \
102                 LEFT JOIN hr_attendance \
103                     ON (hr_attendance.employee_id = foo.employee_id \
104                         AND hr_attendance.name = foo.name) \
105                 WHERE hr_attendance.employee_id IN %s',(tuple(ids),))
106         for res in cr.fetchall():
107             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
108         return result
109
110     _columns = {
111        'state': fields.function(_state, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
112      }
113
114     def _action_check(self, cr, uid, emp_id, dt=False, context=None):
115         cr.execute('select max(name) from hr_attendance where employee_id=%s', (emp_id,))
116         res = cr.fetchone()
117         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
118
119     def attendance_action_change(self, cr, uid, ids, type='action', context=None, dt=False, *args):
120         id = False
121         warning_sign = 'sign'
122
123         #Special case when button calls this method :type=context
124         if isinstance(type, dict):
125             type = type.get('type','action')
126         if type == 'sign_in':
127             warning_sign = "Sign In"
128         elif type == 'sign_out':
129             warning_sign = "Sign Out"
130
131         for emp in self.read(cr, uid, ids, ['id'], context=context):
132             if not self._action_check(cr, uid, emp['id'], dt, context):
133                 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,))
134
135             res = {'action': type, 'employee_id': emp['id']}
136
137             if dt:
138                 res['name'] = dt
139             id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
140
141         if type != 'action':
142             return id
143
144         return True
145
146 hr_employee()
147
148 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: