hr_leave.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com)
  4. import logging
  5. import pytz
  6. from collections import namedtuple, defaultdict
  7. from datetime import datetime, timedelta, time
  8. from pytz import timezone, UTC
  9. from odoo.tools import date_utils
  10. from odoo import api, Command, fields, models, tools
  11. from odoo.addons.base.models.res_partner import _tz_get
  12. from odoo.addons.resource.models.resource import float_to_time, HOURS_PER_DAY
  13. from odoo.exceptions import AccessError, UserError, ValidationError
  14. from odoo.tools import float_compare, format_date
  15. from odoo.tools.float_utils import float_round
  16. from odoo.tools.misc import format_date
  17. from odoo.tools.translate import _
  18. from odoo.osv import expression
  19. _logger = logging.getLogger(__name__)
  20. # Used to agglomerate the attendances in order to find the hour_from and hour_to
  21. # See _compute_date_from_to
  22. DummyAttendance = namedtuple('DummyAttendance', 'hour_from, hour_to, dayofweek, day_period, week_type')
  23. def get_employee_from_context(values, context, user_employee_id):
  24. employee_ids_list = [value[2] for value in values.get('employee_ids', []) if len(value) == 3 and value[0] == Command.SET]
  25. employee_ids = employee_ids_list[-1] if employee_ids_list else []
  26. employee_id_value = employee_ids[0] if employee_ids else False
  27. return employee_id_value or context.get('default_employee_id', context.get('employee_id', user_employee_id))
  28. class HolidaysRequest(models.Model):
  29. """ Leave Requests Access specifications
  30. - a regular employee / user
  31. - can see all leaves;
  32. - cannot see name field of leaves belonging to other user as it may contain
  33. private information that we don't want to share to other people than
  34. HR people;
  35. - can modify only its own not validated leaves (except writing on state to
  36. bypass approval);
  37. - can discuss on its leave requests;
  38. - can reset only its own leaves;
  39. - cannot validate any leaves;
  40. - an Officer
  41. - can see all leaves;
  42. - can validate "HR" single validation leaves from people if
  43. - he is the employee manager;
  44. - he is the department manager;
  45. - he is member of the same department;
  46. - target employee has no manager and no department manager;
  47. - can validate "Manager" single validation leaves from people if
  48. - he is the employee manager;
  49. - he is the department manager;
  50. - target employee has no manager and no department manager;
  51. - can first validate "Both" double validation leaves from people like "HR"
  52. single validation, moving the leaves to validate1 state;
  53. - cannot validate its own leaves;
  54. - can reset only its own leaves;
  55. - can refuse all leaves;
  56. - a Manager
  57. - can do everything he wants
  58. On top of that multicompany rules apply based on company defined on the
  59. leave request leave type.
  60. """
  61. _name = "hr.leave"
  62. _description = "Time Off"
  63. _order = "date_from desc"
  64. _inherit = ['mail.thread', 'mail.activity.mixin']
  65. _mail_post_access = 'read'
  66. @api.model
  67. def default_get(self, fields_list):
  68. defaults = super(HolidaysRequest, self).default_get(fields_list)
  69. defaults = self._default_get_request_parameters(defaults)
  70. if self.env.context.get('holiday_status_name_get', True) and 'holiday_status_id' in fields_list and not defaults.get('holiday_status_id'):
  71. lt = self.env['hr.leave.type'].search(['|', ('requires_allocation', '=', 'no'), ('has_valid_allocation', '=', True)], limit=1, order='sequence')
  72. if lt:
  73. defaults['holiday_status_id'] = lt.id
  74. defaults['request_unit_custom'] = False
  75. if 'state' in fields_list and not defaults.get('state'):
  76. lt = self.env['hr.leave.type'].browse(defaults.get('holiday_status_id'))
  77. defaults['state'] = 'confirm'
  78. if 'date_from' and 'date_to' in fields_list:
  79. now = fields.Datetime.now()
  80. if 'date_from' not in defaults:
  81. defaults['date_from'] = now.replace(hour=0, minute=0, second=0)
  82. if 'date_to' not in defaults:
  83. defaults['date_to'] = now.replace(hour=23, minute=59, second=59)
  84. if (not self._context.get('leave_compute_date_from_to') and defaults['date_from'].time() == time(0, 0, 0) and
  85. defaults['date_to'].time() == time(23, 59, 59)):
  86. employee = self.env['hr.employee'].browse(defaults['employee_id']) if defaults.get('employee_id') else self.env.user.employee_id
  87. date_from = defaults['date_from'].date()
  88. date_to = defaults['date_to'].date()
  89. attendance_from, attendance_to = self._get_attendances(employee, date_from, date_to)
  90. defaults['date_from'] = self._get_start_or_end_from_attendance(attendance_from.hour_from, date_from, employee)
  91. defaults['date_to'] = self._get_start_or_end_from_attendance(attendance_to.hour_to, date_to, employee)
  92. defaults = self._default_get_request_parameters(defaults)
  93. return defaults
  94. def _default_get_request_parameters(self, values):
  95. new_values = dict(values)
  96. if values.get('date_from') and values.get('date_to'):
  97. date_from = self._adjust_date_based_on_tz(values['date_from'].date(), values['date_from'].time())
  98. date_to = self._adjust_date_based_on_tz(values['date_to'].date(), values['date_to'].time())
  99. new_values.update([('request_date_from', date_from), ('request_date_to', date_to)])
  100. employee = self.env['hr.employee'].browse(values['employee_id']) if values.get('employee_id') else self.env.user.employee_id
  101. default_start_time = self._get_start_or_end_from_attendance(7, datetime.now().date(), employee).time()
  102. default_end_time = self._get_start_or_end_from_attendance(19, datetime.now().date(), employee).time()
  103. if values['date_from'].time() == default_start_time and values['date_to'].time() == default_end_time:
  104. attendance_from, attendance_to = self._get_attendances(employee, date_from, date_to)
  105. new_values['date_from'] = self._get_start_or_end_from_attendance(attendance_from.hour_from, date_from, employee)
  106. new_values['date_to'] = self._get_start_or_end_from_attendance(attendance_to.hour_to, date_to, employee)
  107. return new_values
  108. active = fields.Boolean(default=True, readonly=True)
  109. # description
  110. name = fields.Char('Description', compute='_compute_description', inverse='_inverse_description', search='_search_description', compute_sudo=False)
  111. private_name = fields.Char('Time Off Description', groups='hr_holidays.group_hr_holidays_user')
  112. state = fields.Selection([
  113. ('draft', 'To Submit'),
  114. ('confirm', 'To Approve'),
  115. ('refuse', 'Refused'),
  116. ('validate1', 'Second Approval'),
  117. ('validate', 'Approved')
  118. ], string='Status', compute='_compute_state', store=True, tracking=True, copy=False, readonly=False,
  119. help="The status is set to 'To Submit', when a time off request is created." +
  120. "\nThe status is 'To Approve', when time off request is confirmed by user." +
  121. "\nThe status is 'Refused', when time off request is refused by manager." +
  122. "\nThe status is 'Approved', when time off request is approved by manager.")
  123. report_note = fields.Text('HR Comments', copy=False, groups="hr_holidays.group_hr_holidays_manager")
  124. user_id = fields.Many2one('res.users', string='User', related='employee_id.user_id', related_sudo=True, compute_sudo=True, store=True, readonly=True, index=True)
  125. manager_id = fields.Many2one('hr.employee', compute='_compute_from_employee_id', store=True, readonly=False)
  126. # leave type configuration
  127. holiday_status_id = fields.Many2one(
  128. "hr.leave.type", compute='_compute_from_employee_id', store=True, string="Time Off Type", required=True, readonly=False,
  129. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]},
  130. domain="[('company_id', '=?', employee_company_id), '|', ('requires_allocation', '=', 'no'), ('has_valid_allocation', '=', True)]", tracking=True)
  131. holiday_allocation_id = fields.Many2one(
  132. 'hr.leave.allocation', compute='_compute_from_holiday_status_id', string="Allocation", store=True, readonly=False)
  133. color = fields.Integer("Color", related='holiday_status_id.color')
  134. validation_type = fields.Selection(string='Validation Type', related='holiday_status_id.leave_validation_type', readonly=False)
  135. # HR data
  136. employee_id = fields.Many2one(
  137. 'hr.employee', compute='_compute_from_employee_ids', store=True, string='Employee', index=True, readonly=False, ondelete="restrict",
  138. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]},
  139. tracking=True, compute_sudo=False)
  140. employee_company_id = fields.Many2one(related='employee_id.company_id', readonly=True, store=True)
  141. active_employee = fields.Boolean(related='employee_id.active', string='Employee Active', readonly=True)
  142. tz_mismatch = fields.Boolean(compute='_compute_tz_mismatch')
  143. tz = fields.Selection(_tz_get, compute='_compute_tz')
  144. department_id = fields.Many2one(
  145. 'hr.department', compute='_compute_department_id', store=True, string='Department', readonly=False,
  146. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]})
  147. notes = fields.Text('Reasons', readonly=True, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
  148. # duration
  149. date_from = fields.Datetime(
  150. 'Start Date', compute='_compute_date_from_to', store=True, readonly=False, index=True, copy=False, required=True, tracking=True,
  151. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]})
  152. date_to = fields.Datetime(
  153. 'End Date', compute='_compute_date_from_to', store=True, readonly=False, copy=False, required=True, tracking=True,
  154. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]})
  155. number_of_days = fields.Float(
  156. 'Duration (Days)', compute='_compute_number_of_days', store=True, readonly=False, copy=False, tracking=True,
  157. help='Number of days of the time off request. Used in the calculation. To manually correct the duration, use this field.')
  158. number_of_days_display = fields.Float(
  159. 'Duration in days', compute='_compute_number_of_days_display', readonly=True,
  160. help='Number of days of the time off request according to your working schedule. Used for interface.')
  161. number_of_hours_display = fields.Float(
  162. 'Duration in hours', compute='_compute_number_of_hours_display', readonly=True,
  163. help='Number of hours of the time off request according to your working schedule. Used for interface.')
  164. number_of_hours_text = fields.Char(compute='_compute_number_of_hours_text')
  165. duration_display = fields.Char('Requested (Days/Hours)', compute='_compute_duration_display', store=True,
  166. help="Field allowing to see the leave request duration in days or hours depending on the leave_type_request_unit") # details
  167. # details
  168. meeting_id = fields.Many2one('calendar.event', string='Meeting', copy=False)
  169. parent_id = fields.Many2one('hr.leave', string='Parent', copy=False)
  170. linked_request_ids = fields.One2many('hr.leave', 'parent_id', string='Linked Requests')
  171. holiday_type = fields.Selection([
  172. ('employee', 'By Employee'),
  173. ('company', 'By Company'),
  174. ('department', 'By Department'),
  175. ('category', 'By Employee Tag')],
  176. string='Allocation Mode', readonly=True, required=True, default='employee',
  177. states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]},
  178. help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category')
  179. employee_ids = fields.Many2many(
  180. 'hr.employee', compute='_compute_from_holiday_type', store=True, string='Employees', readonly=False, groups="hr_holidays.group_hr_holidays_user",
  181. states={'cancel': [('readonly', True)], 'refuse': [('readonly', True)], 'validate1': [('readonly', True)], 'validate': [('readonly', True)]})
  182. multi_employee = fields.Boolean(
  183. compute='_compute_from_employee_ids', store=True, compute_sudo=False,
  184. help='Holds whether this allocation concerns more than 1 employee')
  185. category_id = fields.Many2one(
  186. 'hr.employee.category', compute='_compute_from_holiday_type', store=True, string='Employee Tag',
  187. states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help='Category of Employee')
  188. mode_company_id = fields.Many2one(
  189. 'res.company', compute='_compute_from_holiday_type', store=True, string='Company Mode',
  190. states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
  191. first_approver_id = fields.Many2one(
  192. 'hr.employee', string='First Approval', readonly=True, copy=False,
  193. help='This area is automatically filled by the user who validate the time off')
  194. second_approver_id = fields.Many2one(
  195. 'hr.employee', string='Second Approval', readonly=True, copy=False,
  196. help='This area is automatically filled by the user who validate the time off with second level (If time off type need second validation)')
  197. can_reset = fields.Boolean('Can reset', compute='_compute_can_reset')
  198. can_approve = fields.Boolean('Can Approve', compute='_compute_can_approve')
  199. can_cancel = fields.Boolean('Can Cancel', compute='_compute_can_cancel')
  200. attachment_ids = fields.One2many('ir.attachment', 'res_id', string="Attachments")
  201. # To display in form view
  202. supported_attachment_ids = fields.Many2many(
  203. 'ir.attachment', string="Attach File", compute='_compute_supported_attachment_ids',
  204. inverse='_inverse_supported_attachment_ids')
  205. supported_attachment_ids_count = fields.Integer(compute='_compute_supported_attachment_ids')
  206. # UX fields
  207. all_employee_ids = fields.Many2many('hr.employee', compute='_compute_all_employees', compute_sudo=True, context={'active_test': False})
  208. leave_type_request_unit = fields.Selection(related='holiday_status_id.request_unit', readonly=True)
  209. leave_type_support_document = fields.Boolean(related="holiday_status_id.support_document")
  210. # Interface fields used when not using hour-based computation
  211. request_date_from = fields.Date('Request Start Date')
  212. request_date_to = fields.Date('Request End Date')
  213. # Interface fields used when using hour-based computation
  214. request_hour_from = fields.Selection([
  215. ('0', '12:00 AM'), ('0.5', '12:30 AM'),
  216. ('1', '1:00 AM'), ('1.5', '1:30 AM'),
  217. ('2', '2:00 AM'), ('2.5', '2:30 AM'),
  218. ('3', '3:00 AM'), ('3.5', '3:30 AM'),
  219. ('4', '4:00 AM'), ('4.5', '4:30 AM'),
  220. ('5', '5:00 AM'), ('5.5', '5:30 AM'),
  221. ('6', '6:00 AM'), ('6.5', '6:30 AM'),
  222. ('7', '7:00 AM'), ('7.5', '7:30 AM'),
  223. ('8', '8:00 AM'), ('8.5', '8:30 AM'),
  224. ('9', '9:00 AM'), ('9.5', '9:30 AM'),
  225. ('10', '10:00 AM'), ('10.5', '10:30 AM'),
  226. ('11', '11:00 AM'), ('11.5', '11:30 AM'),
  227. ('12', '12:00 PM'), ('12.5', '12:30 PM'),
  228. ('13', '1:00 PM'), ('13.5', '1:30 PM'),
  229. ('14', '2:00 PM'), ('14.5', '2:30 PM'),
  230. ('15', '3:00 PM'), ('15.5', '3:30 PM'),
  231. ('16', '4:00 PM'), ('16.5', '4:30 PM'),
  232. ('17', '5:00 PM'), ('17.5', '5:30 PM'),
  233. ('18', '6:00 PM'), ('18.5', '6:30 PM'),
  234. ('19', '7:00 PM'), ('19.5', '7:30 PM'),
  235. ('20', '8:00 PM'), ('20.5', '8:30 PM'),
  236. ('21', '9:00 PM'), ('21.5', '9:30 PM'),
  237. ('22', '10:00 PM'), ('22.5', '10:30 PM'),
  238. ('23', '11:00 PM'), ('23.5', '11:30 PM')], string='Hour from')
  239. request_hour_to = fields.Selection([
  240. ('0', '12:00 AM'), ('0.5', '12:30 AM'),
  241. ('1', '1:00 AM'), ('1.5', '1:30 AM'),
  242. ('2', '2:00 AM'), ('2.5', '2:30 AM'),
  243. ('3', '3:00 AM'), ('3.5', '3:30 AM'),
  244. ('4', '4:00 AM'), ('4.5', '4:30 AM'),
  245. ('5', '5:00 AM'), ('5.5', '5:30 AM'),
  246. ('6', '6:00 AM'), ('6.5', '6:30 AM'),
  247. ('7', '7:00 AM'), ('7.5', '7:30 AM'),
  248. ('8', '8:00 AM'), ('8.5', '8:30 AM'),
  249. ('9', '9:00 AM'), ('9.5', '9:30 AM'),
  250. ('10', '10:00 AM'), ('10.5', '10:30 AM'),
  251. ('11', '11:00 AM'), ('11.5', '11:30 AM'),
  252. ('12', '12:00 PM'), ('12.5', '12:30 PM'),
  253. ('13', '1:00 PM'), ('13.5', '1:30 PM'),
  254. ('14', '2:00 PM'), ('14.5', '2:30 PM'),
  255. ('15', '3:00 PM'), ('15.5', '3:30 PM'),
  256. ('16', '4:00 PM'), ('16.5', '4:30 PM'),
  257. ('17', '5:00 PM'), ('17.5', '5:30 PM'),
  258. ('18', '6:00 PM'), ('18.5', '6:30 PM'),
  259. ('19', '7:00 PM'), ('19.5', '7:30 PM'),
  260. ('20', '8:00 PM'), ('20.5', '8:30 PM'),
  261. ('21', '9:00 PM'), ('21.5', '9:30 PM'),
  262. ('22', '10:00 PM'), ('22.5', '10:30 PM'),
  263. ('23', '11:00 PM'), ('23.5', '11:30 PM')], string='Hour to')
  264. # used only when the leave is taken in half days
  265. request_date_from_period = fields.Selection([
  266. ('am', 'Morning'), ('pm', 'Afternoon')],
  267. string="Date Period Start", default='am')
  268. # request type
  269. request_unit_half = fields.Boolean('Half Day', compute='_compute_request_unit_half', store=True, readonly=False)
  270. request_unit_hours = fields.Boolean('Custom Hours', compute='_compute_request_unit_hours', store=True, readonly=False)
  271. # view
  272. is_hatched = fields.Boolean('Hatched', compute='_compute_is_hatched')
  273. is_striked = fields.Boolean('Striked', compute='_compute_is_hatched')
  274. has_stress_day = fields.Boolean(compute='_compute_has_stress_day')
  275. _sql_constraints = [
  276. ('type_value',
  277. "CHECK((holiday_type='employee' AND (employee_id IS NOT NULL OR multi_employee IS TRUE)) or "
  278. "(holiday_type='company' AND mode_company_id IS NOT NULL) or "
  279. "(holiday_type='category' AND category_id IS NOT NULL) or "
  280. "(holiday_type='department' AND department_id IS NOT NULL) )",
  281. "The employee, department, company or employee category of this request is missing. Please make sure that your user login is linked to an employee."),
  282. ('date_check2', "CHECK ((date_from <= date_to))", "The start date must be anterior to the end date."),
  283. ('duration_check', "CHECK ( number_of_days >= 0 )", "If you want to change the number of days you should use the 'period' mode"),
  284. ]
  285. def _auto_init(self):
  286. res = super(HolidaysRequest, self)._auto_init()
  287. tools.create_index(self._cr, 'hr_leave_date_to_date_from_index',
  288. self._table, ['date_to', 'date_from'])
  289. return res
  290. @api.depends('employee_id', 'employee_ids')
  291. def _compute_all_employees(self):
  292. for leave in self:
  293. leave.all_employee_ids = leave.employee_id | leave.employee_ids
  294. @api.constrains('holiday_status_id', 'number_of_days')
  295. def _check_allocation_duration(self):
  296. # Deprecated as part of https://github.com/odoo/odoo/pull/96545
  297. # TODO: remove in master
  298. return
  299. @api.depends_context('uid')
  300. def _compute_description(self):
  301. self.check_access_rights('read')
  302. self.check_access_rule('read')
  303. is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user')
  304. for leave in self:
  305. if is_officer or leave.user_id == self.env.user or leave.employee_id.leave_manager_id == self.env.user:
  306. leave.name = leave.sudo().private_name
  307. else:
  308. leave.name = '*****'
  309. def _inverse_description(self):
  310. is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user')
  311. for leave in self:
  312. if is_officer or leave.user_id == self.env.user or leave.employee_id.leave_manager_id == self.env.user:
  313. leave.sudo().private_name = leave.name
  314. def _search_description(self, operator, value):
  315. is_officer = self.user_has_groups('hr_holidays.group_hr_holidays_user')
  316. domain = [('private_name', operator, value)]
  317. if not is_officer:
  318. domain = expression.AND([domain, [('user_id', '=', self.env.user.id)]])
  319. leaves = self.search(domain)
  320. return [('id', 'in', leaves.ids)]
  321. @api.depends('holiday_status_id')
  322. def _compute_state(self):
  323. for leave in self:
  324. leave.state = 'confirm' if leave.validation_type != 'no_validation' else 'draft'
  325. @api.depends('holiday_status_id.requires_allocation', 'validation_type', 'employee_id', 'date_from', 'date_to')
  326. def _compute_from_holiday_status_id(self):
  327. # Deprecated as part of https://github.com/odoo/odoo/pull/96545
  328. # TODO: remove in master
  329. self.holiday_allocation_id = False
  330. @api.depends('request_date_from_period', 'request_hour_from', 'request_hour_to', 'request_date_from', 'request_date_to',
  331. 'request_unit_half', 'request_unit_hours', 'employee_id')
  332. def _compute_date_from_to(self):
  333. for holiday in self:
  334. if holiday.request_date_from and holiday.request_date_to and holiday.request_date_from > holiday.request_date_to:
  335. holiday.request_date_to = holiday.request_date_from
  336. if not holiday.request_date_from:
  337. holiday.date_from = False
  338. elif not holiday.request_unit_half and not holiday.request_unit_hours and not holiday.request_date_to:
  339. holiday.date_to = False
  340. else:
  341. if holiday.request_unit_half or holiday.request_unit_hours:
  342. holiday.request_date_to = holiday.request_date_from
  343. attendance_from, attendance_to = holiday._get_attendances(holiday.employee_id, holiday.request_date_from, holiday.request_date_to)
  344. compensated_request_date_from = holiday.request_date_from
  345. compensated_request_date_to = holiday.request_date_to
  346. if holiday.request_unit_half:
  347. if holiday.request_date_from_period == 'am':
  348. hour_from = attendance_from.hour_from
  349. hour_to = attendance_from.hour_to
  350. else:
  351. hour_from = attendance_to.hour_from
  352. hour_to = attendance_to.hour_to
  353. elif holiday.request_unit_hours:
  354. hour_from = holiday.request_hour_from
  355. hour_to = holiday.request_hour_to
  356. else:
  357. hour_from = attendance_from.hour_from
  358. hour_to = attendance_to.hour_to
  359. holiday.date_from = self._get_start_or_end_from_attendance(hour_from, compensated_request_date_from, holiday.employee_id or holiday)
  360. holiday.date_to = self._get_start_or_end_from_attendance(hour_to, compensated_request_date_to, holiday.employee_id or holiday)
  361. @api.depends('holiday_status_id', 'request_unit_hours')
  362. def _compute_request_unit_half(self):
  363. for holiday in self:
  364. if holiday.holiday_status_id or holiday.request_unit_hours:
  365. holiday.request_unit_half = False
  366. @api.depends('holiday_status_id', 'request_unit_half')
  367. def _compute_request_unit_hours(self):
  368. for holiday in self:
  369. if holiday.holiday_status_id or holiday.request_unit_half:
  370. holiday.request_unit_hours = False
  371. @api.depends('employee_ids')
  372. def _compute_from_employee_ids(self):
  373. for holiday in self:
  374. if len(holiday.employee_ids) == 1:
  375. holiday.employee_id = holiday.employee_ids[0]._origin
  376. else:
  377. holiday.employee_id = False
  378. holiday.multi_employee = (len(holiday.employee_ids) > 1)
  379. @api.depends('holiday_type')
  380. def _compute_from_holiday_type(self):
  381. allocation_from_domain = self.env['hr.leave.allocation']
  382. if (self._context.get('active_model') == 'hr.leave.allocation' and
  383. self._context.get('active_id')):
  384. allocation_from_domain = allocation_from_domain.browse(self._context['active_id'])
  385. for holiday in self:
  386. if holiday.holiday_type == 'employee':
  387. if not holiday.employee_ids:
  388. if allocation_from_domain:
  389. holiday.employee_ids = allocation_from_domain.employee_id
  390. holiday.holiday_status_id = allocation_from_domain.holiday_status_id
  391. else:
  392. # This handles the case where a request is made with only the employee_id
  393. # but does not need to be recomputed on employee_id changes
  394. holiday.employee_ids = holiday.employee_id or self.env.user.employee_id
  395. holiday.mode_company_id = False
  396. holiday.category_id = False
  397. elif holiday.holiday_type == 'company':
  398. holiday.employee_ids = False
  399. if not holiday.mode_company_id:
  400. holiday.mode_company_id = self.env.company.id
  401. holiday.category_id = False
  402. elif holiday.holiday_type == 'department':
  403. holiday.employee_ids = False
  404. holiday.mode_company_id = False
  405. holiday.category_id = False
  406. elif holiday.holiday_type == 'category':
  407. holiday.employee_ids = False
  408. holiday.mode_company_id = False
  409. else:
  410. holiday.employee_ids = self.env.context.get('default_employee_id') or holiday.employee_id or self.env.user.employee_id
  411. @api.depends('employee_id', 'employee_ids')
  412. def _compute_from_employee_id(self):
  413. for holiday in self:
  414. holiday.manager_id = holiday.employee_id.parent_id.id
  415. if holiday.holiday_status_id.requires_allocation == 'no':
  416. continue
  417. if not holiday.employee_id or holiday.employee_ids:
  418. holiday.holiday_status_id = False
  419. elif holiday.employee_id.user_id != self.env.user and holiday._origin.employee_id != holiday.employee_id:
  420. if holiday.employee_id and not holiday.holiday_status_id.with_context(employee_id=holiday.employee_id.id).has_valid_allocation:
  421. holiday.holiday_status_id = False
  422. @api.depends('employee_id', 'holiday_type')
  423. def _compute_department_id(self):
  424. for holiday in self:
  425. if holiday.employee_id:
  426. holiday.department_id = holiday.employee_id.department_id
  427. elif holiday.holiday_type == 'department':
  428. if not holiday.department_id:
  429. holiday.department_id = self.env.user.employee_id.department_id
  430. else:
  431. holiday.department_id = False
  432. @api.depends('date_from', 'date_to', 'holiday_status_id')
  433. def _compute_has_stress_day(self):
  434. date_from, date_to = min(self.mapped('date_from')), max(self.mapped('date_to'))
  435. if date_from and date_to:
  436. stress_days = self.employee_id._get_stress_days(
  437. date_from.date(),
  438. date_to.date())
  439. for leave in self:
  440. domain = [
  441. ('start_date', '<=', leave.date_to.date()),
  442. ('end_date', '>=', leave.date_from.date()),
  443. '|',
  444. ('resource_calendar_id', '=', False),
  445. ('resource_calendar_id', '=', (leave.employee_id.resource_calendar_id or self.env.company.resource_calendar_id).id)
  446. ]
  447. if leave.holiday_status_id.company_id:
  448. domain += [('company_id', '=', leave.holiday_status_id.company_id.id)]
  449. leave.has_stress_day = leave.date_from and leave.date_to and stress_days.filtered_domain(domain)
  450. else:
  451. self.has_stress_day = False
  452. @api.depends('date_from', 'date_to', 'employee_id')
  453. def _compute_number_of_days(self):
  454. for holiday in self:
  455. if holiday.date_from and holiday.date_to:
  456. holiday.number_of_days = holiday._get_number_of_days(holiday.date_from, holiday.date_to, holiday.employee_id.id)['days']
  457. else:
  458. holiday.number_of_days = 0
  459. @api.depends('tz')
  460. @api.depends_context('uid')
  461. def _compute_tz_mismatch(self):
  462. for leave in self:
  463. leave.tz_mismatch = leave.tz != self.env.user.tz
  464. @api.depends('employee_id', 'holiday_type', 'department_id.company_id.resource_calendar_id.tz', 'mode_company_id.resource_calendar_id.tz')
  465. def _compute_tz(self):
  466. for leave in self:
  467. tz = False
  468. if leave.holiday_type == 'employee':
  469. tz = leave.employee_id.tz
  470. elif leave.holiday_type == 'department':
  471. tz = leave.department_id.company_id.resource_calendar_id.tz
  472. elif leave.holiday_type == 'company':
  473. tz = leave.mode_company_id.resource_calendar_id.tz
  474. leave.tz = tz or self.env.company.resource_calendar_id.tz or self.env.user.tz or 'UTC'
  475. @api.depends('number_of_days')
  476. def _compute_number_of_days_display(self):
  477. for holiday in self:
  478. holiday.number_of_days_display = holiday.number_of_days
  479. def _get_calendar(self):
  480. self.ensure_one()
  481. return self.employee_id.resource_calendar_id or self.env.company.resource_calendar_id
  482. @api.depends('number_of_days')
  483. def _compute_number_of_hours_display(self):
  484. for holiday in self:
  485. calendar = holiday._get_calendar()
  486. if holiday.date_from and holiday.date_to:
  487. # Take attendances into account, in case the leave validated
  488. # Otherwise, this will result into number_of_hours = 0
  489. # and number_of_hours_display = 0 or (#day * calendar.hours_per_day),
  490. # which could be wrong if the employee doesn't work the same number
  491. # hours each day
  492. if holiday.state == 'validate':
  493. start_dt = holiday.date_from
  494. end_dt = holiday.date_to
  495. if not start_dt.tzinfo:
  496. start_dt = start_dt.replace(tzinfo=UTC)
  497. if not end_dt.tzinfo:
  498. end_dt = end_dt.replace(tzinfo=UTC)
  499. resource = holiday.employee_id.resource_id
  500. intervals = calendar._attendance_intervals_batch(start_dt, end_dt, resource)[resource.id] \
  501. - calendar._leave_intervals_batch(start_dt, end_dt, None)[False] # Substract Global Leaves
  502. number_of_hours = sum((stop - start).total_seconds() / 3600 for start, stop, dummy in intervals)
  503. else:
  504. number_of_hours = holiday._get_number_of_days(holiday.date_from, holiday.date_to, holiday.employee_id.id)['hours']
  505. holiday.number_of_hours_display = number_of_hours or (holiday.number_of_days * (calendar.hours_per_day or HOURS_PER_DAY))
  506. else:
  507. holiday.number_of_hours_display = 0
  508. @api.depends('number_of_hours_display', 'number_of_days_display')
  509. def _compute_duration_display(self):
  510. for leave in self:
  511. leave.duration_display = '%g %s' % (
  512. (float_round(leave.number_of_hours_display, precision_digits=2)
  513. if leave.leave_type_request_unit == 'hour'
  514. else float_round(leave.number_of_days_display, precision_digits=2)),
  515. _('hours') if leave.leave_type_request_unit == 'hour' else _('days'))
  516. @api.depends('number_of_hours_display')
  517. def _compute_number_of_hours_text(self):
  518. # YTI Note: All this because a readonly field takes all the width on edit mode...
  519. for leave in self:
  520. leave.number_of_hours_text = '%s%g %s%s' % (
  521. '' if leave.request_unit_half or leave.request_unit_hours else '(',
  522. float_round(leave.number_of_hours_display, precision_digits=2),
  523. _('Hours'),
  524. '' if leave.request_unit_half or leave.request_unit_hours else ')')
  525. @api.depends('state', 'employee_id', 'department_id')
  526. def _compute_can_reset(self):
  527. for holiday in self:
  528. try:
  529. holiday._check_approval_update('draft')
  530. except (AccessError, UserError):
  531. holiday.can_reset = False
  532. else:
  533. holiday.can_reset = True
  534. @api.depends('state', 'employee_id', 'department_id')
  535. def _compute_can_approve(self):
  536. for holiday in self:
  537. try:
  538. if holiday.state == 'confirm' and holiday.validation_type == 'both':
  539. holiday._check_approval_update('validate1')
  540. else:
  541. holiday._check_approval_update('validate')
  542. except (AccessError, UserError):
  543. holiday.can_approve = False
  544. else:
  545. holiday.can_approve = True
  546. @api.depends_context('uid')
  547. @api.depends('state', 'employee_id')
  548. def _compute_can_cancel(self):
  549. now = fields.Datetime.now()
  550. for leave in self:
  551. leave.can_cancel = leave.id and leave.employee_id.user_id == self.env.user and leave.state == 'validate' and leave.date_from and leave.date_from > now
  552. @api.depends('state')
  553. def _compute_is_hatched(self):
  554. for holiday in self:
  555. holiday.is_striked = holiday.state == 'refuse'
  556. holiday.is_hatched = holiday.state not in ['refuse', 'validate']
  557. @api.depends('leave_type_support_document', 'attachment_ids')
  558. def _compute_supported_attachment_ids(self):
  559. for holiday in self:
  560. holiday.supported_attachment_ids = holiday.attachment_ids
  561. holiday.supported_attachment_ids_count = len(holiday.attachment_ids.ids)
  562. def _inverse_supported_attachment_ids(self):
  563. for holiday in self:
  564. holiday.attachment_ids = holiday.supported_attachment_ids
  565. @api.constrains('date_from', 'date_to', 'employee_id')
  566. def _check_date(self):
  567. if self.env.context.get('leave_skip_date_check', False):
  568. return
  569. all_employees = self.employee_id | self.employee_ids
  570. all_leaves = self.search([
  571. ('date_from', '<', max(self.mapped('date_to'))),
  572. ('date_to', '>', min(self.mapped('date_from'))),
  573. ('employee_id', 'in', all_employees.ids),
  574. ('id', 'not in', self.ids),
  575. ('state', 'not in', ['cancel', 'refuse']),
  576. ])
  577. for holiday in self:
  578. domain = [
  579. ('date_from', '<', holiday.date_to),
  580. ('date_to', '>', holiday.date_from),
  581. ('id', '!=', holiday.id),
  582. ('state', 'not in', ['cancel', 'refuse']),
  583. ]
  584. employee_ids = (holiday.employee_id | holiday.employee_ids).ids
  585. search_domain = domain + [('employee_id', 'in', employee_ids)]
  586. conflicting_holidays = all_leaves.filtered_domain(search_domain)
  587. if conflicting_holidays:
  588. conflicting_holidays_list = []
  589. # Do not display the name of the employee if the conflicting holidays have an employee_id.user_id equivalent to the user id
  590. holidays_only_have_uid = bool(holiday.employee_id)
  591. holiday_states = dict(conflicting_holidays.fields_get(allfields=['state'])['state']['selection'])
  592. for conflicting_holiday in conflicting_holidays:
  593. conflicting_holiday_data = {}
  594. conflicting_holiday_data['employee_name'] = conflicting_holiday.employee_id.name
  595. conflicting_holiday_data['date_from'] = format_date(self.env, min(conflicting_holiday.mapped('date_from')))
  596. conflicting_holiday_data['date_to'] = format_date(self.env, min(conflicting_holiday.mapped('date_to')))
  597. conflicting_holiday_data['state'] = holiday_states[conflicting_holiday.state]
  598. if conflicting_holiday.employee_id.user_id.id != self.env.uid:
  599. holidays_only_have_uid = False
  600. if conflicting_holiday_data not in conflicting_holidays_list:
  601. conflicting_holidays_list.append(conflicting_holiday_data)
  602. if not conflicting_holidays_list:
  603. return
  604. conflicting_holidays_strings = []
  605. if holidays_only_have_uid:
  606. for conflicting_holiday_data in conflicting_holidays_list:
  607. conflicting_holidays_string = _('From %(date_from)s To %(date_to)s - %(state)s',
  608. date_from=conflicting_holiday_data['date_from'],
  609. date_to=conflicting_holiday_data['date_to'],
  610. state=conflicting_holiday_data['state'])
  611. conflicting_holidays_strings.append(conflicting_holidays_string)
  612. raise ValidationError(_('You can not set two time off that overlap on the same day.\nExisting time off:\n%s') %
  613. ('\n'.join(conflicting_holidays_strings)))
  614. for conflicting_holiday_data in conflicting_holidays_list:
  615. conflicting_holidays_string = _('%(employee_name)s - From %(date_from)s To %(date_to)s - %(state)s',
  616. employee_name=conflicting_holiday_data['employee_name'],
  617. date_from=conflicting_holiday_data['date_from'],
  618. date_to=conflicting_holiday_data['date_to'],
  619. state=conflicting_holiday_data['state'])
  620. conflicting_holidays_strings.append(conflicting_holidays_string)
  621. conflicting_employees = set(employee_ids) - set(conflicting_holidays.employee_id.ids)
  622. # Only one employee has a conflicting holiday
  623. if len(conflicting_employees) == len(employee_ids) - 1:
  624. raise ValidationError(_('You can not set two time off that overlap on the same day for the same employee.\nExisting time off:\n%s') %
  625. ('\n'.join(conflicting_holidays_strings)))
  626. raise ValidationError(_('You can not set two time off that overlap on the same day for the same employees.\nExisting time off:\n%s') %
  627. ('\n'.join(conflicting_holidays_strings)))
  628. @api.constrains('state', 'number_of_days', 'holiday_status_id')
  629. def _check_holidays(self):
  630. for holiday in self:
  631. mapped_days = self.holiday_status_id.get_employees_days((holiday.employee_id | holiday.sudo().employee_ids).ids, holiday.date_from.date())
  632. if holiday.holiday_type != 'employee'\
  633. or not holiday.employee_id and not holiday.sudo().employee_ids\
  634. or holiday.holiday_status_id.requires_allocation == 'no':
  635. continue
  636. if holiday.employee_id:
  637. leave_days = mapped_days[holiday.employee_id.id][holiday.holiday_status_id.id]
  638. if float_compare(leave_days['remaining_leaves'], 0, precision_digits=2) == -1\
  639. or float_compare(leave_days['virtual_remaining_leaves'], 0, precision_digits=2) == -1:
  640. raise ValidationError(_('The number of remaining time off is not sufficient for this time off type.\n'
  641. 'Please also check the time off waiting for validation.'))
  642. else:
  643. unallocated_employees = []
  644. for employee in holiday.sudo().employee_ids:
  645. leave_days = mapped_days[employee.id][holiday.holiday_status_id.id]
  646. if float_compare(leave_days['remaining_leaves'], self.number_of_days, precision_digits=2) == -1\
  647. or float_compare(leave_days['virtual_remaining_leaves'], self.number_of_days, precision_digits=2) == -1:
  648. unallocated_employees.append(employee.name)
  649. if unallocated_employees:
  650. raise ValidationError(_('The number of remaining time off is not sufficient for this time off type.\n'
  651. 'Please also check the time off waiting for validation.')
  652. + _('\nThe employees that lack allocation days are:\n%s',
  653. (', '.join(unallocated_employees))))
  654. @api.constrains('date_from', 'date_to', 'employee_id')
  655. def _check_date_state(self):
  656. if self.env.context.get('leave_skip_state_check'):
  657. return
  658. for holiday in self:
  659. if holiday.state in ['cancel', 'refuse', 'validate1', 'validate']:
  660. raise ValidationError(_("This modification is not allowed in the current state."))
  661. def _get_number_of_days_batch(self, date_from, date_to, employee_ids):
  662. """ Returns a float equals to the timedelta between two dates given as string."""
  663. employee = self.env['hr.employee'].browse(employee_ids)
  664. # We force the company in the domain as we are more than likely in a compute_sudo
  665. domain = [('time_type', '=', 'leave'),
  666. ('company_id', 'in', self.env.company.ids + self.env.context.get('allowed_company_ids', []))]
  667. result = employee._get_work_days_data_batch(date_from, date_to, domain=domain)
  668. for employee_id in result:
  669. if self.request_unit_half and result[employee_id]['hours'] > 0:
  670. result[employee_id]['days'] = 0.5
  671. return result
  672. def _get_number_of_days(self, date_from, date_to, employee_id):
  673. """ Returns a float equals to the timedelta between two dates given as string."""
  674. if employee_id:
  675. return self._get_number_of_days_batch(date_from, date_to, employee_id)[employee_id]
  676. today_hours = self.env.company.resource_calendar_id.get_work_hours_count(
  677. datetime.combine(date_from.date(), time.min),
  678. datetime.combine(date_from.date(), time.max),
  679. False)
  680. hours = self.env.company.resource_calendar_id.get_work_hours_count(date_from, date_to)
  681. days = hours / (today_hours or HOURS_PER_DAY) if not self.request_unit_half else 0.5
  682. return {'days': days, 'hours': hours}
  683. def _adjust_date_based_on_tz(self, leave_date, hour):
  684. """ request_date_{from,to} are local to the user's tz but hour_{from,to} are in UTC.
  685. In some cases they are combined (assuming they are in the same tz) as a datetime. When
  686. that happens it's possible we need to adjust one of the dates. This function adjust the
  687. date, so that it can be passed to datetime().
  688. E.g. a leave in US/Pacific for one day:
  689. - request_date_from: 1st of Jan
  690. - request_date_to: 1st of Jan
  691. - hour_from: 15:00 (7:00 local)
  692. - hour_to: 03:00 (19:00 local) <-- this happens on the 2nd of Jan in UTC
  693. """
  694. user_tz = timezone(self.env.user.tz if self.env.user.tz else 'UTC')
  695. request_date_to_utc = UTC.localize(datetime.combine(leave_date, hour)).astimezone(user_tz).replace(tzinfo=None)
  696. return request_date_to_utc.date()
  697. ####################################################
  698. # ORM Overrides methods
  699. ####################################################
  700. @api.depends('employee_id', 'holiday_status_id')
  701. def _compute_display_name(self):
  702. super()._compute_display_name()
  703. def onchange(self, values, field_name, field_onchange):
  704. # Try to force the leave_type name_get when creating new records
  705. # This is called right after pressing create and returns the name_get for
  706. # most fields in the view.
  707. if field_onchange.get('employee_id') and 'employee_id' not in self._context and values:
  708. employee_id = get_employee_from_context(values, self._context, self.env.user.employee_id.id)
  709. self = self.with_context(employee_id=employee_id)
  710. return super().onchange(values, field_name, field_onchange)
  711. def name_get(self):
  712. res = []
  713. for leave in self:
  714. user_tz = timezone(leave.tz)
  715. date_from_utc = leave.date_from and leave.date_from.astimezone(user_tz).date()
  716. date_to_utc = leave.date_to and leave.date_to.astimezone(user_tz).date()
  717. if self.env.context.get('short_name'):
  718. if leave.leave_type_request_unit == 'hour':
  719. res.append((leave.id, _("%s : %.2f hours") % (leave.name or leave.holiday_status_id.name, leave.number_of_hours_display)))
  720. else:
  721. res.append((leave.id, _("%s : %.2f days") % (leave.name or leave.holiday_status_id.name, leave.number_of_days)))
  722. else:
  723. if leave.holiday_type == 'company':
  724. target = leave.mode_company_id.name
  725. elif leave.holiday_type == 'department':
  726. target = leave.department_id.name
  727. elif leave.holiday_type == 'category':
  728. target = leave.category_id.name
  729. elif leave.employee_id:
  730. target = leave.employee_id.name
  731. else:
  732. target = ', '.join(leave.employee_ids.mapped('name'))
  733. display_date = format_date(self.env, date_from_utc) or ""
  734. if leave.leave_type_request_unit == 'hour':
  735. if self.env.context.get('hide_employee_name') and 'employee_id' in self.env.context.get('group_by', []):
  736. res.append((
  737. leave.id,
  738. _("%(person)s on %(leave_type)s: %(duration).2f hours on %(date)s",
  739. person=target,
  740. leave_type=leave.holiday_status_id.name,
  741. duration=leave.number_of_hours_display,
  742. date=display_date,
  743. )
  744. ))
  745. else:
  746. res.append((
  747. leave.id,
  748. _("%(person)s on %(leave_type)s: %(duration).2f hours on %(date)s",
  749. person=target,
  750. leave_type=leave.holiday_status_id.name,
  751. duration=leave.number_of_hours_display,
  752. date=display_date,
  753. )
  754. ))
  755. else:
  756. if leave.number_of_days > 1 and date_from_utc and date_to_utc:
  757. display_date += ' / %s' % format_date(self.env, date_to_utc) or ""
  758. if not target or self.env.context.get('hide_employee_name') and 'employee_id' in self.env.context.get('group_by', []):
  759. res.append((
  760. leave.id,
  761. _("%(leave_type)s: %(duration).2f days (%(start)s)",
  762. leave_type=leave.holiday_status_id.name,
  763. duration=leave.number_of_days,
  764. start=display_date,
  765. )
  766. ))
  767. else:
  768. res.append((
  769. leave.id,
  770. _("%(person)s on %(leave_type)s: %(duration).2f days (%(start)s)",
  771. person=target,
  772. leave_type=leave.holiday_status_id.name,
  773. duration=leave.number_of_days,
  774. start=display_date,
  775. )
  776. ))
  777. return res
  778. def add_follower(self, employee_id):
  779. employee = self.env['hr.employee'].browse(employee_id)
  780. if employee.user_id:
  781. self.message_subscribe(partner_ids=employee.user_id.partner_id.ids)
  782. @api.constrains('holiday_allocation_id')
  783. def _check_allocation_id(self):
  784. # Deprecated as part of https://github.com/odoo/odoo/pull/96545
  785. # TODO: remove in master
  786. return
  787. @api.constrains('holiday_allocation_id', 'date_to', 'date_from')
  788. def _check_leave_type_validity(self):
  789. # Deprecated as part of https://github.com/odoo/odoo/pull/96545
  790. # TODO: remove in master
  791. return
  792. @api.constrains('date_from', 'date_to')
  793. def _check_stress_day(self):
  794. is_leave_user = self.user_has_groups('hr_holidays.group_hr_holidays_user')
  795. if not is_leave_user and any(leave.has_stress_day for leave in self):
  796. raise ValidationError(_('You are not allowed to request a time off on a Stress Day.'))
  797. def _check_double_validation_rules(self, employees, state):
  798. if self.user_has_groups('hr_holidays.group_hr_holidays_manager'):
  799. return
  800. is_leave_user = self.user_has_groups('hr_holidays.group_hr_holidays_user')
  801. if state == 'validate1':
  802. employees = employees.filtered(lambda employee: employee.leave_manager_id != self.env.user)
  803. if employees and not is_leave_user:
  804. raise AccessError(_('You cannot first approve a time off for %s, because you are not his time off manager', employees[0].name))
  805. elif state == 'validate' and not is_leave_user:
  806. # Is probably handled via ir.rule
  807. raise AccessError(_('You don\'t have the rights to apply second approval on a time off request'))
  808. @api.model_create_multi
  809. def create(self, vals_list):
  810. leave_date_employees = defaultdict(list)
  811. employee_ids = []
  812. for values in vals_list:
  813. if values.get('employee_id'):
  814. employee_ids.append(values['employee_id'])
  815. if values.get('date_from') and values.get('date_to'):
  816. date_from = fields.Datetime.to_datetime(values['date_from'])
  817. date_to = fields.Datetime.to_datetime(values['date_to'])
  818. if values['employee_id'] not in leave_date_employees[(date_from, date_to)]:
  819. leave_date_employees[(date_from, date_to)].append(values['employee_id'])
  820. employees = self.env['hr.employee'].browse(employee_ids)
  821. if self._context.get('leave_compute_date_from_to') and employees:
  822. employee_leave_date_duration = defaultdict(dict)
  823. for (date_from, date_to), employee_ids in leave_date_employees.items():
  824. employee_leave_date_duration[(date_from, date_to)] = self._get_number_of_days_batch(date_from, date_to, employee_ids)
  825. for values in vals_list:
  826. employee_id = values.get('employee_id')
  827. if employee_id and values.get('date_from') and values.get('date_to'):
  828. date_from = values.get('date_from')
  829. date_to = values.get('date_to')
  830. employee = employees.filtered(lambda emp: emp.id == employee_id)
  831. attendance_from, attendance_to = self._get_attendances(employee, date_from.date(), date_to.date())
  832. hour_from = float_to_time(attendance_from.hour_from)
  833. hour_to = float_to_time(attendance_to.hour_to)
  834. hour_from = hour_from.hour + hour_from.minute / 60
  835. hour_to = hour_to.hour + hour_to.minute / 60
  836. values['date_from'] = self._get_start_or_end_from_attendance(hour_from, date_from.date(), employee)
  837. values['date_to'] = self._get_start_or_end_from_attendance(hour_to, date_to.date(), employee)
  838. values['request_date_from'], values['request_date_to'] = values['date_from'].date(), values['date_to'].date()
  839. values['number_of_days'] = employee_leave_date_duration[(date_from, date_to)][values['employee_id']]['days']
  840. """ Override to avoid automatic logging of creation """
  841. if not self._context.get('leave_fast_create'):
  842. leave_types = self.env['hr.leave.type'].browse([values.get('holiday_status_id') for values in vals_list if values.get('holiday_status_id')])
  843. mapped_validation_type = {leave_type.id: leave_type.leave_validation_type for leave_type in leave_types}
  844. for values in vals_list:
  845. employee_id = values.get('employee_id', False)
  846. leave_type_id = values.get('holiday_status_id')
  847. # Handle automatic department_id
  848. if not values.get('department_id'):
  849. values.update({'department_id': employees.filtered(lambda emp: emp.id == employee_id).department_id.id})
  850. # Handle no_validation
  851. if mapped_validation_type[leave_type_id] == 'no_validation':
  852. values.update({'state': 'confirm'})
  853. if 'state' not in values:
  854. # To mimic the behavior of compute_state that was always triggered, as the field was readonly
  855. values['state'] = 'confirm' if mapped_validation_type[leave_type_id] != 'no_validation' else 'draft'
  856. # Handle double validation
  857. if mapped_validation_type[leave_type_id] == 'both':
  858. self._check_double_validation_rules(employee_id, values.get('state', False))
  859. holidays = super(HolidaysRequest, self.with_context(mail_create_nosubscribe=True)).create(vals_list)
  860. for holiday in holidays:
  861. if not self._context.get('leave_fast_create'):
  862. # Everything that is done here must be done using sudo because we might
  863. # have different create and write rights
  864. # eg : holidays_user can create a leave request with validation_type = 'manager' for someone else
  865. # but they can only write on it if they are leave_manager_id
  866. holiday_sudo = holiday.sudo()
  867. holiday_sudo.add_follower(employee_id)
  868. if holiday.validation_type == 'manager':
  869. holiday_sudo.message_subscribe(partner_ids=holiday.employee_id.leave_manager_id.partner_id.ids)
  870. if holiday.validation_type == 'no_validation':
  871. # Automatic validation should be done in sudo, because user might not have the rights to do it by himself
  872. holiday_sudo.action_validate()
  873. holiday_sudo.message_subscribe(partner_ids=[holiday._get_responsible_for_approval().partner_id.id])
  874. holiday_sudo.message_post(body=_("The time off has been automatically approved"), subtype_xmlid="mail.mt_comment") # Message from OdooBot (sudo)
  875. elif not self._context.get('import_file'):
  876. holiday_sudo.activity_update()
  877. return holidays
  878. def write(self, values):
  879. if 'active' in values and not self.env.context.get('from_cancel_wizard'):
  880. raise UserError(_("You can't manually archive/unarchive a time off."))
  881. is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user') or self.env.is_superuser()
  882. if not is_officer and values.keys() - {'attachment_ids', 'supported_attachment_ids', 'message_main_attachment_id'}:
  883. if any(hol.date_from.date() < fields.Date.today() and hol.employee_id.leave_manager_id != self.env.user for hol in self):
  884. raise UserError(_('You must have manager rights to modify/validate a time off that already begun'))
  885. # Unlink existing resource.calendar.leaves for validated time off
  886. if 'state' in values and values['state'] != 'validate':
  887. validated_leaves = self.filtered(lambda l: l.state == 'validate')
  888. validated_leaves._remove_resource_leave()
  889. employee_id = values.get('employee_id', False)
  890. if not self.env.context.get('leave_fast_create'):
  891. if values.get('state'):
  892. self._check_approval_update(values['state'])
  893. if any(holiday.validation_type == 'both' for holiday in self):
  894. if values.get('employee_id'):
  895. employees = self.env['hr.employee'].browse(values.get('employee_id'))
  896. else:
  897. employees = self.mapped('employee_id')
  898. self._check_double_validation_rules(employees, values['state'])
  899. if 'date_from' in values:
  900. values['request_date_from'] = values['date_from']
  901. if 'date_to' in values:
  902. values['request_date_to'] = values['date_to']
  903. result = super(HolidaysRequest, self).write(values)
  904. if not self.env.context.get('leave_fast_create'):
  905. for holiday in self:
  906. if employee_id:
  907. holiday.add_follower(employee_id)
  908. return result
  909. @api.ondelete(at_uninstall=False)
  910. def _unlink_if_correct_states(self):
  911. error_message = _('You cannot delete a time off which is in %s state')
  912. state_description_values = {elem[0]: elem[1] for elem in self._fields['state']._description_selection(self.env)}
  913. now = fields.Datetime.now()
  914. if not self.user_has_groups('hr_holidays.group_hr_holidays_user'):
  915. for hol in self:
  916. if hol.state not in ['draft', 'confirm']:
  917. raise UserError(error_message % state_description_values.get(self[:1].state))
  918. if hol.date_from < now:
  919. raise UserError(_('You cannot delete a time off which is in the past'))
  920. if hol.sudo().employee_ids and not hol.employee_id:
  921. raise UserError(_('You cannot delete a time off assigned to several employees'))
  922. else:
  923. for holiday in self.filtered(lambda holiday: holiday.state not in ['draft', 'cancel', 'confirm']):
  924. raise UserError(error_message % (state_description_values.get(holiday.state),))
  925. def unlink(self):
  926. return super(HolidaysRequest, self.with_context(leave_skip_date_check=True)).unlink()
  927. def copy_data(self, default=None):
  928. if default and 'date_from' in default and 'date_to' in default:
  929. default['request_date_from'] = default.get('date_from')
  930. default['request_date_to'] = default.get('date_to')
  931. return super().copy_data(default)
  932. raise UserError(_('A time off cannot be duplicated.'))
  933. def _get_mail_redirect_suggested_company(self):
  934. return self.holiday_status_id.company_id
  935. @api.model
  936. def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
  937. if not self.user_has_groups('hr_holidays.group_hr_holidays_user') and 'private_name' in groupby:
  938. raise UserError(_('Such grouping is not allowed.'))
  939. return super(HolidaysRequest, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
  940. ####################################################
  941. # Business methods
  942. ####################################################
  943. def _prepare_resource_leave_vals_list(self):
  944. """Hook method for others to inject data
  945. """
  946. return [{
  947. 'name': _("%s: Time Off", leave.employee_id.name),
  948. 'date_from': leave.date_from,
  949. 'holiday_id': leave.id,
  950. 'date_to': leave.date_to,
  951. 'resource_id': leave.employee_id.resource_id.id,
  952. 'calendar_id': leave.employee_id.resource_calendar_id.id,
  953. 'time_type': leave.holiday_status_id.time_type,
  954. } for leave in self]
  955. def _create_resource_leave(self):
  956. """ This method will create entry in resource calendar time off object at the time of holidays validated
  957. :returns: created `resource.calendar.leaves`
  958. """
  959. vals_list = self._prepare_resource_leave_vals_list()
  960. return self.env['resource.calendar.leaves'].sudo().create(vals_list)
  961. def _remove_resource_leave(self):
  962. """ This method will create entry in resource calendar time off object at the time of holidays cancel/removed """
  963. return self.env['resource.calendar.leaves'].search([('holiday_id', 'in', self.ids)]).unlink()
  964. def _validate_leave_request(self):
  965. """ Validate time off requests (holiday_type='employee')
  966. by creating a calendar event and a resource time off. """
  967. holidays = self.filtered(lambda request: request.holiday_type == 'employee' and request.employee_id)
  968. holidays._create_resource_leave()
  969. meeting_holidays = holidays.filtered(lambda l: l.holiday_status_id.create_calendar_meeting)
  970. meetings = self.env['calendar.event']
  971. if meeting_holidays:
  972. meeting_values_for_user_id = meeting_holidays._prepare_holidays_meeting_values()
  973. Meeting = self.env['calendar.event']
  974. for user_id, meeting_values in meeting_values_for_user_id.items():
  975. meetings += Meeting.with_user(user_id or self.env.uid).with_context(
  976. allowed_company_ids=[],
  977. no_mail_to_attendees=True,
  978. calendar_no_videocall=True,
  979. active_model=self._name
  980. ).create(meeting_values)
  981. Holiday = self.env['hr.leave']
  982. for meeting in meetings:
  983. Holiday.browse(meeting.res_id).meeting_id = meeting
  984. def _prepare_holidays_meeting_values(self):
  985. result = defaultdict(list)
  986. company_calendar = self.env.company.resource_calendar_id
  987. for holiday in self:
  988. calendar = holiday.employee_id.resource_calendar_id or company_calendar
  989. user = holiday.user_id
  990. if holiday.leave_type_request_unit == 'hour':
  991. meeting_name = _("%s on Time Off : %.2f hour(s)") % (holiday.employee_id.name or holiday.category_id.name, holiday.number_of_hours_display)
  992. else:
  993. meeting_name = _("%s on Time Off : %.2f day(s)") % (holiday.employee_id.name or holiday.category_id.name, holiday.number_of_days)
  994. meeting_values = {
  995. 'name': meeting_name,
  996. 'duration': holiday.number_of_days * (calendar.hours_per_day or HOURS_PER_DAY),
  997. 'description': holiday.notes,
  998. 'user_id': user.id,
  999. 'start': holiday.date_from,
  1000. 'stop': holiday.date_to,
  1001. 'allday': False,
  1002. 'privacy': 'confidential',
  1003. 'event_tz': user.tz,
  1004. 'activity_ids': [(5, 0, 0)],
  1005. 'res_id': holiday.id,
  1006. }
  1007. # Add the partner_id (if exist) as an attendee
  1008. if user and user.partner_id:
  1009. meeting_values['partner_ids'] = [
  1010. (4, user.partner_id.id)]
  1011. result[user.id].append(meeting_values)
  1012. return result
  1013. def _prepare_employees_holiday_values(self, employees):
  1014. self.ensure_one()
  1015. work_days_data = employees._get_work_days_data_batch(self.date_from, self.date_to)
  1016. return [{
  1017. 'name': self.name,
  1018. 'holiday_type': 'employee',
  1019. 'holiday_status_id': self.holiday_status_id.id,
  1020. 'date_from': self.date_from,
  1021. 'date_to': self.date_to,
  1022. 'request_date_from': self.request_date_from,
  1023. 'request_date_to': self.request_date_to,
  1024. 'notes': self.notes,
  1025. 'number_of_days': work_days_data[employee.id]['days'],
  1026. 'parent_id': self.id,
  1027. 'employee_id': employee.id,
  1028. 'employee_ids': employee,
  1029. 'state': 'validate',
  1030. } for employee in employees if work_days_data[employee.id]['days']]
  1031. def action_cancel(self):
  1032. self.ensure_one()
  1033. return {
  1034. 'name': _('Cancel Time Off'),
  1035. 'type': 'ir.actions.act_window',
  1036. 'target': 'new',
  1037. 'res_model': 'hr.holidays.cancel.leave',
  1038. 'view_mode': 'form',
  1039. 'views': [[False, 'form']],
  1040. 'context': {
  1041. 'default_leave_id': self.id,
  1042. }
  1043. }
  1044. def action_draft(self):
  1045. if any(holiday.state not in ['confirm', 'refuse'] for holiday in self):
  1046. raise UserError(_('Time off request state must be "Refused" or "To Approve" in order to be reset to draft.'))
  1047. self.write({
  1048. 'state': 'draft',
  1049. 'first_approver_id': False,
  1050. 'second_approver_id': False,
  1051. })
  1052. linked_requests = self.mapped('linked_request_ids')
  1053. if linked_requests:
  1054. linked_requests.action_draft()
  1055. linked_requests.unlink()
  1056. self.activity_update()
  1057. return True
  1058. def action_confirm(self):
  1059. if self.filtered(lambda holiday: holiday.state != 'draft'):
  1060. raise UserError(_('Time off request must be in Draft state ("To Submit") in order to confirm it.'))
  1061. self.write({'state': 'confirm'})
  1062. holidays = self.filtered(lambda leave: leave.validation_type == 'no_validation')
  1063. if holidays:
  1064. # Automatic validation should be done in sudo, because user might not have the rights to do it by himself
  1065. holidays.sudo().action_validate()
  1066. self.activity_update()
  1067. return True
  1068. def action_approve(self):
  1069. # if validation_type == 'both': this method is the first approval approval
  1070. # if validation_type != 'both': this method calls action_validate() below
  1071. if any(holiday.state != 'confirm' for holiday in self):
  1072. raise UserError(_('Time off request must be confirmed ("To Approve") in order to approve it.'))
  1073. current_employee = self.env.user.employee_id
  1074. self.filtered(lambda hol: hol.validation_type == 'both').write({'state': 'validate1', 'first_approver_id': current_employee.id})
  1075. # Post a second message, more verbose than the tracking message
  1076. for holiday in self.filtered(lambda holiday: holiday.employee_id.user_id):
  1077. user_tz = timezone(holiday.tz)
  1078. utc_tz = pytz.utc.localize(holiday.date_from).astimezone(user_tz)
  1079. holiday.message_post(
  1080. body=_(
  1081. 'Your %(leave_type)s planned on %(date)s has been accepted',
  1082. leave_type=holiday.holiday_status_id.display_name,
  1083. date=utc_tz.replace(tzinfo=None)
  1084. ),
  1085. partner_ids=holiday.employee_id.user_id.partner_id.ids)
  1086. self.filtered(lambda hol: not hol.validation_type == 'both').action_validate()
  1087. if not self.env.context.get('leave_fast_create'):
  1088. self.activity_update()
  1089. return True
  1090. def _get_leaves_on_public_holiday(self):
  1091. return self.filtered(lambda l: l.employee_id and not l.number_of_days)
  1092. def _get_employees_from_holiday_type(self):
  1093. self.ensure_one()
  1094. if self.holiday_type == 'employee':
  1095. employees = self.employee_ids
  1096. elif self.holiday_type == 'category':
  1097. employees = self.category_id.employee_ids
  1098. elif self.holiday_type == 'company':
  1099. employees = self.env['hr.employee'].search([('company_id', '=', self.mode_company_id.id)])
  1100. else:
  1101. employees = self.department_id.member_ids
  1102. return employees
  1103. def action_validate(self):
  1104. current_employee = self.env.user.employee_id
  1105. leaves = self._get_leaves_on_public_holiday()
  1106. if leaves:
  1107. raise ValidationError(_('The following employees are not supposed to work during that period:\n %s') % ','.join(leaves.mapped('employee_id.name')))
  1108. if any(holiday.state not in ['confirm', 'validate1'] and holiday.validation_type != 'no_validation' for holiday in self):
  1109. raise UserError(_('Time off request must be confirmed in order to approve it.'))
  1110. self.write({'state': 'validate'})
  1111. leaves_second_approver = self.env['hr.leave']
  1112. leaves_first_approver = self.env['hr.leave']
  1113. for leave in self:
  1114. if leave.validation_type == 'both':
  1115. leaves_second_approver += leave
  1116. else:
  1117. leaves_first_approver += leave
  1118. if leave.holiday_type != 'employee' or\
  1119. (leave.holiday_type == 'employee' and len(leave.employee_ids) > 1):
  1120. employees = leave._get_employees_from_holiday_type()
  1121. conflicting_leaves = self.env['hr.leave'].with_context(
  1122. tracking_disable=True,
  1123. mail_activity_automation_skip=True,
  1124. leave_fast_create=True
  1125. ).search([
  1126. ('date_from', '<=', leave.date_to),
  1127. ('date_to', '>', leave.date_from),
  1128. ('state', 'not in', ['cancel', 'refuse']),
  1129. ('holiday_type', '=', 'employee'),
  1130. ('employee_id', 'in', employees.ids)])
  1131. if conflicting_leaves:
  1132. # YTI: More complex use cases could be managed in master
  1133. if leave.leave_type_request_unit != 'day' or any(l.leave_type_request_unit == 'hour' for l in conflicting_leaves):
  1134. raise ValidationError(_('You can not have 2 time off that overlaps on the same day.'))
  1135. # keep track of conflicting leaves states before refusal
  1136. target_states = {l.id: l.state for l in conflicting_leaves}
  1137. conflicting_leaves.action_refuse()
  1138. split_leaves_vals = []
  1139. for conflicting_leave in conflicting_leaves:
  1140. if conflicting_leave.leave_type_request_unit == 'half_day' and conflicting_leave.request_unit_half:
  1141. continue
  1142. # Leaves in days
  1143. if conflicting_leave.date_from < leave.date_from:
  1144. before_leave_vals = conflicting_leave.copy_data({
  1145. 'date_from': conflicting_leave.date_from.date(),
  1146. 'date_to': leave.date_from.date() + timedelta(days=-1),
  1147. 'state': target_states[conflicting_leave.id],
  1148. })[0]
  1149. before_leave = self.env['hr.leave'].new(before_leave_vals)
  1150. before_leave._compute_date_from_to()
  1151. # Could happen for part-time contract, that time off is not necessary
  1152. # anymore.
  1153. # Imagine you work on monday-wednesday-friday only.
  1154. # You take a time off on friday.
  1155. # We create a company time off on friday.
  1156. # By looking at the last attendance before the company time off
  1157. # start date to compute the date_to, you would have a date_from > date_to.
  1158. # Just don't create the leave at that time. That's the reason why we use
  1159. # new instead of create. As the leave is not actually created yet, the sql
  1160. # constraint didn't check date_from < date_to yet.
  1161. if before_leave.date_from < before_leave.date_to:
  1162. split_leaves_vals.append(before_leave._convert_to_write(before_leave._cache))
  1163. if conflicting_leave.date_to > leave.date_to:
  1164. after_leave_vals = conflicting_leave.copy_data({
  1165. 'date_from': leave.date_to.date() + timedelta(days=1),
  1166. 'date_to': conflicting_leave.date_to.date(),
  1167. 'state': target_states[conflicting_leave.id],
  1168. })[0]
  1169. after_leave = self.env['hr.leave'].new(after_leave_vals)
  1170. after_leave._compute_date_from_to()
  1171. # Could happen for part-time contract, that time off is not necessary
  1172. # anymore.
  1173. if after_leave.date_from < after_leave.date_to:
  1174. split_leaves_vals.append(after_leave._convert_to_write(after_leave._cache))
  1175. split_leaves = self.env['hr.leave'].with_context(
  1176. tracking_disable=True,
  1177. mail_activity_automation_skip=True,
  1178. leave_fast_create=True,
  1179. leave_skip_state_check=True
  1180. ).create(split_leaves_vals)
  1181. split_leaves.filtered(lambda l: l.state in 'validate')._validate_leave_request()
  1182. values = leave._prepare_employees_holiday_values(employees)
  1183. leaves = self.env['hr.leave'].with_context(
  1184. tracking_disable=True,
  1185. mail_activity_automation_skip=True,
  1186. leave_fast_create=True,
  1187. no_calendar_sync=True,
  1188. leave_skip_state_check=True,
  1189. # date_from and date_to are computed based on the employee tz
  1190. # If _compute_date_from_to is used instead, it will trigger _compute_number_of_days
  1191. # and create a conflict on the number of days calculation between the different leaves
  1192. leave_compute_date_from_to=True,
  1193. ).create(values)
  1194. leaves._validate_leave_request()
  1195. leaves_second_approver.write({'second_approver_id': current_employee.id})
  1196. leaves_first_approver.write({'first_approver_id': current_employee.id})
  1197. employee_requests = self.filtered(lambda hol: hol.holiday_type == 'employee')
  1198. employee_requests._validate_leave_request()
  1199. if not self.env.context.get('leave_fast_create'):
  1200. employee_requests.filtered(lambda holiday: holiday.validation_type != 'no_validation').activity_update()
  1201. return True
  1202. def action_refuse(self):
  1203. current_employee = self.env.user.employee_id
  1204. if any(holiday.state not in ['draft', 'confirm', 'validate', 'validate1'] for holiday in self):
  1205. raise UserError(_('Time off request must be confirmed or validated in order to refuse it.'))
  1206. validated_holidays = self.filtered(lambda hol: hol.state == 'validate1')
  1207. validated_holidays.write({'state': 'refuse', 'first_approver_id': current_employee.id})
  1208. (self - validated_holidays).write({'state': 'refuse', 'second_approver_id': current_employee.id})
  1209. # Delete the meeting
  1210. self.mapped('meeting_id').write({'active': False})
  1211. # If a category that created several holidays, cancel all related
  1212. linked_requests = self.mapped('linked_request_ids')
  1213. if linked_requests:
  1214. linked_requests.action_refuse()
  1215. # Post a second message, more verbose than the tracking message
  1216. for holiday in self:
  1217. if holiday.employee_id.user_id:
  1218. holiday.message_post(
  1219. body=_('Your %(leave_type)s planned on %(date)s has been refused', leave_type=holiday.holiday_status_id.display_name, date=holiday.date_from),
  1220. partner_ids=holiday.employee_id.user_id.partner_id.ids)
  1221. self.activity_update()
  1222. return True
  1223. def _action_user_cancel(self, reason):
  1224. self.ensure_one()
  1225. if not self.can_cancel:
  1226. raise ValidationError(_('This time off cannot be canceled.'))
  1227. self._force_cancel(reason, 'mail.mt_note')
  1228. def _force_cancel(self, reason, msg_subtype='mail.mt_comment'):
  1229. for leave in self:
  1230. leave.message_post(
  1231. body=_('The time off has been canceled: %s', reason),
  1232. subtype_xmlid=msg_subtype
  1233. )
  1234. leave_sudo = self.sudo()
  1235. leave_sudo.with_context(from_cancel_wizard=True).active = False
  1236. leave_sudo.meeting_id.active = False
  1237. leave_sudo._remove_resource_leave()
  1238. def action_documents(self):
  1239. domain = [('id', 'in', self.attachment_ids.ids)]
  1240. return {
  1241. 'name': _("Supporting Documents"),
  1242. 'type': 'ir.actions.act_window',
  1243. 'res_model': 'ir.attachment',
  1244. 'context': {'create': False},
  1245. 'view_mode': 'kanban',
  1246. 'domain': domain
  1247. }
  1248. def _check_approval_update(self, state):
  1249. """ Check if target state is achievable. """
  1250. if self.env.is_superuser():
  1251. return
  1252. current_employee = self.env.user.employee_id
  1253. is_officer = self.env.user.has_group('hr_holidays.group_hr_holidays_user')
  1254. is_manager = self.env.user.has_group('hr_holidays.group_hr_holidays_manager')
  1255. for holiday in self:
  1256. val_type = holiday.validation_type
  1257. if not is_manager and state != 'confirm':
  1258. if state == 'draft':
  1259. if holiday.state == 'refuse':
  1260. raise UserError(_('Only a Time Off Manager can reset a refused leave.'))
  1261. if holiday.date_from and holiday.date_from.date() <= fields.Date.today():
  1262. raise UserError(_('Only a Time Off Manager can reset a started leave.'))
  1263. if holiday.employee_id != current_employee:
  1264. raise UserError(_('Only a Time Off Manager can reset other people leaves.'))
  1265. else:
  1266. if val_type == 'no_validation' and current_employee == holiday.employee_id:
  1267. continue
  1268. # use ir.rule based first access check: department, members, ... (see security.xml)
  1269. holiday.check_access_rule('write')
  1270. # This handles states validate1 validate and refuse
  1271. if holiday.employee_id == current_employee:
  1272. raise UserError(_('Only a Time Off Manager can approve/refuse its own requests.'))
  1273. if (state == 'validate1' and val_type == 'both') and holiday.holiday_type == 'employee':
  1274. if not is_officer and self.env.user != holiday.employee_id.leave_manager_id:
  1275. raise UserError(_('You must be either %s\'s manager or Time off Manager to approve this leave') % (holiday.employee_id.name))
  1276. if (state == 'validate' and val_type == 'manager') and self.env.user != (holiday.employee_id | holiday.sudo().employee_ids).leave_manager_id:
  1277. if holiday.employee_id:
  1278. employees = holiday.employee_id
  1279. else:
  1280. employees = ', '.join(holiday.employee_ids.filtered(lambda e: e.leave_manager_id != self.env.user).mapped('name'))
  1281. raise UserError(_('You must be %s\'s Manager to approve this leave', employees))
  1282. if not is_officer and (state == 'validate' and val_type == 'hr') and holiday.holiday_type == 'employee':
  1283. raise UserError(_('You must either be a Time off Officer or Time off Manager to approve this leave'))
  1284. ###################################################
  1285. # Leave modification methods
  1286. ###################################################
  1287. def _split_leave_on_gto(self, gto): #gto = global time off
  1288. self.ensure_one()
  1289. leave_start = date_utils.start_of(self.date_from, 'day')
  1290. leave_end = date_utils.end_of(self.date_to - timedelta(seconds=1), 'day')
  1291. gto_start = date_utils.start_of(gto['date_from'], 'day')
  1292. gto_end = date_utils.end_of(gto['date_to'], 'day')
  1293. leave_tz = timezone(self.employee_id.resource_id.tz)
  1294. if gto_start <= leave_start\
  1295. and gto_end > leave_start\
  1296. and gto_end < leave_end:
  1297. self.write({
  1298. 'date_from': leave_tz.localize(gto_end + timedelta(seconds=1))\
  1299. .astimezone(UTC).replace(tzinfo=None)
  1300. })
  1301. return self.env['hr.leave']
  1302. if gto_start > leave_start\
  1303. and gto_end < leave_end:
  1304. copys = {
  1305. 'date_from': self.date_from,
  1306. 'date_to': leave_tz.localize(gto_start - timedelta(seconds=1))\
  1307. .astimezone(UTC).replace(tzinfo=None)
  1308. }
  1309. self.write({
  1310. 'date_from': leave_tz.localize(gto_end + timedelta(seconds=1))\
  1311. .astimezone(UTC).replace(tzinfo=None)
  1312. })
  1313. return self.copy(copys)
  1314. if gto_start > leave_start\
  1315. and gto_start < leave_end\
  1316. and gto_end >= leave_end:
  1317. self.write({
  1318. 'date_to': leave_tz.localize(gto_start - timedelta(seconds=1))\
  1319. .astimezone(UTC).replace(tzinfo=None)
  1320. })
  1321. return self.env['hr.leave']
  1322. def split_leave(self, time_domain_dict):
  1323. self.ensure_one()
  1324. new_leaves = self.env['hr.leave']
  1325. for global_time_off in sorted(
  1326. filter(lambda r: r['date_to'] > self.date_from and r['date_from'] < self.date_to, time_domain_dict),
  1327. key=lambda r: r['date_from']):
  1328. new_leave = self._split_leave_on_gto(global_time_off)
  1329. if new_leave:
  1330. new_leaves |= new_leave
  1331. return new_leaves
  1332. # ------------------------------------------------------------
  1333. # Activity methods
  1334. # ------------------------------------------------------------
  1335. def _get_responsible_for_approval(self):
  1336. self.ensure_one()
  1337. responsible = self.env.user
  1338. if self.holiday_type != 'employee':
  1339. return responsible
  1340. if self.validation_type == 'manager' or (self.validation_type == 'both' and self.state == 'confirm'):
  1341. if self.employee_id.leave_manager_id:
  1342. responsible = self.employee_id.leave_manager_id
  1343. elif self.employee_id.parent_id.user_id:
  1344. responsible = self.employee_id.parent_id.user_id
  1345. elif self.validation_type == 'hr' or (self.validation_type == 'both' and self.state == 'validate1'):
  1346. if self.holiday_status_id.responsible_id:
  1347. responsible = self.holiday_status_id.responsible_id
  1348. return responsible
  1349. def activity_update(self):
  1350. to_clean, to_do = self.env['hr.leave'], self.env['hr.leave']
  1351. for holiday in self:
  1352. note = _(
  1353. 'New %(leave_type)s Request created by %(user)s',
  1354. leave_type=holiday.holiday_status_id.name,
  1355. user=holiday.create_uid.name,
  1356. )
  1357. if holiday.state == 'draft':
  1358. to_clean |= holiday
  1359. elif holiday.state == 'confirm':
  1360. holiday.activity_schedule(
  1361. 'hr_holidays.mail_act_leave_approval',
  1362. note=note,
  1363. user_id=holiday.sudo()._get_responsible_for_approval().id or self.env.user.id)
  1364. elif holiday.state == 'validate1':
  1365. holiday.activity_feedback(['hr_holidays.mail_act_leave_approval'])
  1366. holiday.activity_schedule(
  1367. 'hr_holidays.mail_act_leave_second_approval',
  1368. note=note,
  1369. user_id=holiday.sudo()._get_responsible_for_approval().id or self.env.user.id)
  1370. elif holiday.state == 'validate':
  1371. to_do |= holiday
  1372. elif holiday.state == 'refuse':
  1373. to_clean |= holiday
  1374. if to_clean:
  1375. to_clean.activity_unlink(['hr_holidays.mail_act_leave_approval', 'hr_holidays.mail_act_leave_second_approval'])
  1376. if to_do:
  1377. to_do.activity_feedback(['hr_holidays.mail_act_leave_approval', 'hr_holidays.mail_act_leave_second_approval'])
  1378. ####################################################
  1379. # Messaging methods
  1380. ####################################################
  1381. def _notify_change(self, message, subtype_xmlid='mail.mt_note'):
  1382. for leave in self:
  1383. leave.message_post(body=message, subtype_xmlid=subtype_xmlid)
  1384. recipient = None
  1385. if leave.user_id:
  1386. recipient = leave.user_id.partner_id.id
  1387. elif leave.employee_id:
  1388. recipient = leave.employee_id.address_home_id.id
  1389. if recipient:
  1390. self.env['mail.thread'].sudo().message_notify(
  1391. body=message,
  1392. partner_ids=[recipient]
  1393. )
  1394. def _track_subtype(self, init_values):
  1395. if 'state' in init_values and self.state == 'validate':
  1396. leave_notif_subtype = self.holiday_status_id.leave_notif_subtype_id
  1397. return leave_notif_subtype or self.env.ref('hr_holidays.mt_leave')
  1398. return super(HolidaysRequest, self)._track_subtype(init_values)
  1399. def _notify_get_recipients_groups(self, msg_vals=None):
  1400. """ Handle HR users and officers recipients that can validate or refuse holidays
  1401. directly from email. """
  1402. groups = super(HolidaysRequest, self)._notify_get_recipients_groups(msg_vals=msg_vals)
  1403. if not self:
  1404. return groups
  1405. local_msg_vals = dict(msg_vals or {})
  1406. self.ensure_one()
  1407. hr_actions = []
  1408. if self.state == 'confirm':
  1409. app_action = self._notify_get_action_link('controller', controller='/leave/validate', **local_msg_vals)
  1410. hr_actions += [{'url': app_action, 'title': _('Approve')}]
  1411. if self.state in ['confirm', 'validate', 'validate1']:
  1412. ref_action = self._notify_get_action_link('controller', controller='/leave/refuse', **local_msg_vals)
  1413. hr_actions += [{'url': ref_action, 'title': _('Refuse')}]
  1414. holiday_user_group_id = self.env.ref('hr_holidays.group_hr_holidays_user').id
  1415. new_group = (
  1416. 'group_hr_holidays_user',
  1417. lambda pdata: pdata['type'] == 'user' and holiday_user_group_id in pdata['groups'],
  1418. {'actions': hr_actions}
  1419. )
  1420. return [new_group] + groups
  1421. def message_subscribe(self, partner_ids=None, subtype_ids=None):
  1422. # due to record rule can not allow to add follower and mention on validated leave so subscribe through sudo
  1423. if self.state in ['validate', 'validate1']:
  1424. self.check_access_rights('read')
  1425. self.check_access_rule('read')
  1426. return super(HolidaysRequest, self.sudo()).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids)
  1427. return super(HolidaysRequest, self).message_subscribe(partner_ids=partner_ids, subtype_ids=subtype_ids)
  1428. @api.model
  1429. def get_unusual_days(self, date_from, date_to=None):
  1430. return self.env.user.employee_id.sudo(False)._get_unusual_days(date_from, date_to)
  1431. def _get_start_or_end_from_attendance(self, hour, date, employee):
  1432. hour = float_to_time(float(hour))
  1433. holiday_tz = timezone(employee.tz or self.env.user.tz or 'UTC')
  1434. return holiday_tz.localize(datetime.combine(date, hour)).astimezone(UTC).replace(tzinfo=None)
  1435. def _get_attendances(self, employee, request_date_from, request_date_to):
  1436. resource_calendar_id = employee.resource_calendar_id or self.env.company.resource_calendar_id
  1437. domain = [('calendar_id', '=', resource_calendar_id.id), ('display_type', '=', False)]
  1438. attendances = self.env['resource.calendar.attendance'].read_group(domain,
  1439. ['ids:array_agg(id)', 'hour_from:min(hour_from)', 'hour_to:max(hour_to)',
  1440. 'week_type', 'dayofweek', 'day_period'],
  1441. ['week_type', 'dayofweek', 'day_period'], lazy=False)
  1442. # Must be sorted by dayofweek ASC and day_period DESC
  1443. attendances = sorted([DummyAttendance(group['hour_from'], group['hour_to'], group['dayofweek'], group['day_period'], group['week_type']) for group in attendances], key=lambda att: (att.dayofweek, att.day_period != 'morning'))
  1444. default_value = DummyAttendance(0, 0, 0, 'morning', False)
  1445. if resource_calendar_id.two_weeks_calendar:
  1446. # find week type of start_date
  1447. start_week_type = self.env['resource.calendar.attendance'].get_week_type(request_date_from)
  1448. attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == start_week_type]
  1449. attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != start_week_type]
  1450. # First, add days of actual week coming after date_from
  1451. attendance_filtred = [att for att in attendance_actual_week if int(att.dayofweek) >= request_date_from.weekday()]
  1452. # Second, add days of the other type of week
  1453. attendance_filtred += list(attendance_actual_next_week)
  1454. # Third, add days of actual week (to consider days that we have remove first because they coming before date_from)
  1455. attendance_filtred += list(attendance_actual_week)
  1456. end_week_type = self.env['resource.calendar.attendance'].get_week_type(request_date_to)
  1457. attendance_actual_week = [att for att in attendances if att.week_type is False or int(att.week_type) == end_week_type]
  1458. attendance_actual_next_week = [att for att in attendances if att.week_type is False or int(att.week_type) != end_week_type]
  1459. attendance_filtred_reversed = list(reversed([att for att in attendance_actual_week if int(att.dayofweek) <= request_date_to.weekday()]))
  1460. attendance_filtred_reversed += list(reversed(attendance_actual_next_week))
  1461. attendance_filtred_reversed += list(reversed(attendance_actual_week))
  1462. # find first attendance coming after first_day
  1463. attendance_from = attendance_filtred[0]
  1464. # find last attendance coming before last_day
  1465. attendance_to = attendance_filtred_reversed[0]
  1466. else:
  1467. # find first attendance coming after first_day
  1468. attendance_from = next((att for att in attendances if int(att.dayofweek) >= request_date_from.weekday()), attendances[0] if attendances else default_value)
  1469. # find last attendance coming before last_day
  1470. attendance_to = next((att for att in reversed(attendances) if int(att.dayofweek) <= request_date_to.weekday()), attendances[-1] if attendances else default_value)
  1471. return (attendance_from, attendance_to)