"""Workday arithmetic. Pure logic over a WorkCalendar. The holiday source is passed in as a function, so the rules can be tested with any hand made calendar. """ from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import date, timedelta from typing import Literal from ..errors import OutOfRangeError HolidayLookup = Callable[[int], Mapping[date, tuple[str, ...]]] Override = Literal["extra_holiday", "extra_workday"] ONE_DAY = timedelta(days=1) @dataclass(frozen=True) class DayInfo: day: date is_workday: bool is_weekend: bool holidays: tuple[str, ...] override: Override | None @property def is_holiday_off(self) -> bool: """A day off caused by a holiday, not merely by the weekend.""" return not self.is_workday and not self.is_weekend @dataclass(frozen=True) class WorkCalendar: weekend: frozenset[int] min_date: date max_date: date holidays_in_year: HolidayLookup extra_holidays: frozenset[date] = field(default_factory=frozenset) extra_workdays: frozenset[date] = field(default_factory=frozenset) def check_range(self, day: date, field_name: str) -> None: if not self.min_date <= day <= self.max_date: raise OutOfRangeError( f"Datum {day.isoformat()} v poli {field_name} je mimo rozsah kalendare " f"{self.min_date.isoformat()} az {self.max_date.isoformat()}.", { "field": field_name, "value": day.isoformat(), "min": self.min_date.isoformat(), "max": self.max_date.isoformat(), }, ) def describe(self, day: date) -> DayInfo: names = self.holidays_in_year(day.year).get(day, ()) is_weekend = day.weekday() in self.weekend # Explicit overrides from the caller win over the calendar. if day in self.extra_workdays: return DayInfo(day, True, is_weekend, names, "extra_workday") if day in self.extra_holidays: return DayInfo(day, False, is_weekend, names, "extra_holiday") return DayInfo(day, not is_weekend and not names, is_weekend, names, None) def is_workday(self, day: date) -> bool: return self.describe(day).is_workday @dataclass(frozen=True) class AddResult: result: date skipped: tuple[DayInfo, ...] @dataclass(frozen=True) class CountResult: workdays: int weekend_days: int holidays_off: tuple[DayInfo, ...] def _step(calendar: WorkCalendar, day: date, direction: int) -> date: candidate = day + ONE_DAY * direction calendar.check_range(candidate, "result") return candidate def add_workdays(calendar: WorkCalendar, start: date, days: int) -> AddResult: """Move by the given number of workdays, the start day itself is not counted. Negative days move backwards. Zero returns the start unchanged even when it is not a workday, the same as WORKDAY in Excel. """ calendar.check_range(start, "date") direction = 1 if days >= 0 else -1 remaining = abs(days) current = start skipped: list[DayInfo] = [] while remaining: current = _step(calendar, current, direction) info = calendar.describe(current) if info.is_workday: remaining -= 1 elif info.is_holiday_off: skipped.append(info) return AddResult(result=current, skipped=tuple(skipped)) def next_workday(calendar: WorkCalendar, start: date, include_start: bool = False) -> date: calendar.check_range(start, "date") if include_start and calendar.is_workday(start): return start return add_workdays(calendar, start, 1).result def previous_workday(calendar: WorkCalendar, start: date, include_start: bool = False) -> date: calendar.check_range(start, "date") if include_start and calendar.is_workday(start): return start return add_workdays(calendar, start, -1).result def count_workdays(calendar: WorkCalendar, start: date, end: date) -> CountResult: """Workdays between two dates, both ends included. When start is after end the counts are negative, the same as NETWORKDAYS in Excel, so the caller does not have to order the dates. """ calendar.check_range(start, "start") calendar.check_range(end, "end") sign = 1 if start > end: start, end = end, start sign = -1 workdays = 0 weekend_days = 0 holidays_off: list[DayInfo] = [] current = start while current <= end: info = calendar.describe(current) if info.is_workday: workdays += 1 elif info.is_holiday_off: holidays_off.append(info) else: weekend_days += 1 current += ONE_DAY return CountResult( workdays=workdays * sign, weekend_days=weekend_days * sign, holidays_off=tuple(holidays_off), )