[MRG] merge with lp:openobject-addons, changes of stage state task merged in this...
[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 logging
23
24 from openerp.modules.module import get_module_resource
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp import tools
28 from openerp.tools.translate import _
29
30 _logger = logging.getLogger(__name__)
31
32
33 class hr_employee_category(osv.osv):
34
35     def name_get(self, cr, uid, ids, context=None):
36         if not ids:
37             return []
38         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
39         res = []
40         for record in reads:
41             name = record['name']
42             if record['parent_id']:
43                 name = record['parent_id'][1]+' / '+name
44             res.append((record['id'], name))
45         return res
46
47     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
48         res = self.name_get(cr, uid, ids, context=context)
49         return dict(res)
50
51     _name = "hr.employee.category"
52     _description = "Employee Category"
53     _columns = {
54         'name': fields.char("Employee Tag", size=64, required=True),
55         'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
56         'parent_id': fields.many2one('hr.employee.category', 'Parent Employee Tag', select=True),
57         'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'),
58         'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'),
59     }
60
61     def _check_recursion(self, cr, uid, ids, context=None):
62         level = 100
63         while len(ids):
64             cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), ))
65             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
66             if not level:
67                 return False
68             level -= 1
69         return True
70
71     _constraints = [
72         (_check_recursion, 'Error! You cannot create recursive Categories.', ['parent_id'])
73     ]
74
75
76 class hr_job(osv.osv):
77
78     def _no_of_employee(self, cr, uid, ids, name, args, context=None):
79         res = {}
80         for job in self.browse(cr, uid, ids, context=context):
81             nb_employees = len(job.employee_ids or [])
82             res[job.id] = {
83                 'no_of_employee': nb_employees,
84                 'expected_employees': nb_employees + job.no_of_recruitment,
85             }
86         return res
87
88     def _get_job_position(self, cr, uid, ids, context=None):
89         res = []
90         for employee in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
91             if employee.job_id:
92                 res.append(employee.job_id.id)
93         return res
94
95     _name = "hr.job"
96     _description = "Job Position"
97     _inherit = ['mail.thread','ir.needaction_mixin']
98     _columns = {
99         'name': fields.char('Job Name', size=128, required=True, select=True),
100         # TO CLEAN: when doing a cleaning, we should change like this:
101         #   no_of_recruitment: a function field
102         #   expected_employees: float
103         # This would allow a clean update when creating new employees.
104         'expected_employees': fields.function(_no_of_employee, string='Total Forecasted Employees',
105             help='Expected number of employees for this job position after new recruitment.',
106             store = {
107                 'hr.job': (lambda self,cr,uid,ids,c=None: ids, ['no_of_recruitment'], 10),
108                 'hr.employee': (_get_job_position, ['job_id'], 10),
109             },
110             multi='no_of_employee'),
111         'no_of_employee': fields.function(_no_of_employee, string="Current Number of Employees",
112             help='Number of employees currently occupying this job position.',
113             store = {
114                 'hr.employee': (_get_job_position, ['job_id'], 10),
115             },
116             multi='no_of_employee'),
117         'no_of_recruitment': fields.float('Expected New Employees', help='Number of new employees you expect to recruit.'),
118         'no_of_hired_employee':fields.float('Hired Employees', help='Number of hired employees for this job position during recruitment phase.'),
119         'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees', groups='base.group_user'),
120         'description': fields.text('Job Description'),
121         'requirements': fields.text('Requirements'),
122         'department_id': fields.many2one('hr.department', 'Department'),
123         'company_id': fields.many2one('res.company', 'Company'),
124         'state': fields.selection([('open', 'No Recruitment'), ('recruit', 'Recruitment in Progress')], 'Status', readonly=True, required=True,
125             help="By default 'In position', set it to 'In Recruitment' if recruitment process is going on for this job position."),
126         'color': fields.integer('Color Index'),
127     }
128     _defaults = {
129         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c),
130         'state': 'open',
131     }
132
133     _sql_constraints = [
134         ('name_company_uniq', 'unique(name, company_id, department_id)', 'The name of the job position must be unique per department in company!'),
135         ('hired_employee_check', "CHECK ( no_of_hired_employee <= no_of_recruitment )", "Number of hired employee must be less than expected number of employee in recruitment."),
136     ]
137
138
139     def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None):
140         if context is None:
141             context = {}
142         return {'value': {'expected_employees': no_of_recruitment + no_of_employee}}
143
144     def action_employee_to_hire(self, cr, uid, id, value, context=None):
145         return self.write(cr, uid, [id], {'no_of_recruitment': value}, context=context)
146
147     def job_recruitment(self, cr, uid, ids, *args):
148         for job in self.browse(cr, uid, ids):
149             no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment
150             self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment})
151         return True
152
153     def job_open(self, cr, uid, ids, *args):
154         self.write(cr, uid, ids, {'state': 'open', 'no_of_recruitment': 0,'no_of_hired_employee': 0})
155         return True
156
157     def write(self, cr, uid, ids, vals, context=None):
158         if vals.get('state') == 'recruit':
159             self.message_post(cr, uid, ids, body=_('job in <b>Recruitment</b> Stage'), context=context)
160         return super(hr_job, self).write(cr, uid, ids, vals, context=context)
161
162 class hr_employee(osv.osv):
163     _name = "hr.employee"
164     _description = "Employee"
165     _order = 'name_related'
166     _inherits = {'resource.resource': "resource_id"}
167     _inherit = ['mail.thread']
168
169     _mail_post_access = 'read'
170
171     def _get_image(self, cr, uid, ids, name, args, context=None):
172         result = dict.fromkeys(ids, False)
173         for obj in self.browse(cr, uid, ids, context=context):
174             result[obj.id] = tools.image_get_resized_images(obj.image)
175         return result
176
177     def _set_image(self, cr, uid, id, name, value, args, context=None):
178         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
179
180     _columns = {
181         #we need a related field in order to be able to sort the employee by name
182         'name_related': fields.related('resource_id', 'name', type='char', string='Name', readonly=True, store=True),
183         'country_id': fields.many2one('res.country', 'Nationality'),
184         'birthday': fields.date("Date of Birth"),
185         'ssnid': fields.char('SSN No', size=32, help='Social Security Number'),
186         'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"),
187         'identification_id': fields.char('Identification No', size=32),
188         'otherid': fields.char('Other Id', size=64),
189         'gender': fields.selection([('male', 'Male'), ('female', 'Female')], 'Gender'),
190         'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
191         'department_id': fields.many2one('hr.department', 'Department'),
192         'address_id': fields.many2one('res.partner', 'Working Address'),
193         'address_home_id': fields.many2one('res.partner', 'Home Address'),
194         'bank_account_id': fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',address_home_id)]", help="Employee bank salary account"),
195         'work_phone': fields.char('Work Phone', size=32, readonly=False),
196         'mobile_phone': fields.char('Work Mobile', size=32, readonly=False),
197         'work_email': fields.char('Work Email', size=240),
198         'work_location': fields.char('Office Location', size=32),
199         'notes': fields.text('Notes'),
200         'parent_id': fields.many2one('hr.employee', 'Manager'),
201         'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Tags'),
202         'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
203         'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
204         'coach_id': fields.many2one('hr.employee', 'Coach'),
205         'job_id': fields.many2one('hr.job', 'Job'),
206         # image: all image fields are base64 encoded and PIL-supported
207         'image': fields.binary("Photo",
208             help="This field holds the image used as photo for the employee, limited to 1024x1024px."),
209         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
210             string="Medium-sized photo", type="binary", multi="_get_image",
211             store = {
212                 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
213             },
214             help="Medium-sized photo of the employee. It is automatically "\
215                  "resized as a 128x128px image, with aspect ratio preserved. "\
216                  "Use this field in form views or some kanban views."),
217         'image_small': fields.function(_get_image, fnct_inv=_set_image,
218             string="Smal-sized photo", type="binary", multi="_get_image",
219             store = {
220                 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
221             },
222             help="Small-sized photo of the employee. It is automatically "\
223                  "resized as a 64x64px image, with aspect ratio preserved. "\
224                  "Use this field anywhere a small image is required."),
225         'passport_id': fields.char('Passport No', size=64),
226         'color': fields.integer('Color Index'),
227         'city': fields.related('address_id', 'city', type='char', string='City'),
228         'login': fields.related('user_id', 'login', type='char', string='Login', readonly=1),
229         'last_login': fields.related('user_id', 'date', type='datetime', string='Latest Connection', readonly=1),
230     }
231
232     def _get_default_image(self, cr, uid, context=None):
233         image_path = get_module_resource('hr', 'static/src/img', 'default_image.png')
234         return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
235
236     defaults = {
237         'active': 1,
238         'image': _get_default_image,
239         'color': 0,
240     }
241
242     def create(self, cr, uid, data, context=None):
243         if context is None:
244             context = {}
245         create_ctx = dict(context, mail_create_nolog=True)
246         employee_id = super(hr_employee, self).create(cr, uid, data, context=create_ctx)
247         employee = self.browse(cr, uid, employee_id, context=context)
248         if employee.user_id:
249             # send a copy to every user of the company
250             company_id = employee.user_id.partner_id.company_id.id
251             partner_ids = self.pool.get('res.partner').search(cr, uid, [
252                 ('company_id', '=', company_id),
253                 ('user_ids', '!=', False)], context=context)
254         else:
255             partner_ids = []
256         self.message_post(cr, uid, [employee_id],
257             body=_('Welcome to %s! Please help him/her take the first steps with OpenERP!') % (employee.name),
258             partner_ids=partner_ids,
259             subtype='mail.mt_comment', context=context
260         )
261         return employee_id
262
263     def unlink(self, cr, uid, ids, context=None):
264         resource_ids = []
265         for employee in self.browse(cr, uid, ids, context=context):
266             resource_ids.append(employee.resource_id.id)
267         return self.pool.get('resource.resource').unlink(cr, uid, resource_ids, context=context)
268
269     def onchange_address_id(self, cr, uid, ids, address, context=None):
270         if address:
271             address = self.pool.get('res.partner').browse(cr, uid, address, context=context)
272             return {'value': {'work_phone': address.phone, 'mobile_phone': address.mobile}}
273         return {'value': {}}
274
275     def onchange_company(self, cr, uid, ids, company, context=None):
276         address_id = False
277         if company:
278             company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
279             address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
280             address_id = address and address['default'] or False
281         return {'value': {'address_id': address_id}}
282
283     def onchange_department_id(self, cr, uid, ids, department_id, context=None):
284         value = {'parent_id': False}
285         if department_id:
286             department = self.pool.get('hr.department').browse(cr, uid, department_id)
287             value['parent_id'] = department.manager_id.id
288         return {'value': value}
289
290     def onchange_user(self, cr, uid, ids, user_id, context=None):
291         work_email = False
292         if user_id:
293             work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).email
294         return {'value': {'work_email': work_email}}
295
296     def action_follow(self, cr, uid, ids, context=None):
297         """ Wrapper because message_subscribe_users take a user_ids=None
298             that receive the context without the wrapper. """
299         return self.message_subscribe_users(cr, uid, ids, context=context)
300
301     def action_unfollow(self, cr, uid, ids, context=None):
302         """ Wrapper because message_unsubscribe_users take a user_ids=None
303             that receive the context without the wrapper. """
304         return self.message_unsubscribe_users(cr, uid, ids, context=context)
305
306     def get_suggested_thread(self, cr, uid, removed_suggested_threads=None, context=None):
307         """Show the suggestion of employees if display_employees_suggestions if the
308         user perference allows it. """
309         user = self.pool.get('res.users').browse(cr, uid, uid, context)
310         if not user.display_employees_suggestions:
311             return []
312         else:
313             return super(hr_employee, self).get_suggested_thread(cr, uid, removed_suggested_threads, context)
314
315     def _message_get_auto_subscribe_fields(self, cr, uid, updated_fields, auto_follow_fields=['user_id'], context=None):
316         """ Overwrite of the original method to always follow user_id field,
317         even when not track_visibility so that a user will follow it's employee
318         """
319         user_field_lst = []
320         for name, column_info in self._all_columns.items():
321             if name in auto_follow_fields and name in updated_fields and column_info.column._obj == 'res.users':
322                 user_field_lst.append(name)
323         return user_field_lst
324
325     def _check_recursion(self, cr, uid, ids, context=None):
326         level = 100
327         while len(ids):
328             cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
329             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
330             if not level:
331                 return False
332             level -= 1
333         return True
334
335     _constraints = [
336         (_check_recursion, 'Error! You cannot create recursive hierarchy of Employee(s).', ['parent_id']),
337     ]
338
339
340 class hr_department(osv.osv):
341     _description = "Department"
342     _inherit = 'hr.department'
343     _columns = {
344         'manager_id': fields.many2one('hr.employee', 'Manager'),
345         'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
346     }
347
348     def copy(self, cr, uid, ids, default=None, context=None):
349         if default is None:
350             default = {}
351         default = default.copy()
352         default['member_ids'] = []
353         return super(hr_department, self).copy(cr, uid, ids, default, context=context)
354
355 class res_users(osv.osv):
356     _name = 'res.users'
357     _inherit = 'res.users'
358
359     def create(self, cr, uid, data, context=None):
360         user_id = super(res_users, self).create(cr, uid, data, context=context)
361
362         # add shortcut unless 'noshortcut' is True in context
363         if not(context and context.get('noshortcut', False)):
364             data_obj = self.pool.get('ir.model.data')
365             try:
366                 data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee')
367                 view_id  = data_obj.browse(cr, uid, data_id, context=context).res_id
368                 self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = {
369                                             'user_id': user_id}, context=context)
370             except:
371                 # Tolerate a missing shortcut. See product/product.py for similar code.
372                 _logger.debug('Skipped meetings shortcut for user "%s".', data.get('name','<new'))
373
374         return user_id
375
376     _columns = {
377         'employee_ids': fields.one2many('hr.employee', 'user_id', 'Related employees'),
378         }
379
380
381
382 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: