Files
JiriUhlir 0d55e3e89e 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
2026-11-26 13:58:06 +01:00

226 lines
7.5 KiB
Python

"""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__)