Implementace sluzby workdays

- endpointy /workdays/add, is-workday, next, previous, between
- /holidays, /countries (filtr eu), /markets, /health, /version
- data svatku z knihovny holidays 0.109, vsech 27 zemi EU vcetne regionu
- vychozi zeme CZ a cestina pres DEFAULT_COUNTRY a DEFAULT_LANGUAGE
- vlastni vikend, extra_holidays a extra_workdays v requestu
- testy logiky, API a testy proti realnym kalendarum
- CLAUDE.md s povinnym overenim vysledku proti realite
- dokumentace ve slozce documentation
- .gitignore: vyjimka pro app/lib
This commit is contained in:
JiriUhlir
2026-11-26 13:58:06 +01:00
parent 91167e4a0b
commit 0d55e3e89e
31 changed files with 1925 additions and 22 deletions
View File
+225
View File
@@ -0,0 +1,225 @@
"""Holiday data backed by the python-holidays library.
This is the only module that talks to the library. Everything else works with
plain dates and the CalendarInfo returned from here, so the data source can be
replaced without touching the workday logic.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import date
from functools import lru_cache
from typing import Literal
import holidays
from holidays import registry
from holidays.holiday_base import HolidayBase
from ..errors import (
UnknownCategoryError,
UnknownCountryError,
UnknownMarketError,
UnknownRegionError,
)
CalendarKind = Literal["country", "market"]
DEFAULT_CATEGORIES: tuple[str, ...] = ("public",)
# One entry is the holidays of one calendar in one year, a few kilobytes at
# most. 4096 entries cover every EU country with its regions for decades.
YEAR_CACHE_SIZE = 4096
# Members of the European Union, used only to mark and filter the country list.
EU_MEMBERS = frozenset(
"AT BE BG CY CZ DE DK EE ES FI FR GR HR HU IE IT LT LU LV MT NL PL PT RO SE SI SK".split()
)
@dataclass(frozen=True)
class CalendarSpec:
"""Everything that determines which holidays a calendar contains."""
kind: CalendarKind
code: str
region: str | None
categories: tuple[str, ...]
language: str | None
@dataclass(frozen=True)
class CalendarInfo:
spec: CalendarSpec
name: str
default_weekend: frozenset[int]
min_date: date
max_date: date
def _split_camel_case(name: str) -> str:
return re.sub(r"(?<=[a-z])(?=[A-Z])", " ", name)
@lru_cache(maxsize=1)
def _names() -> dict[tuple[CalendarKind, str], str]:
result: dict[tuple[CalendarKind, str], str] = {}
for class_name, code, *_ in registry.COUNTRIES.values():
result[("country", code)] = _split_camel_case(class_name)
for class_name, code, *_ in registry.FINANCIAL.values():
result[("market", code)] = _split_camel_case(class_name)
return result
@lru_cache(maxsize=1024)
def _entity(kind: CalendarKind, code: str) -> HolidayBase:
"""Calendar without years, used for metadata and validation."""
try:
if kind == "country":
return holidays.country_holidays(code)
return holidays.financial_holidays(code)
except NotImplementedError as exc:
if kind == "country":
raise UnknownCountryError(
f"Zeme '{code}' neni podporovana. Seznam je na GET /countries.",
{"country": code},
) from exc
raise UnknownMarketError(
f"Trh '{code}' neni podporovany. Seznam je na GET /markets.",
{"market": code},
) from exc
def _canonical_code(kind: CalendarKind, entity: HolidayBase) -> str:
return str(entity.country if kind == "country" else entity.market)
def _subdivision_names(entity: HolidayBase) -> dict[str, str]:
"""Map subdivision code to its human readable name where the library knows it."""
aliases: dict[str, str] = getattr(entity, "subdivisions_aliases", {}) or {}
names: dict[str, str] = {}
for alias, code in aliases.items():
names.setdefault(code, alias)
return names
def _resolve_region(kind: CalendarKind, code: str, entity: HolidayBase, region: str | None) -> str | None:
if region is None or region.strip() == "":
return None
wanted = region.strip().lower()
subdivisions: tuple[str, ...] = tuple(entity.subdivisions)
for subdivision in subdivisions:
if subdivision.lower() == wanted:
return subdivision
aliases: dict[str, str] = getattr(entity, "subdivisions_aliases", {}) or {}
for alias, subdivision in aliases.items():
if alias.lower() == wanted:
return subdivision
owner = "Zeme" if kind == "country" else "Trh"
raise UnknownRegionError(
f"{owner} '{code}' nema region '{region}'.",
{"region": region, "supported": list(subdivisions)},
)
def _resolve_categories(code: str, entity: HolidayBase, categories: tuple[str, ...] | None) -> tuple[str, ...]:
if not categories:
return DEFAULT_CATEGORIES
supported = set(entity.supported_categories)
unknown = [category for category in categories if category not in supported]
if unknown:
raise UnknownCategoryError(
f"Kalendar '{code}' nezna kategorie: {', '.join(unknown)}.",
{"categories": unknown, "supported": sorted(supported)},
)
return tuple(sorted(set(categories)))
def _resolve_language(entity: HolidayBase, preferred: str | None) -> str | None:
"""Exact match first, then the same language in another variant, then the default.
'en' matches 'en_US', 'cs' stays 'cs', and a language the calendar does not
know at all falls back to the calendar's own language.
"""
supported: tuple[str, ...] = tuple(entity.supported_languages or ())
default: str | None = entity.default_language
if not preferred:
return default
if preferred in supported:
return preferred
base = preferred.split("_")[0].lower()
for language in supported:
if language.split("_")[0].lower() == base:
return language
return default
def resolve_calendar(
kind: CalendarKind,
code: str,
region: str | None,
categories: tuple[str, ...] | None,
language: str | None,
) -> CalendarInfo:
entity = _entity(kind, code.strip().upper())
canonical = _canonical_code(kind, entity)
spec = CalendarSpec(
kind=kind,
code=canonical,
region=_resolve_region(kind, canonical, entity, region),
categories=_resolve_categories(canonical, entity, categories),
language=_resolve_language(entity, language),
)
return CalendarInfo(
spec=spec,
name=_names().get((kind, canonical), canonical),
default_weekend=frozenset(entity.weekend),
min_date=date(entity.start_year, 1, 1),
max_date=date(entity.end_year, 12, 31),
)
@lru_cache(maxsize=YEAR_CACHE_SIZE)
def holidays_in_year(spec: CalendarSpec, year: int) -> dict[date, tuple[str, ...]]:
"""Holidays of one calendar in one year, each date with all its names."""
factory = holidays.country_holidays if spec.kind == "country" else holidays.financial_holidays
data = factory(
spec.code,
subdiv=spec.region,
years=year,
language=spec.language,
categories=spec.categories,
)
return {day: tuple(data.get_list(day)) for day in sorted(data.keys())}
def _describe(kind: CalendarKind, code: str) -> dict:
entity = _entity(kind, code)
names = _subdivision_names(entity)
return {
"code": code,
"name": _names().get((kind, code), code),
"eu": kind == "country" and code in EU_MEMBERS,
"regions": [{"code": item, "name": names.get(item)} for item in entity.subdivisions],
"categories": sorted(entity.supported_categories),
"languages": list(entity.supported_languages or ()),
"default_language": entity.default_language,
"years": {"from": entity.start_year, "to": entity.end_year},
}
@lru_cache(maxsize=1)
def list_countries() -> tuple[dict, ...]:
codes = sorted({code for _, code, *_ in registry.COUNTRIES.values()})
return tuple(_describe("country", code) for code in codes)
@lru_cache(maxsize=1)
def list_markets() -> tuple[dict, ...]:
codes = sorted({code for _, code, *_ in registry.FINANCIAL.values()})
return tuple(_describe("market", code) for code in codes)
def library_version() -> str:
return str(holidays.__version__)
+157
View File
@@ -0,0 +1,157 @@
"""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),
)