Debian Codegraph @

addons/hr_recruitment/models/hr_applicant.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import re
3
4 from markupsafe import Markup
5 from collections import defaultdict
6 from datetime import datetime
7
8 from odoo import api, fields, models, tools
9 from odoo.exceptions import UserError, ValidationError
10 from odoo.fields import Domain
11 from odoo.tools import SQL, clean_context
12 from odoo.tools.translate import _
13
14
15 AVAILABLE_PRIORITIES = [
16 ('0', 'Normal'),
17 ('1', 'Good'),
18 ('2', 'Very Good'),
19 ('3', 'Excellent')
20 ]
21
22
23 class HrApplicant(models.Model):
24 _name = 'hr.applicant'
25 _description = "Applicant"
26 _order = "priority desc, id desc"
27 _inherit = ['mail.thread.cc',
28 'mail.thread.main.attachment',
29 'mail.thread.blacklist',
30 'mail.thread.phone',
31 'mail.activity.mixin',
32 'utm.mixin',
33 'mail.tracking.duration.mixin',
34 ]
35 _rec_name = "partner_name"
36 _mailing_enabled = True
37 _primary_email = 'email_from'
38 _track_duration_field = 'stage_id'
39 _order = "sequence"
40
41 sequence = fields.Integer(string='Sequence', index=True, default=10)
42 active = fields.Boolean("Active", default=True, help="If the active field is set to false, it will allow you to hide the case without removing it.", index=True)
43
44 partner_id = fields.Many2one('res.partner', "Contact", copy=False, index='btree_not_null')
45 partner_name = fields.Char("Applicant's Name")
46 email_from = fields.Char(
47 string="Email",
48 size=128,
49 compute='_compute_partner_phone_email',
50 inverse='_inverse_partner_email',
51 copy=True,
52 store=True,
53 index='trigram',
54 )
55 email_normalized = fields.Char(index='trigram') # inherited via mail.thread.blacklist
56 partner_phone = fields.Char(
57 string="Phone",
58 size=32,
59 compute='_compute_partner_phone_email',
60 inverse='_inverse_partner_email',
61 copy=True,
62 store=True,
63 index='btree_not_null',
64 )
65 partner_phone_sanitized = fields.Char(
66 string="Sanitized Phone Number", compute='_compute_partner_phone_sanitized', store=True, index='btree_not_null'
67 )
68 linkedin_profile = fields.Char('LinkedIn Profile', index='btree_not_null')
69 type_id = fields.Many2one('hr.recruitment.degree', "Degree")
70 availability = fields.Date("Availability", help="The date at which the applicant will be available to start working", tracking=True)
71 color = fields.Integer("Color Index", default=0)
72 employee_id = fields.Many2one('hr.employee', string="Employee", help="Employee linked to the applicant.", copy=False, index='btree_not_null')
73 emp_is_active = fields.Boolean(string="Employee Active", related='employee_id.active')
74 employee_name = fields.Char(related='employee_id.name', string="Employee Name", readonly=False, tracking=False)
75
76 probability = fields.Float("Probability")
77 create_date = fields.Datetime("Applied on", readonly=True)
78 stage_id = fields.Many2one('hr.recruitment.stage', 'Stage', ondelete='restrict', tracking=True,
79 compute='_compute_stage', store=True, readonly=False,
80 domain="['|', ('job_ids', '=', False), ('job_ids', '=', job_id)]",
81 copy=False, index=True,
82 group_expand='_read_group_stage_ids')
83 last_stage_id = fields.Many2one('hr.recruitment.stage', "Last Stage",
84 help="Stage of the applicant before being in the current stage. Used for lost cases analysis.")
85 categ_ids = fields.Many2many('hr.applicant.category', string="Tags")
86 company_id = fields.Many2one('res.company', "Company", compute='_compute_company', store=True, readonly=False, tracking=True)
87 user_id = fields.Many2one(
88 'res.users', "Recruiter", compute='_compute_user', domain="[('share', '=', False), ('company_ids', 'in', company_id)]",
89 tracking=True, store=True, readonly=False)
90 date_closed = fields.Datetime("Hire Date", compute='_compute_date_closed', store=True, readonly=False, tracking=True, copy=False)
91 date_open = fields.Datetime("Assigned", readonly=True)
92 date_last_stage_update = fields.Datetime("Last Stage Update", index=True, default=fields.Datetime.now)
93 priority = fields.Selection(AVAILABLE_PRIORITIES, "Evaluation", default='0')
94 job_id = fields.Many2one('hr.job', "Job Position", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", tracking=True, index=True, copy=False)
95 salary_proposed_extra = fields.Char("Proposed Salary Extra", help="Salary Proposed by the Organisation, extra advantages", tracking=True, groups="hr_recruitment.group_hr_recruitment_user")
96 salary_expected_extra = fields.Char("Expected Salary Extra", help="Salary Expected by Applicant, extra advantages", tracking=True, groups="hr_recruitment.group_hr_recruitment_user")
97 salary_proposed = fields.Float("Proposed", aggregator="avg", help="Salary Proposed by the Organisation", tracking=True, groups="hr_recruitment.group_hr_recruitment_user")
98 salary_expected = fields.Float("Expected", aggregator="avg", help="Salary Expected by Applicant", tracking=True, groups="hr_recruitment.group_hr_recruitment_user")
99 department_id = fields.Many2one(
100 'hr.department', "Department", compute='_compute_department', store=True, readonly=False,
101 domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", tracking=True)
102 day_open = fields.Float(compute='_compute_day', string="Days to Open", compute_sudo=True)
103 day_close = fields.Float(compute='_compute_day', string="Days to Close", compute_sudo=True)
104 delay_close = fields.Float(compute="_compute_delay", string='Delay to Close', readonly=True, aggregator="avg", help="Number of days to close", store=True)
105 user_email = fields.Char(related='user_id.email', string="User Email", readonly=True)
106 attachment_number = fields.Integer(compute='_get_attachment_number', string="Number of Attachments")
107 attachment_ids = fields.One2many('ir.attachment', 'res_id', domain=[('res_model', '=', 'hr.applicant')], string='Attachments')
108 kanban_state = fields.Selection([
109 ('normal', 'In Progress'),
110 ('done', 'Ready for Next Stage'),
111 ('waiting', 'Waiting'),
112 ('blocked', 'Blocked')], string='Kanban State',
113 copy=False, default='normal', required=True)
114 legend_blocked = fields.Char(related='stage_id.legend_blocked', string='Kanban Blocked')
115 legend_done = fields.Char(related='stage_id.legend_done', string='Kanban Valid')
116 legend_waiting = fields.Char(related='stage_id.legend_waiting', string='Kanban Waiting')
117 legend_normal = fields.Char(related='stage_id.legend_normal', string='Kanban Ongoing')
118 refuse_reason_id = fields.Many2one('hr.applicant.refuse.reason', string='Refuse Reason', tracking=True)
119 meeting_ids = fields.One2many('calendar.event', 'applicant_id', 'Meetings')
120 meeting_display_text = fields.Char(compute='_compute_meeting_display')
121 meeting_display_date = fields.Date(compute='_compute_meeting_display')
122 # UTMs - enforcing the fact that we want to 'set null' when relation is unlinked
123 campaign_id = fields.Many2one(ondelete='set null')
124 medium_id = fields.Many2one(ondelete='set null', help="This displays how the applicant has reached out, e.g. via Email, LinkedIn, Website, etc.")
125 source_id = fields.Many2one(ondelete='set null')
126 interviewer_ids = fields.Many2many('res.users', 'hr_applicant_res_users_interviewers_rel',
127 string='Interviewers', index=True, tracking=True, copy=False,
128 domain="[('share', '=', False), ('company_ids', 'in', company_id)]")
129 application_status = fields.Selection([
130 ('ongoing', 'Ongoing'),
131 ('hired', 'Hired'),
132 ('refused', 'Refused'),
133 ('archived', 'Archived'),
134 ], compute="_compute_application_status", search="_search_application_status")
135 application_count = fields.Integer(compute='_compute_application_count', help='Applications with the same email or phone or mobile')
136 applicant_properties = fields.Properties('Properties', definition='job_id.applicant_properties_definition', copy=True)
137 applicant_notes = fields.Html()
138 refuse_date = fields.Datetime('Refuse Date')
139 talent_pool_ids = fields.Many2many(comodel_name="hr.talent.pool", string="Talent Pools")
140 pool_applicant_id = fields.Many2one("hr.applicant", index='btree_not_null')
141 is_pool_applicant = fields.Boolean(compute="_compute_is_pool")
142 is_applicant_in_pool = fields.Boolean(
143 compute="_compute_is_applicant_in_pool", search="_search_is_applicant_in_pool"
144 )
145 talent_pool_count = fields.Integer(compute="_compute_talent_pool_count")
146
147 _job_id_stage_id_idx = models.Index("(job_id, stage_id) WHERE active IS TRUE")
148
149 @api.constrains("talent_pool_ids", "pool_applicant_id")
150 def _check_talent_pool_required(self):
151 for talent in self:
152 if talent.pool_applicant_id == talent and not talent.talent_pool_ids:
153 raise ValidationError(self.env._("Talent must belong to at least one Talent Pool."))
154
155 @api.depends("email_normalized", "partner_phone_sanitized", "linkedin_profile", "pool_applicant_id.talent_pool_ids")
156 def _compute_talent_pool_count(self):
157 """
158 This method will find the amount of talent pools the current application is associated with.
159 An application can either be associated directly with a talent pool through talent_pool_ids
160 and/or pool_applicant_id.talent_pool_ids or indirectly by having the same email, phone
161 number or linkedin as a directly linked application.
162 """
163 pool_applicants = self.filtered("is_applicant_in_pool")
164 (self - pool_applicants).talent_pool_count = 0
165
166 if not pool_applicants:
167 return
168
169 directly_linked = pool_applicants.filtered("pool_applicant_id")
170 for applicant in directly_linked:
171 # All talents(applications with talent_pool_ids set) have a pool_applicant_id set to
172 # themselves which is the reason we only look for that instead of searching for all
173 # applications with talent_pool_ids and all applications with pool_applicant_id seperately
174 applicant.talent_pool_count = len(applicant.pool_applicant_id.talent_pool_ids)
175
176 indirectly_linked = pool_applicants - directly_linked
177 if not indirectly_linked:
178 return
179
180 all_emails = {a.email_normalized for a in indirectly_linked if a.email_normalized}
181 all_phones = {a.partner_phone_sanitized for a in indirectly_linked if a.partner_phone_sanitized}
182 all_linkedins = {a.linkedin_profile for a in indirectly_linked if a.linkedin_profile}
183
184 epl_domain = Domain.FALSE
185 if all_emails:
186 epl_domain |= Domain("email_normalized", "in", list(all_emails))
187 if all_phones:
188 epl_domain |= Domain("partner_phone_sanitized", "in", list(all_phones))
189 if all_linkedins:
190 epl_domain |= Domain("linkedin_profile", "in", list(all_linkedins))
191
192 pool_domain = Domain(["|", ("talent_pool_ids", "!=", False), ("pool_applicant_id", "!=", False)])
193 domain = pool_domain & epl_domain
194 in_pool_applicants = self.env["hr.applicant"].with_context(active_test=True).search(domain)
195
196 in_pool_emails = defaultdict(int)
197 in_pool_phones = defaultdict(int)
198 in_pool_linkedins = defaultdict(int)
199
200 for applicant in in_pool_applicants:
201 talent_pool_count = len(applicant.pool_applicant_id.talent_pool_ids)
202 if applicant.email_normalized:
203 in_pool_emails[applicant.email_normalized] = talent_pool_count
204 if applicant.partner_phone_sanitized:
205 in_pool_phones[applicant.partner_phone_sanitized] = talent_pool_count
206 if applicant.linkedin_profile:
207 in_pool_linkedins[applicant.linkedin_profile] = talent_pool_count
208
209 for applicant in indirectly_linked:
210 if applicant.email_from and in_pool_emails[applicant.email_normalized]:
211 applicant.talent_pool_count = in_pool_emails[applicant.email_normalized]
212 elif applicant.partner_phone_sanitized and in_pool_phones[applicant.partner_phone_sanitized]:
213 applicant.talent_pool_count = in_pool_phones[applicant.partner_phone_sanitized]
214 elif applicant.linkedin_profile and in_pool_linkedins[applicant.linkedin_profile]:
215 applicant.talent_pool_count = in_pool_linkedins[applicant.linkedin_profile]
216 else:
217 applicant.talent_pool_count = 0
218
219 @api.depends("partner_phone")
220 def _compute_partner_phone_sanitized(self):
221 for applicant in self:
222 applicant.partner_phone_sanitized = (
223 applicant._phone_format(fname="partner_phone") or applicant.partner_phone
224 )
225
226 @api.depends("partner_id")
227 def _compute_partner_phone_email(self):
228 for applicant in self:
229 if not applicant.partner_id:
230 continue
231 applicant.email_from = applicant.partner_id.email
232 if not applicant.partner_phone:
233 applicant.partner_phone = applicant.partner_id.phone
234
235 def _inverse_partner_email(self):
236 for applicant in self:
237 email_normalized = tools.email_normalize(applicant.email_from or '')
238 if not email_normalized:
239 continue
240 if not applicant.partner_id:
241 if not applicant.partner_name:
242 raise UserError(_("You must define a Contact Name for this applicant."))
243 applicant.partner_id = applicant._partner_find_from_emails_single(
244 [applicant.email_from], no_create=False,
245 additional_values={
246 email_normalized: {'lang': self.env.lang}
247 },
248 )
249 if applicant.partner_name and applicant.partner_name != applicant.partner_id.name:
250 applicant.partner_id.name = applicant.partner_name
251 if email_normalized and email_normalized != applicant.partner_id.email:
252 applicant.partner_id.email = applicant.email_from
253 if applicant.partner_phone and applicant.partner_phone != applicant.partner_id.phone:
254 applicant.partner_id.phone = applicant.partner_phone
255
256 @api.depends("email_normalized", "partner_phone_sanitized", "linkedin_profile")
257 def _compute_application_count(self):
258 """
259 This method will calculate the number of applications that are either
260 directly or indirectly linked to the current application(s)
261 - An application is considered directly linked if it shares the same
262 pool_applicant_id
263 - An application is considered indirectly_linked if it has the same
264 value as the current application(s) in any of the following field:
265 email, phone number or linkedin
266
267 Note: If self has pool_applicant_id, email, phone number or linkedin set
268 this method will include self in the returned count
269 """
270 domain = self._get_similar_applicants_domain(ignore_talent=True)
271 matching_applicants = self.env["hr.applicant"].with_context(active_test=False).search(domain)
272
273 email_map = defaultdict(set)
274 phone_map = defaultdict(set)
275 linkedin_map = defaultdict(set)
276 pool_applicant_map = defaultdict(set)
277 for app in matching_applicants:
278 if app.email_normalized:
279 email_map[app.email_normalized].add(app.id)
280 if app.partner_phone_sanitized:
281 phone_map[app.partner_phone_sanitized].add(app.id)
282 if app.linkedin_profile:
283 linkedin_map[app.linkedin_profile].add(app.id)
284 if app.pool_applicant_id:
285 pool_applicant_map[app.pool_applicant_id].add(app.id)
286
287 for applicant in self:
288 related_ids = set()
289 if applicant.email_normalized:
290 related_ids.update(email_map.get(applicant.email_normalized, set()))
291 if applicant.partner_phone_sanitized:
292 related_ids.update(phone_map.get(applicant.partner_phone_sanitized, set()))
293 if applicant.linkedin_profile:
294 related_ids.update(linkedin_map.get(applicant.linkedin_profile, set()))
295 if applicant.pool_applicant_id:
296 related_ids.update(pool_applicant_map.get(applicant.pool_applicant_id, set()))
297
298 count = len(related_ids)
299
300 applicant.application_count = max(0, count)
301
302 @api.depends("talent_pool_ids")
303 def _compute_is_pool(self):
304 for applicant in self:
305 applicant.is_pool_applicant = applicant.talent_pool_ids
306
307 def _get_similar_applicants_domain(self, ignore_talent=False, only_talent=False):
308 """
309 This method returns a domain for the applicants whitch match with the
310 current applicant according to email_from, partner_phone or linkedin_profile.
311 Thus, search on the domain will return the current applicant as well
312 if any of the following fields are filled.
313
314 Args:
315 ignore_talent: if you want the domain to only include applicants not belonging to a talent pool
316 only_talent: if you want the domain to only include applicants belonging to a talent pool
317
318 Returns:
319 Domain()
320 """
321 domain = Domain.OR([
322 Domain("id", "in", self.ids),
323 Domain("email_normalized", "in", [email for email in self.mapped("email_normalized") if email]),
324 Domain("partner_phone_sanitized", "in", [phone for phone in self.mapped("partner_phone_sanitized") if phone]),
325 Domain("linkedin_profile", "in", [linkedin_profile for linkedin_profile in self.mapped("linkedin_profile") if linkedin_profile]),
326 Domain("pool_applicant_id", "in", [pool_applicant.id for pool_applicant in self.mapped("pool_applicant_id") if pool_applicant]),
327 ])
328 if ignore_talent:
329 domain &= Domain("talent_pool_ids", "=", False)
330 if only_talent:
331 domain &= Domain("talent_pool_ids", "!=", False)
332 return domain
333
334 @api.depends(
335 "talent_pool_ids", "pool_applicant_id", "email_normalized", "partner_phone_sanitized", "linkedin_profile"
336 )
337 def _compute_is_applicant_in_pool(self):
338 """
339 Computes if an application is linked to a talent pool or not.
340 An application can either be directly or indirectly linked to a talent pool.
341 Direct link:
342 - 1. Application has talent_pool_ids set, meaning this application
343 is a talent pool application, or talent for short.
344 - 2. Application has pool_applicant_id set, meaning this application
345 is a copy or directly linked to a talent (scenario 1)
346
347 Indirect link:
348 - 3. Application shares a phone number, email, or linkedin with a
349 direclty linked application.
350
351 Note: While possible, linking an application to a pool through linking
352 it to an indirect link is currently excluded from the implementation
353 for technical reasons.
354 """
355 direct = self.filtered(lambda a: a.talent_pool_ids or a.pool_applicant_id)
356 direct.is_applicant_in_pool = True
357 indirect = self - direct
358
359 if not indirect:
360 return
361
362 all_emails = {a.email_normalized for a in indirect if a.email_normalized}
363 all_phones = {a.partner_phone_sanitized for a in indirect if a.partner_phone_sanitized}
364 all_linkedins = {a.linkedin_profile for a in indirect if a.linkedin_profile}
365
366 epl_domain = Domain.FALSE
367 if all_emails:
368 epl_domain |= Domain("email_normalized", "in", list(all_emails))
369 if all_phones:
370 epl_domain |= Domain("partner_phone_sanitized", "in", list(all_phones))
371 if all_linkedins:
372 epl_domain |= Domain("linkedin_profile", "in", list(all_linkedins))
373
374 pool_domain = Domain(["|", ("talent_pool_ids", "!=", False), ("pool_applicant_id", "!=", False)])
375 domain = pool_domain & epl_domain
376 in_pool_applicants = self.env["hr.applicant"].with_context(active_test=True).search(domain)
377 in_pool_data = {"emails": set(), "phones": set(), "linkedins": set()}
378
379 for applicant in in_pool_applicants:
380 if applicant.email_normalized:
381 in_pool_data["emails"].add(applicant.email_normalized)
382 if applicant.partner_phone_sanitized:
383 in_pool_data["phones"].add(applicant.partner_phone_sanitized)
384 if applicant.linkedin_profile:
385 in_pool_data["linkedins"].add(applicant.linkedin_profile)
386
387 for applicant in indirect:
388 applicant.is_applicant_in_pool = (
389 applicant.email_normalized in in_pool_data["emails"]
390 or applicant.partner_phone_sanitized in in_pool_data["phones"]
391 or applicant.linkedin_profile in in_pool_data["linkedins"]
392 )
393
394 def _search_is_applicant_in_pool(self, operator, value):
395 """
396 This function is needed to hide duplicates when adding applicants/talents to a talent pool.
397 All applications that have either talent_pool_ids or pool_applicant_id set are considered
398 directly in a pool. Furthermore, any application with the same phone number, email or linkedin
399 as the first applications, that are directly in the pool, are also considered to belong to
400 the same talent pool.
401
402 Returns:
403 returns a domain with ids of applications that are either directly or indirectly linked to a pool
404 """
405 if operator != 'in':
406 return NotImplemented
407
408 return [('id', 'in', SQL("""
409 WITH talent_pool_applicants AS (
410 SELECT
411 a.id as id,
412 email_normalized,
413 partner_phone_sanitized,
414 linkedin_profile
415 FROM hr_applicant a
416 LEFT JOIN hr_applicant_hr_talent_pool_rel rel
417 ON a.id = rel.hr_applicant_id
418 WHERE pool_applicant_id IS NOT NULL
419 OR hr_talent_pool_id IS NOT NULL
420 )
421 SELECT a.id
422 FROM hr_applicant a
423 WHERE
424 -- Check if directly linked to a pool
425 (a.id IN (
426 SELECT DISTINCT id
427 from talent_pool_applicants
428 ))
429 OR
430 -- Check if email matches any talent pool applicant
431 (a.email_normalized IN (
432 SELECT DISTINCT email_normalized
433 FROM talent_pool_applicants
434 WHERE email_normalized IS NOT NULL
435 ))
436 OR
437 -- Check if phone matches any talent pool applicant
438 (a.partner_phone_sanitized IN (
439 SELECT DISTINCT partner_phone_sanitized
440 FROM talent_pool_applicants
441 WHERE partner_phone_sanitized IS NOT NULL
442 ))
443 OR
444 -- Check if LinkedIn profile matches any talent pool applicant
445 (a.linkedin_profile IN (
446 SELECT DISTINCT linkedin_profile
447 FROM talent_pool_applicants
448 WHERE linkedin_profile IS NOT NULL
449 ))
450 """))]
451
452 @api.depends('date_open', 'date_closed')
453 def _compute_day(self):
454 for applicant in self:
455 if applicant.date_open:
456 date_create = applicant.create_date
457 date_open = applicant.date_open
458 applicant.day_open = (date_open - date_create).total_seconds() / (24.0 * 3600)
459 else:
460 applicant.day_open = False
461 if applicant.date_closed:
462 date_create = applicant.create_date
463 date_closed = applicant.date_closed
464 applicant.day_close = (date_closed - date_create).total_seconds() / (24.0 * 3600)
465 else:
466 applicant.day_close = False
467
468 @api.depends('day_open', 'day_close')
469 def _compute_delay(self):
470 for applicant in self:
471 if applicant.date_open and applicant.day_close:
472 applicant.delay_close = applicant.day_close - applicant.day_open
473 else:
474 applicant.delay_close = False
475
476 def _get_rotting_depends_fields(self):
477 return super()._get_rotting_depends_fields() + ['application_status', 'date_closed']
478
479 def _get_rotting_domain(self):
480 return super()._get_rotting_domain() & Domain([
481 ('application_status', '=', 'ongoing'),
482 ('date_closed', '=', False),
483 ])
484
485 @api.depends_context('lang')
486 @api.depends('meeting_ids', 'meeting_ids.start')
487 def _compute_meeting_display(self):
488 applicant_with_meetings = self.filtered('meeting_ids')
489 (self - applicant_with_meetings).update({
490 'meeting_display_text': _('No Meeting'),
491 'meeting_display_date': ''
492 })
493 today = fields.Date.today()
494 for applicant in applicant_with_meetings:
495 count = len(applicant.meeting_ids)
496 dates = applicant.meeting_ids.mapped('start')
497 min_date, max_date = min(dates).date(), max(dates).date()
498 if min_date >= today:
499 applicant.meeting_display_date = min_date
500 else:
501 applicant.meeting_display_date = max_date
502 if count == 1:
503 applicant.meeting_display_text = _('1 Meeting')
504 elif applicant.meeting_display_date >= today:
505 applicant.meeting_display_text = _('Next Meeting')
506 else:
507 applicant.meeting_display_text = _('Last Meeting')
508
509 @api.depends('refuse_reason_id', 'date_closed')
510 def _compute_application_status(self):
511 for applicant in self:
512 if applicant.refuse_reason_id:
513 applicant.application_status = 'refused'
514 elif not applicant.active:
515 applicant.application_status = 'archived'
516 elif applicant.date_closed:
517 applicant.application_status = 'hired'
518 else:
519 applicant.application_status = 'ongoing'
520
521 def _search_application_status(self, operator, value):
522 if operator != 'in':
523 return NotImplemented
524
525 domains = []
526 # Map statuses to domain filters
527 if 'refused' in value:
528 domains.append([('active', '=', True), ('refuse_reason_id', '!=', None)])
529 if 'hired' in value:
530 domains.append([('active', '=', True), ('date_closed', '!=', False)])
531 if 'archived' in value or False in value:
532 domains.append([('active', '=', False)])
533 if 'ongoing' in value:
534 domains.append([('active', '=', True), ('date_closed', '=', False)])
535
536 return Domain.OR(domains)
537
538 def _get_attachment_number(self):
539 read_group_res = self.env['ir.attachment']._read_group(
540 [('res_model', '=', 'hr.applicant'), ('res_id', 'in', self.ids)],
541 ['res_id'], ['__count'])
542 attach_data = dict(read_group_res)
543 for record in self:
544 record.attachment_number = attach_data.get(record.id, 0)
545
546 @api.model
547 def _read_group_stage_ids(self, stages, domain):
548 # retrieve job_id from the context and write the domain: ids + contextual columns (job or default)
549 job_id = self.env.context.get('default_job_id')
550 search_domain = [('job_ids', '=', False)]
551 if job_id:
552 search_domain = ['|', ('job_ids', '=', job_id)] + search_domain
553 if stages:
554 search_domain = ['|', ('id', 'in', stages.ids)] + search_domain
555
556 stage_ids = stages.sudo()._search(search_domain, order=stages._order)
557 return stages.browse(stage_ids)
558
559 @api.depends('job_id', 'department_id')
560 def _compute_company(self):
561 for applicant in self:
562 company_id = False
563 if applicant.department_id:
564 company_id = applicant.department_id.company_id.id
565 if not company_id and applicant.job_id:
566 company_id = applicant.job_id.company_id.id
567 applicant.company_id = company_id or self.env.company.id
568
569 @api.depends('job_id')
570 def _compute_department(self):
571 for applicant in self:
572 applicant.department_id = applicant.job_id.department_id.id
573
574 @api.depends('job_id')
575 def _compute_stage(self):
576 for applicant in self:
577 if applicant.job_id:
578 if not applicant.stage_id:
579 stage_ids = self.env['hr.recruitment.stage'].search([
580 '|',
581 ('job_ids', '=', False),
582 ('job_ids', '=', applicant.job_id.id),
583 ('fold', '=', False)
584 ], order='sequence asc', limit=1).ids
585 applicant.stage_id = stage_ids[0] if stage_ids else False
586 else:
587 applicant.stage_id = False
588
589 @api.depends('job_id')
590 def _compute_user(self):
591 for applicant in self:
592 applicant.user_id = applicant.job_id.user_id.id
593
594 def _phone_get_number_fields(self):
595 """ This method returns the fields to use to find the number to use to
596 send an SMS on a record. """
597 return ['partner_phone']
598
599 @api.depends('stage_id.hired_stage')
600 def _compute_date_closed(self):
601 for applicant in self:
602 if applicant.stage_id and applicant.stage_id.hired_stage and not applicant.date_closed:
603 applicant.date_closed = fields.Datetime.now()
604 if not applicant.stage_id.hired_stage:
605 applicant.date_closed = False
606
607 def copy_data(self, default=None):
608 vals_list = super().copy_data(default=default)
609
610 # Avoid adding `(copy)` to partner_name when an applicant is created trough the talent pool mechanism
611 if not self.env.context.get("no_copy_in_partner_name"):
612 vals_list = [
613 dict(vals, partner_name=self.env._("%s (copy)", applicant.partner_name))
614 for applicant, vals in zip(self, vals_list)
615 ]
616 return vals_list
617
618 @api.model_create_multi
619 def create(self, vals_list):
620 for vals in vals_list:
621 if vals.get('user_id'):
622 vals['date_open'] = fields.Datetime.now()
623 if vals.get('email_from'):
624 vals['email_from'] = vals['email_from'].strip()
625 applicants = super().create(vals_list)
626 applicants.sudo().interviewer_ids._create_recruitment_interviewers()
627
628 for applicant in applicants:
629 if applicant.talent_pool_ids and not applicant.pool_applicant_id:
630 applicant.pool_applicant_id = applicant
631
632 if (applicants.interviewer_ids.partner_id - self.env.user.partner_id):
633 for applicant in applicants:
634 interviewers_to_notify = applicant.interviewer_ids.partner_id - self.env.user.partner_id
635 notification_subject = _("You have been assigned as an interviewer for %s", applicant.display_name)
636 notification_body = _("You have been assigned as an interviewer for the Applicant %s", applicant.partner_name)
637 applicant.message_notify(
638 res_id=applicant.id,
639 model=applicant._name,
640 partner_ids=interviewers_to_notify.ids,
641 author_id=self.env.user.partner_id.id,
642 email_from=self.env.user.email_formatted,
643 subject=notification_subject,
644 body=notification_body,
645 email_layout_xmlid="mail.mail_notification_layout",
646 model_description="Applicant",
647 )
648 return applicants
649
650 def write(self, vals):
651 # user_id change: update date_open
652 if vals.get('user_id'):
653 vals['date_open'] = fields.Datetime.now()
654 old_interviewers = self.interviewer_ids
655 # stage_id: track last stage before update
656 if 'stage_id' in vals:
657 vals['date_last_stage_update'] = fields.Datetime.now()
658 if 'kanban_state' not in vals:
659 vals['kanban_state'] = 'normal'
660 for applicant in self:
661 vals['last_stage_id'] = applicant.stage_id.id
662 new_stage = self.env['hr.recruitment.stage'].browse(vals['stage_id'])
663 if new_stage.hired_stage and not applicant.stage_id.hired_stage:
664 if applicant.job_id.no_of_recruitment > 0:
665 applicant.job_id.no_of_recruitment -= 1
666 elif not new_stage.hired_stage and applicant.stage_id.hired_stage:
667 applicant.job_id.no_of_recruitment += 1
668 # kanban_state: also set date_last_stage_update
669 if 'kanban_state' in vals:
670 vals['date_last_stage_update'] = fields.Datetime.now()
671 res = super().write(vals)
672
673 for applicant in self:
674 if applicant.pool_applicant_id and applicant != applicant.pool_applicant_id and (not applicant.is_pool_applicant):
675 if 'email_from' in vals:
676 applicant.pool_applicant_id.email_from = vals['email_from']
677 if 'partner_phone' in vals:
678 applicant.pool_applicant_id.partner_phone = vals['partner_phone']
679 if 'linkedin_profile' in vals:
680 applicant.pool_applicant_id.linkedin_profile = vals['linkedin_profile']
681 if 'type_id' in vals:
682 applicant.pool_applicant_id.type_id = vals['type_id']
683
684 if 'interviewer_ids' in vals:
685 interviewers_to_clean = old_interviewers - self.interviewer_ids
686 interviewers_to_clean._remove_recruitment_interviewers()
687 self.sudo().interviewer_ids._create_recruitment_interviewers()
688
689 new_interviewers = self.interviewer_ids - old_interviewers - self.env.user
690 if new_interviewers:
691 for applicant in self:
692 notification_subject = _("You have been assigned as an interviewer for %s", applicant.display_name)
693 notification_body = _("You have been assigned as an interviewer for the Applicant %s", applicant.partner_name)
694 applicant.message_notify(
695 res_id=applicant.id,
696 model=applicant._name,
697 partner_ids=new_interviewers.partner_id.ids,
698 author_id=self.env.user.partner_id.id,
699 email_from=self.env.user.email_formatted,
700 subject=notification_subject,
701 body=notification_body,
702 email_layout_xmlid="mail.mail_notification_layout",
703 model_description="Applicant",
704 )
705 return res
706
707 @api.model
708 def get_empty_list_help(self, help_message):
709 if 'active_id' in self.env.context and self.env.context.get('active_model') == 'hr.job':
710 hr_job = self.env['hr.job'].browse(self.env.context['active_id'])
711 elif self.env.context.get('default_job_id'):
712 hr_job = self.env['hr.job'].browse(self.env.context['default_job_id'])
713 else:
714 hr_job = self.env['hr.job']
715
716 nocontent_body = Markup("""
717 <p class="o_view_nocontent_smiling_face">%(help_title)s</p>
718 """) % {
719 'help_title': _("No applications found."),
720 }
721
722 if hr_job.alias_email:
723 nocontent_body += Markup('<p class="o_copy_paste_email oe_view_nocontent_alias">%(helper_email)s <a href="mailto:%(email)s">%(email)s</a></p>') % {
724 'helper_email': _("Send applications to"),
725 'email': hr_job.alias_email,
726 }
727
728 return super().get_empty_list_help(nocontent_body)
729
730 @api.model
731 def get_view(self, view_id=None, view_type='form', **options):
732 if view_type == 'form' and self.env.user.has_group('hr_recruitment.group_hr_recruitment_interviewer')\
733 and not self.env.user.has_group('hr_recruitment.group_hr_recruitment_user'):
734 view_id = self.env.ref('hr_recruitment.hr_applicant_view_form_interviewer').id
735 return super().get_view(view_id, view_type, **options)
736
737 def action_create_meeting(self):
738 """ This opens Meeting's calendar view to schedule meeting on current applicant
739 @return: Dictionary value for created Meeting view
740 """
741 self.ensure_one()
742 if not self.partner_id:
743 if not self.partner_name:
744 raise UserError(_('You must define a Contact Name for this applicant.'))
745 self.partner_id = self.env['res.partner'].create({
746 'is_company': False,
747 'name': self.partner_name,
748 'email': self.email_from,
749 })
750
751 partners = self.partner_id | self.department_id.manager_id.user_id.partner_id
752 if self.env.user.has_group('hr_recruitment.group_hr_recruitment_interviewer') and not self.env.user.has_group('hr_recruitment.group_hr_recruitment_user'):
753 partners |= self.env.user.partner_id
754 else:
755 partners |= self.user_id.partner_id
756
757 res = self.env['ir.actions.act_window']._for_xml_id('calendar.action_calendar_event')
758 # As we are redirected from the hr.applicant, calendar checks rules on "hr.applicant",
759 # in order to decide whether to allow creation of a meeting.
760 # As interviewer does not have create right on the hr.applicant, in order to allow them
761 # to create a meeting for an applicant, we pass 'create': True to the context.
762 res['context'] = {
763 'create': True,
764 'default_applicant_id': self.id,
765 'default_partner_ids': partners.ids,
766 'default_user_id': self.env.uid,
767 'default_name': self.partner_name,
768 'attachment_ids': self.attachment_ids.ids
769 }
770 return res
771
772 def action_open_attachments(self):
773 return {
774 'type': 'ir.actions.act_window',
775 'res_model': 'ir.attachment',
776 'name': _('Documents'),
777 'context': {
778 'default_res_model': 'hr.applicant',
779 'default_res_id': self.ids[0],
780 'show_partner_name': 1,
781 },
782 'view_mode': 'list,form',
783 'views': [
784 (self.env.ref('hr_recruitment.ir_attachment_hr_recruitment_list_view').id, 'list'),
785 (False, 'form'),
786 ],
787 'search_view_id': self.env.ref('hr_recruitment.ir_attachment_view_search_inherit_hr_recruitment').ids,
788 'domain': [('res_model', '=', 'hr.applicant'), ('res_id', 'in', self.ids), ],
789 }
790
791 def action_open_employee(self):
792 self.ensure_one()
793 return {
794 'name': _('Employee'),
795 'type': 'ir.actions.act_window',
796 'res_model': 'hr.employee',
797 'view_mode': 'form',
798 'res_id': self.employee_id.id,
799 }
800
801 def action_open_applications(self):
802 self.ensure_one()
803 similar_applicants = (
804 self.env["hr.applicant"]
805 .with_context(active_test=False)
806 .search(
807 self._get_similar_applicants_domain(ignore_talent=True),
808 )
809 )
810 return {
811 "name": _("Applications"),
812 "type": "ir.actions.act_window",
813 "res_model": "hr.applicant",
814 "view_mode": "list,form",
815 "domain": [("id", "in", similar_applicants.ids)],
816 "context": {
817 "active_test": False,
818 "search_default_stage": 1,
819 "default_applicant_ids": self.ids,
820 "no_create_application_button": True,
821 },
822 }
823
824 def action_talent_pool_stat_button(self):
825 self.ensure_one()
826 # If the applicant has other applications linked to pool but for some
827 # reason this applicant is not linked to that account then link it
828 if not self.pool_applicant_id:
829 self.link_applicant_to_talent()
830 return {
831 "type": "ir.actions.act_window",
832 "res_model": "hr.applicant",
833 "view_mode": "form",
834 "target": "current",
835 "res_id": self.pool_applicant_id.id,
836 }
837
838 def link_applicant_to_talent(self):
839 talent = self.env["hr.applicant"].search(domain=self._get_similar_applicants_domain(only_talent=True))
840 self.pool_applicant_id = talent
841
842 def action_talent_pool_add_applicants(self):
843 return {
844 "name": _("Add applicant(s) to the pool"),
845 "type": "ir.actions.act_window",
846 "res_model": "talent.pool.add.applicants",
847 "target": "new",
848 "views": [[False, "form"]],
849 "context": {
850 "is_modal": True,
851 "dialog_size": "medium",
852 "default_talent_pool_ids": self.env.context.get(
853 "default_talent_pool_ids"
854 )
855 or [],
856 "default_applicant_ids": self.ids,
857 },
858 }
859
860 def action_job_add_applicants(self):
861 return {
862 "name": _("Create Applications"),
863 "type": "ir.actions.act_window",
864 "res_model": "job.add.applicants",
865 "target": "new",
866 "views": [[False, "form"]],
867 "context": {
868 "is_modal": True,
869 "dialog_size": "medium",
870 "default_applicant_ids": self.ids
871 or self.env.context.get("default_applicant_ids"),
872 },
873 }
874
875 def _track_template(self, changes):
876 res = super()._track_template(changes)
877 applicant = self[0]
878 # When applcant is unarchived, they are put back to the default stage automatically. In this case,
879 # don't post automated message related to the stage change.
880 if 'stage_id' in changes and applicant.exists()\
881 and applicant.stage_id.template_id\
882 and not applicant.env.context.get('just_moved')\
883 and not applicant.env.context.get('just_unarchived'):
884 res['stage_id'] = (applicant.stage_id.template_id, {
885 'auto_delete_keep_log': False,
886 'subtype_id': self.env['ir.model.data']._xmlid_to_res_id('mail.mt_note'),
887 'email_layout_xmlid': 'hr_recruitment.mail_notification_light_without_background'
888 })
889 return res
890
891 def _creation_subtype(self):
892 self.ensure_one()
893 if self.is_pool_applicant:
894 return self.env.ref('hr_recruitment.mt_talent_new', raise_if_not_found=False)
895 return self.env.ref('hr_recruitment.mt_applicant_new')
896
897 def _track_subtype(self, init_values):
898 record = self[0]
899 if 'stage_id' in init_values and record.stage_id:
900 return self.env.ref('hr_recruitment.mt_applicant_stage_changed')
901 return super()._track_subtype(init_values)
902
903 def _notify_get_reply_to(self, default=None, author_id=False):
904 """ Override to set alias of applicants to their job definition if any. """
905 aliases = self.mapped('job_id')._notify_get_reply_to(default=default, author_id=author_id)
906 res = {app.id: aliases.get(app.job_id.id) for app in self}
907 leftover = self.filtered(lambda rec: not rec.job_id)
908 if leftover:
909 res.update(super(HrApplicant, leftover)._notify_get_reply_to(default=default, author_id=author_id))
910 return res
911
912 def _get_customer_information(self):
913 email_keys_to_values = super()._get_customer_information()
914
915 for applicant in self:
916 email_key = tools.email_normalize(applicant.email_from) or applicant.email_from
917 # do not fill Falsy with random data, unless monorecord (= always correct)
918 if not email_key and len(self) > 1:
919 continue
920 email_keys_to_values.setdefault(email_key, {}).update({
921 'name': applicant.partner_name or tools.parse_contact_from_email(applicant.email_from)[0] or applicant.email_from,
922 'phone': applicant.partner_phone,
923 })
924 return email_keys_to_values
925
926 @api.depends('partner_name')
927 @api.depends_context('show_partner_name')
928 def _compute_display_name(self):
929 if not self.env.context.get('show_partner_name'):
930 return super()._compute_display_name()
931 for applicant in self:
932 applicant.display_name = applicant.partner_name
933
934 @api.model
935 def message_new(self, msg_dict, custom_values=None):
936 # Remove default author when going through the mail gateway. Indeed, we
937 # do not want to explicitly set user_id to False; however we do not
938 # want the gateway user to be responsible if no other responsible is
939 # found.
940 self = self.with_context(default_user_id=False)
941 stage = False
942 if custom_values and 'job_id' in custom_values:
943 job = self.env['hr.job'].browse(custom_values['job_id'])
944 stage = job._get_first_stage()
945
946 partner_name, email_from_normalized = tools.parse_contact_from_email(msg_dict.get('from'))
947
948 defaults = {
949 'partner_name': partner_name,
950 }
951 job_platform = self.env['hr.job.platform'].search([('email', '=', email_from_normalized)], limit=1)
952
953 if msg_dict.get('from') and not job_platform:
954 defaults['email_from'] = msg_dict.get('from')
955 defaults['partner_id'] = msg_dict.get('author_id', False)
956 if msg_dict.get('email_from') and job_platform:
957 subject_pattern = re.compile(job_platform.regex or '')
958 regex_results = re.findall(subject_pattern, msg_dict.get('subject')) + re.findall(subject_pattern, msg_dict.get('body'))
959 defaults['partner_name'] = regex_results[0] if regex_results else partner_name
960 del msg_dict['email_from']
961 if msg_dict.get('priority'):
962 defaults['priority'] = msg_dict.get('priority')
963 if stage and stage.id:
964 defaults['stage_id'] = stage.id
965 if custom_values:
966 defaults.update(custom_values)
967 res = super().message_new(msg_dict, custom_values=defaults)
968 res._compute_partner_phone_email()
969 return res
970
971 def _message_post_after_hook(self, message, msg_vals):
972 if self.email_from and not self.partner_id:
973 # we consider that posting a message with a specified recipient (not a follower, a specific one)
974 # on a document without customer means that it was created through the chatter using
975 # suggested recipients. This heuristic allows to avoid ugly hacks in JS.
976 email_normalized = tools.email_normalize(self.email_from)
977 new_partner = message.partner_ids.filtered(
978 lambda partner: partner.email == self.email_from or (email_normalized and partner.email_normalized == email_normalized)
979 )
980 if new_partner:
981 if new_partner[0].create_date.date() == fields.Date.today():
982 new_partner[0].write({
983 'name': self.partner_name or self.email_from,
984 })
985 if new_partner[0].email_normalized:
986 email_domain = ('email_from', 'in', [new_partner[0].email, new_partner[0].email_normalized])
987 else:
988 email_domain = ('email_from', '=', new_partner[0].email)
989 self.search([
990 ('partner_id', '=', False), email_domain, ('stage_id.fold', '=', False)
991 ]).write({'partner_id': new_partner[0].id})
992 return super()._message_post_after_hook(message, msg_vals)
993
994 def create_employee_from_applicant(self):
995 """ Create an employee from applicant """
996 self.ensure_one()
997 self._check_interviewer_access()
998
999 if not self.partner_id:
1000 if not self.partner_name:
1001 raise UserError(_('Please provide an applicant name.'))
1002 self.partner_id = self.env['res.partner'].create({
1003 'is_company': False,
1004 'name': self.partner_name,
1005 'email': self.email_from,
1006 })
1007
1008 action = self.env['ir.actions.act_window']._for_xml_id('hr.open_view_employee_list')
1009 employee = self.env['hr.employee'].with_context(clean_context(self.env.context)).create(self._get_employee_create_vals())
1010 action['res_id'] = employee.id
1011 employee_attachments = self.env['ir.attachment'].search([('res_model', '=','hr.employee'), ('res_id', '=', employee.id)])
1012 unique_attachments = self.attachment_ids.filtered(
1013 lambda attachment: attachment.datas not in employee_attachments.mapped('datas')
1014 )
1015 unique_attachments.copy({'res_model': 'hr.employee', 'res_id': employee.id})
1016 employee.write({
1017 'job_id': self.job_id.id,
1018 'job_title': self.job_id.name,
1019 'department_id': self.department_id.id,
1020 'work_email': self.department_id.company_id.email or self.email_from, # To have a valid email address by default
1021 'work_phone': self.department_id.company_id.phone,
1022 })
1023 return action
1024
1025 def _get_employee_create_vals(self):
1026 self.ensure_one()
1027 address_id = self.partner_id.address_get(['contact'])['contact']
1028 address_sudo = self.env['res.partner'].sudo().browse(address_id)
1029 return {
1030 'name': self.partner_name or self.partner_id.display_name,
1031 'work_contact_id': self.partner_id.id,
1032 'job_id': self.job_id.id,
1033 'job_title': self.job_id.name,
1034 'private_street': address_sudo.street,
1035 'private_street2': address_sudo.street2,
1036 'private_city': address_sudo.city,
1037 'private_state_id': address_sudo.state_id.id,
1038 'private_zip': address_sudo.zip,
1039 'private_country_id': address_sudo.country_id.id,
1040 'private_phone': address_sudo.phone,
1041 'private_email': address_sudo.email,
1042 'lang': address_sudo.lang,
1043 'department_id': self.department_id.id,
1044 'address_id': self.company_id.partner_id.id,
1045 'work_email': self.department_id.company_id.email or self.email_from, # To have a valid email address by default
1046 'work_phone': self.department_id.company_id.phone,
1047 'applicant_ids': self.ids,
1048 'phone': self.partner_phone
1049 }
1050
1051 def _check_interviewer_access(self):
1052 if self.env.user.has_group('hr_recruitment.group_hr_recruitment_interviewer') and not self.env.user.has_group('hr_recruitment.group_hr_recruitment_user'):
1053 raise UserError(_('You are not allowed to perform this action.'))
1054
1055 def archive_applicant(self):
1056 return {
1057 'type': 'ir.actions.act_window',
1058 'name': _('Refuse Reason'),
1059 'res_model': 'applicant.get.refuse.reason',
1060 'view_mode': 'form',
1061 'target': 'new',
1062 'context': {
1063 'default_applicant_ids': self.ids,
1064 'active_test': False,
1065 'hide_mail_template_management_options': True,
1066 },
1067 'views': [[False, 'form']]
1068 }
1069
1070 def reset_applicant(self):
1071 """ Reinsert the applicant into the recruitment pipe in the first stage"""
1072 default_stage = dict()
1073 for job_id in self.mapped('job_id'):
1074 default_stage[job_id.id] = self.env['hr.recruitment.stage'].search(
1075 [
1076 '|',
1077 ('job_ids', '=', False),
1078 ('job_ids', '=', job_id.id),
1079 ('fold', '=', False)
1080 ], order='sequence asc', limit=1).id
1081 for applicant in self:
1082 applicant.write(
1083 {'stage_id': applicant.job_id.id and default_stage[applicant.job_id.id],
1084 'refuse_reason_id': False})
1085
1086 def action_archive(self):
1087 return super(HrApplicant, self.with_context(just_unarchived=True)).action_archive()
1088
1089 def action_unarchive(self):
1090 res = super(HrApplicant, self.with_context(just_unarchived=True)).action_unarchive()
1091 self.reset_applicant()
1092 return res
1093
1094 def action_send_email(self):
1095 return {
1096 'name': _('Send Email'),
1097 'type': 'ir.actions.act_window',
1098 'target': 'new',
1099 'view_mode': 'form',
1100 'res_model': 'applicant.send.mail',
1101 'context': {
1102 'default_applicant_ids': self.ids,
1103 }
1104 }
1105
1106 def _get_duration_from_tracking(self, trackings):
1107 json = super()._get_duration_from_tracking(trackings)
1108 now = datetime.now()
1109 for applicant in self:
1110 if applicant.refuse_reason_id and applicant.refuse_date:
1111 json[applicant.stage_id.id] -= (now - applicant.refuse_date).total_seconds()
1112 return json