Files
hr-tools/hr_employee_stats_sheet/models/hr_employee_stats.py
Valentin Lab 567a0a1d0d [IMP]hr_employee_stats_sheet:read the public holidays once per employee
Each day searched the public holidays of its own date. The days computed
together now run one search per employee over their date range, then
keep for each day the holidays the per-day search returned: those whose
UTC range covers the day. The check in the employee time zone is
unchanged, and two holidays on the same day still raise the same error.

With this change, the number of SQL queries needed to compute the days of
an employee no longer grows with the number of days.

Assisted-by: Claude:claude-opus-5-5
Assisted-by: GPT:gpt-6.1-sol
Assisted-by: GPT:gpt-6.2-astra-ultrafast
2026-11-19 14:09:26 +01:00

301 lines
13 KiB
Python

import logging
import pytz
from collections import defaultdict
from odoo import api, fields, models, _
from datetime import timedelta
from pytz import utc
from odoo.exceptions import UserError
from odoo.osv import expression
class HrEmployeeStats(models.Model):
_name = "hr.employee.stats"
_description = "Employee Stats"
_order = "date desc"
_inherit = ["mail.thread", "mail.activity.mixin"]
name = fields.Char("Name", compute="_compute_name", store=True)
dayofweek = fields.Integer("Day of Week", compute="_compute_dayofweek")
is_public_holiday = fields.Boolean("Public Holiday", compute="_compute_dayofweek")
employee_id = fields.Many2one("hr.employee", "Employee", required=True)
department_id = fields.Many2one("hr.department", "Department")
timesheet_line_ids = fields.Many2many(
"account.analytic.line",
compute="_compute_timesheet_line_ids",
string="Timesheet lines",
)
date = fields.Date("Date", required=True)
company_id = fields.Many2one(
"res.company",
"Company",
default=lambda self: self.env.company,
required=True,
)
sheet_id = fields.Many2one("hr_timesheet.sheet", "Timesheet")
total_hours = fields.Float("Total Hours", compute="_compute_hours")
total_planned_hours = fields.Float("Total Planning Hours", compute="_compute_hours")
total_leave_hours = fields.Float("Total Leave Hours", compute="_compute_hours")
total_recovery_hours = fields.Float(
"Total Recovery Hours", compute="_compute_hours"
)
gap_hours = fields.Float("Gap Hours", compute="_compute_hours")
def _get_holiday_status_id(self):
recovery_type_id = self.env.company.recovery_type_id
if recovery_type_id:
return recovery_type_id.id
else:
return False
def _dates_by_employee(self):
dates = defaultdict(set)
for stat in self:
dates[stat.employee_id].add(stat.date)
return dates
def _timesheet_lines_by_day(self):
"""Return {(employee, date): lines} with a single search. Each day
keeps the search order (date desc, id desc), so sums are unchanged."""
if not self:
return {}
lines = self.env["account.analytic.line"].search(self.get_total_hours_domain())
line_ids = defaultdict(list)
for line in lines:
line_ids[line.employee_id, line.date].append(line.id)
return {day: lines.browse(ids) for day, ids in line_ids.items()}
def _compute_timesheet_line_ids(self):
lines = self._timesheet_lines_by_day()
no_lines = self.env["account.analytic.line"]
for stat in self:
stat.timesheet_line_ids = lines.get((stat.employee_id, stat.date), no_lines)
def _get_intersects(
self, datetime1_start, datetime1_end, datetime2_start, datetime2_end
):
latest_start = max(datetime1_start, datetime2_start)
earliest_end = min(datetime1_end, datetime2_end)
delta = (earliest_end - latest_start).total_seconds() / 3600
return max(0, delta)
def get_total_hours_domain(self):
"""Timesheet lines counted in the total hours of these days."""
return expression.OR([
[("employee_id", "=", employee.id), ("date", "in", list(dates))]
for employee, dates in self._dates_by_employee().items()
])
def _total_hours_by_stat(self):
days = self.filtered(lambda stat: stat.date and stat.employee_id)
lines = days._timesheet_lines_by_day()
no_lines = self.env["account.analytic.line"]
return {
stat: sum(lines.get((stat.employee_id, stat.date), no_lines).mapped("unit_amount"))
for stat in days
}
@api.depends("timesheet_line_ids")
def _get_total_hours(self):
self.ensure_one()
return self._total_hours_by_stat().get(self, 0)
def _planned_hours_by_stat(self):
"""Return {stat: planned hours} from the calendar each employee had
that day. Public holidays and days without employee or date are left
out: they have no planned hours."""
days = self.filtered(lambda stat: stat.employee_id and stat.date and not stat.is_public_holiday)
dates_by_employee = days._dates_by_employee()
if not dates_by_employee:
return {}
histories = self.env["hr.employee.calendar"].search(expression.OR([
[
("employee_id", "=", employee.id),
("date_start", "<=", max(dates)),
"|", ("date_end", "=", False), ("date_end", ">=", min(dates)),
]
for employee, dates in dates_by_employee.items()
]))
calendars = {}
for employee, dates in dates_by_employee.items():
employee_histories = histories.filtered(lambda history: history.employee_id == employee)
for date in dates:
# same lines as _get_calendar_in_progress_during_a_time_period(date, date)
calendars[employee, date] = employee._select_stats_calendar(employee_histories.filtered(
lambda history: history.date_start <= date
and (not history.date_end or date <= history.date_end)
))
attendances = self.env["resource.calendar.attendance"].search(
[("calendar_id", "in", [calendar.id for calendar in set(calendars.values())])]
)
hours = defaultdict(float)
for attendance in attendances:
week_type = attendance.week_type if attendance.calendar_id.two_weeks_calendar else None
key = (attendance.calendar_id, attendance.dayofweek, week_type)
hours[key] += attendance.hour_to - attendance.hour_from
planned_hours = {}
for stat in days:
calendar = calendars[stat.employee_id, stat.date]
week_type = str(stat.date.isocalendar()[1] % 2) if calendar.two_weeks_calendar else None
planned_hours[stat] = hours.get((calendar, str(stat.date.weekday()), week_type), 0)
return planned_hours
def _get_total_planned_hours(self):
self.ensure_one()
return self._planned_hours_by_stat().get(self, 0)
def _validated_leaves_by_day(self):
"""Return {(employee, date): validated leaves} with a single search,
in its order (date_from desc)."""
dates_by_employee = self.filtered(lambda stat: stat.employee_id and stat.date)._dates_by_employee()
if not dates_by_employee:
return {}
leaves = self.env["hr.leave"].search(expression.AND([
[("state", "=", "validate"), ("active", "=", True)],
expression.OR([
[
("employee_id", "=", employee.id),
("request_date_from", "<=", max(dates)),
("request_date_to", ">=", min(dates)),
]
for employee, dates in dates_by_employee.items()
]),
]))
leaves_by_day = defaultdict(list)
for leave in leaves:
for date in dates_by_employee[leave.employee_id]:
if leave.request_date_from <= date <= leave.request_date_to:
leaves_by_day[leave.employee_id, date].append(leave)
return leaves_by_day
def _absence_hours_by_stat(self, planned_hours):
"""Return {stat: (recovery hours, other leave hours)}."""
leaves = self._validated_leaves_by_day()
absence_hours = {}
for stat in self:
recovery_type = stat._get_holiday_status_id()
recovery_hours = leave_hours = 0
for leave in leaves.get((stat.employee_id, stat.date), ()):
if leave.request_date_from == leave.request_date_to:
# single-day request (hours or half-day):
# Odoo already computed the hours from the calendar
hours = leave.number_of_hours_display
else:
# multi-day request: we take the planned hours
# of THAT specific day
hours = planned_hours.get(stat, 0)
if recovery_type and leave.holiday_status_id.id == recovery_type:
recovery_hours += hours
else:
leave_hours += hours
absence_hours[stat] = (recovery_hours, leave_hours)
return absence_hours
def _get_total_recovery_hours(self):
self.ensure_one()
return self._absence_hours_by_stat(self._planned_hours_by_stat())[self][0]
def _get_total_leave_hours(self):
self.ensure_one()
return self._absence_hours_by_stat(self._planned_hours_by_stat())[self][1]
@api.depends("employee_id", "date")
def _compute_name(self):
for stat in self:
stat.name = "%s - %s" % (stat.employee_id.name, stat.date)
@api.depends("date","employee_id")
def _compute_dayofweek(self):
public_holidays = self._public_holidays_by_day()
for stat in self:
if not stat.date:
stat.dayofweek = None
stat.is_public_holiday = False
continue
stat.dayofweek = int(stat.date.strftime("%u")) - 1
stat.is_public_holiday = stat._matches_public_holiday(
public_holidays.get((stat.employee_id, stat.date))
)
def _convert_to_employee_tz(self, date):
"""Convert a UTC datetime to the employee's timezone datetime."""
self.ensure_one()
if not date:
return None
employee_tz = pytz.timezone(self.employee_id.tz or "UTC")
if date.tzinfo is None:
dt = pytz.utc.localize(date)
return dt.astimezone(employee_tz)
def _public_holidays_by_day(self):
"""Return {(employee, date): public holidays} with one search per
employee: the holidays _get_public_holidays(date, date) returns."""
public_holidays = {}
days = self.filtered(lambda stat: stat.employee_id and stat.date)
for employee, dates in days._dates_by_employee().items():
holidays = employee._get_public_holidays(min(dates), max(dates))
for date in dates:
# the search compares the UTC datetimes with the whole day
public_holidays[employee, date] = holidays.filtered(
lambda holiday: holiday.date_from.date() <= date <= holiday.date_to.date()
)
return public_holidays
def _is_public_holiday_accordig_to_employe_tz(self):
self.ensure_one()
return self._matches_public_holiday(
self._public_holidays_by_day().get((self.employee_id, self.date))
)
def _matches_public_holiday(self, public_holidays):
self.ensure_one()
if not public_holidays:
return False
if len(public_holidays) > 1:
raise UserError(
_("Several holidays have been found ont he date '%s'. Please correct the anomaly before continuing.") % self.date
)
ph = public_holidays[0]
# Convert public holiday to the employee timezone
ph_datetime_from_tz = self._convert_to_employee_tz(ph.date_from)
ph_datetime_to_tz = self._convert_to_employee_tz(ph.date_to)
# Convert datetime to date
ph_date_from = ph_datetime_from_tz.date()
ph_date_to = ph_datetime_to_tz.date()
# Check if the stat date falls within the public holiday range after conversion in employee tz
if ph_date_from <= self.date <= ph_date_to:
return True
else:
return False
def _get_gap_hours(self, total_hours, total_recovery_hours, total_leave_hours, total_planned_hours):
self.ensure_one()
balance = (
total_hours
+ total_recovery_hours
+ total_leave_hours
- total_planned_hours
)
return balance
@api.depends(
"employee_id",
"date",
"total_hours",
"total_planned_hours",
"timesheet_line_ids",
)
def _compute_hours(self):
# read what the days need once for all of them, not day by day
hours = self._total_hours_by_stat()
planned_hours = self._planned_hours_by_stat()
absence_hours = self._absence_hours_by_stat(planned_hours)
for stat in self:
total_hours = hours.get(stat, 0)
total_planned_hours = planned_hours.get(stat, 0)
total_recovery_hours, total_leave_hours = absence_hours[stat]
stat.total_hours = total_hours
stat.total_planned_hours = total_planned_hours
stat.gap_hours = stat._get_gap_hours(total_hours, total_recovery_hours, total_leave_hours, total_planned_hours)
stat.total_recovery_hours = total_recovery_hours
stat.total_leave_hours = total_leave_hours