1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from openerp import tools
24 from datetime import datetime
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp.tools import html2plaintext
29 AVAILABLE_PRIORITIES = [
38 class hr_recruitment_source(osv.osv):
39 """ Sources of HR Recruitment """
40 _name = "hr.recruitment.source"
41 _description = "Source of Applicants"
43 'name': fields.char('Source Name', size=64, required=True, translate=True),
46 class hr_recruitment_stage(osv.osv):
47 """ Stage of HR Recruitment """
48 _name = "hr.recruitment.stage"
49 _description = "Stage of Recruitment"
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 'template_id': fields.many2one('email.template', 'Use template', help="If set, a message is posted on the applicant using the template when the applicant is set to the stage."),
57 'fold': fields.boolean('Folded in Kanban View',
58 help='This stage is folded in the kanban view when'
59 'there are no records in that stage to display.'),
65 class hr_recruitment_degree(osv.osv):
66 """ Degree of HR Recruitment """
67 _name = "hr.recruitment.degree"
68 _description = "Degree of Recruitment"
70 'name': fields.char('Name', size=64, required=True, translate=True),
71 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of degrees."),
77 ('name_uniq', 'unique (name)', 'The name of the Degree of Recruitment must be unique!')
80 class hr_applicant(osv.Model):
81 _name = "hr.applicant"
82 _description = "Applicant"
84 _inherit = ['mail.thread', 'ir.needaction_mixin']
87 # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages
88 'hr_recruitment.mt_applicant_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1,
89 'hr_recruitment.mt_applicant_stage_changed': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1,
93 def _get_default_department_id(self, cr, uid, context=None):
94 """ Gives default department by checking if present in the context """
95 return (self._resolve_department_id_from_context(cr, uid, context=context) or False)
97 def _get_default_stage_id(self, cr, uid, context=None):
98 """ Gives default stage_id """
99 department_id = self._get_default_department_id(cr, uid, context=context)
100 return self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
102 def _resolve_department_id_from_context(self, cr, uid, context=None):
103 """ Returns ID of department based on the value of 'default_department_id'
104 context key, or None if it cannot be resolved to a single
109 if type(context.get('default_department_id')) in (int, long):
110 return context.get('default_department_id')
111 if isinstance(context.get('default_department_id'), basestring):
112 department_name = context['default_department_id']
113 department_ids = self.pool.get('hr.department').name_search(cr, uid, name=department_name, context=context)
114 if len(department_ids) == 1:
115 return int(department_ids[0][0])
118 def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
119 access_rights_uid = access_rights_uid or uid
120 stage_obj = self.pool.get('hr.recruitment.stage')
121 order = stage_obj._order
122 # lame hack to allow reverting search, should just work in the trivial case
123 if read_group_order == 'stage_id desc':
124 order = "%s desc" % order
125 # retrieve section_id from the context and write the domain
126 # - ('id', 'in', 'ids'): add columns that should be present
127 # - OR ('department_id', '=', False), ('fold', '=', False): add default columns that are not folded
128 # - OR ('department_id', 'in', department_id), ('fold', '=', False) if department_id: add department columns that are not folded
129 department_id = self._resolve_department_id_from_context(cr, uid, context=context)
132 search_domain += ['|', ('department_id', '=', department_id)]
133 search_domain += ['|', ('id', 'in', ids), ('department_id', '=', False)]
134 stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
135 result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
136 # restore order of the search
137 result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
140 for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
141 fold[stage.id] = stage.fold or False
144 def _compute_day(self, cr, uid, ids, fields, args, context=None):
146 @param cr: the current row, from the database cursor,
147 @param uid: the current user’s ID for security checks,
148 @param ids: List of Openday’s IDs
149 @return: difference between current date and log date
150 @param context: A standard dictionary for contextual values
153 for issue in self.browse(cr, uid, ids, context=context):
160 if field in ['day_open']:
162 date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
163 date_open = datetime.strptime(issue.date_open, "%Y-%m-%d %H:%M:%S")
164 ans = date_open - date_create
166 elif field in ['day_close']:
167 if issue.date_closed:
168 date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
169 date_close = datetime.strptime(issue.date_closed, "%Y-%m-%d %H:%M:%S")
170 ans = date_close - date_create
172 duration = float(ans.days)
173 res[issue.id][field] = abs(float(duration))
176 def _get_attachment_number(self, cr, uid, ids, fields, args, context=None):
177 res = dict.fromkeys(ids, 0)
179 res[app_id] = self.pool['ir.attachment'].search_count(cr, uid, [('res_model', '=', 'hr.applicant'), ('res_id', '=', app_id)], context=context)
183 'name': fields.char('Subject / Application Name', size=128, required=True),
184 'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the case without removing it."),
185 'description': fields.text('Description'),
186 'email_from': fields.char('Email', size=128, help="These people will receive email."),
187 '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"),
188 'probability': fields.float('Probability'),
189 'partner_id': fields.many2one('res.partner', 'Contact'),
190 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
191 'write_date': fields.datetime('Update Date', readonly=True),
192 'stage_id': fields.many2one ('hr.recruitment.stage', 'Stage', track_visibility='onchange',
193 domain="['|', ('department_id', '=', department_id), ('department_id', '=', False)]"),
194 'last_stage_id': fields.many2one('hr.recruitment.stage', 'Last Stage',
195 help='Stage of the applicant before being in the current stage. Used for lost cases analysis.'),
196 'categ_ids': fields.many2many('hr.applicant_category', string='Tags'),
197 'company_id': fields.many2one('res.company', 'Company'),
198 'user_id': fields.many2one('res.users', 'Responsible', track_visibility='onchange'),
199 'date_closed': fields.datetime('Closed', readonly=True, select=True),
200 'date_open': fields.datetime('Assigned', readonly=True, select=True),
201 'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
202 'date_action': fields.date('Next Action Date'),
203 'title_action': fields.char('Next Action', size=64),
204 'priority': fields.selection(AVAILABLE_PRIORITIES, 'Appreciation'),
205 'job_id': fields.many2one('hr.job', 'Applied Job'),
206 'salary_proposed_extra': fields.char('Proposed Salary Extra', size=100, help="Salary Proposed by the Organisation, extra advantages"),
207 'salary_expected_extra': fields.char('Expected Salary Extra', size=100, help="Salary Expected by Applicant, extra advantages"),
208 'salary_proposed': fields.float('Proposed Salary', help="Salary Proposed by the Organisation"),
209 'salary_expected': fields.float('Expected Salary', help="Salary Expected by Applicant"),
210 'availability': fields.integer('Availability', help="The number of days in which the applicant will be available to start working"),
211 'partner_name': fields.char("Applicant's Name", size=64),
212 'partner_phone': fields.char('Phone', size=32),
213 'partner_mobile': fields.char('Mobile', size=32),
214 'type_id': fields.many2one('hr.recruitment.degree', 'Degree'),
215 'department_id': fields.many2one('hr.department', 'Department'),
216 'survey': fields.related('job_id', 'survey_id', type='many2one', relation='survey', string='Survey'),
217 'response': fields.integer("Response"),
218 'reference': fields.char('Referred By', size=128),
219 'source_id': fields.many2one('hr.recruitment.source', 'Source'),
220 'day_open': fields.function(_compute_day, string='Days to Open', \
221 multi='day_open', type="float", store=True),
222 'day_close': fields.function(_compute_day, string='Days to Close', \
223 multi='day_close', type="float", store=True),
224 'color': fields.integer('Color Index'),
225 'emp_id': fields.many2one('hr.employee', string='Employee', help='Employee linked to the applicant.'),
226 'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
227 'attachment_number': fields.function(_get_attachment_number, string='Number of Attachments', type="integer"),
231 'active': lambda *a: 1,
232 'user_id': lambda s, cr, uid, c: uid,
233 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
234 'department_id': lambda s, cr, uid, c: s._get_default_department_id(cr, uid, c),
235 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'hr.applicant', context=c),
237 'date_last_stage_update': fields.datetime.now,
241 'stage_id': _read_group_stage_ids
244 def onchange_job(self, cr, uid, ids, job_id=False, context=None):
245 department_id = False
247 job_record = self.pool.get('hr.job').browse(cr, uid, job_id, context=context)
248 department_id = job_record and job_record.department_id and job_record.department_id.id or False
249 return {'value': {'department_id': department_id}}
251 def onchange_department_id(self, cr, uid, ids, department_id=False, stage_id=False, context=None):
253 stage_id = self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
254 return {'value': {'stage_id': stage_id}}
256 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
257 data = {'partner_phone': False,
258 'partner_mobile': False,
261 addr = self.pool.get('res.partner').browse(cr, uid, partner_id, context)
262 data.update({'partner_phone': addr.phone,
263 'partner_mobile': addr.mobile,
264 'email_from': addr.email})
265 return {'value': data}
267 def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
268 """ Override of the base.stage method
269 Parameter of the stage search taken from the lead:
270 - department_id: if set, stages must belong to this section or
273 if isinstance(cases, (int, long)):
274 cases = self.browse(cr, uid, cases, context=context)
275 # collect all section_ids
278 department_ids.append(section_id)
280 if case.department_id:
281 department_ids.append(case.department_id.id)
282 # OR all section_ids and OR with case_default
285 search_domain += ['|', ('department_id', 'in', department_ids)]
286 search_domain.append(('department_id', '=', False))
287 # AND with the domain in parameter
288 search_domain += list(domain)
289 # perform search, return the first found
290 stage_ids = self.pool.get('hr.recruitment.stage').search(cr, uid, search_domain, order=order, context=context)
295 def action_makeMeeting(self, cr, uid, ids, context=None):
296 """ This opens Meeting's calendar view to schedule meeting on current applicant
297 @return: Dictionary value for created Meeting view
299 applicant = self.browse(cr, uid, ids[0], context)
301 if applicant.partner_id:
302 applicant_ids.append(applicant.partner_id.id)
303 if applicant.department_id and applicant.department_id.manager_id and applicant.department_id.manager_id.user_id and applicant.department_id.manager_id.user_id.partner_id:
304 applicant_ids.append(applicant.department_id.manager_id.user_id.partner_id.id)
305 category = self.pool.get('ir.model.data').get_object(cr, uid, 'hr_recruitment', 'categ_meet_interview', context)
306 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'calendar', 'action_calendar_event', context)
308 'default_partner_ids': applicant_ids,
309 'default_user_id': uid,
310 'default_name': applicant.name,
311 'default_categ_ids': category and [category.id] or False,
315 def action_print_survey(self, cr, uid, ids, context=None):
317 If response is available then print this response otherwise print survey form(print template of the survey).
319 @param self: The object pointer
320 @param cr: the current row, from the database cursor,
321 @param uid: the current user’s ID for security checks,
322 @param ids: List of Survey IDs
323 @param context: A standard dictionary for contextual values
324 @return: Dictionary value for print survey form.
328 record = self.browse(cr, uid, ids, context=context)
329 record = record and record[0]
330 context.update({'survey_id': record.survey.id, 'response_id': [record.response], 'response_no': 0, })
331 value = self.pool.get("survey").action_print_survey(cr, uid, ids, context=context)
334 def action_get_attachment_tree_view(self, cr, uid, ids, context):
335 domain = ['&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', ids)]
337 'name': _('Attachments'),
339 'res_model': 'ir.attachment',
340 'type': 'ir.actions.act_window',
342 'view_mode': 'tree,form',
345 'context': "{'default_res_model': '%s'}" % (self._name)
348 def message_get_suggested_recipients(self, cr, uid, ids, context=None):
349 recipients = super(hr_applicant, self).message_get_suggested_recipients(cr, uid, ids, context=context)
350 for applicant in self.browse(cr, uid, ids, context=context):
351 if applicant.partner_id:
352 self._message_add_suggested_recipient(cr, uid, recipients, applicant, partner=applicant.partner_id, reason=_('Contact'))
353 elif applicant.email_from:
354 self._message_add_suggested_recipient(cr, uid, recipients, applicant, email=applicant.email_from, reason=_('Contact Email'))
357 def message_new(self, cr, uid, msg, custom_values=None, context=None):
358 """ Overrides mail_thread message_new that is called by the mailgateway
359 through message_process.
360 This override updates the document according to the email.
362 if custom_values is None:
364 val = msg.get('from').split('<')[0]
366 'name': msg.get('subject') or _("No Subject"),
368 'email_from': msg.get('from'),
369 'email_cc': msg.get('cc'),
371 'partner_id': msg.get('author_id', False),
373 if msg.get('priority'):
374 defaults['priority'] = msg.get('priority')
375 defaults.update(custom_values)
376 return super(hr_applicant, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
378 def create(self, cr, uid, vals, context=None):
381 if vals.get('department_id') and not context.get('default_department_id'):
382 context['default_department_id'] = vals.get('department_id')
384 obj_id = super(hr_applicant, self).create(cr, uid, vals, context=context)
385 applicant = self.browse(cr, uid, obj_id, context=context)
387 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)
390 def write(self, cr, uid, ids, vals, context=None):
391 if isinstance(ids, (int, long)):
395 # user_id change: update date_start
396 if vals.get('user_id'):
397 vals['date_start'] = fields.datetime.now()
398 # stage_id: track last stage before update
399 if 'stage_id' in vals:
400 vals['date_last_stage_update'] = fields.datetime.now()
401 for applicant in self.browse(cr, uid, ids, context=None):
402 vals['last_stage_id'] = applicant.stage_id.id
403 res = super(hr_applicant, self).write(cr, uid, [applicant.id], vals, context=context)
405 res = super(hr_applicant, self).write(cr, uid, ids, vals, context=context)
407 # post processing: if stage changed, post a message in the chatter
408 if vals.get('stage_id'):
409 stage = self.pool['hr.recruitment.stage'].browse(cr, uid, vals['stage_id'], context=context)
410 if stage.template_id:
411 # TDENOTE: probably factorize me in a message_post_with_template generic method FIXME
412 compose_ctx = dict(context,
414 compose_id = self.pool['mail.compose.message'].create(
417 'composition_mode': 'mass_mail',
418 'template_id': stage.template_id.id,
422 }, context=compose_ctx)
423 self.pool['mail.compose.message'].write(
424 cr, uid, [compose_id],
425 self.pool['mail.compose.message'].onchange_template_id(
426 cr, uid, [compose_id],
427 stage.template_id.id, 'mass_mail', self._name, False,
428 context=compose_ctx)['value'],
430 self.pool['mail.compose.message'].send_mail(cr, uid, [compose_id], context=compose_ctx)
433 def create_employee_from_applicant(self, cr, uid, ids, context=None):
434 """ Create an hr.employee from the hr.applicants """
437 hr_employee = self.pool.get('hr.employee')
438 model_data = self.pool.get('ir.model.data')
439 act_window = self.pool.get('ir.actions.act_window')
441 for applicant in self.browse(cr, uid, ids, context=context):
442 address_id = contact_name = False
443 if applicant.partner_id:
444 address_id = self.pool.get('res.partner').address_get(cr, uid, [applicant.partner_id.id], ['contact'])['contact']
445 contact_name = self.pool.get('res.partner').name_get(cr, uid, [applicant.partner_id.id])[0][1]
446 if applicant.job_id and (applicant.partner_name or contact_name):
447 applicant.job_id.write({'no_of_recruitment': applicant.job_id.no_of_recruitment - 1})
448 emp_id = hr_employee.create(cr, uid, {'name': applicant.partner_name or contact_name,
449 'job_id': applicant.job_id.id,
450 'address_home_id': address_id,
451 'department_id': applicant.department_id.id or False,
452 'address_id': applicant.company_id and applicant.company_id.partner_id and applicant.company_id.partner_id.id or False,
453 'work_email': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.email or False,
454 'work_phone': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.phone or False,
456 self.write(cr, uid, [applicant.id], {'emp_id': emp_id}, context=context)
458 raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
460 action_model, action_id = model_data.get_object_reference(cr, uid, 'hr', 'open_view_employee_list')
461 dict_act_window = act_window.read(cr, uid, action_id, [])
463 dict_act_window['res_id'] = emp_id
464 dict_act_window['view_mode'] = 'form,tree'
465 return dict_act_window
467 def set_priority(self, cr, uid, ids, priority, *args):
468 """Set applicant priority
470 return self.write(cr, uid, ids, {'priority': priority})
472 def set_high_priority(self, cr, uid, ids, *args):
473 """Set applicant priority to high
475 return self.set_priority(cr, uid, ids, '1')
477 def set_normal_priority(self, cr, uid, ids, *args):
478 """Set applicant priority to normal
480 return self.set_priority(cr, uid, ids, '3')
482 def get_empty_list_help(self, cr, uid, help, context=None):
483 context['empty_list_help_model'] = 'hr.job'
484 context['empty_list_help_id'] = context.get('default_job_id', None)
485 context['empty_list_help_document_name'] = _("job applicants")
486 return super(hr_applicant, self).get_empty_list_help(cr, uid, help, context=context)
489 class hr_job(osv.osv):
492 _inherits = {'mail.alias': 'alias_id'}
494 '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"),
495 'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
496 help="Email alias for this job position. New emails will automatically "
497 "create new applicants for this job position."),
498 'address_id': fields.many2one('res.partner', 'Job Location', help="Address where employees are working"),
500 def _address_get(self, cr, uid, context=None):
501 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
502 return user.company_id.partner_id.id
504 'address_id': _address_get
507 def _auto_init(self, cr, context=None):
508 """Installation hook to create aliases for all jobs and avoid constraint errors."""
509 return self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(hr_job, self)._auto_init,
510 'hr.applicant', self._columns['alias_id'], 'name', alias_prefix='job+', alias_defaults={'job_id': 'id'}, context=context)
512 def create(self, cr, uid, vals, context=None):
513 alias_context = dict(context, alias_model_name='hr.applicant', alias_parent_model_name=self._name)
514 job_id = super(hr_job, self).create(cr, uid, vals, context=alias_context)
515 job = self.browse(cr, uid, job_id, context=context)
516 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)
519 def unlink(self, cr, uid, ids, context=None):
520 # Cascade-delete mail aliases as well, as they should not exist without the job position.
521 mail_alias = self.pool.get('mail.alias')
522 alias_ids = [job.alias_id.id for job in self.browse(cr, uid, ids, context=context) if job.alias_id]
523 res = super(hr_job, self).unlink(cr, uid, ids, context=context)
524 mail_alias.unlink(cr, uid, alias_ids, context=context)
527 def action_print_survey(self, cr, uid, ids, context=None):
531 record = self.browse(cr, uid, ids, context=context)[0]
533 datas['ids'] = [record.survey_id.id]
534 datas['model'] = 'survey.print'
535 context.update({'response_id': [0], 'response_no': 0})
537 'type': 'ir.actions.report.xml',
538 'report_name': 'survey.form',
545 class applicant_category(osv.osv):
546 """ Category of applicant """
547 _name = "hr.applicant_category"
548 _description = "Category of applicant"
550 'name': fields.char('Name', size=64, required=True, translate=True),
553 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: