replace tabs with 4 spaces
[odoo/odoo.git] / addons / hr / hr.py
1 ##############################################################################
2 #
3 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # $Id$
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 from mx import DateTime
31 import time
32
33 from osv import fields, osv
34 from tools.translate import _
35
36 class hr_timesheet_group(osv.osv):
37     _name = "hr.timesheet.group"
38     _description = "Working Time"
39     _columns = {
40         'name' : fields.char("Group name", size=64, required=True),
41         'timesheet_id' : fields.one2many('hr.timesheet', 'tgroup_id', 'Working Time'),
42         'manager' : fields.many2one('res.users', 'Workgroup manager'),
43     }
44     #
45     # TODO: improve; very slow !
46     #       bug if transition to another period
47     #
48     def interval_get(self, cr, uid, id, dt_from, hours, byday=True):
49         if not id:
50             return [(dt_from,dt_from+DateTime.RelativeDateTime(hours=int(hours)*3))]
51         todo = hours
52         cycle = 0
53         result = []
54         while todo>0:
55             cr.execute('select hour_from,hour_to from hr_timesheet where dayofweek=%d and tgroup_id=%d order by hour_from', (dt_from.day_of_week,id))
56             for (hour_from,hour_to) in cr.fetchall():
57                 h1,m1 = map(int,hour_from.split(':'))
58                 h2,m2 = map(int,hour_to.split(':'))
59                 d1 = DateTime.DateTime(dt_from.year,dt_from.month,dt_from.day,h1,m1)
60                 d2 = DateTime.DateTime(dt_from.year,dt_from.month,dt_from.day,h2,m2)
61                 if dt_from<d2:
62                     date1 = max(dt_from,d1)
63                     if date1+DateTime.RelativeDateTime(hours=todo)<=d2:
64                         result.append((date1, date1+DateTime.RelativeDateTime(hours=todo)))
65                         todo = 0
66                     else:
67                         todo -= (d2-date1).hours
68                         result.append((date1, d2))
69             dt_from = DateTime.DateTime(dt_from.year,dt_from.month,dt_from.day)+DateTime.RelativeDateTime(days=1)
70             cycle+=1
71             if cycle>7 and todo==hours:
72                 return [(dt_from,dt_from+DateTime.RelativeDateTime(hours=hours*3))]
73         if byday:
74             i = 1
75             while i<len(result):
76                 if (result[i][0]-result[i-1][1]).days<1:
77                     result[i-1]=(result[i-1][0],result[i][1])
78                     del result[i]
79                 else:
80                     i+=1
81         return result
82 hr_timesheet_group()
83
84
85 class hr_employee_category(osv.osv):
86     _name = "hr.employee.category"
87     _description = "Employee Category"
88     _columns = {
89         'name' : fields.char("Category", size=64, required=True),
90         'parent_id': fields.many2one('hr.employee.category', 'Parent category', select=True),
91         'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Childs Categories')
92     }
93 hr_employee_category()
94
95 class hr_employee(osv.osv):
96     _name = "hr.employee"
97     _description = "Employee"
98
99     def _state(self, cr, uid, ids, name, args, context={}):
100         result = {}
101         for id in ids:
102             result[id] = 'absent'
103         cr.execute('SELECT hr_attendance.action, hr_attendance.employee_id \
104                 FROM ( \
105                     SELECT MAX(name) AS name, employee_id \
106                     FROM hr_attendance \
107                     WHERE action in (\'sign_in\', \'sign_out\') \
108                     GROUP BY employee_id \
109                 ) AS foo \
110                 LEFT JOIN hr_attendance \
111                     ON (hr_attendance.employee_id = foo.employee_id \
112                         AND hr_attendance.name = foo.name) \
113                 WHERE hr_attendance.employee_id \
114                     in (' + ','.join([str(x) for x in ids]) + ')')
115         for res in cr.fetchall():
116             result[res[1]] = res[0] == 'sign_in' and 'present' or 'absent'
117         return result
118
119     _columns = {
120         'name' : fields.char("Employee", size=128, required=True),
121         'active' : fields.boolean('Active'),
122         'company_id': fields.many2one('res.company', 'Company'),
123         'address_id': fields.many2one('res.partner.address', 'Contact address'),
124         'state': fields.function(_state, method=True, type='selection', selection=[('absent', 'Absent'), ('present', 'Present')], string='Attendance'),
125         'started' : fields.date("Started on"),
126         'notes': fields.text('Notes'),
127         'attendances' : fields.one2many('hr.attendance', 'employee_id', "Employee's attendances"),
128         'holidays' : fields.one2many('hr.holidays', 'employee_id', "Employee's holidays"),
129         'workgroups' : fields.many2many('hr.timesheet.group', 'hr_timesheet_employee_rel', 'emp_id', 'tgroup_id', "Employee's work team"),
130         'user_id' : fields.many2one('res.users', 'Tiny ERP User'),
131         'category_id' : fields.many2one('hr.employee.category', 'Category'),
132         'regime' : fields.float('Workhours by week'),
133         'holiday_max' : fields.integer("Number of holidays"),
134         'parent_id': fields.many2one('hr.employee', 'Boss', select=True),
135         'child_ids': fields.one2many('hr.employee', 'parent_id','Subordinates'),
136     }
137     _defaults = {
138         'active' : lambda *a: True,
139         'state' : lambda *a: 'absent',
140     }
141     def sign_change(self, cr, uid, ids, context={}, dt=False):
142         for emp in self.browse(cr, uid, ids):
143             if not self._action_check(cr, uid, emp.id, dt, context):
144                 raise osv.except_osv(_('Warning'), _('You tried to sign with a date anterior to another event !\nTry to contact the administrator to correct attendances.'))
145             res = {'action':'action', 'employee_id':emp.id}
146             if dt:
147                 res['name'] = dt
148             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
149         return True
150
151     def sign_out(self, cr, uid, ids, context={}, dt=False, *args):
152         id = False
153         for emp in self.browse(cr, uid, ids):
154             if not self._action_check(cr, uid, emp.id, dt, context):
155                 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.'))
156             res = {'action':'sign_out', 'employee_id':emp.id}
157             if dt:
158                 res['name'] = dt
159             att_id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
160             id = att_id
161         return id
162
163     def _action_check(self, cr, uid, emp_id, dt=False,context={}):
164         cr.execute('select max(name) from hr_attendance where employee_id=%d', (emp_id,))
165         res = cr.fetchone()
166         return not (res and (res[0]>=(dt or time.strftime('%Y-%m-%d %H:%M:%S'))))
167
168     def sign_in(self, cr, uid, ids, context={}, dt=False, *args):
169         id = False
170         for emp in self.browse(cr, uid, ids):
171             if not self._action_check(cr, uid, emp.id, dt, context):
172                 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.'))
173             res = {'action':'sign_in', 'employee_id':emp.id}
174             if dt:
175                 res['name'] = dt
176             id = self.pool.get('hr.attendance').create(cr, uid, res, context=context)
177         return id
178
179 hr_employee()
180
181 class hr_timesheet(osv.osv):
182     _name = "hr.timesheet"
183     _description = "Timesheet Line"
184     _columns = {
185         'name' : fields.char("Name", size=64, required=True),
186         'dayofweek': fields.selection([('0','Monday'),('1','Tuesday'),('2','Wednesday'),('3','Thursday'),('4','Friday'),('5','Saturday'),('6','Sunday')], 'Day of week'),
187         'date_from' : fields.date('Starting date'),
188         'hour_from' : fields.char('Work from', size=8, required=True),
189         'hour_to' : fields.char("Work to", size=8, required=True),
190         'tgroup_id' : fields.many2one("hr.timesheet.group", "Employee's timesheet group", select=True),
191     }
192     _order = 'dayofweek, hour_from'
193 hr_timesheet()
194
195 class hr_action_reason(osv.osv):
196     _name = "hr.action.reason"
197     _description = "Action reason"
198     _columns = {
199         'name' : fields.char('Reason', size=64, required=True),
200         'action_type' : fields.selection([('sign_in', 'Sign in'), ('sign_out', 'Sign out')], "Action's type"),
201     }
202     _defaults = {
203         'action_type' : lambda *a: 'sign_in',
204     }
205 hr_action_reason()
206
207 def _employee_get(obj,cr,uid,context={}):
208     ids = obj.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
209     if ids:
210         return ids[0]
211     return False
212
213 class hr_attendance(osv.osv):
214     _name = "hr.attendance"
215     _description = "Attendance"
216     _columns = {
217         'name' : fields.datetime('Date', required=True),
218         'action' : fields.selection([('sign_in', 'Sign In'), ('sign_out', 'Sign Out'),('action','Action')], 'Action', required=True),
219         'action_desc' : fields.many2one("hr.action.reason", "Action reason", domain="[('action_type', '=', action)]"),
220         'employee_id' : fields.many2one('hr.employee', 'Employee', required=True, select=True),
221     }
222     _defaults = {
223         'name' : lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
224         'employee_id' : _employee_get,
225     }
226     
227     def _altern_si_so(self, cr, uid, ids):
228         for id in ids:
229             sql = '''
230             select action, name
231             from hr_attendance as att
232             where employee_id = (select employee_id from hr_attendance where id=%s)
233             and action in ('sign_in','sign_out')
234             and name <= (select name from hr_attendance where id=%s)
235             order by name desc
236             limit 2
237             ''' % (id, id)
238             cr.execute(sql)
239             atts = cr.fetchall()
240             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])):
241                 return False
242         return True
243     
244     _constraints = [(_altern_si_so, 'Error: Sign in (resp. Sign out) must follow Sign out (resp. Sign in)', ['action'])]
245     _order = 'name desc'
246 hr_attendance()
247
248 class hr_holidays_status(osv.osv):
249     _name = "hr.holidays.status"
250     _description = "Holidays Status"
251     _columns = {
252         'name' : fields.char('Holiday Status', size=64, required=True, translate=True),
253     }
254 hr_holidays_status()
255
256 class hr_holidays(osv.osv):
257     _name = "hr.holidays"
258     _description = "Holidays"
259     _columns = {
260         'name' : fields.char('Description', required=True, size=64),
261         'date_from' : fields.datetime('Vacation start day', required=True),
262         'date_to' : fields.datetime('Vacation end day'),
263         'holiday_status' : fields.many2one("hr.holidays.status", "Holiday's Status"),
264         'employee_id' : fields.many2one('hr.employee', 'Employee', select=True),
265     }
266     _defaults = {
267         'employee_id' : _employee_get
268     }
269     _order = 'date_from desc'
270 hr_holidays()
271
272 # vim:tw=0:noexpandtab