[IMP] use model._fields instead of model._all_columns to cover all fields
[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 import SUPERUSER_ID
25 from openerp import tools
26 from openerp.modules.module import get_module_resource
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29
30 _logger = logging.getLogger(__name__)
31
32
33 class hr_employee_category(osv.Model):
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", 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.Model):
77
78     def _get_nbr_employees(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', required=True, select=True),
100         'expected_employees': fields.function(_get_nbr_employees, string='Total Forecasted Employees',
101             help='Expected number of employees for this job position after new recruitment.',
102             store = {
103                 'hr.job': (lambda self,cr,uid,ids,c=None: ids, ['no_of_recruitment'], 10),
104                 'hr.employee': (_get_job_position, ['job_id'], 10),
105             }, type='integer',
106             multi='_get_nbr_employees'),
107         'no_of_employee': fields.function(_get_nbr_employees, string="Current Number of Employees",
108             help='Number of employees currently occupying this job position.',
109             store = {
110                 'hr.employee': (_get_job_position, ['job_id'], 10),
111             }, type='integer',
112             multi='_get_nbr_employees'),
113         'no_of_recruitment': fields.integer('Expected New Employees', copy=False,
114                                             help='Number of new employees you expect to recruit.'),
115         'no_of_hired_employee': fields.integer('Hired Employees', copy=False,
116                                                help='Number of hired employees for this job position during recruitment phase.'),
117         'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees', groups='base.group_user'),
118         'description': fields.text('Job Description'),
119         'requirements': fields.text('Requirements'),
120         'department_id': fields.many2one('hr.department', 'Department'),
121         'company_id': fields.many2one('res.company', 'Company'),
122         'state': fields.selection([('open', 'Recruitment Closed'), ('recruit', 'Recruitment in Progress')],
123                                   string='Status', readonly=True, required=True,
124                                   track_visibility='always', copy=False,
125                                   help="By default 'Closed', set it to 'In Recruitment' if recruitment process is going on for this job position."),
126         'write_date': fields.datetime('Update Date', readonly=True),
127     }
128
129     _defaults = {
130         'company_id': lambda self, cr, uid, ctx=None: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=ctx),
131         'state': 'open',
132     }
133
134     _sql_constraints = [
135         ('name_company_uniq', 'unique(name, company_id, department_id)', 'The name of the job position must be unique per department in company!'),
136         ('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."),
137     ]
138
139     def set_recruit(self, cr, uid, ids, context=None):
140         for job in self.browse(cr, uid, ids, context=context):
141             no_of_recruitment = job.no_of_recruitment == 0 and 1 or job.no_of_recruitment
142             self.write(cr, uid, [job.id], {'state': 'recruit', 'no_of_recruitment': no_of_recruitment}, context=context)
143         return True
144
145     def set_open(self, cr, uid, ids, context=None):
146         self.write(cr, uid, ids, {
147             'state': 'open',
148             'no_of_recruitment': 0,
149             'no_of_hired_employee': 0
150         }, context=context)
151         return True
152
153     def copy(self, cr, uid, id, default=None, context=None):
154         if default is None:
155             default = {}
156         if 'name' not in default:
157             job = self.browse(cr, uid, id, context=context)
158             default['name'] = _("%s (copy)") % (job.name)
159         return super(hr_job, self).copy(cr, uid, id, default=default, context=context)
160
161     # ----------------------------------------
162     # Compatibility methods
163     # ----------------------------------------
164     _no_of_employee = _get_nbr_employees  # v7 compatibility
165     job_open = set_open  # v7 compatibility
166     job_recruitment = set_recruit  # v7 compatibility
167
168
169 class hr_employee(osv.osv):
170     _name = "hr.employee"
171     _description = "Employee"
172     _order = 'name_related'
173     _inherits = {'resource.resource': "resource_id"}
174     _inherit = ['mail.thread']
175
176     _mail_post_access = 'read'
177
178     def _get_image(self, cr, uid, ids, name, args, context=None):
179         result = dict.fromkeys(ids, False)
180         for obj in self.browse(cr, uid, ids, context=context):
181             result[obj.id] = tools.image_get_resized_images(obj.image)
182         return result
183
184     def _set_image(self, cr, uid, id, name, value, args, context=None):
185         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
186
187     _columns = {
188         #we need a related field in order to be able to sort the employee by name
189         'name_related': fields.related('resource_id', 'name', type='char', string='Name', readonly=True, store=True),
190         'country_id': fields.many2one('res.country', 'Nationality'),
191         'birthday': fields.date("Date of Birth"),
192         'ssnid': fields.char('SSN No', help='Social Security Number'),
193         'sinid': fields.char('SIN No', help="Social Insurance Number"),
194         'identification_id': fields.char('Identification No'),
195         'otherid': fields.char('Other Id'),
196         'gender': fields.selection([('male', 'Male'), ('female', 'Female')], 'Gender'),
197         'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
198         'department_id': fields.many2one('hr.department', 'Department'),
199         'address_id': fields.many2one('res.partner', 'Working Address'),
200         'address_home_id': fields.many2one('res.partner', 'Home Address'),
201         'bank_account_id': fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',address_home_id)]", help="Employee bank salary account"),
202         'work_phone': fields.char('Work Phone', readonly=False),
203         'mobile_phone': fields.char('Work Mobile', readonly=False),
204         'work_email': fields.char('Work Email', size=240),
205         'work_location': fields.char('Office Location'),
206         'notes': fields.text('Notes'),
207         'parent_id': fields.many2one('hr.employee', 'Manager'),
208         'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Tags'),
209         'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
210         'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True, auto_join=True),
211         'coach_id': fields.many2one('hr.employee', 'Coach'),
212         'job_id': fields.many2one('hr.job', 'Job Title'),
213         # image: all image fields are base64 encoded and PIL-supported
214         'image': fields.binary("Photo",
215             help="This field holds the image used as photo for the employee, limited to 1024x1024px."),
216         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
217             string="Medium-sized photo", type="binary", multi="_get_image",
218             store = {
219                 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
220             },
221             help="Medium-sized photo of the employee. It is automatically "\
222                  "resized as a 128x128px image, with aspect ratio preserved. "\
223                  "Use this field in form views or some kanban views."),
224         'image_small': fields.function(_get_image, fnct_inv=_set_image,
225             string="Small-sized photo", type="binary", multi="_get_image",
226             store = {
227                 'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
228             },
229             help="Small-sized photo of the employee. It is automatically "\
230                  "resized as a 64x64px image, with aspect ratio preserved. "\
231                  "Use this field anywhere a small image is required."),
232         'passport_id': fields.char('Passport No'),
233         'color': fields.integer('Color Index'),
234         'city': fields.related('address_id', 'city', type='char', string='City'),
235         'login': fields.related('user_id', 'login', type='char', string='Login', readonly=1),
236         'last_login': fields.related('user_id', 'date', type='datetime', string='Latest Connection', readonly=1),
237     }
238
239     def _get_default_image(self, cr, uid, context=None):
240         image_path = get_module_resource('hr', 'static/src/img', 'default_image.png')
241         return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
242
243     defaults = {
244         'active': 1,
245         'image': _get_default_image,
246         'color': 0,
247     }
248
249     def _broadcast_welcome(self, cr, uid, employee_id, context=None):
250         """ Broadcast the welcome message to all users in the employee company. """
251         employee = self.browse(cr, uid, employee_id, context=context)
252         partner_ids = []
253         _model, group_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'base', 'group_user')
254         if employee.user_id:
255             company_id = employee.user_id.company_id.id
256         elif employee.company_id:
257             company_id = employee.company_id.id
258         elif employee.job_id:
259             company_id = employee.job_id.company_id.id
260         elif employee.department_id:
261             company_id = employee.department_id.company_id.id
262         else:
263             company_id = self.pool['res.company']._company_default_get(cr, uid, 'hr.employee', context=context)
264         res_users = self.pool['res.users']
265         user_ids = res_users.search(
266             cr, SUPERUSER_ID, [
267                 ('company_id', '=', company_id),
268                 ('groups_id', 'in', group_id)
269             ], context=context)
270         partner_ids = list(set(u.partner_id.id for u in res_users.browse(cr, SUPERUSER_ID, user_ids, context=context)))
271         self.message_post(
272             cr, uid, [employee_id],
273             body=_('Welcome to %s! Please help him/her take the first steps with Odoo!') % (employee.name),
274             partner_ids=partner_ids,
275             subtype='mail.mt_comment', context=context
276         )
277         return True
278
279     def create(self, cr, uid, data, context=None):
280         context = dict(context or {})
281         if context.get("mail_broadcast"):
282             context['mail_create_nolog'] = True
283
284         employee_id = super(hr_employee, self).create(cr, uid, data, context=context)
285
286         if context.get("mail_broadcast"):
287             self._broadcast_welcome(cr, uid, employee_id, context=context)
288         return employee_id
289
290     def unlink(self, cr, uid, ids, context=None):
291         resource_ids = []
292         for employee in self.browse(cr, uid, ids, context=context):
293             resource_ids.append(employee.resource_id.id)
294         super(hr_employee, self).unlink(cr, uid, ids, context=context)
295         return self.pool.get('resource.resource').unlink(cr, uid, resource_ids, context=context)
296
297     def onchange_address_id(self, cr, uid, ids, address, context=None):
298         if address:
299             address = self.pool.get('res.partner').browse(cr, uid, address, context=context)
300             return {'value': {'work_phone': address.phone, 'mobile_phone': address.mobile}}
301         return {'value': {}}
302
303     def onchange_company(self, cr, uid, ids, company, context=None):
304         address_id = False
305         if company:
306             company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
307             address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
308             address_id = address and address['default'] or False
309         return {'value': {'address_id': address_id}}
310
311     def onchange_department_id(self, cr, uid, ids, department_id, context=None):
312         value = {'parent_id': False}
313         if department_id:
314             department = self.pool.get('hr.department').browse(cr, uid, department_id)
315             value['parent_id'] = department.manager_id.id
316         return {'value': value}
317
318     def onchange_user(self, cr, uid, ids, user_id, context=None):
319         work_email = False
320         if user_id:
321             work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).email
322         return {'value': {'work_email': work_email}}
323
324     def action_follow(self, cr, uid, ids, context=None):
325         """ Wrapper because message_subscribe_users take a user_ids=None
326             that receive the context without the wrapper. """
327         return self.message_subscribe_users(cr, uid, ids, context=context)
328
329     def action_unfollow(self, cr, uid, ids, context=None):
330         """ Wrapper because message_unsubscribe_users take a user_ids=None
331             that receive the context without the wrapper. """
332         return self.message_unsubscribe_users(cr, uid, ids, context=context)
333
334     def get_suggested_thread(self, cr, uid, removed_suggested_threads=None, context=None):
335         """Show the suggestion of employees if display_employees_suggestions if the
336         user perference allows it. """
337         user = self.pool.get('res.users').browse(cr, uid, uid, context)
338         if not user.display_employees_suggestions:
339             return []
340         else:
341             return super(hr_employee, self).get_suggested_thread(cr, uid, removed_suggested_threads, context)
342
343     def _message_get_auto_subscribe_fields(self, cr, uid, updated_fields, auto_follow_fields=None, context=None):
344         """ Overwrite of the original method to always follow user_id field,
345         even when not track_visibility so that a user will follow it's employee
346         """
347         if auto_follow_fields is None:
348             auto_follow_fields = ['user_id']
349         user_field_lst = []
350         for name, field in self._fields.items():
351             if name in auto_follow_fields and name in updated_fields and field.comodel_name == 'res.users':
352                 user_field_lst.append(name)
353         return user_field_lst
354
355     def _check_recursion(self, cr, uid, ids, context=None):
356         level = 100
357         while len(ids):
358             cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
359             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
360             if not level:
361                 return False
362             level -= 1
363         return True
364
365     _constraints = [
366         (_check_recursion, 'Error! You cannot create recursive hierarchy of Employee(s).', ['parent_id']),
367     ]
368
369
370 class hr_department(osv.osv):
371
372     def _dept_name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
373         res = self.name_get(cr, uid, ids, context=context)
374         return dict(res)
375
376     _name = "hr.department"
377     _columns = {
378         'name': fields.char('Department Name', required=True),
379         'complete_name': fields.function(_dept_name_get_fnc, type="char", string='Name'),
380         'company_id': fields.many2one('res.company', 'Company', select=True, required=False),
381         'parent_id': fields.many2one('hr.department', 'Parent Department', select=True),
382         'child_ids': fields.one2many('hr.department', 'parent_id', 'Child Departments'),
383         'manager_id': fields.many2one('hr.employee', 'Manager'),
384         'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
385         'jobs_ids': fields.one2many('hr.job', 'department_id', 'Jobs'),
386         'note': fields.text('Note'),
387     }
388
389     _defaults = {
390         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.department', context=c),
391     }
392
393     def _check_recursion(self, cr, uid, ids, context=None):
394         if context is None:
395             context = {}
396         level = 100
397         while len(ids):
398             cr.execute('select distinct parent_id from hr_department where id IN %s',(tuple(ids),))
399             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
400             if not level:
401                 return False
402             level -= 1
403         return True
404
405     _constraints = [
406         (_check_recursion, 'Error! You cannot create recursive departments.', ['parent_id'])
407     ]
408
409     def name_get(self, cr, uid, ids, context=None):
410         if context is None:
411             context = {}
412         if not ids:
413             return []
414         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
415         res = []
416         for record in reads:
417             name = record['name']
418             if record['parent_id']:
419                 name = record['parent_id'][1]+' / '+name
420             res.append((record['id'], name))
421         return res
422
423
424 class res_users(osv.osv):
425     _name = 'res.users'
426     _inherit = 'res.users'
427     _columns = {
428         'employee_ids': fields.one2many('hr.employee', 'user_id', 'Related employees'),
429     }
430
431
432 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: