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