[REF] mail: same_thread field changed into no_auto_thread, its contrary, to avoid...
[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 = "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         '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 stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
280         """ Override of the base.stage method
281             Parameter of the stage search taken from the lead:
282             - department_id: if set, stages must belong to this section or
283               be a default case
284         """
285         if isinstance(cases, (int, long)):
286             cases = self.browse(cr, uid, cases, context=context)
287         # collect all section_ids
288         department_ids = []
289         if section_id:
290             department_ids.append(section_id)
291         for case in cases:
292             if case.department_id:
293                 department_ids.append(case.department_id.id)
294         # OR all section_ids and OR with case_default
295         search_domain = []
296         if department_ids:
297             search_domain += ['|', ('department_id', 'in', department_ids)]
298         search_domain.append(('department_id', '=', False))
299         # AND with the domain in parameter
300         search_domain += list(domain)
301         # perform search, return the first found
302         stage_ids = self.pool.get('hr.recruitment.stage').search(cr, uid, search_domain, order=order, context=context)
303         if stage_ids:
304             return stage_ids[0]
305         return False
306
307     def action_makeMeeting(self, cr, uid, ids, context=None):
308         """ This opens Meeting's calendar view to schedule meeting on current applicant
309             @return: Dictionary value for created Meeting view
310         """
311         applicant = self.browse(cr, uid, ids[0], context)
312         applicant_ids = []
313         if applicant.partner_id:
314             applicant_ids.append(applicant.partner_id.id)
315         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:
316             applicant_ids.append(applicant.department_id.manager_id.user_id.partner_id.id)
317         category = self.pool.get('ir.model.data').get_object(cr, uid, 'hr_recruitment', 'categ_meet_interview', context)
318         res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'calendar', 'action_calendar_event', context)
319         res['context'] = {
320             'default_partner_ids': applicant_ids,
321             'default_user_id': uid,
322             'default_name': applicant.name,
323             'default_categ_ids': category and [category.id] or False,
324         }
325         return res
326
327     def action_start_survey(self, cr, uid, ids, context=None):
328         context = dict(context or {})
329         applicant = self.browse(cr, uid, ids, context=context)[0]
330         survey_obj = self.pool.get('survey.survey')
331         response_obj = self.pool.get('survey.user_input')
332         # create a response and link it to this applicant
333         if not applicant.response_id:
334             response_id = response_obj.create(cr, uid, {'survey_id': applicant.survey.id, 'partner_id': applicant.partner_id.id}, context=context)
335             self.write(cr, uid, ids[0], {'response_id': response_id}, context=context)
336         else:
337             response_id = applicant.response_id.id
338         # grab the token of the response and start surveying
339         response = response_obj.browse(cr, uid, response_id, context=context)
340         context.update({'survey_token': response.token})
341         return survey_obj.action_start_survey(cr, uid, [applicant.survey.id], context=context)
342
343     def action_print_survey(self, cr, uid, ids, context=None):
344         """ If response is available then print this response otherwise print survey form (print template of the survey) """
345         context = dict(context or {})
346         applicant = self.browse(cr, uid, ids, context=context)[0]
347         survey_obj = self.pool.get('survey.survey')
348         response_obj = self.pool.get('survey.user_input')
349         if not applicant.response_id:
350             return survey_obj.action_print_survey(cr, uid, [applicant.survey.id], context=context)
351         else:
352             response = response_obj.browse(cr, uid, applicant.response_id.id, context=context)
353             context.update({'survey_token': response.token})
354             return survey_obj.action_print_survey(cr, uid, [applicant.survey.id], context=context)
355
356     def action_get_attachment_tree_view(self, cr, uid, ids, context=None):
357         model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_attachment')
358         action = self.pool.get(model).read(cr, uid, action_id, context=context)
359         action['context'] = {'default_res_model': self._name, 'default_res_id': ids[0]}
360         action['domain'] = str(['&', ('res_model', '=', self._name), ('res_id', 'in', ids)])
361         return action
362
363     def message_get_reply_to(self, cr, uid, ids, context=None):
364         """ Override to get the reply_to of the parent project. """
365         applicants = self.browse(cr, SUPERUSER_ID, ids, context=context)
366         job_ids = set([applicant.job_id.id for applicant in applicants if applicant.job_id])
367         aliases = self.pool['project.project'].message_get_reply_to(cr, uid, list(job_ids), context=context)
368         return dict((applicant.id, aliases.get(applicant.job_id and applicant.job_id.id or 0, False)) for applicant in applicants)
369
370     def message_get_suggested_recipients(self, cr, uid, ids, context=None):
371         recipients = super(hr_applicant, self).message_get_suggested_recipients(cr, uid, ids, context=context)
372         for applicant in self.browse(cr, uid, ids, context=context):
373             if applicant.partner_id:
374                 self._message_add_suggested_recipient(cr, uid, recipients, applicant, partner=applicant.partner_id, reason=_('Contact'))
375             elif applicant.email_from:
376                 self._message_add_suggested_recipient(cr, uid, recipients, applicant, email=applicant.email_from, reason=_('Contact Email'))
377         return recipients
378
379     def message_new(self, cr, uid, msg, custom_values=None, context=None):
380         """ Overrides mail_thread message_new that is called by the mailgateway
381             through message_process.
382             This override updates the document according to the email.
383         """
384         if custom_values is None:
385             custom_values = {}
386         val = msg.get('from').split('<')[0]
387         defaults = {
388             'name':  msg.get('subject') or _("No Subject"),
389             'partner_name': val,
390             'email_from': msg.get('from'),
391             'email_cc': msg.get('cc'),
392             'user_id': False,
393             'partner_id': msg.get('author_id', False),
394         }
395         if msg.get('priority'):
396             defaults['priority'] = msg.get('priority')
397         defaults.update(custom_values)
398         return super(hr_applicant, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
399
400     def create(self, cr, uid, vals, context=None):
401         context = dict(context or {})
402         context['mail_create_nolog'] = True
403         if vals.get('department_id') and not context.get('default_department_id'):
404             context['default_department_id'] = vals.get('department_id')
405         if vals.get('job_id') or context.get('default_job_id'):
406             job_id = vals.get('job_id') or context.get('default_job_id')
407             vals.update(self.onchange_job(cr, uid, [], job_id, context=context)['value'])
408         obj_id = super(hr_applicant, self).create(cr, uid, vals, context=context)
409         applicant = self.browse(cr, uid, obj_id, context=context)
410         if applicant.job_id:
411             name = applicant.partner_name if applicant.partner_name else applicant.name
412             self.pool['hr.job'].message_post(
413                 cr, uid, [applicant.job_id.id],
414                 body=_('New application from %s') % name,
415                 subtype="hr_recruitment.mt_job_applicant_new", context=context)
416         return obj_id
417
418     def write(self, cr, uid, ids, vals, context=None):
419         if isinstance(ids, (int, long)):
420             ids = [ids]
421         res = True
422
423         # user_id change: update date_open
424         if vals.get('user_id'):
425             vals['date_open'] = fields.datetime.now()
426         # stage_id: track last stage before update
427         if 'stage_id' in vals:
428             vals['date_last_stage_update'] = fields.datetime.now()
429             for applicant in self.browse(cr, uid, ids, context=None):
430                 vals['last_stage_id'] = applicant.stage_id.id
431                 res = super(hr_applicant, self).write(cr, uid, [applicant.id], vals, context=context)
432         else:
433             res = super(hr_applicant, self).write(cr, uid, ids, vals, context=context)
434
435         # post processing: if job changed, post a message on the job
436         if vals.get('job_id'):
437             for applicant in self.browse(cr, uid, ids, context=None):
438                 name = applicant.partner_name if applicant.partner_name else applicant.name
439                 self.pool['hr.job'].message_post(
440                     cr, uid, [vals['job_id']],
441                     body=_('New application from %s') % name,
442                     subtype="hr_recruitment.mt_job_applicant_new", context=context)
443
444         # post processing: if stage changed, post a message in the chatter
445         if vals.get('stage_id'):
446             stage = self.pool['hr.recruitment.stage'].browse(cr, uid, vals['stage_id'], context=context)
447             if stage.template_id:
448                 # TDENOTE: probably factorize me in a message_post_with_template generic method FIXME
449                 compose_ctx = dict(context,
450                                    active_ids=ids)
451                 compose_id = self.pool['mail.compose.message'].create(
452                     cr, uid, {
453                         'model': self._name,
454                         'composition_mode': 'mass_mail',
455                         'template_id': stage.template_id.id,
456                         'post': True,
457                         'notify': True,
458                     }, context=compose_ctx)
459                 self.pool['mail.compose.message'].write(
460                     cr, uid, [compose_id],
461                     self.pool['mail.compose.message'].onchange_template_id(
462                         cr, uid, [compose_id],
463                         stage.template_id.id, 'mass_mail', self._name, False,
464                         context=compose_ctx)['value'],
465                     context=compose_ctx)
466                 self.pool['mail.compose.message'].send_mail(cr, uid, [compose_id], context=compose_ctx)
467         return res
468
469     def create_employee_from_applicant(self, cr, uid, ids, context=None):
470         """ Create an hr.employee from the hr.applicants """
471         if context is None:
472             context = {}
473         hr_employee = self.pool.get('hr.employee')
474         model_data = self.pool.get('ir.model.data')
475         act_window = self.pool.get('ir.actions.act_window')
476         emp_id = False
477         for applicant in self.browse(cr, uid, ids, context=context):
478             address_id = contact_name = False
479             if applicant.partner_id:
480                 address_id = self.pool.get('res.partner').address_get(cr, uid, [applicant.partner_id.id], ['contact'])['contact']
481                 contact_name = self.pool.get('res.partner').name_get(cr, uid, [applicant.partner_id.id])[0][1]
482             if applicant.job_id and (applicant.partner_name or contact_name):
483                 applicant.job_id.write({'no_of_hired_employee': applicant.job_id.no_of_hired_employee + 1}, context=context)
484                 create_ctx = dict(context, mail_broadcast=True)
485                 emp_id = hr_employee.create(cr, uid, {'name': applicant.partner_name or contact_name,
486                                                      'job_id': applicant.job_id.id,
487                                                      'address_home_id': address_id,
488                                                      'department_id': applicant.department_id.id or False,
489                                                      'address_id': applicant.company_id and applicant.company_id.partner_id and applicant.company_id.partner_id.id or False,
490                                                      'work_email': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.email or False,
491                                                      'work_phone': applicant.department_id and applicant.department_id.company_id and applicant.department_id.company_id.phone or False,
492                                                      }, context=create_ctx)
493                 self.write(cr, uid, [applicant.id], {'emp_id': emp_id}, context=context)
494                 self.pool['hr.job'].message_post(
495                     cr, uid, [applicant.job_id.id],
496                     body=_('New Employee %s Hired') % applicant.partner_name if applicant.partner_name else applicant.name,
497                     subtype="hr_recruitment.mt_job_applicant_hired", context=context)
498             else:
499                 raise osv.except_osv(_('Warning!'), _('You must define an Applied Job and a Contact Name for this applicant.'))
500
501         action_model, action_id = model_data.get_object_reference(cr, uid, 'hr', 'open_view_employee_list')
502         dict_act_window = act_window.read(cr, uid, [action_id], [])[0]
503         if emp_id:
504             dict_act_window['res_id'] = emp_id
505         dict_act_window['view_mode'] = 'form,tree'
506         return dict_act_window
507
508     def get_empty_list_help(self, cr, uid, help, context=None):
509         context = dict(context or {})
510         context['empty_list_help_model'] = 'hr.job'
511         context['empty_list_help_id'] = context.get('default_job_id', None)
512         context['empty_list_help_document_name'] = _("job applicants")
513         return super(hr_applicant, self).get_empty_list_help(cr, uid, help, context=context)
514
515
516 class hr_job(osv.osv):
517     _inherit = "hr.job"
518     _name = "hr.job"
519     _inherits = {'mail.alias': 'alias_id'}
520
521     def _get_attached_docs(self, cr, uid, ids, field_name, arg, context=None):
522         res = {}
523         attachment_obj = self.pool.get('ir.attachment')
524         for job_id in ids:
525             applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', '=', job_id)], context=context)
526             res[job_id] = attachment_obj.search(
527                 cr, uid, [
528                     '|',
529                     '&', ('res_model', '=', 'hr.job'), ('res_id', '=', job_id),
530                     '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)
531                 ], context=context)
532         return res
533
534     def _count_all(self, cr, uid, ids, field_name, arg, context=None):
535         Applicant = self.pool['hr.applicant']
536         return {
537             job_id: {
538                 'application_count': Applicant.search_count(cr,uid, [('job_id', '=', job_id)], context=context),
539                 'documents_count': len(self._get_attached_docs(cr, uid, [job_id], field_name, arg, context=context)[job_id])
540             }
541             for job_id in ids
542         }
543
544     _columns = {
545         '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"),
546         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
547                                     help="Email alias for this job position. New emails will automatically "
548                                          "create new applicants for this job position."),
549         'address_id': fields.many2one('res.partner', 'Job Location', help="Address where employees are working"),
550         'application_ids': fields.one2many('hr.applicant', 'job_id', 'Applications'),
551         'application_count': fields.function(_count_all, type='integer', string='Applications', multi=True),
552         'manager_id': fields.related('department_id', 'manager_id', type='many2one', string='Department Manager', relation='hr.employee', readonly=True, store=True),
553         'document_ids': fields.function(_get_attached_docs, type='one2many', relation='ir.attachment', string='Applications'),
554         'documents_count': fields.function(_count_all, type='integer', string='Documents', multi=True),
555         'user_id': fields.many2one('res.users', 'Recruitment Responsible', track_visibility='onchange'),
556         'color': fields.integer('Color Index'),
557     }
558
559     def _address_get(self, cr, uid, context=None):
560         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
561         return user.company_id.partner_id.id
562
563     _defaults = {
564         'address_id': _address_get
565     }
566
567     def _auto_init(self, cr, context=None):
568         """Installation hook to create aliases for all jobs and avoid constraint errors."""
569         return self.pool.get('mail.alias').migrate_to_alias(cr, self._name, self._table, super(hr_job, self)._auto_init,
570             'hr.applicant', self._columns['alias_id'], 'name', alias_prefix='job+', alias_defaults={'job_id': 'id'}, context=context)
571
572     def create(self, cr, uid, vals, context=None):
573         alias_context = dict(context, alias_model_name='hr.applicant', alias_parent_model_name=self._name)
574         job_id = super(hr_job, self).create(cr, uid, vals, context=alias_context)
575         job = self.browse(cr, uid, job_id, context=context)
576         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)
577         return job_id
578
579     def unlink(self, cr, uid, ids, context=None):
580         # Cascade-delete mail aliases as well, as they should not exist without the job position.
581         mail_alias = self.pool.get('mail.alias')
582         alias_ids = [job.alias_id.id for job in self.browse(cr, uid, ids, context=context) if job.alias_id]
583         res = super(hr_job, self).unlink(cr, uid, ids, context=context)
584         mail_alias.unlink(cr, uid, alias_ids, context=context)
585         return res
586
587     def action_print_survey(self, cr, uid, ids, context=None):
588         job = self.browse(cr, uid, ids, context=context)[0]
589         survey_id = job.survey_id.id
590         return self.pool.get('survey.survey').action_print_survey(cr, uid, [survey_id], context=context)
591
592     def action_get_attachment_tree_view(self, cr, uid, ids, context=None):
593         #open attachments of job and related applicantions.
594         model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_attachment')
595         action = self.pool.get(model).read(cr, uid, action_id, context=context)
596         applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', 'in', ids)], context=context)
597         action['context'] = {'default_res_model': self._name, 'default_res_id': ids[0]}
598         action['domain'] = str(['|', '&', ('res_model', '=', 'hr.job'), ('res_id', 'in', ids), '&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)])
599         return action
600
601     def action_set_no_of_recruitment(self, cr, uid, id, value, context=None):
602         return self.write(cr, uid, [id], {'no_of_recruitment': value}, context=context)
603
604
605 class applicant_category(osv.osv):
606     """ Category of applicant """
607     _name = "hr.applicant_category"
608     _description = "Category of applicant"
609     _columns = {
610         'name': fields.char('Name', required=True, translate=True),
611     }
612
613 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: