hr_employee.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import base64
  4. from pytz import UTC
  5. from datetime import datetime, time
  6. from random import choice
  7. from string import digits
  8. from werkzeug.urls import url_encode
  9. from dateutil.relativedelta import relativedelta
  10. from odoo import api, fields, models, _
  11. from odoo.exceptions import ValidationError, AccessError
  12. from odoo.osv import expression
  13. from odoo.tools import format_date, Query
  14. class HrEmployeePrivate(models.Model):
  15. """
  16. NB: Any field only available on the model hr.employee (i.e. not on the
  17. hr.employee.public model) should have `groups="hr.group_hr_user"` on its
  18. definition to avoid being prefetched when the user hasn't access to the
  19. hr.employee model. Indeed, the prefetch loads the data for all the fields
  20. that are available according to the group defined on them.
  21. """
  22. _name = "hr.employee"
  23. _description = "Employee"
  24. _order = 'name'
  25. _inherit = ['hr.employee.base', 'mail.thread', 'mail.activity.mixin', 'resource.mixin', 'avatar.mixin']
  26. _mail_post_access = 'read'
  27. # resource and user
  28. # required on the resource, make sure required="True" set in the view
  29. name = fields.Char(string="Employee Name", related='resource_id.name', store=True, readonly=False, tracking=True)
  30. user_id = fields.Many2one('res.users', 'User', related='resource_id.user_id', store=True, readonly=False)
  31. user_partner_id = fields.Many2one(related='user_id.partner_id', related_sudo=False, string="User's partner")
  32. active = fields.Boolean('Active', related='resource_id.active', default=True, store=True, readonly=False)
  33. company_id = fields.Many2one('res.company', required=True)
  34. company_country_id = fields.Many2one('res.country', 'Company Country', related='company_id.country_id', readonly=True)
  35. company_country_code = fields.Char(related='company_country_id.code', depends=['company_country_id'], readonly=True)
  36. # private partner
  37. address_home_id = fields.Many2one(
  38. 'res.partner', 'Address', help='Enter here the private address of the employee, not the one linked to your company.',
  39. groups="hr.group_hr_user", tracking=True,
  40. domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
  41. is_address_home_a_company = fields.Boolean(
  42. 'The employee address has a company linked',
  43. compute='_compute_is_address_home_a_company',
  44. )
  45. private_email = fields.Char(related='address_home_id.email', string="Private Email", groups="hr.group_hr_user")
  46. lang = fields.Selection(related='address_home_id.lang', string="Lang", groups="hr.group_hr_user", readonly=False)
  47. country_id = fields.Many2one(
  48. 'res.country', 'Nationality (Country)', groups="hr.group_hr_user", tracking=True)
  49. gender = fields.Selection([
  50. ('male', 'Male'),
  51. ('female', 'Female'),
  52. ('other', 'Other')
  53. ], groups="hr.group_hr_user", tracking=True)
  54. marital = fields.Selection([
  55. ('single', 'Single'),
  56. ('married', 'Married'),
  57. ('cohabitant', 'Legal Cohabitant'),
  58. ('widower', 'Widower'),
  59. ('divorced', 'Divorced')
  60. ], string='Marital Status', groups="hr.group_hr_user", default='single', tracking=True)
  61. spouse_complete_name = fields.Char(string="Spouse Complete Name", groups="hr.group_hr_user", tracking=True)
  62. spouse_birthdate = fields.Date(string="Spouse Birthdate", groups="hr.group_hr_user", tracking=True)
  63. children = fields.Integer(string='Number of Dependent Children', groups="hr.group_hr_user", tracking=True)
  64. place_of_birth = fields.Char('Place of Birth', groups="hr.group_hr_user", tracking=True)
  65. country_of_birth = fields.Many2one('res.country', string="Country of Birth", groups="hr.group_hr_user", tracking=True)
  66. birthday = fields.Date('Date of Birth', groups="hr.group_hr_user", tracking=True)
  67. ssnid = fields.Char('SSN No', help='Social Security Number', groups="hr.group_hr_user", tracking=True)
  68. sinid = fields.Char('SIN No', help='Social Insurance Number', groups="hr.group_hr_user", tracking=True)
  69. identification_id = fields.Char(string='Identification No', groups="hr.group_hr_user", tracking=True)
  70. passport_id = fields.Char('Passport No', groups="hr.group_hr_user", tracking=True)
  71. bank_account_id = fields.Many2one(
  72. 'res.partner.bank', 'Bank Account Number',
  73. domain="[('partner_id', '=', address_home_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
  74. groups="hr.group_hr_user",
  75. tracking=True,
  76. help='Employee bank account to pay salaries')
  77. permit_no = fields.Char('Work Permit No', groups="hr.group_hr_user", tracking=True)
  78. visa_no = fields.Char('Visa No', groups="hr.group_hr_user", tracking=True)
  79. visa_expire = fields.Date('Visa Expire Date', groups="hr.group_hr_user", tracking=True)
  80. work_permit_expiration_date = fields.Date('Work Permit Expiration Date', groups="hr.group_hr_user", tracking=True)
  81. has_work_permit = fields.Binary(string="Work Permit", groups="hr.group_hr_user", tracking=True)
  82. work_permit_scheduled_activity = fields.Boolean(default=False, groups="hr.group_hr_user")
  83. work_permit_name = fields.Char('work_permit_name', compute='_compute_work_permit_name')
  84. additional_note = fields.Text(string='Additional Note', groups="hr.group_hr_user", tracking=True)
  85. certificate = fields.Selection([
  86. ('graduate', 'Graduate'),
  87. ('bachelor', 'Bachelor'),
  88. ('master', 'Master'),
  89. ('doctor', 'Doctor'),
  90. ('other', 'Other'),
  91. ], 'Certificate Level', default='other', groups="hr.group_hr_user", tracking=True)
  92. study_field = fields.Char("Field of Study", groups="hr.group_hr_user", tracking=True)
  93. study_school = fields.Char("School", groups="hr.group_hr_user", tracking=True)
  94. emergency_contact = fields.Char("Contact Name", groups="hr.group_hr_user", tracking=True)
  95. emergency_phone = fields.Char("Contact Phone", groups="hr.group_hr_user", tracking=True)
  96. km_home_work = fields.Integer(string="Home-Work Distance", groups="hr.group_hr_user", tracking=True)
  97. job_id = fields.Many2one(tracking=True)
  98. phone = fields.Char(related='address_home_id.phone', related_sudo=False, readonly=False, string="Private Phone", groups="hr.group_hr_user")
  99. # employee in company
  100. child_ids = fields.One2many('hr.employee', 'parent_id', string='Direct subordinates')
  101. category_ids = fields.Many2many(
  102. 'hr.employee.category', 'employee_category_rel',
  103. 'emp_id', 'category_id', groups="hr.group_hr_user",
  104. string='Tags')
  105. # misc
  106. notes = fields.Text('Notes', groups="hr.group_hr_user")
  107. color = fields.Integer('Color Index', default=0)
  108. barcode = fields.Char(string="Badge ID", help="ID used for employee identification.", groups="hr.group_hr_user", copy=False)
  109. pin = fields.Char(string="PIN", groups="hr.group_hr_user", copy=False,
  110. help="PIN used to Check In/Out in the Kiosk Mode of the Attendance application (if enabled in Configuration) and to change the cashier in the Point of Sale application.")
  111. departure_reason_id = fields.Many2one("hr.departure.reason", string="Departure Reason", groups="hr.group_hr_user",
  112. copy=False, tracking=True, ondelete='restrict')
  113. departure_description = fields.Html(string="Additional Information", groups="hr.group_hr_user", copy=False, tracking=True)
  114. departure_date = fields.Date(string="Departure Date", groups="hr.group_hr_user", copy=False, tracking=True)
  115. message_main_attachment_id = fields.Many2one(groups="hr.group_hr_user")
  116. id_card = fields.Binary(string="ID Card Copy", groups="hr.group_hr_user")
  117. driving_license = fields.Binary(string="Driving License", groups="hr.group_hr_user")
  118. currency_id = fields.Many2one('res.currency', related='company_id.currency_id', readonly=True)
  119. _sql_constraints = [
  120. ('barcode_uniq', 'unique (barcode)', "The Badge ID must be unique, this one is already assigned to another employee."),
  121. ('user_uniq', 'unique (user_id, company_id)', "A user cannot be linked to multiple employees in the same company.")
  122. ]
  123. @api.depends('name', 'user_id.avatar_1920', 'image_1920')
  124. def _compute_avatar_1920(self):
  125. super()._compute_avatar_1920()
  126. @api.depends('name', 'user_id.avatar_1024', 'image_1024')
  127. def _compute_avatar_1024(self):
  128. super()._compute_avatar_1024()
  129. @api.depends('name', 'user_id.avatar_512', 'image_512')
  130. def _compute_avatar_512(self):
  131. super()._compute_avatar_512()
  132. @api.depends('name', 'user_id.avatar_256', 'image_256')
  133. def _compute_avatar_256(self):
  134. super()._compute_avatar_256()
  135. @api.depends('name', 'user_id.avatar_128', 'image_128')
  136. def _compute_avatar_128(self):
  137. super()._compute_avatar_128()
  138. def _compute_avatar(self, avatar_field, image_field):
  139. for employee in self:
  140. avatar = employee._origin[image_field]
  141. if not avatar:
  142. if employee.user_id:
  143. avatar = employee.user_id[avatar_field]
  144. else:
  145. avatar = base64.b64encode(employee._avatar_get_placeholder())
  146. employee[avatar_field] = avatar
  147. @api.depends('name', 'permit_no')
  148. def _compute_work_permit_name(self):
  149. for employee in self:
  150. name = employee.name.replace(' ', '_') + '_' if employee.name else ''
  151. permit_no = '_' + employee.permit_no if employee.permit_no else ''
  152. employee.work_permit_name = "%swork_permit%s" % (name, permit_no)
  153. def action_create_user(self):
  154. self.ensure_one()
  155. if self.user_id:
  156. raise ValidationError(_("This employee already has an user."))
  157. return {
  158. 'name': _('Create User'),
  159. 'type': 'ir.actions.act_window',
  160. 'res_model': 'res.users',
  161. 'view_mode': 'form',
  162. 'view_id': self.env.ref('hr.view_users_simple_form').id,
  163. 'target': 'new',
  164. 'context': {
  165. 'default_create_employee_id': self.id,
  166. 'default_name': self.name,
  167. 'default_phone': self.work_phone,
  168. 'default_mobile': self.mobile_phone,
  169. 'default_login': self.work_email,
  170. }
  171. }
  172. def name_get(self):
  173. if self.check_access_rights('read', raise_exception=False):
  174. return super(HrEmployeePrivate, self).name_get()
  175. return self.env['hr.employee.public'].browse(self.ids).name_get()
  176. def _read(self, fields):
  177. if self.check_access_rights('read', raise_exception=False):
  178. return super(HrEmployeePrivate, self)._read(fields)
  179. # HACK: retrieve publicly available values from hr.employee.public and
  180. # copy them to the cache of self; non-public data will be missing from
  181. # cache, and interpreted as an access error
  182. self.flush_recordset(fields)
  183. public = self.env['hr.employee.public'].browse(self._ids)
  184. public.read(fields)
  185. for fname in fields:
  186. values = self.env.cache.get_values(public, public._fields[fname])
  187. if self._fields[fname].translate:
  188. values = [(value.copy() if value else None) for value in values]
  189. self.env.cache.update_raw(self, self._fields[fname], values)
  190. @api.model
  191. def _cron_check_work_permit_validity(self):
  192. # Called by a cron
  193. # Schedule an activity 1 month before the work permit expires
  194. outdated_days = fields.Date.today() + relativedelta(months=+1)
  195. nearly_expired_work_permits = self.search([('work_permit_scheduled_activity', '=', False), ('work_permit_expiration_date', '<', outdated_days)])
  196. employees_scheduled = self.env['hr.employee']
  197. for employee in nearly_expired_work_permits.filtered(lambda employee: employee.parent_id):
  198. responsible_user_id = employee.parent_id.user_id.id
  199. if responsible_user_id:
  200. employees_scheduled |= employee
  201. lang = self.env['res.users'].browse(responsible_user_id).lang
  202. formated_date = format_date(employee.env, employee.work_permit_expiration_date, date_format="dd MMMM y", lang_code=lang)
  203. employee.activity_schedule(
  204. 'mail.mail_activity_data_todo',
  205. note=_('The work permit of %(employee)s expires at %(date)s.',
  206. employee=employee.name,
  207. date=formated_date),
  208. user_id=responsible_user_id)
  209. employees_scheduled.write({'work_permit_scheduled_activity': True})
  210. def read(self, fields, load='_classic_read'):
  211. if self.check_access_rights('read', raise_exception=False):
  212. return super(HrEmployeePrivate, self).read(fields, load=load)
  213. private_fields = set(fields).difference(self.env['hr.employee.public']._fields.keys())
  214. if private_fields:
  215. raise AccessError(_('The fields "%s" you try to read is not available on the public employee profile.') % (','.join(private_fields)))
  216. return self.env['hr.employee.public'].browse(self.ids).read(fields, load=load)
  217. @api.model
  218. def get_view(self, view_id=None, view_type='form', **options):
  219. if self.check_access_rights('read', raise_exception=False):
  220. return super().get_view(view_id, view_type, **options)
  221. return self.env['hr.employee.public'].get_view(view_id, view_type, **options)
  222. @api.model
  223. def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
  224. """
  225. We override the _search because it is the method that checks the access rights
  226. This is correct to override the _search. That way we enforce the fact that calling
  227. search on an hr.employee returns a hr.employee recordset, even if you don't have access
  228. to this model, as the result of _search (the ids of the public employees) is to be
  229. browsed on the hr.employee model. This can be trusted as the ids of the public
  230. employees exactly match the ids of the related hr.employee.
  231. """
  232. if self.check_access_rights('read', raise_exception=False):
  233. return super(HrEmployeePrivate, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
  234. try:
  235. ids = self.env['hr.employee.public']._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
  236. except ValueError:
  237. raise AccessError(_('You do not have access to this document.'))
  238. if not count and isinstance(ids, Query):
  239. # the result is expected from this table, so we should link tables
  240. ids = super(HrEmployeePrivate, self.sudo())._search([('id', 'in', ids)])
  241. return ids
  242. def get_formview_id(self, access_uid=None):
  243. """ Override this method in order to redirect many2one towards the right model depending on access_uid """
  244. if access_uid:
  245. self_sudo = self.with_user(access_uid)
  246. else:
  247. self_sudo = self
  248. if self_sudo.check_access_rights('read', raise_exception=False):
  249. return super(HrEmployeePrivate, self).get_formview_id(access_uid=access_uid)
  250. # Hardcode the form view for public employee
  251. return self.env.ref('hr.hr_employee_public_view_form').id
  252. def get_formview_action(self, access_uid=None):
  253. """ Override this method in order to redirect many2one towards the right model depending on access_uid """
  254. res = super(HrEmployeePrivate, self).get_formview_action(access_uid=access_uid)
  255. if access_uid:
  256. self_sudo = self.with_user(access_uid)
  257. else:
  258. self_sudo = self
  259. if not self_sudo.check_access_rights('read', raise_exception=False):
  260. res['res_model'] = 'hr.employee.public'
  261. return res
  262. @api.constrains('pin')
  263. def _verify_pin(self):
  264. for employee in self:
  265. if employee.pin and not employee.pin.isdigit():
  266. raise ValidationError(_("The PIN must be a sequence of digits."))
  267. @api.onchange('user_id')
  268. def _onchange_user(self):
  269. if self.user_id:
  270. self.update(self._sync_user(self.user_id, (bool(self.image_1920))))
  271. if not self.name:
  272. self.name = self.user_id.name
  273. @api.onchange('resource_calendar_id')
  274. def _onchange_timezone(self):
  275. if self.resource_calendar_id and not self.tz:
  276. self.tz = self.resource_calendar_id.tz
  277. def _sync_user(self, user, employee_has_image=False):
  278. vals = dict(
  279. work_contact_id=user.partner_id.id,
  280. user_id=user.id,
  281. )
  282. if not employee_has_image:
  283. vals['image_1920'] = user.image_1920
  284. if user.tz:
  285. vals['tz'] = user.tz
  286. return vals
  287. def _prepare_resource_values(self, vals, tz):
  288. resource_vals = super()._prepare_resource_values(vals, tz)
  289. vals.pop('name') # Already considered by super call but no popped
  290. # We need to pop it to avoid useless resource update (& write) call
  291. # on every newly created resource (with the correct name already)
  292. user_id = vals.pop('user_id', None)
  293. if user_id:
  294. resource_vals['user_id'] = user_id
  295. active_status = vals.get('active')
  296. if active_status is not None:
  297. resource_vals['active'] = active_status
  298. return resource_vals
  299. @api.model_create_multi
  300. def create(self, vals_list):
  301. for vals in vals_list:
  302. if vals.get('user_id'):
  303. user = self.env['res.users'].browse(vals['user_id'])
  304. vals.update(self._sync_user(user, bool(vals.get('image_1920'))))
  305. vals['name'] = vals.get('name', user.name)
  306. employees = super().create(vals_list)
  307. if self.env.context.get('salary_simulation'):
  308. return employees
  309. employee_departments = employees.department_id
  310. if employee_departments:
  311. self.env['mail.channel'].sudo().search([
  312. ('subscription_department_ids', 'in', employee_departments.ids)
  313. ])._subscribe_users_automatically()
  314. onboarding_notes_bodies = {}
  315. hr_root_menu = self.env.ref('hr.menu_hr_root')
  316. for employee in employees:
  317. employee._message_subscribe(employee.address_home_id.ids)
  318. # Launch onboarding plans
  319. url = '/web#%s' % url_encode({
  320. 'action': 'hr.plan_wizard_action',
  321. 'active_id': employee.id,
  322. 'active_model': 'hr.employee',
  323. 'menu_id': hr_root_menu.id,
  324. })
  325. onboarding_notes_bodies[employee.id] = _(
  326. '<b>Congratulations!</b> May I recommend you to setup an <a href="%s">onboarding plan?</a>',
  327. url,
  328. )
  329. employees._message_log_batch(onboarding_notes_bodies)
  330. return employees
  331. def write(self, vals):
  332. if 'address_home_id' in vals:
  333. account_ids = vals.get('bank_account_id') or self.bank_account_id.ids
  334. if account_ids:
  335. self.env['res.partner.bank'].browse(account_ids).partner_id = vals['address_home_id']
  336. self.message_unsubscribe(self.address_home_id.ids)
  337. if vals['address_home_id']:
  338. self._message_subscribe([vals['address_home_id']])
  339. if 'user_id' in vals:
  340. # Update the profile pictures with user, except if provided
  341. vals.update(self._sync_user(self.env['res.users'].browse(vals['user_id']),
  342. (bool(all(emp.image_1920 for emp in self)))))
  343. if 'work_permit_expiration_date' in vals:
  344. vals['work_permit_scheduled_activity'] = False
  345. res = super(HrEmployeePrivate, self).write(vals)
  346. if vals.get('department_id') or vals.get('user_id'):
  347. department_id = vals['department_id'] if vals.get('department_id') else self[:1].department_id.id
  348. # When added to a department or changing user, subscribe to the channels auto-subscribed by department
  349. self.env['mail.channel'].sudo().search([
  350. ('subscription_department_ids', 'in', department_id)
  351. ])._subscribe_users_automatically()
  352. return res
  353. def unlink(self):
  354. resources = self.mapped('resource_id')
  355. super(HrEmployeePrivate, self).unlink()
  356. return resources.unlink()
  357. def _get_employee_m2o_to_empty_on_archived_employees(self):
  358. return ['parent_id', 'coach_id']
  359. def _get_user_m2o_to_empty_on_archived_employees(self):
  360. return []
  361. def toggle_active(self):
  362. res = super(HrEmployeePrivate, self).toggle_active()
  363. unarchived_employees = self.filtered(lambda employee: employee.active)
  364. unarchived_employees.write({
  365. 'departure_reason_id': False,
  366. 'departure_description': False,
  367. 'departure_date': False
  368. })
  369. archived_addresses = unarchived_employees.mapped('address_home_id').filtered(lambda addr: not addr.active)
  370. archived_addresses.toggle_active()
  371. archived_employees = self.filtered(lambda e: not e.active)
  372. if archived_employees:
  373. # Empty links to this employees (example: manager, coach, time off responsible, ...)
  374. employee_fields_to_empty = self._get_employee_m2o_to_empty_on_archived_employees()
  375. user_fields_to_empty = self._get_user_m2o_to_empty_on_archived_employees()
  376. employee_domain = [[(field, 'in', archived_employees.ids)] for field in employee_fields_to_empty]
  377. user_domain = [[(field, 'in', archived_employees.user_id.ids) for field in user_fields_to_empty]]
  378. employees = self.env['hr.employee'].search(expression.OR(employee_domain + user_domain))
  379. for employee in employees:
  380. for field in employee_fields_to_empty:
  381. if employee[field] in archived_employees:
  382. employee[field] = False
  383. for field in user_fields_to_empty:
  384. if employee[field] in archived_employees.user_id:
  385. employee[field] = False
  386. if len(self) == 1 and not self.active and not self.env.context.get('no_wizard', False):
  387. return {
  388. 'type': 'ir.actions.act_window',
  389. 'name': _('Register Departure'),
  390. 'res_model': 'hr.departure.wizard',
  391. 'view_mode': 'form',
  392. 'target': 'new',
  393. 'context': {'active_id': self.id},
  394. 'views': [[False, 'form']]
  395. }
  396. return res
  397. @api.onchange('company_id')
  398. def _onchange_company_id(self):
  399. if self._origin:
  400. return {'warning': {
  401. 'title': _("Warning"),
  402. 'message': _("To avoid multi company issues (losing the access to your previous contracts, leaves, ...), you should create another employee in the new company instead.")
  403. }}
  404. def generate_random_barcode(self):
  405. for employee in self:
  406. employee.barcode = '041'+"".join(choice(digits) for i in range(9))
  407. @api.depends('address_home_id', 'user_partner_id')
  408. def _compute_related_contacts(self):
  409. super()._compute_related_contacts()
  410. for employee in self:
  411. employee.related_contact_ids |= employee.address_home_id | employee.user_partner_id
  412. @api.depends('address_home_id.parent_id')
  413. def _compute_is_address_home_a_company(self):
  414. """Checks that chosen address (res.partner) is not linked to a company.
  415. """
  416. for employee in self:
  417. try:
  418. employee.is_address_home_a_company = employee.address_home_id.parent_id.id is not False
  419. except AccessError:
  420. employee.is_address_home_a_company = False
  421. def _get_tz(self):
  422. # Finds the first valid timezone in his tz, his work hours tz,
  423. # the company calendar tz or UTC and returns it as a string
  424. self.ensure_one()
  425. return self.tz or\
  426. self.resource_calendar_id.tz or\
  427. self.company_id.resource_calendar_id.tz or\
  428. 'UTC'
  429. def _get_tz_batch(self):
  430. # Finds the first valid timezone in his tz, his work hours tz,
  431. # the company calendar tz or UTC
  432. # Returns a dict {employee_id: tz}
  433. return {emp.id: emp._get_tz() for emp in self}
  434. # ---------------------------------------------------------
  435. # Business Methods
  436. # ---------------------------------------------------------
  437. @api.model
  438. def get_import_templates(self):
  439. return [{
  440. 'label': _('Import Template for Employees'),
  441. 'template': '/hr/static/xls/hr_employee.xls'
  442. }]
  443. def _post_author(self):
  444. """
  445. When a user updates his own employee's data, all operations are performed
  446. by super user. However, tracking messages should not be posted as OdooBot
  447. but as the actual user.
  448. This method is used in the overrides of `_message_log` and `message_post`
  449. to post messages as the correct user.
  450. """
  451. real_user = self.env.context.get('binary_field_real_user')
  452. if self.env.is_superuser() and real_user:
  453. self = self.with_user(real_user)
  454. return self
  455. def _get_unusual_days(self, date_from, date_to=None):
  456. # Checking the calendar directly allows to not grey out the leaves taken
  457. # by the employee or fallback to the company calendar
  458. return (self.resource_calendar_id or self.env.company.resource_calendar_id)._get_unusual_days(
  459. datetime.combine(fields.Date.from_string(date_from), time.min).replace(tzinfo=UTC),
  460. datetime.combine(fields.Date.from_string(date_to), time.max).replace(tzinfo=UTC)
  461. )
  462. # ---------------------------------------------------------
  463. # Messaging
  464. # ---------------------------------------------------------
  465. def _message_log(self, **kwargs):
  466. return super(HrEmployeePrivate, self._post_author())._message_log(**kwargs)
  467. @api.returns('mail.message', lambda value: value.id)
  468. def message_post(self, **kwargs):
  469. return super(HrEmployeePrivate, self._post_author()).message_post(**kwargs)
  470. def _sms_get_partner_fields(self):
  471. return ['user_partner_id']
  472. def _sms_get_number_fields(self):
  473. return ['mobile_phone']