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