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 datetime import datetime
24 from openerp import tools
25 from openerp import SUPERUSER_ID
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
30 AVAILABLE_PRIORITIES = [
37 class hr_recruitment_source(osv.osv):
38 """ Sources of HR Recruitment """
39 _name = "hr.recruitment.source"
40 _description = "Source of Applicants"
42 'name': fields.char('Source Name', required=True, translate=True),
45 class hr_recruitment_stage(osv.osv):
46 """ Stage of HR Recruitment """
47 _name = "hr.recruitment.stage"
48 _description = "Stage of Recruitment"
51 'name': fields.char('Name', required=True, translate=True),
52 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of stages."),
53 '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."),
54 'requirements': fields.text('Requirements'),
55 '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."),
56 'legend_priority': fields.text(
57 'Priority Management Explanation', translate=True,
58 help='Explanation text to help users using the star and priority mechanism on applicants that are in this stage.'),
59 'fold': fields.boolean('Folded in Kanban View',
60 help='This stage is folded in the kanban view when'
61 'there are no records in that stage to display.'),
67 class hr_recruitment_degree(osv.osv):
68 """ Degree of HR Recruitment """
69 _name = "hr.recruitment.degree"
70 _description = "Degree of Recruitment"
72 'name': fields.char('Name', required=True, translate=True),
73 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of degrees."),
79 ('name_uniq', 'unique (name)', 'The name of the Degree of Recruitment must be unique!')
82 class hr_applicant(osv.Model):
83 _name = "hr.applicant"
84 _description = "Applicant"
85 _order = "priority desc, id desc"
86 _inherit = ['mail.thread', 'ir.needaction_mixin']
90 'hr_recruitment.mt_applicant_hired': lambda self, cr, uid, obj, ctx=None: obj.emp_id,
93 # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages
94 'hr_recruitment.mt_applicant_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1,
95 'hr_recruitment.mt_applicant_stage_changed': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1,
98 _mail_mass_mailing = _('Applicants')
100 def _get_default_department_id(self, cr, uid, context=None):
101 """ Gives default department by checking if present in the context """
102 return (self._resolve_department_id_from_context(cr, uid, context=context) or False)
104 def _get_default_stage_id(self, cr, uid, context=None):
105 """ Gives default stage_id """
106 department_id = self._get_default_department_id(cr, uid, context=context)
107 return self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
109 def _resolve_department_id_from_context(self, cr, uid, context=None):
110 """ Returns ID of department based on the value of 'default_department_id'
111 context key, or None if it cannot be resolved to a single
116 if type(context.get('default_department_id')) in (int, long):
117 return context.get('default_department_id')
118 if isinstance(context.get('default_department_id'), basestring):
119 department_name = context['default_department_id']
120 department_ids = self.pool.get('hr.department').name_search(cr, uid, name=department_name, context=context)
121 if len(department_ids) == 1:
122 return int(department_ids[0][0])
125 def _get_default_company_id(self, cr, uid, department_id=None, context=None):
128 department = self.pool['hr.department'].browse(cr, uid, department_id, context=context)
129 company_id = department.company_id.id if department and department.company_id else False
131 company_id = self.pool['res.company']._company_default_get(cr, uid, 'hr.applicant', context=context)
134 def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
135 access_rights_uid = access_rights_uid or uid
136 stage_obj = self.pool.get('hr.recruitment.stage')
137 order = stage_obj._order
138 # lame hack to allow reverting search, should just work in the trivial case
139 if read_group_order == 'stage_id desc':
140 order = "%s desc" % order
141 # retrieve section_id from the context and write the domain
142 # - ('id', 'in', 'ids'): add columns that should be present
143 # - OR ('department_id', '=', False), ('fold', '=', False): add default columns that are not folded
144 # - OR ('department_id', 'in', department_id), ('fold', '=', False) if department_id: add department columns that are not folded
145 department_id = self._resolve_department_id_from_context(cr, uid, context=context)
148 search_domain += ['|', ('department_id', '=', department_id)]
149 search_domain += ['|', ('id', 'in', ids), ('department_id', '=', False)]
150 stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
151 result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
152 # restore order of the search
153 result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
156 for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
157 fold[stage.id] = stage.fold or False
160 def _compute_day(self, cr, uid, ids, fields, args, context=None):
161 res = dict((res_id, {}) for res_id in ids)
162 for issue in self.browse(cr, uid, ids, context=context):
169 date_create = datetime.strptime(issue.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
170 date_open = datetime.strptime(issue.date_open, tools.DEFAULT_SERVER_DATETIME_FORMAT)
171 values['day_open'] = (date_open - date_create).total_seconds() / (24.0 * 3600)
173 if issue.date_closed:
174 date_create = datetime.strptime(issue.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
175 date_closed = datetime.strptime(issue.date_closed, tools.DEFAULT_SERVER_DATETIME_FORMAT)
176 values['day_close'] = (date_closed - date_create).total_seconds() / (24.0 * 3600)
178 # filter only required values
180 res[issue.id][field] = values[field]
183 def _get_attachment_number(self, cr, uid, ids, fields, args, context=None):
184 res = dict.fromkeys(ids, 0)
186 res[app_id] = self.pool['ir.attachment'].search_count(cr, uid, [('res_model', '=', 'hr.applicant'), ('res_id', '=', app_id)], context=context)
190 'name': fields.char('Subject / Application Name', required=True),
191 'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the case without removing it."),
192 'description': fields.text('Description'),
193 'email_from': fields.char('Email', size=128, help="These people will receive email."),
194 '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"),
195 'probability': fields.float('Probability'),
196 'partner_id': fields.many2one('res.partner', 'Contact'),
197 'create_date': fields.datetime('Creation Date', readonly=True, select=True),
198 'write_date': fields.datetime('Update Date', readonly=True),
199 'stage_id': fields.many2one ('hr.recruitment.stage', 'Stage', track_visibility='onchange',
200 domain="['|', ('department_id', '=', department_id), ('department_id', '=', False)]"),
201 'last_stage_id': fields.many2one('hr.recruitment.stage', 'Last Stage',
202 help='Stage of the applicant before being in the current stage. Used for lost cases analysis.'),
203 'categ_ids': fields.many2many('hr.applicant_category', string='Tags'),
204 'company_id': fields.many2one('res.company', 'Company'),
205 'user_id': fields.many2one('res.users', 'Responsible', track_visibility='onchange'),
206 'date_closed': fields.datetime('Closed', readonly=True, select=True),
207 'date_open': fields.datetime('Assigned', readonly=True, select=True),
208 'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
209 'date_action': fields.date('Next Action Date'),
210 'title_action': fields.char('Next Action', size=64),
211 'priority': fields.selection(AVAILABLE_PRIORITIES, 'Appreciation'),
212 'job_id': fields.many2one('hr.job', 'Applied Job'),
213 'salary_proposed_extra': fields.char('Proposed Salary Extra', help="Salary Proposed by the Organisation, extra advantages"),
214 'salary_expected_extra': fields.char('Expected Salary Extra', help="Salary Expected by Applicant, extra advantages"),
215 'salary_proposed': fields.float('Proposed Salary', help="Salary Proposed by the Organisation"),
216 'salary_expected': fields.float('Expected Salary', help="Salary Expected by Applicant"),
217 'availability': fields.integer('Availability', help="The number of days in which the applicant will be available to start working"),
218 'partner_name': fields.char("Applicant's Name"),
219 'partner_phone': fields.char('Phone', size=32),
220 'partner_mobile': fields.char('Mobile', size=32),
221 'type_id': fields.many2one('hr.recruitment.degree', 'Degree'),
222 'department_id': fields.many2one('hr.department', 'Department'),
223 'survey': fields.related('job_id', 'survey_id', type='many2one', relation='survey.survey', string='Survey'),
224 'response_id': fields.many2one('survey.user_input', "Response", ondelete='set null', oldname="response"),
225 'reference': fields.char('Referred By'),
226 'source_id': fields.many2one('hr.recruitment.source', 'Source'),
227 'day_open': fields.function(_compute_day, string='Days to Open',
228 multi='day_open', type="float",
229 store={'hr.applicant': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}),
230 'day_close': fields.function(_compute_day, string='Days to Close',
231 multi='day_close', type="float",
232 store={'hr.applicant': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}),
233 'color': fields.integer('Color Index'),
234 'emp_id': fields.many2one('hr.employee', string='Employee', track_visibility='onchange', help='Employee linked to the applicant.'),
235 'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
236 'attachment_number': fields.function(_get_attachment_number, string='Number of Attachments', type="integer"),
240 'active': lambda *a: 1,
241 'user_id': lambda s, cr, uid, c: uid,
242 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
243 'department_id': lambda s, cr, uid, c: s._get_default_department_id(cr, uid, c),
244 'company_id': lambda s, cr, uid, c: s._get_default_company_id(cr, uid, s._get_default_department_id(cr, uid, c), c),
247 'date_last_stage_update': fields.datetime.now,
251 'stage_id': _read_group_stage_ids
254 def onchange_job(self, cr, uid, ids, job_id=False, context=None):
255 department_id = False
258 job_record = self.pool.get('hr.job').browse(cr, uid, job_id, context=context)
259 department_id = job_record and job_record.department_id and job_record.department_id.id or False
260 user_id = job_record and job_record.user_id and job_record.user_id.id or False
261 return {'value': {'department_id': department_id, 'user_id': user_id}}
263 def onchange_department_id(self, cr, uid, ids, department_id=False, stage_id=False, context=None):
265 stage_id = self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
266 return {'value': {'stage_id': stage_id}}
268 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
269 data = {'partner_phone': False,
270 'partner_mobile': False,
273 addr = self.pool.get('res.partner').browse(cr, uid, partner_id, context)
274 data.update({'partner_phone': addr.phone,
275 'partner_mobile': addr.mobile,
276 'email_from': addr.email})
277 return {'value': data}
279 def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):
282 stage = self.pool['hr.recruitment.stage'].browse(cr, uid, stage_id, context=context)
284 return {'value': {'date_closed': fields.datetime.now()}}
285 return {'value': {'date_closed': False}}
287 def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
288 """ Override of the base.stage method
289 Parameter of the stage search taken from the lead:
290 - department_id: if set, stages must belong to this section or
293 if isinstance(cases, (int, long)):
294 cases = self.browse(cr, uid, cases, context=context)
295 # collect all section_ids
298 department_ids.append(section_id)
300 if case.department_id:
301 department_ids.append(case.department_id.id)
302 # OR all section_ids and OR with case_default
305 search_domain += ['|', ('department_id', 'in', department_ids)]
306 search_domain.append(('department_id', '=', False))
307 # AND with the domain in parameter
308 search_domain += list(domain)
309 # perform search, return the first found
310 stage_ids = self.pool.get('hr.recruitment.stage').search(cr, uid, search_domain, order=order, context=context)
315 def action_makeMeeting(self, cr, uid, ids, context=None):
316 """ This opens Meeting's calendar view to schedule meeting on current applicant
317 @return: Dictionary value for created Meeting view
319 applicant = self.browse(cr, uid, ids[0], context)
321 if applicant.partner_id:
322 applicant_ids.append(applicant.partner_id.id)
323 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:
324 applicant_ids.append(applicant.department_id.manager_id.user_id.partner_id.id)
325 category = self.pool.get('ir.model.data').get_object(cr, uid, 'hr_recruitment', 'categ_meet_interview', context)
326 res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'calendar', 'action_calendar_event', context)
328 'default_partner_ids': applicant_ids,
329 'default_user_id': uid,
330 'default_name': applicant.name,
331 'default_categ_ids': category and [category.id] or False,
335 def action_start_survey(self, cr, uid, ids, context=None):
336 context = dict(context or {})
337 applicant = self.browse(cr, uid, ids, context=context)[0]
338 survey_obj = self.pool.get('survey.survey')
339 response_obj = self.pool.get('survey.user_input')
340 # create a response and link it to this applicant
341 if not applicant.response_id:
342 response_id = response_obj.create(cr, uid, {'survey_id': applicant.survey.id, 'partner_id': applicant.partner_id.id}, context=context)
343 self.write(cr, uid, ids[0], {'response_id': response_id}, context=context)
345 response_id = applicant.response_id.id
346 # grab the token of the response and start surveying
347 response = response_obj.browse(cr, uid, response_id, context=context)
348 context.update({'survey_token': response.token})
349 return survey_obj.action_start_survey(cr, uid, [applicant.survey.id], context=context)
351 def action_print_survey(self, cr, uid, ids, context=None):
352 """ If response is available then print this response otherwise print survey form (print template of the survey) """
353 context = dict(context or {})
354 applicant = self.browse(cr, uid, ids, context=context)[0]
355 survey_obj = self.pool.get('survey.survey')
356 response_obj = self.pool.get('survey.user_input')
357 if not applicant.response_id:
358 return survey_obj.action_print_survey(cr, uid, [applicant.survey.id], context=context)
360 response = response_obj.browse(cr, uid, applicant.response_id.id, context=context)
361 context.update({'survey_token': response.token})
362 return survey_obj.action_print_survey(cr, uid, [applicant.survey.id], context=context)
364 def action_get_attachment_tree_view(self, cr, uid, ids, context=None):
365 model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_attachment')
366 action = self.pool.get(model).read(cr, uid, action_id, context=context)
367 action['context'] = {'default_res_model': self._name, 'default_res_id': ids[0]}
368 action['domain'] = str(['&', ('res_model', '=', self._name), ('res_id', 'in', ids)])
371 def message_get_reply_to(self, cr, uid, ids, context=None):
372 """ Override to get the reply_to of the parent project. """
373 applicants = self.browse(cr, SUPERUSER_ID, ids, context=context)
374 job_ids = set([applicant.job_id.id for applicant in applicants if applicant.job_id])
375 aliases = self.pool['project.project'].message_get_reply_to(cr, uid, list(job_ids), context=context)
376 return dict((applicant.id, aliases.get(applicant.job_id and applicant.job_id.id or 0, False)) for applicant in applicants)
378 def message_get_suggested_recipients(self, cr, uid, ids, context=None):
379 recipients = super(hr_applicant, self).message_get_suggested_recipients(cr, uid, ids, context=context)
380 for applicant in self.browse(cr, uid, ids, context=context):
381 if applicant.partner_id:
382 self._message_add_suggested_recipient(cr, uid, recipients, applicant, partner=applicant.partner_id, reason=_('Contact'))
383 elif applicant.email_from:
384 self._message_add_suggested_recipient(cr, uid, recipients, applicant, email=applicant.email_from, reason=_('Contact Email'))
387 def message_new(self, cr, uid, msg, custom_values=None, context=None):
388 """ Overrides mail_thread message_new that is called by the mailgateway
389 through message_process.
390 This override updates the document according to the email.
392 if custom_values is None:
394 val = msg.get('from').split('<')[0]
396 'name': msg.get('subject') or _("No Subject"),
398 'email_from': msg.get('from'),
399 'email_cc': msg.get('cc'),
401 'partner_id': msg.get('author_id', False),
403 if msg.get('priority'):
404 defaults['priority'] = msg.get('priority')
405 defaults.update(custom_values)
406 return super(hr_applicant, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
408 def create(self, cr, uid, vals, context=None):
409 context = dict(context or {})
410 context['mail_create_nolog'] = True
411 if vals.get('department_id') and not context.get('default_department_id'):
412 context['default_department_id'] = vals.get('department_id')
413 if vals.get('job_id') or context.get('default_job_id'):
414 job_id = vals.get('job_id') or context.get('default_job_id')
415 vals.update(self.onchange_job(cr, uid, [], job_id, context=context)['value'])
416 if vals.get('user_id'):
417 vals['date_open'] = fields.datetime.now()
418 if 'stage_id' in vals:
419 vals.update(self.onchange_stage_id(cr, uid, None, vals.get('stage_id'), context=context)['value'])
420 obj_id = super(hr_applicant, self).create(cr, uid, vals, context=context)
421 applicant = self.browse(cr, uid, obj_id, context=context)
423 name = applicant.partner_name if applicant.partner_name else applicant.name
424 self.pool['hr.job'].message_post(
425 cr, uid, [applicant.job_id.id],
426 body=_('New application from %s') % name,
427 subtype="hr_recruitment.mt_job_applicant_new", context=context)
430 def write(self, cr, uid, ids, vals, context=None):
431 if isinstance(ids, (int, long)):
435 # user_id change: update date_open
436 if vals.get('user_id'):
437 vals['date_open'] = fields.datetime.now()
438 # stage_id: track last stage before update
439 if 'stage_id' in vals:
440 vals['date_last_stage_update'] = fields.datetime.now()
441 vals.update(self.onchange_stage_id(cr, uid, ids, vals.get('stage_id'), context=context)['value'])
442 for applicant in self.browse(cr, uid, ids, context=None):
443 vals['last_stage_id'] = applicant.stage_id.id
444 res = super(hr_applicant, self).write(cr, uid, [applicant.id], vals, context=context)
446 res = super(hr_applicant, self).write(cr, uid, ids, vals, context=context)
448 # post processing: if job changed, post a message on the job
449 if vals.get('job_id'):
450 for applicant in self.browse(cr, uid, ids, context=None):
451 name = applicant.partner_name if applicant.partner_name else applicant.name
452 self.pool['hr.job'].message_post(
453 cr, uid, [vals['job_id']],
454 body=_('New application from %s') % name,
455 subtype="hr_recruitment.mt_job_applicant_new", context=context)
457 # post processing: if stage changed, post a message in the chatter
458 if vals.get('stage_id'):
459 stage = self.pool['hr.recruitment.stage'].browse(cr, uid, vals['stage_id'], context=context)
460 if stage.template_id:
461 # TDENOTE: probably factorize me in a message_post_with_template generic method FIXME
462 compose_ctx = dict(context,
464 compose_id = self.pool['mail.compose.message'].create(
467 'composition_mode': 'mass_mail',
468 'template_id': stage.template_id.id,
471 }, context=compose_ctx)
472 self.pool['mail.compose.message'].write(
473 cr, uid, [compose_id],
474 self.pool['mail.compose.message'].onchange_template_id(
475 cr, uid, [compose_id],
476 stage.template_id.id, 'mass_mail', self._name, False,
477 context=compose_ctx)['value'],
479 self.pool['mail.compose.message'].send_mail(cr, uid, [compose_id], context=compose_ctx)
482 def create_employee_from_applicant(self, cr, uid, ids, context=None):
483 """ Create an hr.employee from the hr.applicants """
486 hr_employee = self.pool.get('hr.employee')
487 model_data = self.pool.get('ir.model.data')
488 act_window = self.pool.get('ir.actions.act_window')
490 for applicant in self.browse(cr, uid, ids, context=context):
491 address_id = contact_name = False
492 if applicant.partner_id:
493 address_id = self.pool.get('res.partner').address_get(cr, uid, [applicant.partner_id.id], ['contact'])['contact']
494 contact_name = self.pool.get('res.partner').name_get(cr, uid, [applicant.partner_id.id])[0][1]
495 if applicant.job_id and (applicant.partner_name or contact_name):
496 applicant.job_id.write({'no_of_hired_employee': applicant.job_id.no_of_hired_employee + 1}, context=context)
497 create_ctx = dict(context, mail_broadcast=True)
498 emp_id = hr_employee.create(cr, uid, {'name': applicant.partner_name or contact_name,
499 'job_id': applicant.job_id.id,
500 'address_home_id': address_id,
501 'department_id': applicant.department_id.id or False,
502 'address_id': applicant.company_id and applicant.company_id.partner_id and applicant.company_id.partner_id.id or False,
503 'work_email': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.email or False,
504 'work_phone': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.phone or False,
505 }, context=create_ctx)
506 self.write(cr, uid, [applicant.id], {'emp_id': emp_id}, context=context)
507 self.pool['hr.job'].message_post(
508 cr, uid, [applicant.job_id.id],
509 body=_('New Employee %s Hired') % applicant.partner_name if applicant.partner_name else applicant.name,
510 subtype="hr_recruitment.mt_job_applicant_hired", context=context)
512 raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
514 action_model, action_id = model_data.get_object_reference(cr, uid, 'hr', 'open_view_employee_list')
515 dict_act_window = act_window.read(cr, uid, [action_id], [])[0]
517 dict_act_window['res_id'] = emp_id
518 dict_act_window['view_mode'] = 'form,tree'
519 return dict_act_window
521 def get_empty_list_help(self, cr, uid, help, context=None):
522 context = dict(context or {})
523 context['empty_list_help_model'] = 'hr.job'
524 context['empty_list_help_id'] = context.get('default_job_id', None)
525 context['empty_list_help_document_name'] = _("job applicants")
526 return super(hr_applicant, self).get_empty_list_help(cr, uid, help, context=context)
529 class hr_job(osv.osv):
532 _inherits = {'mail.alias': 'alias_id'}
534 def _get_attached_docs(self, cr, uid, ids, field_name, arg, context=None):
536 attachment_obj = self.pool.get('ir.attachment')
538 applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', '=', job_id)], context=context)
539 res[job_id] = attachment_obj.search(
542 '&', ('res_model', '=', 'hr.job'), ('res_id', '=', job_id),
543 '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)
547 def _count_all(self, cr, uid, ids, field_name, arg, context=None):
548 Applicant = self.pool['hr.applicant']
551 'application_count': Applicant.search_count(cr,uid, [('job_id', '=', job_id)], context=context),
552 'documents_count': len(self._get_attached_docs(cr, uid, [job_id], field_name, arg, context=context)[job_id])
558 'survey_id': fields.many2one('survey.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"),
559 'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
560 help="Email alias for this job position. New emails will automatically "
561 "create new applicants for this job position."),
562 'address_id': fields.many2one('res.partner', 'Job Location', help="Address where employees are working"),
563 'application_ids': fields.one2many('hr.applicant', 'job_id', 'Applications'),
564 'application_count': fields.function(_count_all, type='integer', string='Applications', multi=True),
565 'manager_id': fields.related('department_id', 'manager_id', type='many2one', string='Department Manager', relation='hr.employee', readonly=True, store=True),
566 'document_ids': fields.function(_get_attached_docs, type='one2many', relation='ir.attachment', string='Applications'),
567 'documents_count': fields.function(_count_all, type='integer', string='Documents', multi=True),
568 'user_id': fields.many2one('res.users', 'Recruitment Responsible', track_visibility='onchange'),
569 'color': fields.integer('Color Index'),
572 def _address_get(self, cr, uid, context=None):
573 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
574 return user.company_id.partner_id.id
577 'address_id': _address_get
580 def _auto_init(self, cr, context=None):
581 """Installation hook to create aliases for all jobs and avoid constraint errors."""
582 return self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(hr_job, self)._auto_init,
583 'hr.applicant', self._columns['alias_id'], 'name', alias_prefix='job+', alias_defaults={'job_id': 'id'}, context=context)
585 def create(self, cr, uid, vals, context=None):
586 # TDE note: shouldn't it be in mail_create_nolog ?
587 alias_context = dict(context, alias_model_name='hr.applicant', alias_parent_model_name=self._name)
588 job_id = super(hr_job, self).create(cr, uid, vals, context=alias_context)
589 job = self.browse(cr, uid, job_id, context=context)
590 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)
593 def unlink(self, cr, uid, ids, context=None):
594 # Cascade-delete mail aliases as well, as they should not exist without the job position.
595 mail_alias = self.pool.get('mail.alias')
596 alias_ids = [job.alias_id.id for job in self.browse(cr, uid, ids, context=context) if job.alias_id]
597 res = super(hr_job, self).unlink(cr, uid, ids, context=context)
598 mail_alias.unlink(cr, uid, alias_ids, context=context)
601 def action_print_survey(self, cr, uid, ids, context=None):
602 job = self.browse(cr, uid, ids, context=context)[0]
603 survey_id = job.survey_id.id
604 return self.pool.get('survey.survey').action_print_survey(cr, uid, [survey_id], context=context)
606 def action_get_attachment_tree_view(self, cr, uid, ids, context=None):
607 #open attachments of job and related applicantions.
608 model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_attachment')
609 action = self.pool.get(model).read(cr, uid, action_id, context=context)
610 applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', 'in', ids)], context=context)
611 action['context'] = {'default_res_model': self._name, 'default_res_id': ids[0]}
612 action['domain'] = str(['|', '&', ('res_model', '=', 'hr.job'), ('res_id', 'in', ids), '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)])
615 def action_set_no_of_recruitment(self, cr, uid, id, value, context=None):
616 return self.write(cr, uid, [id], {'no_of_recruitment': value}, context=context)
619 class applicant_category(osv.osv):
620 """ Category of applicant """
621 _name = "hr.applicant_category"
622 _description = "Category of applicant"
624 'name': fields.char('Name', required=True, translate=True),