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