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