[FIX] hr : job position, bad computation of employee field
[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 from osv import fields, osv
23 import logging
24 import addons
25
26 class hr_employee_category(osv.osv):
27
28     def name_get(self, cr, uid, ids, context=None):
29         if not ids:
30             return []
31         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
32         res = []
33         for record in reads:
34             name = record['name']
35             if record['parent_id']:
36                 name = record['parent_id'][1]+' / '+name
37             res.append((record['id'], name))
38         return res
39
40     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
41         res = self.name_get(cr, uid, ids, context=context)
42         return dict(res)
43
44     _name = "hr.employee.category"
45     _description = "Employee Category"
46     _columns = {
47         'name': fields.char("Category", size=64, required=True),
48         'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
49         'parent_id': fields.many2one('hr.employee.category', 'Parent Category', select=True),
50         'child_ids': fields.one2many('hr.employee.category', 'parent_id', 'Child Categories'),
51         'employee_ids': fields.many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', 'Employees'),
52     }
53
54     def _check_recursion(self, cr, uid, ids, context=None):
55         level = 100
56         while len(ids):
57             cr.execute('select distinct parent_id from hr_employee_category where id IN %s', (tuple(ids), ))
58             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
59             if not level:
60                 return False
61             level -= 1
62         return True
63
64     _constraints = [
65         (_check_recursion, 'Error ! You cannot create recursive Categories.', ['parent_id'])
66     ]
67
68 hr_employee_category()
69
70 class hr_job(osv.osv):
71
72     def _no_of_employee(self, cr, uid, ids, name, args, context=None):
73         res = {}
74         for job in self.browse(cr, uid, ids, context=context):
75             nb_employees = len(job.employee_ids or [])
76             res[job.id] = {
77                 'no_of_employee': nb_employees,
78                 'expected_employees': nb_employees + job.no_of_recruitment,
79             }
80         return res
81
82     def _get_job_position(self, cr, uid, ids, context=None):
83         result = {}
84         for data in self.pool.get('hr.employee').browse(cr, uid, ids, context=context):
85             if data.job_id:
86                 result[data.job_id.id] = True
87         return result.keys()
88
89     _name = "hr.job"
90     _description = "Job Description"
91     _columns = {
92         'name': fields.char('Job Name', size=128, required=True, select=True),
93         'expected_employees': fields.function(_no_of_employee, string='Expected Employees', help='Required number of Employees in total for that job.',
94              store={
95                 'hr.employee': (_get_job_position, ['job_id'], 10),
96                 },
97             multi='no_of_employee'),
98         'no_of_employee': fields.function(_no_of_employee, string="No of Employee", help='Number of employee with that job.',
99              store={
100                 'hr.employee': (_get_job_position, ['job_id'], 10),
101                 },
102             multi='no_of_employee'),
103         'no_of_recruitment': fields.float('Expected in Recruitment'),
104         'employee_ids': fields.one2many('hr.employee', 'job_id', 'Employees'),
105         'description': fields.text('Job Description'),
106         'requirements': fields.text('Requirements'),
107         'department_id': fields.many2one('hr.department', 'Department'),
108         'company_id': fields.many2one('res.company', 'Company'),
109         'state': fields.selection([('open', 'In Position'),('old', 'Old'),('recruit', 'In Recruitement')], 'State', readonly=True, required=True),
110     }
111     _defaults = {
112         'expected_employees': 1,
113         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'hr.job', context=c),
114         'state': 'open',
115     }
116
117     _sql_constraints = [
118         ('name_company_uniq', 'unique(name, company_id)', 'The name of the job position must be unique per company!'),
119     ]
120
121
122     def on_change_expected_employee(self, cr, uid, ids, no_of_recruitment, no_of_employee, context=None):
123         if context is None:
124             context = {}
125         return {'value': {'expected_employees': no_of_recruitment + no_of_employee}}
126
127     def job_old(self, cr, uid, ids, *args):
128         self.write(cr, uid, ids, {'state': 'old', 'no_of_recruitment': 0})
129         return True
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     _columns = {
148         'country_id': fields.many2one('res.country', 'Nationality'),
149         'birthday': fields.date("Date of Birth"),
150         'ssnid': fields.char('SSN No', size=32, help='Social Security Number'),
151         'sinid': fields.char('SIN No', size=32, help="Social Insurance Number"),
152         'identification_id': fields.char('Identification No', size=32),
153         'otherid': fields.char('Other Id', size=64),
154         'gender': fields.selection([('male', 'Male'),('female', 'Female')], 'Gender'),
155         'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),
156         'department_id':fields.many2one('hr.department', 'Department'),
157         'address_id': fields.many2one('res.partner.address', 'Working Address'),
158         'address_home_id': fields.many2one('res.partner.address', 'Home Address'),
159         'partner_id': fields.related('address_home_id', 'partner_id', type='many2one', relation='res.partner', readonly=True, help="Partner that is related to the current employee. Accounting transaction will be written on this partner belongs to employee."),
160         'bank_account_id':fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',partner_id)]", help="Employee bank salary account"),
161         'work_phone': fields.char('Work Phone', size=32, readonly=False),
162         'mobile_phone': fields.char('Work Mobile', size=32, readonly=False),
163         'work_email': fields.char('Work E-mail', size=240),
164         'work_location': fields.char('Office Location', size=32),
165         'notes': fields.text('Notes'),
166         'parent_id': fields.many2one('hr.employee', 'Manager'),
167         'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Categories'),
168         'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),
169         'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
170         'coach_id': fields.many2one('hr.employee', 'Coach'),
171         'job_id': fields.many2one('hr.job', 'Job'),
172         'photo': fields.binary('Photo'),
173         'passport_id':fields.char('Passport No', size=64),
174         'color': fields.integer('Color Index'),
175         'city': fields.related('address_id', 'city', type='char', string='City'),
176     }
177
178     def unlink(self, cr, uid, ids, context=None):
179         resource_obj = self.pool.get('resource.resource')
180         resource_ids = []
181         for employee in self.browse(cr, uid, ids, context=context):
182             resource = employee.resource_id
183             if resource:
184                 resource_ids.append(resource.id)
185         if resource_ids:
186             resource_obj.unlink(cr, uid, resource_ids, context=context)
187         return super(hr_employee, self).unlink(cr, uid, ids, context=context)
188
189     def onchange_address_id(self, cr, uid, ids, address, context=None):
190         if address:
191             address = self.pool.get('res.partner.address').browse(cr, uid, address, context=context)
192             return {'value': {'work_email': address.email, 'work_phone': address.phone, 'mobile_phone': address.mobile}}
193         return {'value': {}}
194
195     def onchange_company(self, cr, uid, ids, company, context=None):
196         address_id = False
197         if company:
198             company_id = self.pool.get('res.company').browse(cr, uid, company, context=context)
199             address = self.pool.get('res.partner').address_get(cr, uid, [company_id.partner_id.id], ['default'])
200             address_id = address and address['default'] or False
201         return {'value': {'address_id' : address_id}}
202
203     def onchange_department_id(self, cr, uid, ids, department_id, context=None):
204         value = {'parent_id': False}
205         if department_id:
206             department = self.pool.get('hr.department').browse(cr, uid, department_id)
207             value['parent_id'] = department.manager_id.id
208         return {'value': value}
209
210     def onchange_user(self, cr, uid, ids, user_id, context=None):
211         work_email = False
212         if user_id:
213             work_email = self.pool.get('res.users').browse(cr, uid, user_id, context=context).user_email
214         return {'value': {'work_email' : work_email}}
215
216     def _get_photo(self, cr, uid, context=None):
217         photo_path = addons.get_module_resource('hr','images','photo.png')
218         return open(photo_path, 'rb').read().encode('base64')
219
220     _defaults = {
221         'active': 1,
222         'photo': _get_photo,
223         'marital': 'single',
224         'color': 0,
225     }
226
227     def _check_recursion(self, cr, uid, ids, context=None):
228         level = 100
229         while len(ids):
230             cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
231             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
232             if not level:
233                 return False
234             level -= 1
235         return True
236
237     _constraints = [
238         (_check_recursion, 'Error ! You cannot create recursive Hierarchy of Employees.', ['parent_id']),
239     ]
240
241 hr_employee()
242
243 class hr_department(osv.osv):
244     _description = "Department"
245     _inherit = 'hr.department'
246     _columns = {
247         'manager_id': fields.many2one('hr.employee', 'Manager'),
248         'member_ids': fields.one2many('hr.employee', 'department_id', 'Members', readonly=True),
249     }
250
251 hr_department()
252
253
254 class res_users(osv.osv):
255     _name = 'res.users'
256     _inherit = 'res.users'
257
258     def create(self, cr, uid, data, context=None):
259         user_id = super(res_users, self).create(cr, uid, data, context=context)
260
261         # add shortcut unless 'noshortcut' is True in context
262         if not(context and context.get('noshortcut', False)):
263             data_obj = self.pool.get('ir.model.data')
264             try:
265                 data_id = data_obj._get_id(cr, uid, 'hr', 'ir_ui_view_sc_employee')
266                 view_id  = data_obj.browse(cr, uid, data_id, context=context).res_id
267                 self.pool.get('ir.ui.view_sc').copy(cr, uid, view_id, default = {
268                                             'user_id': user_id}, context=context)
269             except:
270                 # Tolerate a missing shortcut. See product/product.py for similar code.
271                 logging.getLogger('orm').debug('Skipped meetings shortcut for user "%s"', data.get('name','<new'))
272
273         return user_id
274
275 res_users()
276
277
278 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: