diff --git a/l10n_fr_hr_holidays/models/hr_leave.py b/l10n_fr_hr_holidays/models/hr_leave.py index 442dfa5..e8daa31 100644 --- a/l10n_fr_hr_holidays/models/hr_leave.py +++ b/l10n_fr_hr_holidays/models/hr_leave.py @@ -1,7 +1,10 @@ # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. +from datetime import datetime, time + from dateutil.relativedelta import relativedelta +from pytz import timezone, UTC from odoo import fields, models, _, api from odoo.exceptions import UserError @@ -74,6 +77,45 @@ class HrLeave(models.Model): self.resource_calendar_id != self.employee_company_id.resource_calendar_id and \ self.holiday_status_id == self.employee_company_id._get_fr_reference_leave_type() + def _l10n_fr_is_public_holiday(self, date): + """Return True if `date` is fully covered by a global leave (public + holiday) registered on the employee calendar, the company calendar or + on no calendar at all.""" + self.ensure_one() + calendar = self.resource_calendar_id + company_calendar = self.employee_company_id.resource_calendar_id + tz = timezone(calendar.tz or company_calendar.tz or 'UTC') + day_start = tz.localize(datetime.combine(date, time.min)).astimezone(UTC).replace(tzinfo=None) + day_end = tz.localize(datetime.combine(date, time.max)).astimezone(UTC).replace(tzinfo=None) + calendar_ids = [False] + (calendar | company_calendar).ids + holidays = self.env['resource.calendar.leaves'].sudo().search([ + ('resource_id', '=', False), + ('time_type', '=', 'leave'), + ('calendar_id', 'in', calendar_ids), + ('date_from', '<=', day_end), + ('date_to', '>=', day_start), + ]) + if not holidays: + return False + # The holiday must cover all the employee attendances of that day + attendance_intervals = calendar._attendance_intervals_batch( + tz.localize(datetime.combine(date, time.min)), + tz.localize(datetime.combine(date, time.max)), + )[False] + for start, stop, _meta in attendance_intervals: + start_utc = start.astimezone(UTC).replace(tzinfo=None) + stop_utc = stop.astimezone(UTC).replace(tzinfo=None) + if not any(h.date_from <= start_utc and h.date_to >= stop_utc for h in holidays): + return False + return True + + def _l10n_fr_employee_works_on_date(self, date, working_days=None): + """Return True if the employee actually works on `date`: the day is a + working day in their calendar and is not a public holiday.""" + self.ensure_one() + return (self.resource_calendar_id._works_on_date(date, working_days) + and not self._l10n_fr_is_public_holiday(date)) + def _get_fr_date_from_to(self, date_from, date_to): self.ensure_one() # What we need to compute is how much we will need to push date_to in order to account for the lost days @@ -83,6 +125,8 @@ class HrLeave(models.Model): # which the employee works zero hours. if not (self.resource_calendar_id.attendance_ids): raise UserError(_("An employee cannot take a paid time off in a period they work no hours.")) + calendar = self.resource_calendar_id + working_days = calendar._get_working_hours() if self.request_unit_half and self.request_date_from_period == 'am': # In normal workflows request_unit_half implies that date_from and date_to are the same @@ -103,7 +147,7 @@ class HrLeave(models.Model): if attendances_am and not attendances_pm: # If the employee does not work in the afternoon, postpone date_to to the next working day next_date = date_from + relativedelta(days=1) - while not self.resource_calendar_id._works_on_date(next_date): + while not self._l10n_fr_employee_works_on_date(next_date, working_days): next_date += relativedelta(days=1) return (date_from, next_date) elif attendances_am and attendances_pm: @@ -116,7 +160,7 @@ class HrLeave(models.Model): current_date = date_from days_count = 0 while current_date <= date_to: - if self.resource_calendar_id._works_on_date(current_date): + if calendar._works_on_date(current_date, working_days): days_count += 1 current_date += relativedelta(days=1) # Adjust date_to so it matches the expected number of days @@ -126,7 +170,7 @@ class HrLeave(models.Model): current_date = date_from counted = 0 while counted < days_count: - if self.resource_calendar_id._works_on_date(current_date): + if calendar._works_on_date(current_date, working_days): counted += 1 if counted == days_count: break @@ -140,9 +184,12 @@ class HrLeave(models.Model): # the employee calendar as otherwise days worked on by the company # calendar before the actual start of the leave would be taken into # account. - while not self.resource_calendar_id._works_on_date(date_start): + while not calendar._works_on_date(date_start, working_days): date_start += relativedelta(days=1) - while not self.resource_calendar_id._works_on_date(date_target + relativedelta(days=1)): + # Public holidays are skipped too: if the employee's next scheduled + # working day is a public holiday, they only come back on the following + # actual working day, so the leave must cover the days in between. + while not self._l10n_fr_employee_works_on_date(date_target + relativedelta(days=1), working_days): date_target += relativedelta(days=1) # Undo the last day increment @@ -192,8 +239,9 @@ class HrLeave(models.Model): ] calendar = self._get_calendar() result = employee._get_work_days_data_batch(date_from, date_to, calendar=calendar, domain=domain) + l10n_fr_applies = self._l10n_fr_leave_applies() for employee_id in result: - if self._l10n_fr_leave_applies(): + if l10n_fr_applies: company_calendar = calendar employee_calendar = self.resource_calendar_id first_day = date_from.date() @@ -226,24 +274,18 @@ class HrLeave(models.Model): other_half = employee_calendar.attendance_ids.filtered( lambda a: a.dayofweek == dayofweek and a.day_period == other_period ) - first_day_count = 0.5 if (other_half and first_day in working_dates) else (1.0 if first_day in working_dates else 0.0) - days_count = first_day_count + if first_day in working_dates: + days_count = 0.5 if other_half else 1.0 + else: + days_count = 0.0 current_date = first_day + relativedelta(days=1) else: - days_count = 0 + days_count = 0.0 current_date = first_day - while current_date <= last_date: - if current_date in working_dates: - days_count += 1 - current_date += relativedelta(days=1) - + days_count += sum(1 for d in working_dates if current_date <= d <= last_date) result[employee_id]['days'] = float(days_count) elif self.request_unit_half and result[employee_id]['hours'] > 0: # Non-French context: a half-day leave always counts as 0.5 day result[employee_id]['days'] = 0.5 return result - - def _round_to_nearest_half(self, x): - """Round a float to the nearest 0.5.""" - return round(x * 2) / 2 diff --git a/l10n_fr_hr_holidays/models/resource_calendar.py b/l10n_fr_hr_holidays/models/resource_calendar.py index 460b2a1..01c18a4 100644 --- a/l10n_fr_hr_holidays/models/resource_calendar.py +++ b/l10n_fr_hr_holidays/models/resource_calendar.py @@ -4,16 +4,22 @@ from collections import defaultdict from datetime import datetime, time +from pytz import timezone + from odoo import models class ResourceCalendar(models.Model): _inherit = 'resource.calendar' - def _works_on_date(self, date): + def _works_on_date(self, date, working_days=None): + """Return True if the calendar has attendances on the weekday of `date`. + `working_days` can be given (result of `_get_working_hours`) to avoid + recomputing it when called in a loop.""" self.ensure_one() - working_days = self._get_working_hours() + if working_days is None: + working_days = self._get_working_hours() dayofweek = str(date.weekday()) if self.two_weeks_calendar: weektype = str(self.env['resource.calendar.attendance'].get_week_type(date)) @@ -34,7 +40,6 @@ class ResourceCalendar(models.Model): and other global leaves registered on the calendar. """ self.ensure_one() - from pytz import timezone tz = timezone(self.tz or 'UTC') from_dt = tz.localize(datetime.combine(from_date, time.min)) to_dt = tz.localize(datetime.combine(to_date, time(23, 59, 59))) diff --git a/l10n_fr_hr_holidays/tests/test_french_leaves.py b/l10n_fr_hr_holidays/tests/test_french_leaves.py index 8d65cd6..9f56e6c 100644 --- a/l10n_fr_hr_holidays/tests/test_french_leaves.py +++ b/l10n_fr_hr_holidays/tests/test_french_leaves.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. +from datetime import date + from odoo.tests.common import TransactionCase, tagged @tagged('post_install_l10n', 'post_install', '-at_install', 'french_leaves') @@ -619,3 +621,65 @@ class TestFrenchLeaves(TransactionCase): self.assertEqual(leave.number_of_days, 5.0, 'The number of days should be 5 (14/07 excluded as public holiday).') leave.unlink() + + def test_public_holiday_postpones_return_day(self): + # Company works Mon-Sat. Employee works Wed afternoon, Thu and Fri. + # Public holidays: 25/12/2020 (Fri), 26/12/2020 (Sat), 01/01/2021 (Fri). + # Leave requested from Wed 23/12/2020 to Thu 31/12/2020. + # The next scheduled working day (Fri 01/01) is a public holiday, so the + # employee only comes back on Wed 06/01/2021: the leave must be extended + # to Tue 05/01/2021. + # Company working days excluding public holidays: + # 23, 24, 28, 29, 30, 31/12 and 02, 04, 05/01 = 9 days + company_calendar = self.env['resource.calendar'].create({ + 'name': 'Company Calendar 6d/week', + 'company_id': self.company.id, + 'tz': 'Europe/Paris', + 'attendance_ids': [ + (0, 0, {'name': 'Morning %s' % d, 'dayofweek': str(d), 'hour_from': 9, 'hour_to': 12.5, 'day_period': 'morning'}) + for d in range(6) + ] + [ + (0, 0, {'name': 'Afternoon %s' % d, 'dayofweek': str(d), 'hour_from': 13.5, 'hour_to': 17, 'day_period': 'afternoon'}) + for d in range(6) + ], + }) + employee_calendar = self.env['resource.calendar'].create({ + 'name': 'Employee Calendar Wed PM-Fri', + 'company_id': self.company.id, + 'tz': 'Europe/Paris', + 'attendance_ids': [ + (0, 0, {'name': 'Wednesday Afternoon', 'dayofweek': '2', 'hour_from': 13.5, 'hour_to': 17, 'day_period': 'afternoon'}), + (0, 0, {'name': 'Thursday Morning', 'dayofweek': '3', 'hour_from': 9, 'hour_to': 12.5, 'day_period': 'morning'}), + (0, 0, {'name': 'Thursday Afternoon', 'dayofweek': '3', 'hour_from': 13.5, 'hour_to': 17, 'day_period': 'afternoon'}), + (0, 0, {'name': 'Friday Morning', 'dayofweek': '4', 'hour_from': 9, 'hour_to': 12.5, 'day_period': 'morning'}), + (0, 0, {'name': 'Friday Afternoon', 'dayofweek': '4', 'hour_from': 13.5, 'hour_to': 17, 'day_period': 'afternoon'}), + ], + }) + self.company.resource_calendar_id = company_calendar + self._set_employee_calendar(employee_calendar) + self.employee.tz = 'Europe/Paris' + + for name, day in [('Noel', '2020-12-25'), ('Saint Etienne', '2020-12-26'), ('Jour de l an', '2021-01-01')]: + self.env['resource.calendar.leaves'].create({ + 'name': name, + 'calendar_id': False, + 'company_id': self.company.id, + 'date_from': '%s 06:00:00' % day, + 'date_to': '%s 18:00:00' % day, + }) + + leave = self.env['hr.leave'].create({ + 'name': 'Test holiday before return', + 'holiday_status_id': self.time_off_type.id, + 'employee_id': self.employee.id, + 'request_date_from': '2020-12-23', + 'request_date_to': '2020-12-31', + 'employee_company_id': self.company.id, + 'resource_calendar_id': self.employee.resource_calendar_id.id, + }) + leave._compute_date_from_to() + self.assertEqual(leave.date_to.date(), date(2021, 1, 5), + 'The leave should be extended until the day before the return (05/01/2021).') + self.assertEqual(leave.number_of_days, 9.0, + 'The number of days should be 9.') + leave.unlink()