[IMP] hr_recruitment: applicant kanban customization
[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         '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.'),
62     }
63     _defaults = {
64         'sequence': 1,
65     }
66
67 class hr_recruitment_degree(osv.osv):
68     """ Degree of HR Recruitment """
69     _name = "hr.recruitment.degree"
70     _description = "Degree of Recruitment"
71     _columns = {
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."),
74     }
75     _defaults = {
76         'sequence': 1,
77     }
78     _sql_constraints = [
79         ('name_uniq', 'unique (name)', 'The name of the Degree of Recruitment must be unique!')
80     ]
81
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']
87
88     _track = {
89         'emp_id': {
90             'hr_recruitment.mt_applicant_hired': lambda self, cr, uid, obj, ctx=None: obj.emp_id,
91         },
92         'stage_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,
96         },
97     }
98     _mail_mass_mailing = _('Applicants')
99
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)
103
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)
108
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
112             department.
113         """
114         if context is None:
115             context = {}
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])
123         return None
124
125     def _get_default_company_id(self, cr, uid, department_id=None, context=None):
126         company_id = False
127         if department_id:
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
130         if not company_id:
131             company_id = self.pool['res.company']._company_default_get(cr, uid, 'hr.applicant', context=context)
132         return company_id            
133
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)
146         search_domain = []
147         if department_id:
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])))
154
155         fold = {}
156         for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
157             fold[stage.id] = stage.fold or False
158         return result, fold
159
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):
163             values = {
164                 'day_open': 0.0,
165                 'day_close': 0.0,
166             }
167
168             if issue.date_open:
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)
172
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)
177
178             # filter only required values
179             for field in fields:
180                 res[issue.id][field] = values[field]
181         return res
182
183     def _get_attachment_number(self, cr, uid, ids, fields, args, context=None):
184         res = dict.fromkeys(ids, 0)
185         for app_id in ids:
186             res[app_id] = self.pool['ir.attachment'].search_count(cr, uid, [('res_model', '=', 'hr.applicant'), ('res_id', '=', app_id)], context=context)
187         return res
188
189     _columns = {
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"),
237     }
238
239     _defaults = {
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),
245         'color': 0,
246         'priority': '0',
247         'date_last_stage_update': fields.datetime.now,
248     }
249
250     _group_by_full = {
251         'stage_id': _read_group_stage_ids
252     }
253
254     def onchange_job(self, cr, uid, ids, job_id=False, context=None):
255         department_id = False
256         user_id = False
257         if job_id:
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}}
262
263     def onchange_department_id(self, cr, uid, ids, department_id=False, stage_id=False, context=None):
264         if not stage_id:
265             stage_id = self.stage_find(cr, uid, [], department_id, [('fold', '=', False)], context=context)
266         return {'value': {'stage_id': stage_id}}
267
268     def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
269         data = {'partner_phone': False,
270                 'partner_mobile': False,
271                 'email_from': False}
272         if partner_id:
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}
278
279     def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):
280         if not stage_id:
281             return {'value': {}}
282         stage = self.pool['hr.recruitment.stage'].browse(cr, uid, stage_id, context=context)
283         if stage.fold:
284             return {'value': {'date_closed': fields.datetime.now()}}
285         return {'value': {'date_closed': False}}
286
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
291               be a default case
292         """
293         if isinstance(cases, (int, long)):
294             cases = self.browse(cr, uid, cases, context=context)
295         # collect all section_ids
296         department_ids = []
297         if section_id:
298             department_ids.append(section_id)
299         for case in cases:
300             if case.department_id:
301                 department_ids.append(case.department_id.id)
302         # OR all section_ids and OR with case_default
303         search_domain = []
304         if department_ids:
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)
311         if stage_ids:
312             return stage_ids[0]
313         return False
314
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
318         """
319         applicant = self.browse(cr, uid, ids[0], context)
320         applicant_ids = []
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)
327         res['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,
332         }
333         return res
334
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)
344         else:
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)
350
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)
359         else:
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)
363
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)])
369         return action
370
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)
377
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'))
385         return recipients
386
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.
391         """
392         if custom_values is None:
393             custom_values = {}
394         val = msg.get('from').split('<')[0]
395         defaults = {
396             'name':  msg.get('subject') or _("No Subject"),
397             'partner_name': val,
398             'email_from': msg.get('from'),
399             'email_cc': msg.get('cc'),
400             'user_id': False,
401             'partner_id': msg.get('author_id', False),
402         }
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)
407
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)
422         if applicant.job_id:
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)
428         return obj_id
429
430     def write(self, cr, uid, ids, vals, context=None):
431         if isinstance(ids, (int, long)):
432             ids = [ids]
433         res = True
434
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)
445         else:
446             res = super(hr_applicant, self).write(cr, uid, ids, vals, context=context)
447
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)
456
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,
463                                    active_ids=ids)
464                 compose_id = self.pool['mail.compose.message'].create(
465                     cr, uid, {
466                         'model': self._name,
467                         'composition_mode': 'mass_mail',
468                         'template_id': stage.template_id.id,
469                         'post': True,
470                         'notify': True,
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'],
478                     context=compose_ctx)
479                 self.pool['mail.compose.message'].send_mail(cr, uid, [compose_id], context=compose_ctx)
480         return res
481
482     def create_employee_from_applicant(self, cr, uid, ids, context=None):
483         """ Create an hr.employee from the hr.applicants """
484         if context is None:
485             context = {}
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')
489         emp_id = False
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)
511             else:
512                 raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
513
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]
516         if emp_id:
517             dict_act_window['res_id'] = emp_id
518         dict_act_window['view_mode'] = 'form,tree'
519         return dict_act_window
520
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)
527
528
529 class hr_job(osv.osv):
530     _inherit = "hr.job"
531     _name = "hr.job"
532     _inherits = {'mail.alias': 'alias_id'}
533
534     def _get_attached_docs(self, cr, uid, ids, field_name, arg, context=None):
535         res = {}
536         attachment_obj = self.pool.get('ir.attachment')
537         for job_id in ids:
538             applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', '=', job_id)], context=context)
539             res[job_id] = attachment_obj.search(
540                 cr, uid, [
541                     '|',
542                     '&', ('res_model', '=', 'hr.job'), ('res_id', '=', job_id),
543                     '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)
544                 ], context=context)
545         return res
546
547     def _count_all(self, cr, uid, ids, field_name, arg, context=None):
548         Applicant = self.pool['hr.applicant']
549         return {
550             job_id: {
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])
553             }
554             for job_id in ids
555         }
556
557     _columns = {
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'),
570     }
571
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
575
576     _defaults = {
577         'address_id': _address_get
578     }
579
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)
584
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)
591         return job_id
592
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)
599         return res
600
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)
605
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)])
613         return action
614
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)
617
618
619 class applicant_category(osv.osv):
620     """ Category of applicant """
621     _name = "hr.applicant_category"
622     _description = "Category of applicant"
623     _columns = {
624         'name': fields.char('Name', required=True, translate=True),
625     }