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