[IMP]hr_holidays: remove done state and change report
[odoo/odoo.git] / addons / hr / hr.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 addons
23 import io
24 import logging
25 from osv import fields, osv
26 from PIL import Image
27 import StringIO
28
29 class hr_employee_category(osv.osv):
30
31     def name_get(self, cr, uid, ids, context=None):
32         if not ids:
33             return []
34         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
35         res = []
36         for record in reads:
37             name = record['name']
38             if record['parent_id']:
39                 name = record['parent_id'][1]+' / '+name
40             res.append((record['id'], name))
41         return res
42
43     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
44         res = self.name_get(cr, uid, ids, context=context)
45         return dict(res)
46
47     _name = "hr.employee.category"
48     _description = "Employee Category"
49     _columns = {
50         'name': fields.char("Category", size=64, required=True),
51         'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
52         'parent_id': fields.many2one('hr.employee.category', 'Parent Category', select=True),
53         'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'),
54         'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'),
55     }
56
57     def _check_recursion(self, cr, uid, ids, context=None):
58         level = 100
59         while len(ids):
60             cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), ))
61             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
62             if not level:
63                 return False
64             level -= 1
65         return True
66
67     _constraints = [
68         (_check_recursion, 'Error ! You cannot create recursive Categories.', ['parent_id'])
69     ]
70
71 hr_employee_category()
72
73 class hr_job(osv.osv):
74
75     def _no_of_employee(self, cr, uid, ids, name, args, context=None):
76         res = {}
77         for job in self.browse(cr, uid, ids, context=context):
78             nb_employees = len(job.employee_ids or [])
79             res[job.id] = {
80                 'no_of_employee': nb_employees,
81                 'expected_employees': nb_employees + job.no_of_recruitment,
82             }
83         return res
84
85     def _get_job_position(self, cr, uid, ids, context=None):
86         res = []
87         for employee in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
88             if employee.job_id:
89                 res.append(employee.job_id.id)
90         return res
91
92     _name = "hr.job"
93     _description = "Job Description"
94     _columns = {
95         'name': fields.char('Job Name', size=128, required=True, select=True),
96         'expected_employees': fields.function(_no_of_employee, string='Total Employees', help='Expected number of employees in total for this job position after new recruitment.',
97             store = {
98                 'hr.job': (lambda self,cr,uid,ids,c=None: ids, ['no_of_recruitment'], 10),
99                 'hr.employee': (_get_job_position, ['job_id'], 10),
100             },
101             multi='no_of_employee'),
102         'no_of_employee': fields.function(_no_of_employee, string="Number of Employees", help='Number of employees currently having this job position.',
103             store = {
104                 'hr.employee': (_get_job_position, ['job_id'], 10),
105             },
106             multi='no_of_employee'),
107         'no_of_recruitment': fields.float('Expected in Recruitment', help='Number of new employees you expect to recruit.'),
108         'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees'),
109         'description': fields.text('Job Description'),
110         'requirements': fields.text('Requirements'),
111         'department_id': fields.many2one('hr.department', 'Department'),
112         'company_id': fields.many2one('res.company', 'Company'),
113         'state': fields.selection([('open', 'In Position'),('recruit', 'In Recruitement')], 'Status', readonly=True, required=True, help='By default all job are \'In position\', set it \'In Recruitment\' if recruitment process is going on for this job position.'),
114     }
115     _defaults = {
116         'expected_employees': 1,
117         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c),
118         'state': 'open',
119     }
120
121     _sql_constraints = [
122         ('name_company_uniq', 'unique(name, company_id)', 'The name of the job position must be unique per company!'),
123     ]
124
125
126     def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None):
127         if context is None:
128             context = {}
129         return {'value': {'expected_employees': no_of_recruitment + no_of_employee}}
130
131     def job_recruitement(self, cr, uid, ids, *args):
132         for job in self.browse(cr, uid, ids):
133             no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment
134             self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment})
135         return True
136
137     def job_open(self, cr, uid, ids, *args):
138         self.write(cr, uid, ids, {'state': 'open', 'no_of_recruitment': 0})
139         return True
140
141 hr_job()
142
143 class hr_employee(osv.osv):
144     _name = "hr.employee"
145     _description = "Employee"
146     _inherits = {'resource.resource': "resource_id"}
147
148     def onchange_photo(self, cr, uid, ids, value, context=None):
149         if not value:
150             return {'value': {'photo_big': value, 'photo': value} }
151         return {'value': {'photo_big': self._photo_resize(cr, uid, value, 540, 450, context=context), 'photo': self._photo_resize(cr, uid, value, context=context)} }
152     
153     def _set_photo(self, cr, uid, id, name, value, args, context=None):
154         if not value:
155             vals = {'photo_big': value}
156         else:
157             vals = {'photo_big': self._photo_resize(cr, uid, value, 540, 450, context=context)}
158         return self.write(cr, uid, [id], vals, context=context)
159     
160     def _photo_resize(self, cr, uid, photo, heigth=180, width=150, context=None):
161         image_stream = io.BytesIO(photo.decode('base64'))
162         img = Image.open(image_stream)
163         img.thumbnail((heigth, width), Image.ANTIALIAS)
164         img_stream = StringIO.StringIO()
165         img.save(img_stream, "JPEG")
166         return img_stream.getvalue().encode('base64')
167     
168     def _get_photo(self, cr, uid, ids, name, args, context=None):
169         result = dict.fromkeys(ids, False)
170         for hr_empl in self.browse(cr, uid, ids, context=context):
171             if hr_empl.photo_big:
172                 result[hr_empl.id] = self._photo_resize(cr, uid, hr_empl.photo_big, context=context)
173         return result
174     
175     _columns = {
176         'country_id': fields.many2one('res.country', 'Nationality'),
177         'birthday': fields.date("Date of Birth"),
178         'ssnid': fields.char('SSN No', size=32, help='Social Security Number'),
179         'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"),
180         'identification_id': fields.char('Identification No', size=32),
181         'otherid': fields.char('Other Id', size=64),
182         'gender': fields.selection([('male', 'Male'),('female', 'Female')], 'Gender'),
183         'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
184         'department_id':fields.many2one('hr.department', 'Department'),
185         'address_id': fields.many2one('res.partner', 'Working Address'),
186         'address_home_id': fields.many2one('res.partner', 'Home Address'),
187         'bank_account_id':fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',address_home_id)]", help="Employee bank salary account"),
188         'work_phone': fields.char('Work Phone', size=32, readonly=False),
189         'mobile_phone': fields.char('Work Mobile', size=32, readonly=False),
190         'work_email': fields.char('Work E-mail', size=240),
191         'work_location': fields.char('Office Location', size=32),
192         'notes': fields.text('Notes'),
193         'parent_id': fields.many2one('hr.employee', 'Manager'),
194         'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Categories'),
195         'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
196         'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
197         'coach_id': fields.many2one('hr.employee', 'Coach'),
198         'job_id': fields.many2one('hr.job', 'Job'),
199         'photo_big': fields.binary('Big-sized employee photo', help="This field holds the photo of the employee. The photo field is used as an interface to access this field. The image is base64 encoded, and PIL-supported. Full-sized photo are however resized to 540x450 px."),
200         'photo': fields.function(_get_photo, fnct_inv=_set_photo, string='Employee photo', type="binary",
201             store = {
202                 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['photo_big'], 10),
203             }, help="Image used as photo for the employee. It is automatically resized as a 180x150 px image. A larger photo is stored inside the photo_big field."),
204         'passport_id':fields.char('Passport No', size=64),
205         'color': fields.integer('Color Index'),
206         'city': fields.related('address_id', 'city', type='char', string='City'),
207         'login': fields.related('user_id', 'login', type='char', string='Login', readonly=1),
208     }
209
210     def unlink(self, cr, uid, ids, context=None):
211         resource_obj = self.pool.get('resource.resource')
212         resource_ids = []
213         for employee in self.browse(cr, uid, ids, context=context):
214             resource = employee.resource_id
215             if resource:
216                 resource_ids.append(resource.id)
217         if resource_ids:
218             resource_obj.unlink(cr, uid, resource_ids, context=context)
219         return super(hr_employee, self).unlink(cr, uid, ids, context=context)
220
221     def onchange_address_id(self, cr, uid, ids, address, context=None):
222         if address:
223             address = self.pool.get('res.partner').browse(cr, uid, address, context=context)
224             return {'value': {'work_email': address.email, 'work_phone': address.phone, 'mobile_phone': address.mobile}}
225         return {'value': {}}
226
227     def onchange_company(self, cr, uid, ids, company, context=None):
228         address_id = False
229         if company:
230             company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
231             address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
232             address_id = address and address['default'] or False
233         return {'value': {'address_id' : address_id}}
234
235     def onchange_department_id(self, cr, uid, ids, department_id, context=None):
236         value = {'parent_id': False}
237         if department_id:
238             department = self.pool.get('hr.department').browse(cr, uid, department_id)
239             value['parent_id'] = department.manager_id.id
240         return {'value': value}
241
242     def onchange_user(self, cr, uid, ids, user_id, context=None):
243         work_email = False
244         if user_id:
245             work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).user_email
246         return {'value': {'work_email' : work_email}}
247
248     def _get_photo(self, cr, uid, context=None):
249         photo_path = addons.get_module_resource('hr','images','photo.png')
250         return self._photo_resize(cr, uid, open(photo_path, 'rb').read().encode('base64'), context=context)
251
252     _defaults = {
253         'active': 1,
254         'photo': _get_photo,
255         'marital': 'single',
256         'color': 0,
257     }
258
259     def _check_recursion(self, cr, uid, ids, context=None):
260         level = 100
261         while len(ids):
262             cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
263             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
264             if not level:
265                 return False
266             level -= 1
267         return True
268
269     _constraints = [
270         (_check_recursion, 'Error ! You cannot create recursive Hierarchy of Employees.', ['parent_id']),
271     ]
272
273 hr_employee()
274
275 class hr_department(osv.osv):
276     _description = "Department"
277     _inherit = 'hr.department'
278     _columns = {
279         'manager_id': fields.many2one('hr.employee', 'Manager'),
280         'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
281     }
282
283 hr_department()
284
285
286 class res_users(osv.osv):
287     _name = 'res.users'
288     _inherit = 'res.users'
289
290     def create(self, cr, uid, data, context=None):
291         user_id = super(res_users, self).create(cr, uid, data, context=context)
292
293         # add shortcut unless 'noshortcut' is True in context
294         if not(context and context.get('noshortcut', False)):
295             data_obj = self.pool.get('ir.model.data')
296             try:
297                 data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee')
298                 view_id  = data_obj.browse(cr, uid, data_id, context=context).res_id
299                 self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = {
300                                             'user_id': user_id}, context=context)
301             except:
302                 # Tolerate a missing shortcut. See product/product.py for similar code.
303                 logging.getLogger('orm').debug('Skipped meetings shortcut for user "%s"', data.get('name','<new'))
304
305         return user_id
306
307 res_users()
308
309
310 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: