3 Commits

Author SHA1 Message Date
ef3c9143dd [REF]l10n_fr_hr_holidays:clean up leave days computation
- remove unused _round_to_nearest_half
- evaluate _l10n_fr_leave_applies once in _get_number_of_days_batch and
  count working dates without a day-by-day loop
- compute the calendar working hours once per date lookup loop
- move pytz import to the top of resource_calendar.py

No functional change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:46:57 +00:00
646ab82880 [FIX]l10n_fr_hr_holidays:skip public holidays when looking for the return day of part-time employees
When the next scheduled working day of a part-time employee after the
leave is a public holiday, the leave end date was not postponed to the
day before the actual return, so company working days in between were
not counted (e.g. Wed PM-Fri employee, leave 23/12 -> 31/12 with 01/01
being a Friday: 6 days counted instead of 9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:46:57 +00:00
991fd43167 [FIX]hr_employee_stats_sheet:use employee calendar hours per day to convert recovery hours into allocation days
Odoo displays allocation hours with the hours per day of the employee's
resource calendar. Converting recovery hours with another calendar (planning
calendar or company calendar) made the generated allocation display a wrong
number of hours (e.g. 18.21h instead of 19h).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:35:27 +01:00
5 changed files with 174 additions and 35 deletions

View File

@@ -102,18 +102,21 @@ class HrTimesheetSheet(models.Model):
def _get_working_hours_per_day(self):
"""
Get the hours per day for the employee according to:
- the employee's work contract,
- or their resource calendar,
Get the hours per day used to convert recovery hours into allocation days.
It must be the same ratio as the one used by Odoo to convert the allocation
days back into hours (see hr.leave.allocation._compute_number_of_hours_display),
otherwise the allocation won't display the recovery hours of the timesheet sheet:
- the employee's resource calendar,
- or the company's resource calendar,
- or the default value of 8 hours per day.
:return: hours per day
"""
# get ressource calendar id used during the timesheet sheet time period
ressource_calendar_id = self.employee_id._get_calendar_in_progress_during_a_time_period(self.date_start,self.date_end)
if ressource_calendar_id:
return ressource_calendar_id.hours_per_day
return HOURS_PER_DAY
self.ensure_one()
return (
self.employee_id.sudo().resource_calendar_id.hours_per_day
or self.company_id.resource_calendar_id.hours_per_day
or HOURS_PER_DAY
)
def action_generate_recovery_allocation(self):
# check if the user has the right to review the timesheet sheet
@@ -147,6 +150,9 @@ class HrTimesheetSheet(models.Model):
# get recovery hours from total gap hours of the timesheet sheet
recovery_hours = self._get_timesheet_sheet_recovery_hours()
# raise an error if the employee's calendar changes during the timesheet sheet time period
employee_id._get_calendar_in_progress_during_a_time_period(self.date_start, self.date_end)
# convert recovery hours into days
recovery_days = recovery_hours / self._get_working_hours_per_day()

View File

@@ -128,8 +128,27 @@ class TestHrEmployeeStatsRecovery(TransactionCase):
timesheet_sheet.action_generate_recovery_allocation()
recovery_allocation = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet.id)])
self.assertEqual(len(recovery_allocation), 1, "There should be one recovery")
self.assertEqual(recovery_allocation.number_of_days,0.8928571428571429, "The recovery allocation should be for 6.25h/7h = 0.8928571428571429 day")
self.assertAlmostEqual(recovery_allocation.number_of_hours_display, 6.25, msg="The recovery allocation should display 6.25 hours")
def test_recovery_allocation_hours_with_employee_calendar_different_from_planning(self):
# the employee's resource calendar hours per day differs from the planning calendar one:
# the allocation must still display the recovery hours of the timesheet sheet
self.env['hr.employee.calendar'].create({
'employee_id': self.employee.id,
'date_start': Date.to_date("2025-01-01"),
'date_end': None,
'calendar_id': self.base_calendar.id,
})
self.employee.resource_calendar_id.hours_per_day = 7.3
start_date = date.today() - timedelta(days=date.today().weekday() + 7) # lundi de la semaine dernière
timesheet_sheet = self._create_timesheet_sheet(start_date)
list(self._create_stats(start_date, 5, 8))
self.assertEqual(timesheet_sheet.timesheet_sheet_recovery_hours, 6.25, "timesheet_sheet_recovery_hours should be 6,25",)
timesheet_sheet.action_generate_recovery_allocation()
recovery_allocation = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet.id)])
self.assertEqual(len(recovery_allocation), 1, "There should be one recovery")
self.assertAlmostEqual(recovery_allocation.number_of_hours_display, 6.25, msg="The recovery allocation should display 6.25 hours")
def test_negative_recovery_hours(self):
self.env['hr.employee.calendar'].create({
'employee_id': self.employee.id,
@@ -153,7 +172,7 @@ class TestHrEmployeeStatsRecovery(TransactionCase):
timesheet_sheet.action_generate_recovery_allocation()
recovery_allocation = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet.id)])
self.assertEqual(len(recovery_allocation), 1, "There should be one recovery")
self.assertEqual(recovery_allocation.number_of_days, -0.7142857142857143, "The recovery allocation should be for -5/7 hours = −0,714285714")
self.assertAlmostEqual(recovery_allocation.number_of_hours_display, -5, msg="The recovery allocation should display -5 hours")
def test_sheet_totals_update_after_timesheet_change(self):
"""Regression test: the sheet totals must reflect the addition and
@@ -371,7 +390,9 @@ class TestHrEmployeeStatsRecovery(TransactionCase):
self.assertEqual(timesheet_sheet_1.timesheet_sheet_recovery_hours, 6.25, "timesheet_sheet_recovery_hours should be 6,25",)
allocation_1 = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet_1.id)])
self.assertEqual(len(allocation_1), 1, "There should be one recovery")
self.assertEqual(allocation_1.number_of_days,0.8928571428571429, "The recovery allocation should be for 0.8928571428571429 day")
# days are computed with the employee's current calendar (9h/day), as Odoo does to display hours
self.assertAlmostEqual(allocation_1.number_of_days, 6.25 / 9, msg="The recovery allocation should be for 6.25/9 day")
self.assertAlmostEqual(allocation_1.number_of_hours_display, 6.25, msg="The recovery allocation should display 6.25 hours")
#create stats during period of part time calendar for the employee
# generation 4 stats of 10h each, the employee is supposed to work 9h per day during 4 days
@@ -390,8 +411,9 @@ class TestHrEmployeeStatsRecovery(TransactionCase):
allocation_2 = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet_2.id)])
self.assertEqual(len(allocation_2), 1, "There should be one recovery")
self.assertEqual(allocation_2.number_of_days,0.5555555555555556, "The recovery allocation should be for 0,555555556 (5/9) day")
self.assertAlmostEqual(allocation_2.number_of_hours_display, 5, msg="The recovery allocation should display 5 hours")
#check that allocation_1 hasn't changed
self.assertEqual(allocation_1.number_of_days,0.8928571428571429, "The recovery allocation should be for 0,892857143 day")
self.assertAlmostEqual(allocation_1.number_of_hours_display, 6.25, msg="The recovery allocation should still display 6.25 hours")
def test_public_holiday(self):
self.env['hr.employee.calendar'].create({
@@ -431,7 +453,7 @@ class TestHrEmployeeStatsRecovery(TransactionCase):
timesheet_sheet.action_generate_recovery_allocation()
recovery_allocation = self.env["hr.leave.allocation"].search([("timesheet_sheet_id","=",timesheet_sheet.id)])
self.assertEqual(len(recovery_allocation), 1, "Il doit y avoir une allocation de récupération générée")
self.assertEqual(recovery_allocation.number_of_days,1.25, "The recovery allocation should be 1,25 days")
self.assertAlmostEqual(recovery_allocation.number_of_hours_display, 8.75, msg="The recovery allocation should display 8.75 hours")
@tagged("post_install", "-at_install")

View File

@@ -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

View File

@@ -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)))

View File

@@ -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()