make new module named hr_attendance
[odoo/odoo.git] / addons / hr_attendance / hr_attendance.py
1 from mx import DateTime
2 import time
3
4 from osv import fields, osv
5 from tools.translate import _
6
7 class hr_action_reason(osv.osv):
8     _name = "hr.action.reason"
9     _description = "Action reason"
10     _columns = {
11         'name' : fields.char('Reason', size=64, required=True),
12         'action_type' : fields.selection([('sign_in', 'Sign in'), ('sign_out', 'Sign out')], "Action's type"),
13     }
14     _defaults = {
15         'action_type' : lambda *a: 'sign_in',
16     }
17 hr_action_reason()
18
19 def _employee_get(obj,cr,uid,context={}):
20     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
21     if ids:
22         return ids[0]
23     return False
24
25 class hr_attendance(osv.osv):
26     _name = "hr.attendance"
27     _description = "Attendance"
28     _columns = {
29         'name' : fields.datetime('Date', required=True),
30         'action' : fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'),('action','Action')], 'Action', required=True),
31         'action_desc' : fields.many2one("hr.action.reason", "Action reason", domain="[('action_type', '=', action)]"),
32         'employee_id' : fields.many2one('hr.employee', 'Employee', required=True, select=True),
33     }
34     _defaults = {
35         'name' : lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
36         'employee_id' : _employee_get,
37     }
38     
39     def _altern_si_so(self, cr, uid, ids):
40         for id in ids:
41             sql = '''
42             select action, name
43             from hr_attendance as att
44             where employee_id = (select employee_id from hr_attendance where id=%s)
45             and action in ('sign_in','sign_out')
46             and name <= (select name from hr_attendance where id=%s)
47             order by name desc
48             limit 2
49             ''' % (id, id)
50             cr.execute(sql)
51             atts = cr.fetchall()
52             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])):
53                 return False
54         return True
55     
56     _constraints = [(_altern_si_so, 'Error: Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
57     _order = 'name desc'
58 hr_attendance()
59
60 class hr_employee(osv.osv):
61     _inherit = "hr.employee"
62     _description = "Employee"
63     
64     def _state(self, cr, uid, ids, name, args, context={}):
65         result = {}
66         for id in ids:
67             result[id] = 'absent'
68         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
69                 FROM ( \
70                     SELECT MAX(name) AS name, employee_id \
71                     FROM hr_attendance \
72                     WHERE action in (\'sign_in\', \'sign_out\') \
73                     GROUP BY employee_id \
74                 ) AS foo \
75                 LEFT JOIN hr_attendance \
76                     ON (hr_attendance.employee_id = foo.employee_id \
77                         AND hr_attendance.name = foo.name) \
78                 WHERE hr_attendance.employee_id \
79                     in (' + ','.join([str(x) for x in ids]) + ')')
80         for res in cr.fetchall():
81             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
82         return result
83     
84     _columns = {
85        'state': fields.function(_state, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
86      }
87     
88     def sign_change(self, cr, uid, ids, context={}, dt=False):
89         for emp in self.browse(cr, uid, ids):
90             if not self._action_check(cr, uid, emp.id, dt, context):
91                 raise osv.except_osv(_('Warning'), _('You tried to sign with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
92             res = {'action':'action', 'employee_id':emp.id}
93             if dt:
94                 res['name'] = dt
95             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
96         return True
97
98     def sign_out(self, cr, uid, ids, context={}, dt=False, *args):
99         id = False
100         for emp in self.browse(cr, uid, ids):
101             if not self._action_check(cr, uid, emp.id, dt, context):
102                 raise osv.except_osv(_('Warning'), _('You tried to sign out with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
103             res = {'action':'sign_out', 'employee_id':emp.id}
104             if dt:
105                 res['name'] = dt
106             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
107             id = att_id
108         return id
109
110     def _action_check(self, cr, uid, emp_id, dt=False,context={}):
111         cr.execute('select max(name) from hr_attendance where employee_id=%d', (emp_id,))
112         res = cr.fetchone()
113         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
114
115     def sign_in(self, cr, uid, ids, context={}, dt=False, *args):
116         id = False
117         for emp in self.browse(cr, uid, ids):
118             if not self._action_check(cr, uid, emp.id, dt, context):
119                 raise osv.except_osv(_('Warning'), _('You tried to sign in with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
120             res = {'action':'sign_in', 'employee_id':emp.id}
121             if dt:
122                 res['name'] = dt
123             id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
124         return id
125     
126 hr_employee()
127     
128