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