780c4390a092fe56f216172bdb00db1a4b4c354d
[odoo/odoo.git] / addons / hr_recruitment / hr_recruitment.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 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 openerp import tools
23
24 from datetime import datetime
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp.tools import html2plaintext
28
29 AVAILABLE_PRIORITIES = [
30     ('', ''),
31     ('5', 'Not Good'),
32     ('4', 'On Average'),
33     ('3', 'Good'),
34     ('2', 'Very Good'),
35     ('1', 'Excellent')
36 ]
37
38 class hr_recruitment_source(osv.osv):
39     """ Sources of HR Recruitment """
40     _name = "hr.recruitment.source"
41     _description = "Source of Applicants"
42     _columns = {
43         'name': fields.char('Source Name', size=64, required=True, translate=True),
44     }
45
46 class hr_recruitment_stage(osv.osv):
47     """ Stage of HR Recruitment """
48     _name = "hr.recruitment.stage"
49     _description = "Stage of Recruitment"
50     _order = 'sequence'
51     _columns = {
52         'name': fields.char('Name', size=64, required=True, translate=True),
53         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of stages."),
54         'department_id':fields.many2one('hr.department', 'Specific to a Department', help="Stages of the recruitment process may be different per department. If this stage is common to all departments, keep this field empty."),
55         'requirements': fields.text('Requirements'),
56         'fold': fields.boolean('Folded in Kanban View',
57                                help='This stage is folded in the kanban view when'
58                                'there are no records in that stage to display.'),
59     }
60     _defaults = {
61         'sequence': 1,
62     }
63
64 class hr_recruitment_degree(osv.osv):
65     """ Degree of HR Recruitment """
66     _name = "hr.recruitment.degree"
67     _description = "Degree of Recruitment"
68     _columns = {
69         'name': fields.char('Name', size=64, required=True, translate=True),
70         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of degrees."),
71     }
72     _defaults = {
73         'sequence': 1,
74     }
75     _sql_constraints = [
76         ('name_uniq', 'unique (name)', 'The name of the Degree of Recruitment must be unique!')
77     ]
78
79 class hr_applicant(osv.Model):
80     _name = "hr.applicant"
81     _description = "Applicant"
82     _order = "id desc"
83     _inherit = ['mail.thread', 'ir.needaction_mixin']
84     _track = {
85         'stage_id': {
86             # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages
87             'hr_recruitment.mt_applicant_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1,
88             'hr_recruitment.mt_applicant_stage_changed': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1,
89         },
90     }
91
92     def _get_default_department_id(self, cr, uid, context=None):
93         """ Gives default department by checking if present in the context """
94         return (self._resolve_department_id_from_context(cr, uid, context=context) or False)
95
96     def _get_default_stage_id(self, cr, uid, context=None):
97         """ Gives default stage_id """
98         department_id = self._get_default_department_id(cr, uid, context=context)
99         return self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
100
101     def _resolve_department_id_from_context(self, cr, uid, context=None):
102         """ Returns ID of department based on the value of 'default_department_id'
103             context key, or None if it cannot be resolved to a single
104             department.
105         """
106         if context is None:
107             context = {}
108         if type(context.get('default_department_id')) in (int, long):
109             return context.get('default_department_id')
110         if isinstance(context.get('default_department_id'), basestring):
111             department_name = context['default_department_id']
112             department_ids = self.pool.get('hr.department').name_search(cr, uid, name=department_name, context=context)
113             if len(department_ids) == 1:
114                 return int(department_ids[0][0])
115         return None
116
117     def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
118         access_rights_uid = access_rights_uid or uid
119         stage_obj = self.pool.get('hr.recruitment.stage')
120         order = stage_obj._order
121         # lame hack to allow reverting search, should just work in the trivial case
122         if read_group_order == 'stage_id desc':
123             order = "%s desc" % order
124         # retrieve section_id from the context and write the domain
125         # - ('id', 'in', 'ids'): add columns that should be present
126         # - OR ('department_id', '=', False), ('fold', '=', False): add default columns that are not folded
127         # - OR ('department_id', 'in', department_id), ('fold', '=', False) if department_id: add department columns that are not folded
128         department_id = self._resolve_department_id_from_context(cr, uid, context=context)
129         search_domain = []
130         if department_id:
131             search_domain += ['|', ('department_id', '=', department_id)]
132         search_domain += ['|', ('id', 'in', ids), ('department_id', '=', False)]
133         stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
134         result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
135         # restore order of the search
136         result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
137
138         fold = {}
139         for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
140             fold[stage.id] = stage.fold or False
141         return result, fold
142
143     def _compute_day(self, cr, uid, ids, fields, args, context=None):
144         """
145         @param cr: the current row, from the database cursor,
146         @param uid: the current user’s ID for security checks,
147         @param ids: List of Openday’s IDs
148         @return: difference between current date and log date
149         @param context: A standard dictionary for contextual values
150         """
151         res = {}
152         for issue in self.browse(cr, uid, ids, context=context):
153             for field in fields:
154                 res[issue.id] = {}
155                 duration = 0
156                 ans = False
157                 hours = 0
158
159                 if field in ['day_open']:
160                     if issue.date_open:
161                         date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
162                         date_open = datetime.strptime(issue.date_open, "%Y-%m-%d %H:%M:%S")
163                         ans = date_open - date_create
164
165                 elif field in ['day_close']:
166                     if issue.date_closed:
167                         date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
168                         date_close = datetime.strptime(issue.date_closed, "%Y-%m-%d %H:%M:%S")
169                         ans = date_close - date_create
170                 if ans:
171                     duration = float(ans.days)
172                     res[issue.id][field] = abs(float(duration))
173         return res
174
175     _columns = {
176         'name': fields.char('Subject', size=128, required=True),
177         'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the case without removing it."),
178         'description': fields.text('Description'),
179         'email_from': fields.char('Email', size=128, help="These people will receive email."),
180         'email_cc': fields.text('Watchers Emails', size=252, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"),
181         'probability': fields.float('Probability'),
182         'partner_id': fields.many2one('res.partner', 'Contact'),
183         'create_date': fields.datetime('Creation Date', readonly=True, select=True),
184         'write_date': fields.datetime('Update Date', readonly=True),
185         'stage_id': fields.many2one ('hr.recruitment.stage', 'Stage', track_visibility='onchange',
186                         domain="['|', ('department_id', '=', department_id), ('department_id', '=', False)]"),
187         'last_stage_id': fields.many2one('hr.recruitment.stage', 'Last Stage',
188                                          help='Stage of the applicant before being in the current stage. Used for lost cases analysis.'),
189         'categ_ids': fields.many2many('hr.applicant_category', string='Tags'),
190         'company_id': fields.many2one('res.company', 'Company'),
191         'user_id': fields.many2one('res.users', 'Responsible', track_visibility='onchange'),
192         'date_closed': fields.datetime('Closed', readonly=True, select=True),
193         'date_open': fields.datetime('Assigned', readonly=True, select=True),
194         'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
195         'date_action': fields.date('Next Action Date'),
196         'title_action': fields.char('Next Action', size=64),
197         'priority': fields.selection(AVAILABLE_PRIORITIES, 'Appreciation'),
198         'job_id': fields.many2one('hr.job', 'Applied Job'),
199         'salary_proposed_extra': fields.char('Proposed Salary Extra', size=100, help="Salary Proposed by the Organisation, extra advantages"),
200         'salary_expected_extra': fields.char('Expected Salary Extra', size=100, help="Salary Expected by Applicant, extra advantages"),
201         'salary_proposed': fields.float('Proposed Salary', help="Salary Proposed by the Organisation"),
202         'salary_expected': fields.float('Expected Salary', help="Salary Expected by Applicant"),
203         'availability': fields.integer('Availability'),
204         'partner_name': fields.char("Applicant's Name", size=64),
205         'partner_phone': fields.char('Phone', size=32),
206         'partner_mobile': fields.char('Mobile', size=32),
207         'type_id': fields.many2one('hr.recruitment.degree', 'Degree'),
208         'department_id': fields.many2one('hr.department', 'Department'),
209         'survey': fields.related('job_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
210         'response': fields.integer("Response"),
211         'reference': fields.char('Referred By', size=128),
212         'source_id': fields.many2one('hr.recruitment.source', 'Source'),
213         'day_open': fields.function(_compute_day, string='Days to Open', \
214                                 multi='day_open', type="float", store=True),
215         'day_close': fields.function(_compute_day, string='Days to Close', \
216                                 multi='day_close', type="float", store=True),
217         'color': fields.integer('Color Index'),
218         'emp_id': fields.many2one('hr.employee', string='Employee',
219             help='Employee linked to the applicant.'),
220         'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
221     }
222
223     _defaults = {
224         'active': lambda *a: 1,
225         'user_id': lambda s, cr, uid, c: uid,
226         'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
227         'department_id': lambda s, cr, uid, c: s._get_default_department_id(cr, uid, c),
228         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'hr.applicant', context=c),
229         'color': 0,
230         'date_last_stage_update': fields.datetime.now,
231     }
232
233     _group_by_full = {
234         'stage_id': _read_group_stage_ids
235     }
236
237     def onchange_job(self, cr, uid, ids, job_id=False, context=None):
238         if job_id:
239             job_record = self.pool.get('hr.job').browse(cr, uid, job_id, context=context)
240             if job_record and job_record.department_id:
241                 return {'value': {'department_id': job_record.department_id.id}}
242         return {}
243
244     def onchange_department_id(self, cr, uid, ids, department_id=False, stage_id=False, context=None):
245         if not stage_id:
246             stage_id = self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
247         return {'value': {'stage_id': stage_id}}
248
249     def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
250         data = {'partner_phone': False,
251                 'partner_mobile': False,
252                 'email_from': False}
253         if partner_id:
254             addr = self.pool.get('res.partner').browse(cr, uid, partner_id, context)
255             data.update({'partner_phone': addr.phone,
256                         'partner_mobile': addr.mobile,
257                         'email_from': addr.email})
258         return {'value': data}
259
260     def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
261         """ Override of the base.stage method
262             Parameter of the stage search taken from the lead:
263             - department_id: if set, stages must belong to this section or
264               be a default case
265         """
266         if isinstance(cases, (int, long)):
267             cases = self.browse(cr, uid, cases, context=context)
268         # collect all section_ids
269         department_ids = []
270         if section_id:
271             department_ids.append(section_id)
272         for case in cases:
273             if case.department_id:
274                 department_ids.append(case.department_id.id)
275         # OR all section_ids and OR with case_default
276         search_domain = []
277         if department_ids:
278             search_domain += ['|', ('department_id', 'in', department_ids)]
279         search_domain.append(('department_id', '=', False))
280         # AND with the domain in parameter
281         search_domain += list(domain)
282         # perform search, return the first found
283         stage_ids = self.pool.get('hr.recruitment.stage').search(cr, uid, search_domain, order=order, context=context)
284         if stage_ids:
285             return stage_ids[0]
286         return False
287
288     def action_makeMeeting(self, cr, uid, ids, context=None):
289         """ This opens Meeting's calendar view to schedule meeting on current applicant
290             @return: Dictionary value for created Meeting view
291         """
292         applicant = self.browse(cr, uid, ids[0], context)
293         category = self.pool.get('ir.model.data').get_object(cr, uid, 'hr_recruitment', 'categ_meet_interview', context)
294         res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'base_calendar', 'action_crm_meeting', context)
295         res['context'] = {
296             'default_partner_ids': applicant.partner_id and [applicant.partner_id.id] or False,
297             'default_user_id': uid,
298             'default_name': applicant.name,
299             'default_categ_ids': category and [category.id] or False,
300         }
301         return res
302
303     def action_print_survey(self, cr, uid, ids, context=None):
304         """
305         If response is available then print this response otherwise print survey form(print template of the survey).
306
307         @param self: The object pointer
308         @param cr: the current row, from the database cursor,
309         @param uid: the current user’s ID for security checks,
310         @param ids: List of Survey IDs
311         @param context: A standard dictionary for contextual values
312         @return: Dictionary value for print survey form.
313         """
314         if context is None:
315             context = {}
316         record = self.browse(cr, uid, ids, context=context)
317         record = record and record[0]
318         context.update({'survey_id': record.survey.id, 'response_id': [record.response], 'response_no': 0, })
319         value = self.pool.get("survey").action_print_survey(cr, uid, ids, context=context)
320         return value
321
322     def message_get_suggested_recipients(self, cr, uid, ids, context=None):
323         recipients = super(hr_applicant, self).message_get_suggested_recipients(cr, uid, ids, context=context)
324         for applicant in self.browse(cr, uid, ids, context=context):
325             if applicant.partner_id:
326                 self._message_add_suggested_recipient(cr, uid, recipients, applicant, partner=applicant.partner_id, reason=_('Contact'))
327             elif applicant.email_from:
328                 self._message_add_suggested_recipient(cr, uid, recipients, applicant, email=applicant.email_from, reason=_('Contact Email'))
329         return recipients
330
331     def message_new(self, cr, uid, msg, custom_values=None, context=None):
332         """ Overrides mail_thread message_new that is called by the mailgateway
333             through message_process.
334             This override updates the document according to the email.
335         """
336         if custom_values is None: custom_values = {}
337         val = msg.get('from').split('<')[0]
338         defaults = {
339             'name':  msg.get('subject') or _("No Subject"),
340             'partner_name':val,
341             'email_from': msg.get('from'),
342             'email_cc': msg.get('cc'),
343             'user_id': False,
344             'partner_id': msg.get('author_id', False),
345         }
346         if msg.get('priority'):
347             defaults['priority'] = msg.get('priority')
348         defaults.update(custom_values)
349         return super(hr_applicant,self).message_new(cr, uid, msg, custom_values=defaults, context=context)
350
351     def message_update(self, cr, uid, ids, msg, update_vals=None, context=None):
352         """ Override mail_thread message_update that is called by the mailgateway
353             through message_process.
354             This method updates the document according to the email.
355         """
356         if isinstance(ids, (str, int, long)):
357             ids = [ids]
358         if update_vals is None:
359             update_vals = {}
360
361         update_vals.update({
362             'email_from': msg.get('from'),
363             'email_cc': msg.get('cc'),
364         })
365         if msg.get('priority'):
366             update_vals['priority'] = msg.get('priority')
367
368         maps = {
369             'cost': 'planned_cost',
370             'revenue': 'planned_revenue',
371             'probability': 'probability',
372         }
373         for line in msg.get('body', '').split('\n'):
374             line = line.strip()
375             res = tools.command_re.match(line)
376             if res and maps.get(res.group(1).lower(), False):
377                 key = maps.get(res.group(1).lower())
378                 update_vals[key] = res.group(2).lower()
379
380         return super(hr_applicant, self).message_update(cr, uid, ids, msg, update_vals=update_vals, context=context)
381
382     def create(self, cr, uid, vals, context=None):
383         if context is None:
384             context = {}
385         if vals.get('department_id') and not context.get('default_department_id'):
386             context['default_department_id'] = vals.get('department_id')
387
388         obj_id = super(hr_applicant, self).create(cr, uid, vals, context=context)
389         applicant = self.browse(cr, uid, obj_id, context=context)
390         if applicant.job_id:
391             self.pool.get('hr.job').message_post(cr, uid, [applicant.job_id.id], body=_('Applicant <b>created</b>'), subtype="hr_recruitment.mt_job_new_applicant", context=context)
392         return obj_id
393
394     def write(self, cr, uid, ids, vals, context=None):
395         if isinstance(ids, (int, long)):
396             ids = [ids]
397         # user_id change: update date_start
398         if vals.get('user_id'):
399             vals['date_start'] = fields.datetime.now()
400         # stage_id: track last stage before update
401         if 'stage_id' in vals:
402             vals['date_last_stage_update'] = fields.datetime.now()
403             for applicant in self.browse(cr, uid, ids, context=None):
404                 vals['last_stage_id'] = applicant.stage_id.id
405                 res = super(hr_applicant, self).write(cr, uid, [applicant.id], vals, context=context)
406             return res
407         return super(hr_applicant, self).write(cr, uid, ids, vals, context=context)
408
409     def create_employee_from_applicant(self, cr, uid, ids, context=None):
410         """ Create an hr.employee from the hr.applicants """
411         if context is None:
412             context = {}
413         hr_employee = self.pool.get('hr.employee')
414         model_data = self.pool.get('ir.model.data')
415         act_window = self.pool.get('ir.actions.act_window')
416         emp_id = False
417         for applicant in self.browse(cr, uid, ids, context=context):
418             address_id = contact_name = False
419             if applicant.partner_id:
420                 address_id = self.pool.get('res.partner').address_get(cr, uid, [applicant.partner_id.id], ['contact'])['contact']
421                 contact_name = self.pool.get('res.partner').name_get(cr, uid, [applicant.partner_id.id])[0][1]
422             if applicant.job_id and (applicant.partner_name or contact_name):
423                 applicant.job_id.write({'no_of_recruitment': applicant.job_id.no_of_recruitment - 1})
424                 emp_id = hr_employee.create(cr, uid, {'name': applicant.partner_name or contact_name,
425                                                      'job_id': applicant.job_id.id,
426                                                      'address_home_id': address_id,
427                                                      'department_id': applicant.department_id.id
428                                                      })
429                 self.write(cr, uid, [applicant.id], {'emp_id': emp_id}, context=context)
430             else:
431                 raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
432
433         action_model, action_id = model_data.get_object_reference(cr, uid, 'hr', 'open_view_employee_list')
434         dict_act_window = act_window.read(cr, uid, action_id, [])
435         if emp_id:
436             dict_act_window['res_id'] = emp_id
437         dict_act_window['view_mode'] = 'form,tree'
438         return dict_act_window
439
440     def set_priority(self, cr, uid, ids, priority, *args):
441         """Set applicant priority
442         """
443         return self.write(cr, uid, ids, {'priority': priority})
444
445     def set_high_priority(self, cr, uid, ids, *args):
446         """Set applicant priority to high
447         """
448         return self.set_priority(cr, uid, ids, '1')
449
450     def set_normal_priority(self, cr, uid, ids, *args):
451         """Set applicant priority to normal
452         """
453         return self.set_priority(cr, uid, ids, '3')
454
455     def get_empty_list_help(self, cr, uid, help, context=None):
456         context['empty_list_help_model'] = 'hr.job'
457         context['empty_list_help_id'] = context.get('default_job_id', None)
458         context['empty_list_help_document_name'] = _("job applicants")
459         return super(hr_applicant, self).get_empty_list_help(cr, uid, help, context=context)
460
461
462 class hr_job(osv.osv):
463     _inherit = "hr.job"
464     _name = "hr.job"
465     _inherits = {'mail.alias': 'alias_id'}
466     _columns = {
467         'survey_id': fields.many2one('survey', 'Interview Form', help="Choose an interview form for this job position and you will be able to print/answer this interview from all applicants who apply for this job"),
468         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
469                                     help="Email alias for this job position. New emails will automatically "
470                                          "create new applicants for this job position."),
471     }
472
473     def _auto_init(self, cr, context=None):
474         """Installation hook to create aliases for all jobs and avoid constraint errors."""
475         return self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(hr_job, self)._auto_init,
476             'hr.applicant', self._columns['alias_id'], 'name', alias_prefix='job+', alias_defaults={'job_id': 'id'}, context=context)
477
478     def create(self, cr, uid, vals, context=None):
479         alias_context = dict(context, alias_model_name='hr.applicant', alias_parent_model_name=self._name)
480         job_id = super(hr_job, self).create(cr, uid, vals, context=alias_context)
481         job = self.browse(cr, uid, job_id, context=context)
482         self.pool.get('mail.alias').write(cr, uid, [job.alias_id.id], {'alias_parent_thread_id': job_id, "alias_defaults": {'job_id': job_id}}, context)
483         return job_id
484
485     def unlink(self, cr, uid, ids, context=None):
486         # Cascade-delete mail aliases as well, as they should not exist without the job position.
487         mail_alias = self.pool.get('mail.alias')
488         alias_ids = [job.alias_id.id for job in self.browse(cr, uid, ids, context=context) if job.alias_id]
489         res = super(hr_job, self).unlink(cr, uid, ids, context=context)
490         mail_alias.unlink(cr, uid, alias_ids, context=context)
491         return res
492
493     def action_print_survey(self, cr, uid, ids, context=None):
494         if context is None:
495             context = {}
496         datas = {}
497         record = self.browse(cr, uid, ids, context=context)[0]
498         if record.survey_id:
499             datas['ids'] = [record.survey_id.id]
500         datas['model'] = 'survey.print'
501         context.update({'response_id': [0], 'response_no': 0})
502         return {
503             'type': 'ir.actions.report.xml',
504             'report_name': 'survey.form',
505             'datas': datas,
506             'context': context,
507             'nodestroy': True,
508         }
509
510
511 class applicant_category(osv.osv):
512     """ Category of applicant """
513     _name = "hr.applicant_category"
514     _description = "Category of applicant"
515     _columns = {
516         'name': fields.char('Name', size=64, required=True, translate=True),
517     }
518
519 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: