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:
@@ -0,0 +1,15 @@
|
|||||||
|
# Nazev a verze v dokumentaci a v /version
|
||||||
|
APP_NAME=workdays
|
||||||
|
APP_VERSION=1.0.0
|
||||||
|
|
||||||
|
# Prefix reverse proxy, v AppFactory /apps/workdays
|
||||||
|
ROOT_PATH=
|
||||||
|
|
||||||
|
# Uroven logovani: DEBUG, INFO, WARNING, ERROR
|
||||||
|
LOG_LEVEL=INFO
|
||||||
|
|
||||||
|
# Zeme, kdyz request neuvede country ani market (ISO 3166 alpha-2)
|
||||||
|
DEFAULT_COUNTRY=CZ
|
||||||
|
|
||||||
|
# Preferovany jazyk nazvu svatku, zeme bez jeho podpory pouzije vlastni jazyk
|
||||||
|
DEFAULT_LANGUAGE=cs
|
||||||
@@ -174,3 +174,6 @@ cython_debug/
|
|||||||
# PyPI configuration file
|
# PyPI configuration file
|
||||||
.pypirc
|
.pypirc
|
||||||
|
|
||||||
|
|
||||||
|
# Application package folder, not a Python build artefact
|
||||||
|
!app/lib/
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Pravidla pro sluzbu workdays
|
||||||
|
|
||||||
|
Plati navic k `AGENTS.md` a k obecnemu `CLAUDE.md` v nadrazene slozce.
|
||||||
|
`AGENTS.md` ma prednost.
|
||||||
|
|
||||||
|
## Testy proti realite jsou povinne
|
||||||
|
|
||||||
|
U teto sluzby se testy spousteji vzdy, bez dalsiho ptani, po kazde zmene
|
||||||
|
vypoctu, parametru, zavislosti nebo verze knihovny `holidays`.
|
||||||
|
|
||||||
|
Nestaci, ze testy projdou. Cilem je overit, ze **vysledky odpovidaji
|
||||||
|
skutecnosti**, tedy platnym zakonum o svatcich a skutecnemu kalendari.
|
||||||
|
|
||||||
|
1. Spustit cele `pytest` v lokalnim `.venv`:
|
||||||
|
`.venv/Scripts/python -m pytest -q`
|
||||||
|
(prostredi: `python -m venv .venv` a
|
||||||
|
`.venv/Scripts/python -m pip install -r requirements-dev.txt`).
|
||||||
|
2. Referencni hodnoty jsou v `tests/test_reality.py`. Kazda ocekavana hodnota
|
||||||
|
musi pochazet ze zdroje mimo sluzbu (zakon, oficialni kalendar, uradem
|
||||||
|
zverejneny fond pracovni doby), ne z vystupu sluzby samotne. Zdroj se pise
|
||||||
|
do hlavicky souboru.
|
||||||
|
3. Kdyz se zmeni vypocet nebo pribude zeme ci operace, pridat do
|
||||||
|
`tests/test_reality.py` aspon jeden pripad s realnymi daty, napriklad
|
||||||
|
prechod pres Velikonoce, Vanoce nebo regionalni svatek.
|
||||||
|
4. Kdyz test proti realite selze po aktualizaci knihovny, nejdriv overit
|
||||||
|
zdroj. Mohl se zmenit zakon, ne kod. Ocekavanou hodnotu menit jen podle
|
||||||
|
overeneho zdroje a zmenu zapsat do `documentation/zmeny.md`.
|
||||||
|
5. Vysledek testu (pocet, co selhalo a proc) uvest v odpovedi uzivateli.
|
||||||
@@ -1,3 +1,33 @@
|
|||||||
# workdays
|
# workdays
|
||||||
|
|
||||||
Generated by AppFactory.
|
Sluzba pocita s pracovnimi dny, vikendy a svatky. Pricte pracovni dny k datu,
|
||||||
|
najde dalsi pracovni den, spocita pracovni dny v intervalu a vypise svatky.
|
||||||
|
Pokryva vsechny zeme EU vcetne regionu, vychozi zeme je CZ.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl "https://services.csbot.cz/apps/workdays/workdays/add?date=2026-11-26&days=3"
|
||||||
|
```
|
||||||
|
|
||||||
|
Vraci `"result": "2026-12-01"`.
|
||||||
|
|
||||||
|
## Spusteni
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m venv .venv
|
||||||
|
.venv/Scripts/python -m pip install -r requirements-dev.txt
|
||||||
|
.venv/Scripts/python -m uvicorn app.main:app --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
Swagger je na `/docs`, health na `/health`. V AppFactory se sluzba sestavi
|
||||||
|
z `Dockerfile` a bezi na portu 8000.
|
||||||
|
|
||||||
|
## Promenne prostredi
|
||||||
|
|
||||||
|
`APP_NAME`, `APP_VERSION`, `ROOT_PATH`, `LOG_LEVEL`, `DEFAULT_COUNTRY`,
|
||||||
|
`DEFAULT_LANGUAGE`. Zadna neni povinna, popis je v
|
||||||
|
[documentation/konfigurace.md](documentation/konfigurace.md)
|
||||||
|
a v [.env.example](.env.example).
|
||||||
|
|
||||||
|
## Dokumentace
|
||||||
|
|
||||||
|
[documentation/README.md](documentation/README.md)
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Runtime configuration read from environment variables.
|
||||||
|
|
||||||
|
AppFactory injects variables through the generated runtime .env file, so every
|
||||||
|
option below has a safe default and the service starts without any variable set.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
|
||||||
|
def _str(name: str, default: str) -> str:
|
||||||
|
raw = os.getenv(name)
|
||||||
|
if raw is None or raw.strip() == "":
|
||||||
|
return default
|
||||||
|
return raw.strip()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Settings:
|
||||||
|
app_name: str = field(default_factory=lambda: _str("APP_NAME", "workdays"))
|
||||||
|
app_version: str = field(default_factory=lambda: _str("APP_VERSION", "1.0.0"))
|
||||||
|
root_path: str = field(
|
||||||
|
default_factory=lambda: os.getenv("ROOT_PATH") or os.getenv("BASE_PATH") or ""
|
||||||
|
)
|
||||||
|
log_level: str = field(default_factory=lambda: _str("LOG_LEVEL", "INFO").upper())
|
||||||
|
|
||||||
|
# Calendar used when the request names neither a country nor a market.
|
||||||
|
default_country: str = field(default_factory=lambda: _str("DEFAULT_COUNTRY", "CZ").upper())
|
||||||
|
# Preferred language of holiday names. A country that does not support it
|
||||||
|
# falls back to its own default language.
|
||||||
|
default_language: str = field(default_factory=lambda: _str("DEFAULT_LANGUAGE", "cs"))
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Application errors.
|
||||||
|
|
||||||
|
Every failure carries a machine readable error_code and a message in Czech,
|
||||||
|
because the message is shown to the caller.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceError(Exception):
|
||||||
|
error_code = "internal_error"
|
||||||
|
status_code = 500
|
||||||
|
|
||||||
|
def __init__(self, message: str, detail: dict | None = None) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
self.detail = detail or {}
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
payload: dict = {"error_code": self.error_code, "message": self.message}
|
||||||
|
if self.detail:
|
||||||
|
payload["detail"] = self.detail
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidRequestError(ServiceError):
|
||||||
|
error_code = "invalid_request"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidDateError(ServiceError):
|
||||||
|
error_code = "invalid_date"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownCountryError(ServiceError):
|
||||||
|
error_code = "unknown_country"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownMarketError(ServiceError):
|
||||||
|
error_code = "unknown_market"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownRegionError(ServiceError):
|
||||||
|
error_code = "unknown_region"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownCategoryError(ServiceError):
|
||||||
|
error_code = "unknown_category"
|
||||||
|
status_code = 400
|
||||||
|
|
||||||
|
|
||||||
|
class OutOfRangeError(ServiceError):
|
||||||
|
"""The date or the computed result lies outside the years the calendar covers."""
|
||||||
|
|
||||||
|
error_code = "out_of_range"
|
||||||
|
status_code = 400
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Parsing of dates and weekday lists coming from query parameters.
|
||||||
|
|
||||||
|
Pure functions without any dependency on the application.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from ..errors import InvalidDateError, InvalidRequestError
|
||||||
|
|
||||||
|
# ISO 8601 is the canonical format. The Czech D.M.YYYY form is accepted too,
|
||||||
|
# because that is how people write dates here, optionally with spaces.
|
||||||
|
_ISO = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
||||||
|
_CZECH = re.compile(r"^(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4})$")
|
||||||
|
|
||||||
|
WEEKDAY_NAMES = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
|
||||||
|
_WEEKDAY_ALIASES = {
|
||||||
|
"po": 0, "ut": 1, "st": 2, "ct": 3, "pa": 4, "so": 5, "ne": 6,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(value: str, field_name: str = "date") -> date:
|
||||||
|
raw = value.strip()
|
||||||
|
match = _ISO.match(raw)
|
||||||
|
if match:
|
||||||
|
year, month, day = (int(part) for part in match.groups())
|
||||||
|
else:
|
||||||
|
match = _CZECH.match(raw)
|
||||||
|
if not match:
|
||||||
|
raise InvalidDateError(
|
||||||
|
f"Neplatny format data v poli {field_name}: '{value}'. "
|
||||||
|
"Pouzijte YYYY-MM-DD nebo D.M.YYYY.",
|
||||||
|
{"field": field_name, "value": value},
|
||||||
|
)
|
||||||
|
day, month, year = (int(part) for part in match.groups())
|
||||||
|
try:
|
||||||
|
return date(year, month, day)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise InvalidDateError(
|
||||||
|
f"Datum v poli {field_name} neexistuje: '{value}'.",
|
||||||
|
{"field": field_name, "value": value},
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date_list(value: str | None, field_name: str) -> frozenset[date]:
|
||||||
|
if value is None or value.strip() == "":
|
||||||
|
return frozenset()
|
||||||
|
return frozenset(
|
||||||
|
parse_date(part, field_name) for part in value.split(",") if part.strip()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weekend(value: str | None) -> frozenset[int] | None:
|
||||||
|
"""Return weekday numbers (Monday is 0) or None when the caller left it empty.
|
||||||
|
|
||||||
|
The literal 'none' means a calendar without weekend days.
|
||||||
|
"""
|
||||||
|
if value is None or value.strip() == "":
|
||||||
|
return None
|
||||||
|
raw = value.strip().lower()
|
||||||
|
if raw == "none":
|
||||||
|
return frozenset()
|
||||||
|
days: set[int] = set()
|
||||||
|
for part in raw.split(","):
|
||||||
|
token = part.strip()
|
||||||
|
if not token:
|
||||||
|
continue
|
||||||
|
if token in WEEKDAY_NAMES:
|
||||||
|
days.add(WEEKDAY_NAMES.index(token))
|
||||||
|
elif token in _WEEKDAY_ALIASES:
|
||||||
|
days.add(_WEEKDAY_ALIASES[token])
|
||||||
|
else:
|
||||||
|
raise InvalidRequestError(
|
||||||
|
f"Neznamy den v parametru weekend: '{token}'. "
|
||||||
|
"Pouzijte mon,tue,wed,thu,fri,sat,sun nebo po,ut,st,ct,pa,so,ne.",
|
||||||
|
{"field": "weekend", "value": value},
|
||||||
|
)
|
||||||
|
if len(days) == len(WEEKDAY_NAMES):
|
||||||
|
raise InvalidRequestError(
|
||||||
|
"Parametr weekend nesmi obsahovat vsech sedm dni, kalendar by nemel zadny pracovni den.",
|
||||||
|
{"field": "weekend", "value": value},
|
||||||
|
)
|
||||||
|
return frozenset(days)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Structured JSON logging, one JSON object per line."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_RESERVED = {
|
||||||
|
"args", "asctime", "created", "exc_info", "exc_text", "filename", "funcName",
|
||||||
|
"levelname", "levelno", "lineno", "module", "msecs", "message", "msg", "name",
|
||||||
|
"pathname", "process", "processName", "relativeCreated", "stack_info",
|
||||||
|
"thread", "threadName", "taskName",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class JsonFormatter(logging.Formatter):
|
||||||
|
def format(self, record: logging.LogRecord) -> str:
|
||||||
|
payload: dict[str, object] = {
|
||||||
|
"ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S%z"),
|
||||||
|
"level": record.levelname,
|
||||||
|
"logger": record.name,
|
||||||
|
"message": record.getMessage(),
|
||||||
|
}
|
||||||
|
for key, value in record.__dict__.items():
|
||||||
|
if key not in _RESERVED and not key.startswith("_"):
|
||||||
|
payload[key] = value
|
||||||
|
if record.exc_info:
|
||||||
|
payload["exception"] = self.formatException(record.exc_info)
|
||||||
|
return json.dumps(payload, ensure_ascii=False, default=str)
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logging(level: str) -> None:
|
||||||
|
handler = logging.StreamHandler(sys.stdout)
|
||||||
|
handler.setFormatter(JsonFormatter())
|
||||||
|
|
||||||
|
root = logging.getLogger()
|
||||||
|
root.handlers.clear()
|
||||||
|
root.addHandler(handler)
|
||||||
|
root.setLevel(getattr(logging, level, logging.INFO))
|
||||||
|
|
||||||
|
# uvicorn keeps its own handlers, route them through ours as well
|
||||||
|
for name in ("uvicorn", "uvicorn.access", "uvicorn.error"):
|
||||||
|
logger = logging.getLogger(name)
|
||||||
|
logger.handlers.clear()
|
||||||
|
logger.propagate = True
|
||||||
+115
-19
@@ -1,25 +1,121 @@
|
|||||||
import os
|
"""Service entry point.
|
||||||
from fastapi import FastAPI
|
|
||||||
|
The application runs behind the AppFactory reverse proxy under
|
||||||
|
/apps/<app-id>. The prefix is stripped before the request reaches the
|
||||||
|
container, so only the OpenAPI document has to know about it. That is what
|
||||||
|
root_path does.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from .config import get_settings
|
||||||
|
from .errors import ServiceError
|
||||||
|
from .logging_setup import setup_logging
|
||||||
|
from .routers import health as health_router
|
||||||
|
from .routers import holidays as holidays_router
|
||||||
|
from .routers import workdays as workdays_router
|
||||||
|
from .services.calendars import holidays_in_year, library_version, resolve_calendar
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
DESCRIPTION = """
|
||||||
|
Sluzba pocita s pracovnimi dny, vikendy a statnimi svatky. Pokryva vsechny
|
||||||
|
zeme EU vcetne regionu a dalsi zeme a financni kalendare. Data svatku dodava
|
||||||
|
knihovna python-holidays.
|
||||||
|
|
||||||
|
## Vychozi chovani
|
||||||
|
|
||||||
|
- zeme je CZ (promenna `DEFAULT_COUNTRY`), nazvy svatku cesky
|
||||||
|
(`DEFAULT_LANGUAGE`)
|
||||||
|
- pocitaji se jen statni svatky, kategorie `public`
|
||||||
|
- vikend je vikend dane zeme, v EU vzdy sobota a nedele
|
||||||
|
- data se zadavaji jako `YYYY-MM-DD` nebo `D.M.YYYY`, vraci se vzdy `YYYY-MM-DD`
|
||||||
|
|
||||||
|
## Pravidla vypoctu
|
||||||
|
|
||||||
|
- **add** vychozi den se nepocita. Ctvrtek 26.11.2026 plus 3 pracovni dny
|
||||||
|
v CZ je utery 1.12.2026. Zaporne `days` posouva zpet, `days=0` vrati vychozi
|
||||||
|
den beze zmeny.
|
||||||
|
- **next** a **previous** vraci nejblizsi pracovni den po nebo pred datem,
|
||||||
|
s `include_start=true` vrati vychozi den, kdyz je pracovni.
|
||||||
|
- **between** pocita oba krajni dny vcetne. Obracene poradi dat vrati zaporne
|
||||||
|
pocty.
|
||||||
|
- `extra_holidays` prida dny volna, `extra_workdays` udela z libovolneho dne
|
||||||
|
pracovni den a ma prednost.
|
||||||
|
- Kazdy kalendar pokryva jen urcity rozsah let (v GET /countries). Datum nebo
|
||||||
|
vysledek mimo nej vraci chybu `out_of_range`, sluzba nikdy nepocita
|
||||||
|
s chybejicimi svatky.
|
||||||
|
|
||||||
|
## Regiony
|
||||||
|
|
||||||
|
Nektere svatky plati jen v regionu, napriklad Bozi Telo v Bavorsku
|
||||||
|
(`country=DE®ion=BY`) nebo 26. prosinec v Alsasku a Mosele
|
||||||
|
(`country=FR®ion=57`). Bez regionu se pocitaji jen celostatni svatky.
|
||||||
|
|
||||||
|
## Financni kalendare
|
||||||
|
|
||||||
|
Parametr `market` nahradi zemi financnim kalendarem, napriklad `XECB` pro
|
||||||
|
platebni system TARGET2.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Cached settings are read once here so that a broken configuration stops the
|
||||||
|
# service at start instead of at the first request.
|
||||||
|
settings = get_settings()
|
||||||
|
setup_logging(settings.log_level)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
default = resolve_calendar("country", settings.default_country, None, None, settings.default_language)
|
||||||
|
holidays_in_year(default.spec, date.today().year)
|
||||||
|
logger.info(
|
||||||
|
"Service started",
|
||||||
|
extra={
|
||||||
|
"default_country": default.spec.code,
|
||||||
|
"language": default.spec.language,
|
||||||
|
"holidays_library": library_version(),
|
||||||
|
"root_path": settings.root_path,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
yield
|
||||||
|
logger.info("Service stopped")
|
||||||
|
|
||||||
APP_NAME = os.getenv("APP_NAME", "workdays")
|
|
||||||
APP_VERSION = os.getenv("APP_VERSION", "1.0.0")
|
|
||||||
ROOT_PATH = os.getenv("ROOT_PATH", "")
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title=APP_NAME,
|
title=settings.app_name,
|
||||||
version=APP_VERSION,
|
version=settings.app_version,
|
||||||
root_path=ROOT_PATH
|
description=DESCRIPTION,
|
||||||
|
root_path=settings.root_path,
|
||||||
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health():
|
|
||||||
return {"status": "ok"}
|
|
||||||
|
|
||||||
@app.get("/version")
|
@app.exception_handler(ServiceError)
|
||||||
def version():
|
async def service_error_handler(request: Request, exc: ServiceError) -> JSONResponse:
|
||||||
return {
|
logger.info(
|
||||||
"app": APP_NAME,
|
"Request rejected",
|
||||||
"version": APP_VERSION,
|
extra={"error_code": exc.error_code, "path": request.url.path, "status_code": exc.status_code},
|
||||||
"language": "python",
|
)
|
||||||
"root_path": ROOT_PATH
|
return JSONResponse(status_code=exc.status_code, content=exc.to_dict())
|
||||||
}
|
|
||||||
|
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
logger.exception("Unhandled error", extra={"path": request.url.path})
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=500,
|
||||||
|
content={"error_code": "internal_error", "message": "Doslo k neocekavane chybe sluzby."},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
app.include_router(health_router.router)
|
||||||
|
app.include_router(workdays_router.router)
|
||||||
|
app.include_router(holidays_router.router)
|
||||||
|
|||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
"""Response models. They are the single description of the API shape."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
Weekday = Literal["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarRef(BaseModel):
|
||||||
|
"""Kalendar, podle ktereho se pocitalo. Vraci se v kazde odpovedi."""
|
||||||
|
|
||||||
|
type: Literal["country", "market"]
|
||||||
|
code: str = Field(examples=["CZ"])
|
||||||
|
name: str = Field(examples=["Czechia"])
|
||||||
|
region: str | None = Field(default=None, examples=[None])
|
||||||
|
categories: list[str] = Field(examples=[["public"]])
|
||||||
|
language: str | None = Field(default=None, examples=["cs"])
|
||||||
|
weekend: list[Weekday] = Field(examples=[["sat", "sun"]])
|
||||||
|
|
||||||
|
|
||||||
|
class DayInfoModel(BaseModel):
|
||||||
|
"""Popis jednoho dne."""
|
||||||
|
|
||||||
|
date: date
|
||||||
|
weekday: Weekday
|
||||||
|
is_workday: bool
|
||||||
|
is_weekend: bool
|
||||||
|
holidays: list[str] = Field(description="Nazvy svatku v tento den, prazdne kdyz zadny neni.")
|
||||||
|
override: Literal["extra_holiday", "extra_workday"] | None = Field(
|
||||||
|
default=None,
|
||||||
|
description="Den zmeneny parametrem extra_holidays nebo extra_workdays.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AddWorkdaysResponse(BaseModel):
|
||||||
|
calendar: CalendarRef
|
||||||
|
date: date
|
||||||
|
days: int
|
||||||
|
result: date = Field(examples=["2026-12-01"])
|
||||||
|
skipped_holidays: list[DayInfoModel] = Field(
|
||||||
|
description="Svatky a dny volna mimo vikend, ktere vypocet preskocil."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DayResponse(DayInfoModel):
|
||||||
|
calendar: CalendarRef
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftResponse(BaseModel):
|
||||||
|
calendar: CalendarRef
|
||||||
|
date: date
|
||||||
|
result: date
|
||||||
|
|
||||||
|
|
||||||
|
class BetweenResponse(BaseModel):
|
||||||
|
calendar: CalendarRef
|
||||||
|
start: date
|
||||||
|
end: date
|
||||||
|
workdays: int = Field(description="Pocet pracovnich dnu, oba krajni dny vcetne.")
|
||||||
|
weekend_days: int
|
||||||
|
holidays_off: int = Field(description="Pocet svatku a dnu volna, ktere padly mimo vikend.")
|
||||||
|
holidays: list[DayInfoModel] = Field(description="Svatky a dny volna mimo vikend v intervalu.")
|
||||||
|
|
||||||
|
|
||||||
|
class HolidayItem(BaseModel):
|
||||||
|
date: date
|
||||||
|
weekday: Weekday
|
||||||
|
names: list[str]
|
||||||
|
is_weekend: bool
|
||||||
|
|
||||||
|
|
||||||
|
class HolidaysResponse(BaseModel):
|
||||||
|
calendar: CalendarRef
|
||||||
|
year: int
|
||||||
|
holidays: list[HolidayItem]
|
||||||
|
|
||||||
|
|
||||||
|
class RegionItem(BaseModel):
|
||||||
|
code: str
|
||||||
|
name: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class YearRange(BaseModel):
|
||||||
|
from_: int = Field(alias="from")
|
||||||
|
to: int
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarDescription(BaseModel):
|
||||||
|
code: str
|
||||||
|
name: str
|
||||||
|
eu: bool
|
||||||
|
regions: list[RegionItem]
|
||||||
|
categories: list[str]
|
||||||
|
languages: list[str]
|
||||||
|
default_language: str | None
|
||||||
|
years: YearRange
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarListResponse(BaseModel):
|
||||||
|
items: list[CalendarDescription]
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(BaseModel):
|
||||||
|
status: Literal["ok"]
|
||||||
|
app: str
|
||||||
|
version: str
|
||||||
|
holidays_library: str
|
||||||
|
default_country: str
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorResponse(BaseModel):
|
||||||
|
error_code: str
|
||||||
|
message: str
|
||||||
|
detail: dict | None = None
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Health and version endpoints required by AppFactory."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from ..config import get_settings
|
||||||
|
from ..models import HealthResponse
|
||||||
|
from ..services.calendars import library_version
|
||||||
|
|
||||||
|
router = APIRouter(tags=["service"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", response_model=HealthResponse, summary="Stav sluzby")
|
||||||
|
def health() -> HealthResponse:
|
||||||
|
settings = get_settings()
|
||||||
|
return HealthResponse(
|
||||||
|
status="ok",
|
||||||
|
app=settings.app_name,
|
||||||
|
version=settings.app_version,
|
||||||
|
holidays_library=library_version(),
|
||||||
|
default_country=settings.default_country,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/version", summary="Verze a zakladni informace o sluzbe")
|
||||||
|
def version() -> dict:
|
||||||
|
settings = get_settings()
|
||||||
|
return {
|
||||||
|
"app": settings.app_name,
|
||||||
|
"version": settings.app_version,
|
||||||
|
"language": "python",
|
||||||
|
"root_path": settings.root_path,
|
||||||
|
"holidays_library": library_version(),
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""Holiday lists and the catalogue of supported calendars."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
|
||||||
|
from ..errors import OutOfRangeError
|
||||||
|
from ..models import (
|
||||||
|
CalendarDescription,
|
||||||
|
CalendarListResponse,
|
||||||
|
ErrorResponse,
|
||||||
|
HolidayItem,
|
||||||
|
HolidaysResponse,
|
||||||
|
)
|
||||||
|
from ..services.calendars import holidays_in_year, list_countries, list_markets
|
||||||
|
from .params import ResolvedCalendar, calendar_params, weekday_name
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
tags=["holidays"],
|
||||||
|
responses={400: {"model": ErrorResponse, "description": "Neplatny vstup"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/holidays", response_model=HolidaysResponse, summary="Svatky v roce")
|
||||||
|
def holiday_list(
|
||||||
|
calendar: Annotated[ResolvedCalendar, Depends(calendar_params)],
|
||||||
|
year: Annotated[int | None, Query(description="Rok, vychozi je aktualni.", examples=[2026])] = None,
|
||||||
|
) -> HolidaysResponse:
|
||||||
|
"""Svatky kalendare v jednom roce. Parametry extra_holidays a extra_workdays se tu neuplatni."""
|
||||||
|
info = calendar.info
|
||||||
|
wanted = year if year is not None else date.today().year
|
||||||
|
if not info.min_date.year <= wanted <= info.max_date.year:
|
||||||
|
raise OutOfRangeError(
|
||||||
|
f"Rok {wanted} je mimo rozsah kalendare {info.min_date.year} az {info.max_date.year}.",
|
||||||
|
{"year": wanted, "min": info.min_date.year, "max": info.max_date.year},
|
||||||
|
)
|
||||||
|
weekend = calendar.calendar.weekend
|
||||||
|
items = [
|
||||||
|
HolidayItem(
|
||||||
|
date=day,
|
||||||
|
weekday=weekday_name(day),
|
||||||
|
names=list(names),
|
||||||
|
is_weekend=day.weekday() in weekend,
|
||||||
|
)
|
||||||
|
for day, names in holidays_in_year(info.spec, wanted).items()
|
||||||
|
]
|
||||||
|
return HolidaysResponse(calendar=calendar.ref(), year=wanted, holidays=items)
|
||||||
|
|
||||||
|
|
||||||
|
def _filtered(items: tuple[dict, ...], eu: bool) -> CalendarListResponse:
|
||||||
|
selected = [item for item in items if item["eu"]] if eu else list(items)
|
||||||
|
return CalendarListResponse(items=[CalendarDescription.model_validate(item) for item in selected])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/countries", response_model=CalendarListResponse, summary="Podporovane zeme")
|
||||||
|
def countries(
|
||||||
|
eu: Annotated[bool, Query(description="Jen clenske staty EU.")] = False,
|
||||||
|
) -> CalendarListResponse:
|
||||||
|
"""Zeme s regiony, kategoriemi svatku, jazyky a rozsahem let, ktere data pokryvaji."""
|
||||||
|
return _filtered(list_countries(), eu)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/markets", response_model=CalendarListResponse, summary="Podporovane financni kalendare")
|
||||||
|
def markets() -> CalendarListResponse:
|
||||||
|
"""Financni kalendare, napriklad XECB (TARGET2) nebo burzy."""
|
||||||
|
return _filtered(list_markets(), eu=False)
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""Query parameters shared by every calendar endpoint and their conversion."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Query
|
||||||
|
|
||||||
|
from ..config import get_settings
|
||||||
|
from ..errors import InvalidRequestError
|
||||||
|
from ..lib.dates import WEEKDAY_NAMES, parse_date_list, parse_weekend
|
||||||
|
from ..models import CalendarRef, DayInfoModel
|
||||||
|
from ..services.calendars import CalendarInfo, holidays_in_year, resolve_calendar
|
||||||
|
from ..services.workdays import DayInfo, WorkCalendar
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ResolvedCalendar:
|
||||||
|
info: CalendarInfo
|
||||||
|
calendar: WorkCalendar
|
||||||
|
|
||||||
|
def ref(self) -> CalendarRef:
|
||||||
|
spec = self.info.spec
|
||||||
|
return CalendarRef(
|
||||||
|
type=spec.kind,
|
||||||
|
code=spec.code,
|
||||||
|
name=self.info.name,
|
||||||
|
region=spec.region,
|
||||||
|
categories=list(spec.categories),
|
||||||
|
language=spec.language,
|
||||||
|
weekend=[WEEKDAY_NAMES[day] for day in sorted(self.calendar.weekend)],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _split(value: str | None) -> tuple[str, ...] | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
parts = tuple(part.strip() for part in value.split(",") if part.strip())
|
||||||
|
return parts or None
|
||||||
|
|
||||||
|
|
||||||
|
def calendar_params(
|
||||||
|
country: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Kod zeme ISO 3166, alpha-2 nebo alpha-3. Vychozi je DEFAULT_COUNTRY, tedy CZ.",
|
||||||
|
examples=["CZ"],
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
region: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Region zeme, kod nebo nazev, napriklad BY nebo Bayern pro Bavorsko. "
|
||||||
|
"Seznam je v GET /countries.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
market: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Financni kalendar misto zeme, napriklad XECB pro TARGET2 Evropske centralni banky. "
|
||||||
|
"Nelze kombinovat s country. Seznam je v GET /markets.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
categories: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Kategorie svatku oddelene carkou. Vychozi je public, tedy statni svatky. "
|
||||||
|
"Podporovane kategorie zeme jsou v GET /countries.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
language: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Jazyk nazvu svatku. Vychozi je DEFAULT_LANGUAGE, tedy cs. "
|
||||||
|
"Kdyz ho kalendar neumi, pouzije se jeho vlastni jazyk.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
weekend: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Vikendove dny oddelene carkou, napriklad sat,sun nebo so,ne. "
|
||||||
|
"Hodnota none znamena kalendar bez vikendu. Vychozi je vikend dane zeme.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
extra_holidays: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Dalsi dny volna oddelene carkou, napriklad firemni dovolena. "
|
||||||
|
"Datum ve formatu YYYY-MM-DD nebo D.M.YYYY.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
extra_workdays: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
description="Dny, ktere jsou pracovni i pres vikend nebo svatek, oddelene carkou. "
|
||||||
|
"Maji prednost pred extra_holidays.",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
) -> ResolvedCalendar:
|
||||||
|
if country and market:
|
||||||
|
raise InvalidRequestError(
|
||||||
|
"Parametry country a market nelze pouzit zaroven.",
|
||||||
|
{"country": country, "market": market},
|
||||||
|
)
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
if market:
|
||||||
|
info = resolve_calendar("market", market, region, _split(categories), language)
|
||||||
|
else:
|
||||||
|
info = resolve_calendar(
|
||||||
|
"country",
|
||||||
|
country or settings.default_country,
|
||||||
|
region,
|
||||||
|
_split(categories),
|
||||||
|
language or settings.default_language,
|
||||||
|
)
|
||||||
|
|
||||||
|
custom_weekend = parse_weekend(weekend)
|
||||||
|
spec = info.spec
|
||||||
|
calendar = WorkCalendar(
|
||||||
|
weekend=info.default_weekend if custom_weekend is None else custom_weekend,
|
||||||
|
min_date=info.min_date,
|
||||||
|
max_date=info.max_date,
|
||||||
|
holidays_in_year=lambda year: holidays_in_year(spec, year),
|
||||||
|
extra_holidays=parse_date_list(extra_holidays, "extra_holidays"),
|
||||||
|
extra_workdays=parse_date_list(extra_workdays, "extra_workdays"),
|
||||||
|
)
|
||||||
|
return ResolvedCalendar(info=info, calendar=calendar)
|
||||||
|
|
||||||
|
|
||||||
|
def day_model(info: DayInfo) -> DayInfoModel:
|
||||||
|
return DayInfoModel(
|
||||||
|
date=info.day,
|
||||||
|
weekday=WEEKDAY_NAMES[info.day.weekday()],
|
||||||
|
is_workday=info.is_workday,
|
||||||
|
is_weekend=info.is_weekend,
|
||||||
|
holidays=list(info.holidays),
|
||||||
|
override=info.override,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def weekday_name(day: date) -> str:
|
||||||
|
return WEEKDAY_NAMES[day.weekday()]
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""Workday operations."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
|
||||||
|
from ..lib.dates import parse_date
|
||||||
|
from ..models import AddWorkdaysResponse, BetweenResponse, DayResponse, ErrorResponse, ShiftResponse
|
||||||
|
from ..services.workdays import add_workdays, count_workdays, next_workday, previous_workday
|
||||||
|
from .params import ResolvedCalendar, calendar_params, day_model
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
prefix="/workdays",
|
||||||
|
tags=["workdays"],
|
||||||
|
responses={400: {"model": ErrorResponse, "description": "Neplatny vstup"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
DateParam = Annotated[
|
||||||
|
str,
|
||||||
|
Query(description="Datum ve formatu YYYY-MM-DD nebo D.M.YYYY.", examples=["2026-11-26"]),
|
||||||
|
]
|
||||||
|
IncludeStartParam = Annotated[
|
||||||
|
bool,
|
||||||
|
Query(description="Kdyz je vychozi den pracovni, vrati se on sam."),
|
||||||
|
]
|
||||||
|
Calendar = Annotated[ResolvedCalendar, Depends(calendar_params)]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/add", response_model=AddWorkdaysResponse, summary="Pricte pracovni dny")
|
||||||
|
def add(
|
||||||
|
date: DateParam,
|
||||||
|
days: Annotated[
|
||||||
|
int,
|
||||||
|
Query(description="Pocet pracovnich dnu. Zaporne cislo posouva zpet.", examples=[3]),
|
||||||
|
],
|
||||||
|
calendar: Calendar,
|
||||||
|
) -> AddWorkdaysResponse:
|
||||||
|
"""Posune datum o zadany pocet pracovnich dnu.
|
||||||
|
|
||||||
|
Vychozi den se nepocita. Ctvrtek 26.11.2026 plus 3 pracovni dny v CZ je
|
||||||
|
utery 1.12.2026. Pri `days=0` se vrati vychozi datum beze zmeny, i kdyz
|
||||||
|
neni pracovni.
|
||||||
|
"""
|
||||||
|
start = parse_date(date, "date")
|
||||||
|
outcome = add_workdays(calendar.calendar, start, days)
|
||||||
|
return AddWorkdaysResponse(
|
||||||
|
calendar=calendar.ref(),
|
||||||
|
date=start,
|
||||||
|
days=days,
|
||||||
|
result=outcome.result,
|
||||||
|
skipped_holidays=[day_model(info) for info in outcome.skipped],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/is-workday", response_model=DayResponse, summary="Je den pracovni")
|
||||||
|
def is_workday(date: DateParam, calendar: Calendar) -> DayResponse:
|
||||||
|
"""Popis dne: zda je pracovni, zda je vikend a jake svatky na nej pripadaji."""
|
||||||
|
day = parse_date(date, "date")
|
||||||
|
calendar.calendar.check_range(day, "date")
|
||||||
|
info = day_model(calendar.calendar.describe(day))
|
||||||
|
return DayResponse(calendar=calendar.ref(), **info.model_dump())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/next", response_model=ShiftResponse, summary="Nejblizsi dalsi pracovni den")
|
||||||
|
def next_day(date: DateParam, calendar: Calendar, include_start: IncludeStartParam = False) -> ShiftResponse:
|
||||||
|
start = parse_date(date, "date")
|
||||||
|
result = next_workday(calendar.calendar, start, include_start)
|
||||||
|
return ShiftResponse(calendar=calendar.ref(), date=start, result=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/previous", response_model=ShiftResponse, summary="Nejblizsi predchozi pracovni den")
|
||||||
|
def previous_day(
|
||||||
|
date: DateParam, calendar: Calendar, include_start: IncludeStartParam = False
|
||||||
|
) -> ShiftResponse:
|
||||||
|
start = parse_date(date, "date")
|
||||||
|
result = previous_workday(calendar.calendar, start, include_start)
|
||||||
|
return ShiftResponse(calendar=calendar.ref(), date=start, result=result)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/between", response_model=BetweenResponse, summary="Pocet pracovnich dnu v intervalu")
|
||||||
|
def between(
|
||||||
|
start: Annotated[str, Query(description="Prvni den intervalu.", examples=["2026-12-01"])],
|
||||||
|
end: Annotated[str, Query(description="Posledni den intervalu.", examples=["2026-12-31"])],
|
||||||
|
calendar: Calendar,
|
||||||
|
) -> BetweenResponse:
|
||||||
|
"""Spocita pracovni dny mezi dvema daty, oba krajni dny vcetne.
|
||||||
|
|
||||||
|
Kdyz je `start` po `end`, pocty vychazi zaporne, stejne jako NETWORKDAYS
|
||||||
|
v Excelu.
|
||||||
|
"""
|
||||||
|
first = parse_date(start, "start")
|
||||||
|
last = parse_date(end, "end")
|
||||||
|
outcome = count_workdays(calendar.calendar, first, last)
|
||||||
|
return BetweenResponse(
|
||||||
|
calendar=calendar.ref(),
|
||||||
|
start=first,
|
||||||
|
end=last,
|
||||||
|
workdays=outcome.workdays,
|
||||||
|
weekend_days=outcome.weekend_days,
|
||||||
|
holidays_off=len(outcome.holidays_off),
|
||||||
|
holidays=[day_model(info) for info in outcome.holidays_off],
|
||||||
|
)
|
||||||
@@ -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__)
|
||||||
@@ -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),
|
||||||
|
)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Dokumentace sluzby workdays
|
||||||
|
|
||||||
|
Sluzba pocita s pracovnimi dny podle vikendu a svatku dane zeme. Data svatku
|
||||||
|
dodava knihovna python-holidays, ktera pokryva vsech 27 zemi EU vcetne regionu,
|
||||||
|
dalsich zhruba 220 zemi a financni kalendare jako TARGET2.
|
||||||
|
|
||||||
|
## Obsah dokumentace
|
||||||
|
|
||||||
|
- [api.md](api.md) endpointy, parametry a pravidla vypoctu
|
||||||
|
- [architektura.md](architektura.md) struktura kodu a proc je udelana takhle
|
||||||
|
- [konfigurace.md](konfigurace.md) environment variables
|
||||||
|
- [zmeny.md](zmeny.md) zaznam zmen
|
||||||
|
|
||||||
|
## Aktualni stav
|
||||||
|
|
||||||
|
Verze 1.0.0, stav development.
|
||||||
|
|
||||||
|
Hotovo:
|
||||||
|
|
||||||
|
- pricteni a odecteni pracovnich dnu (`/workdays/add`)
|
||||||
|
- popis dne, zda je pracovni a jake svatky na nej pripadaji
|
||||||
|
- dalsi a predchozi pracovni den
|
||||||
|
- pocet pracovnich dnu v intervalu, oba konce vcetne
|
||||||
|
- seznam svatku v roce, seznam zemi a financnich kalendaru
|
||||||
|
- regiony (napriklad DE-BY, FR-57), kategorie svatku, jazyk nazvu
|
||||||
|
- vlastni vikend, vlastni dny volna a vlastni pracovni dny v requestu
|
||||||
|
- vychozi zeme CZ a cestina, nastavitelne pres promenne
|
||||||
|
- testy logiky, API a testy proti realnym kalendarum (CZ, DE, AT, FR, PL,
|
||||||
|
SK, TARGET2, fond pracovni doby CZ 2026)
|
||||||
|
|
||||||
|
Overeno lokalne testy pres TestClient (54 testu). Neovereno: build Docker
|
||||||
|
image a chovani za Caddy na `services.csbot.cz/apps/workdays`.
|
||||||
|
|
||||||
|
Neni hotovo a neni v zadani:
|
||||||
|
|
||||||
|
- autentizace, pristup resi reverse proxy
|
||||||
|
- davkovy endpoint pro vice vypoctu v jednom requestu
|
||||||
|
- pracovni dny s casem (hodiny, casova pasma)
|
||||||
|
|
||||||
|
## Zname vlastnosti
|
||||||
|
|
||||||
|
- Kalendar pokryva jen roky, ktere zna knihovna (u CZ 1952 az 2100). Mimo
|
||||||
|
rozsah sluzba vraci `out_of_range`, aby nikdy nepocitala s chybejicimi
|
||||||
|
svatky. Tim je zaroven omezena delka vypoctu.
|
||||||
|
- Nektere svatky plati jen v casti regionu. Treba Nanebevzeti Panny Marie
|
||||||
|
v Bavorsku je v kategorii `catholic`, ne `public`, protoze plati jen
|
||||||
|
v obcich s prevahou katoliku.
|
||||||
|
- Svatky se meni zakonem. Aktualnost dat zavisi na verzi knihovny `holidays`,
|
||||||
|
proto je dobre ji pravidelne zvysovat a pak spustit testy proti realite.
|
||||||
|
|
||||||
|
## Dalsi krok
|
||||||
|
|
||||||
|
Nasadit pres AppFactory a overit `/health`, `/docs` a Swagger Try it out
|
||||||
|
pres `/apps/workdays`.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# API
|
||||||
|
|
||||||
|
Vsechny cesty jsou relativni. Verejne se volaji s prefixem `/apps/workdays`,
|
||||||
|
ktery Caddy pred predanim do containeru odstranuje. Vsechny endpointy jsou GET
|
||||||
|
a vraci JSON.
|
||||||
|
|
||||||
|
## Spolecne parametry kalendare
|
||||||
|
|
||||||
|
Plati pro `/workdays/*` a `/holidays`.
|
||||||
|
|
||||||
|
| Parametr | Vychozi | Vyznam |
|
||||||
|
|---|---|---|
|
||||||
|
| `country` | `DEFAULT_COUNTRY` (CZ) | kod zeme ISO 3166, alpha-2 i alpha-3, velikost pismen nevadi |
|
||||||
|
| `region` | zadny | kod nebo nazev regionu, napriklad `BY` nebo `Bayern` |
|
||||||
|
| `market` | zadny | financni kalendar misto zeme, napriklad `XECB`; s `country` nelze kombinovat |
|
||||||
|
| `categories` | `public` | kategorie svatku oddelene carkou, napriklad `public,catholic` |
|
||||||
|
| `language` | `DEFAULT_LANGUAGE` (cs) | jazyk nazvu; `en` najde `en_US`, neznamy jazyk se nahradi jazykem zeme |
|
||||||
|
| `weekend` | vikend zeme | dny oddelene carkou: `mon..sun` nebo `po,ut,st,ct,pa,so,ne`; `none` je bez vikendu |
|
||||||
|
| `extra_holidays` | zadne | dalsi dny volna oddelene carkou |
|
||||||
|
| `extra_workdays` | zadne | dny, ktere jsou pracovni i pres vikend nebo svatek; maji prednost |
|
||||||
|
|
||||||
|
Data se zadavaji jako `YYYY-MM-DD` nebo `D.M.YYYY`, vraci se vzdy `YYYY-MM-DD`.
|
||||||
|
|
||||||
|
Kazda odpoved obsahuje blok `calendar`, podle ktereho se skutecne pocitalo
|
||||||
|
(zeme, region, kategorie, pouzity jazyk, vikend).
|
||||||
|
|
||||||
|
## GET /workdays/add
|
||||||
|
|
||||||
|
Parametry `date`, `days`.
|
||||||
|
|
||||||
|
Vychozi den se nepocita. Zaporne `days` posouva zpet. `days=0` vrati vychozi
|
||||||
|
den beze zmeny, i kdyz neni pracovni, stejne jako WORKDAY v Excelu. Kdyz
|
||||||
|
vychozi den neni pracovni a `days=1`, vysledkem je nejblizsi pracovni den.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"calendar": {"type": "country", "code": "CZ", "name": "Czechia", "region": null,
|
||||||
|
"categories": ["public"], "language": "cs", "weekend": ["sat", "sun"]},
|
||||||
|
"date": "2026-12-23",
|
||||||
|
"days": 1,
|
||||||
|
"result": "2026-12-28",
|
||||||
|
"skipped_holidays": [
|
||||||
|
{"date": "2026-12-24", "weekday": "thu", "is_workday": false, "is_weekend": false,
|
||||||
|
"holidays": ["Štědrý den"], "override": null},
|
||||||
|
{"date": "2026-12-25", "weekday": "fri", "is_workday": false, "is_weekend": false,
|
||||||
|
"holidays": ["1. svátek vánoční"], "override": null}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`skipped_holidays` obsahuje jen dny volna mimo vikend, bezne soboty a nedele
|
||||||
|
v nem nejsou.
|
||||||
|
|
||||||
|
## GET /workdays/is-workday
|
||||||
|
|
||||||
|
Parametr `date`. Vraci popis dne: `is_workday`, `is_weekend`, `holidays`
|
||||||
|
(nazvy svatku, i kdyz padnou na vikend) a `override`, pokud den zmenil
|
||||||
|
parametr `extra_holidays` nebo `extra_workdays`.
|
||||||
|
|
||||||
|
## GET /workdays/next a GET /workdays/previous
|
||||||
|
|
||||||
|
Parametry `date` a `include_start` (vychozi `false`). Nejblizsi pracovni den po
|
||||||
|
nebo pred datem. S `include_start=true` se vrati vychozi den, kdyz je pracovni.
|
||||||
|
|
||||||
|
## GET /workdays/between
|
||||||
|
|
||||||
|
Parametry `start`, `end`. Pocet pracovnich dnu, oba krajni dny vcetne. Vraci
|
||||||
|
`workdays`, `weekend_days`, `holidays_off` (pocet dnu volna mimo vikend)
|
||||||
|
a jejich seznam `holidays`. Kdyz je `start` po `end`, pocty jsou zaporne,
|
||||||
|
stejne jako NETWORKDAYS v Excelu.
|
||||||
|
|
||||||
|
## GET /holidays
|
||||||
|
|
||||||
|
Parametr `year`, vychozi aktualni rok. Svatky kalendare v roce, u kazdeho datum,
|
||||||
|
den v tydnu, nazvy a priznak `is_weekend`. `extra_holidays` a `extra_workdays`
|
||||||
|
se tu neuplatni.
|
||||||
|
|
||||||
|
## GET /countries a GET /markets
|
||||||
|
|
||||||
|
Seznam kalendaru s regiony, kategoriemi, jazyky a rozsahem let. `/countries`
|
||||||
|
ma parametr `eu=true` pro zeme EU. Prvni volani trva dele, sestavuje se seznam
|
||||||
|
vsech zemi, pak je v pameti.
|
||||||
|
|
||||||
|
## GET /health a GET /version
|
||||||
|
|
||||||
|
`/health` vraci `status`, verzi sluzby, verzi knihovny `holidays` a vychozi
|
||||||
|
zemi.
|
||||||
|
|
||||||
|
## Chyby
|
||||||
|
|
||||||
|
HTTP 400 s telem napriklad `{"error_code": "unknown_country", "message": "Zeme 'XX' neni podporovana. Seznam je na GET /countries.", "detail": {"country": "XX"}}`.
|
||||||
|
|
||||||
|
| error_code | Kdy |
|
||||||
|
|---|---|
|
||||||
|
| `invalid_date` | spatny format nebo neexistujici datum |
|
||||||
|
| `invalid_request` | `country` spolu s `market`, spatny `weekend` |
|
||||||
|
| `unknown_country` | zeme neni podporovana |
|
||||||
|
| `unknown_market` | financni kalendar neni podporovany |
|
||||||
|
| `unknown_region` | zeme takovy region nema, `detail.supported` je seznam |
|
||||||
|
| `unknown_category` | kategorie neni podporovana, `detail.supported` je seznam |
|
||||||
|
| `out_of_range` | datum nebo vysledek mimo roky, ktere kalendar pokryva |
|
||||||
|
|
||||||
|
Chybejici nebo necitelny `days` ci `year` vraci standardni HTTP 422 z FastAPI.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Architektura
|
||||||
|
|
||||||
|
## Struktura projektu
|
||||||
|
|
||||||
|
```text
|
||||||
|
app/
|
||||||
|
main.py vytvoreni aplikace, popis pro Swagger, obsluha chyb
|
||||||
|
config.py konfigurace z environment variables
|
||||||
|
models.py Pydantic modely odpovedi
|
||||||
|
errors.py typove chyby s error_code
|
||||||
|
logging_setup.py JSON logovani
|
||||||
|
lib/
|
||||||
|
dates.py parsovani data, seznamu dat a vikendu
|
||||||
|
services/
|
||||||
|
calendars.py jediny pristup ke knihovne holidays, cache po rocich
|
||||||
|
workdays.py ciste funkce nad WorkCalendar: add, next, previous, count
|
||||||
|
routers/
|
||||||
|
params.py spolecne parametry kalendare, sestaveni WorkCalendar
|
||||||
|
workdays.py /workdays/*
|
||||||
|
holidays.py /holidays, /countries, /markets
|
||||||
|
health.py /health, /version
|
||||||
|
tests/
|
||||||
|
test_workdays.py logika nad rucne sestavenym kalendarem
|
||||||
|
test_reality.py porovnani s realnymi kalendari, zdroje v hlavicce
|
||||||
|
test_api.py HTTP vrstva, chyby, prefix proxy v OpenAPI
|
||||||
|
```
|
||||||
|
|
||||||
|
## Proc je to udelane takhle
|
||||||
|
|
||||||
|
- **Knihovna je jen v `services/calendars.py`.** Logika v `services/workdays.py`
|
||||||
|
dostava svatky jako funkci `rok -> {datum: nazvy}`. Zdroj dat jde vymenit
|
||||||
|
a logika se testuje bez knihovny.
|
||||||
|
- **Cache po rocich.** Svatky jednoho kalendare v jednom roce se spocitaji
|
||||||
|
jednou a drzi v `lru_cache` (4096 polozek). Vypocet je pak jen vyhledani
|
||||||
|
v dict, odpoved trva zlomky milisekundy.
|
||||||
|
- **Krokovani po dnech.** Jednoduche a zrejme spravne. Delku omezuje rozsah let
|
||||||
|
kalendare, nejhorsi pripad je par set tisic kroku.
|
||||||
|
- **Rozsah let z knihovny, ne vlastni limit.** Mimo `start_year` az
|
||||||
|
`end_year` knihovna vraci prazdny seznam svatku, coz by tise dalo spatny
|
||||||
|
vysledek. Proto `out_of_range`.
|
||||||
|
- **Region podle kodu i nazvu, bez ohledu na velikost pismen.** Knihovna sama
|
||||||
|
bere jen presny kod.
|
||||||
|
- **Vychozi kategorie `public`.** Jen statni svatky, ktere jsou dnem volna.
|
||||||
|
Ostatni kategorie (napriklad bank, catholic, school) si klient vyzada.
|
||||||
|
- **Datum i v ceskem tvaru.** `D.M.YYYY` se prijima, protoze se tak v CZ pise.
|
||||||
|
Vystup je vzdy ISO.
|
||||||
|
|
||||||
|
## Odchylky od obecnych zasad
|
||||||
|
|
||||||
|
Struktura drzi sablonu AppFactory a sousedni sluzbu `html-to-pdf`
|
||||||
|
(`app/` misto src layoutu, `requirements.txt` misto `pyproject.toml` a `uv`).
|
||||||
|
Dockerfile ze sablony se nemenil.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Konfigurace
|
||||||
|
|
||||||
|
Vsechno se cte z environment variables v `app/config.py`. AppFactory je predava
|
||||||
|
pres vygenerovany runtime `.env`. Zadna promenna neni povinna.
|
||||||
|
|
||||||
|
| Promenna | Vychozi | Vyznam |
|
||||||
|
|---|---|---|
|
||||||
|
| `APP_NAME` | `workdays` | nazev v dokumentaci a v /version |
|
||||||
|
| `APP_VERSION` | `1.0.0` | verze |
|
||||||
|
| `ROOT_PATH` | prazdne | prefix reverse proxy, napriklad `/apps/workdays` |
|
||||||
|
| `BASE_PATH` | prazdne | pouzije se, kdyz `ROOT_PATH` neni nastavene |
|
||||||
|
| `LOG_LEVEL` | `INFO` | uroven logovani |
|
||||||
|
| `DEFAULT_COUNTRY` | `CZ` | zeme, kdyz request neuvede `country` ani `market` |
|
||||||
|
| `DEFAULT_LANGUAGE` | `cs` | preferovany jazyk nazvu svatku |
|
||||||
|
|
||||||
|
Neplatna `DEFAULT_COUNTRY` zastavi sluzbu pri startu, ne az pri prvnim
|
||||||
|
requestu.
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Zaznam zmen
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
Prvni verze.
|
||||||
|
|
||||||
|
- endpointy `/workdays/add`, `/workdays/is-workday`, `/workdays/next`,
|
||||||
|
`/workdays/previous`, `/workdays/between`, `/holidays`, `/countries`,
|
||||||
|
`/markets`, `/health`, `/version`
|
||||||
|
- data svatku z knihovny `holidays` 0.109
|
||||||
|
- vychozi zeme CZ a cestina
|
||||||
|
- testy logiky, API a testy proti realnym kalendarum
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[pytest]
|
||||||
|
pythonpath = .
|
||||||
|
testpaths = tests
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest~=8.3
|
||||||
|
httpx~=0.28
|
||||||
+4
-2
@@ -1,2 +1,4 @@
|
|||||||
fastapi
|
fastapi~=0.115
|
||||||
uvicorn[standard]
|
uvicorn[standard]~=0.34
|
||||||
|
pydantic~=2.9
|
||||||
|
holidays~=0.109
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""HTTP layer: parameters, responses, errors and the reverse proxy prefix."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client():
|
||||||
|
with TestClient(app) as test_client:
|
||||||
|
yield test_client
|
||||||
|
|
||||||
|
|
||||||
|
def test_health(client):
|
||||||
|
response = client.get("/health")
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert body["status"] == "ok"
|
||||||
|
assert body["default_country"] == "CZ"
|
||||||
|
|
||||||
|
|
||||||
|
def test_docs(client):
|
||||||
|
assert client.get("/docs").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_openapi_servers_use_proxy_prefix():
|
||||||
|
with TestClient(app, root_path="/apps/workdays") as proxied:
|
||||||
|
schema = proxied.get("/openapi.json").json()
|
||||||
|
assert schema["servers"][0]["url"] == "/apps/workdays"
|
||||||
|
assert "/workdays/add" in schema["paths"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_defaults_to_cz(client):
|
||||||
|
body = client.get("/workdays/add", params={"date": "26.11.2026", "days": 3}).json()
|
||||||
|
assert body["result"] == "2026-12-01"
|
||||||
|
assert body["calendar"]["code"] == "CZ"
|
||||||
|
assert body["calendar"]["language"] == "cs"
|
||||||
|
assert body["calendar"]["weekend"] == ["sat", "sun"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_lists_skipped_holidays(client):
|
||||||
|
body = client.get("/workdays/add", params={"date": "2026-12-23", "days": 1}).json()
|
||||||
|
assert body["result"] == "2026-12-28"
|
||||||
|
assert [item["date"] for item in body["skipped_holidays"]] == ["2026-12-24", "2026-12-25"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_with_extra_days(client):
|
||||||
|
body = client.get(
|
||||||
|
"/workdays/add",
|
||||||
|
params={"date": "2026-11-26", "days": 1, "extra_holidays": "2026-11-27", "extra_workdays": "28.11.2026"},
|
||||||
|
).json()
|
||||||
|
assert body["result"] == "2026-11-28"
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_workday(client):
|
||||||
|
body = client.get("/workdays/is-workday", params={"date": "2026-12-24"}).json()
|
||||||
|
assert body["is_workday"] is False
|
||||||
|
assert body["holidays"] == ["Štědrý den"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_language_falls_back_to_country_default(client):
|
||||||
|
body = client.get("/workdays/is-workday", params={"date": "2026-10-03", "country": "DE"}).json()
|
||||||
|
assert body["calendar"]["language"] == "de"
|
||||||
|
assert body["holidays"] == ["Tag der Deutschen Einheit"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_language_variant_match(client):
|
||||||
|
body = client.get("/workdays/is-workday", params={"date": "2026-12-24", "language": "en"}).json()
|
||||||
|
assert body["calendar"]["language"] == "en_US"
|
||||||
|
|
||||||
|
|
||||||
|
def test_region_and_market(client):
|
||||||
|
body = client.get("/workdays/is-workday", params={"date": "2026-06-04", "country": "de", "region": "by"}).json()
|
||||||
|
assert body["is_workday"] is False
|
||||||
|
assert body["calendar"]["region"] == "BY"
|
||||||
|
|
||||||
|
body = client.get("/workdays/next", params={"date": "2026-04-02", "market": "XECB"}).json()
|
||||||
|
assert body["result"] == "2026-04-07"
|
||||||
|
assert body["calendar"]["type"] == "market"
|
||||||
|
|
||||||
|
|
||||||
|
def test_between(client):
|
||||||
|
body = client.get("/workdays/between", params={"start": "2026-12-01", "end": "2026-12-31"}).json()
|
||||||
|
assert body["workdays"] == 21
|
||||||
|
assert body["holidays_off"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_holidays_list(client):
|
||||||
|
body = client.get("/holidays", params={"year": 2026}).json()
|
||||||
|
assert len(body["holidays"]) == 13
|
||||||
|
christmas = next(item for item in body["holidays"] if item["date"] == "2026-12-26")
|
||||||
|
assert christmas["is_weekend"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_countries_eu_filter(client):
|
||||||
|
items = client.get("/countries", params={"eu": True}).json()["items"]
|
||||||
|
assert len(items) == 27
|
||||||
|
germany = next(item for item in items if item["code"] == "DE")
|
||||||
|
assert {"code": "BY", "name": "Bayern"} in germany["regions"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_markets(client):
|
||||||
|
items = client.get("/markets").json()["items"]
|
||||||
|
assert any(item["code"] == "XECB" for item in items)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("params", "error_code"),
|
||||||
|
[
|
||||||
|
({"date": "2026-13-01", "days": 1}, "invalid_date"),
|
||||||
|
({"date": "zitra", "days": 1}, "invalid_date"),
|
||||||
|
({"date": "2026-11-26", "days": 1, "country": "XX"}, "unknown_country"),
|
||||||
|
({"date": "2026-11-26", "days": 1, "country": "DE", "region": "ZZ"}, "unknown_region"),
|
||||||
|
({"date": "2026-11-26", "days": 1, "categories": "foo"}, "unknown_category"),
|
||||||
|
({"date": "2026-11-26", "days": 1, "country": "CZ", "market": "XECB"}, "invalid_request"),
|
||||||
|
({"date": "2026-11-26", "days": 1, "weekend": "mon,tue,wed,thu,fri,sat,sun"}, "invalid_request"),
|
||||||
|
({"date": "1900-01-01", "days": 1}, "out_of_range"),
|
||||||
|
({"date": "2100-12-30", "days": 5}, "out_of_range"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_errors(client, params, error_code):
|
||||||
|
response = client.get("/workdays/add", params=params)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["error_code"] == error_code
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""Results compared with real calendars.
|
||||||
|
|
||||||
|
Every expected value below comes from a source outside this service, mostly
|
||||||
|
the law that defines the holidays. When a test here fails after a library
|
||||||
|
update, check the source first: the law may have changed, not the code.
|
||||||
|
|
||||||
|
Sources:
|
||||||
|
- CZ: zakon c. 245/2000 Sb., o statnich svatcich, ve zneni od roku 2016
|
||||||
|
(Velky patek). Fond pracovni doby 2026 je 250 dnu.
|
||||||
|
- DE: Feiertagsgesetze der Lander, Bayern: Fronleichnam celostatne v BY,
|
||||||
|
Maria Himmelfahrt jen v obcich s prevahou katoliku.
|
||||||
|
- AT: Feiertagsruhegesetz 1957.
|
||||||
|
- FR: Code du travail L3133-1, Alsasko a Mosela navic Vendredi saint a 26.12.
|
||||||
|
- PL: ustawa o dniach wolnych od pracy, Wigilia 24.12 od roku 2025.
|
||||||
|
- SK: zakon c. 241/1993 Z. z.
|
||||||
|
- XECB: kalendar TARGET2 Evropske centralni banky.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from app.services.calendars import holidays_in_year, resolve_calendar
|
||||||
|
from app.services.workdays import WorkCalendar, add_workdays, count_workdays
|
||||||
|
|
||||||
|
|
||||||
|
def calendar_for(kind="country", code="CZ", region=None, categories=None, language="cs") -> WorkCalendar:
|
||||||
|
info = resolve_calendar(kind, code, region, categories, language)
|
||||||
|
return WorkCalendar(
|
||||||
|
weekend=info.default_weekend,
|
||||||
|
min_date=info.min_date,
|
||||||
|
max_date=info.max_date,
|
||||||
|
holidays_in_year=lambda year: holidays_in_year(info.spec, year),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def holiday_dates(kind="country", code="CZ", region=None, categories=None, year=2026) -> set[date]:
|
||||||
|
info = resolve_calendar(kind, code, region, categories, None)
|
||||||
|
return set(holidays_in_year(info.spec, year))
|
||||||
|
|
||||||
|
|
||||||
|
# Czechia
|
||||||
|
|
||||||
|
|
||||||
|
CZ_2026 = {
|
||||||
|
date(2026, 1, 1),
|
||||||
|
date(2026, 4, 3),
|
||||||
|
date(2026, 4, 6),
|
||||||
|
date(2026, 5, 1),
|
||||||
|
date(2026, 5, 8),
|
||||||
|
date(2026, 7, 5),
|
||||||
|
date(2026, 7, 6),
|
||||||
|
date(2026, 9, 28),
|
||||||
|
date(2026, 10, 28),
|
||||||
|
date(2026, 11, 17),
|
||||||
|
date(2026, 12, 24),
|
||||||
|
date(2026, 12, 25),
|
||||||
|
date(2026, 12, 26),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_2026_holidays_exactly_match_law():
|
||||||
|
assert holiday_dates(code="CZ", year=2026) == CZ_2026
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_2027_easter():
|
||||||
|
dates = holiday_dates(code="CZ", year=2027)
|
||||||
|
assert date(2027, 3, 26) in dates
|
||||||
|
assert date(2027, 3, 29) in dates
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_working_time_fund_2026():
|
||||||
|
calendar = calendar_for()
|
||||||
|
assert count_workdays(calendar, date(2026, 1, 1), date(2026, 12, 31)).workdays == 250
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_example_from_assignment():
|
||||||
|
assert add_workdays(calendar_for(), date(2026, 11, 26), 3).result == date(2026, 12, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_over_christmas():
|
||||||
|
assert add_workdays(calendar_for(), date(2026, 12, 23), 1).result == date(2026, 12, 28)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_over_easter():
|
||||||
|
assert add_workdays(calendar_for(), date(2026, 4, 2), 1).result == date(2026, 4, 7)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_backwards_over_may_holidays():
|
||||||
|
assert add_workdays(calendar_for(), date(2026, 5, 11), -1).result == date(2026, 5, 7)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cz_names_in_czech():
|
||||||
|
info = resolve_calendar("country", "CZ", None, None, "cs")
|
||||||
|
names = holidays_in_year(info.spec, 2026)[date(2026, 12, 24)]
|
||||||
|
assert names == ("Štědrý den",)
|
||||||
|
|
||||||
|
|
||||||
|
# Germany
|
||||||
|
|
||||||
|
|
||||||
|
def test_de_corpus_christi_only_in_region():
|
||||||
|
assert date(2026, 6, 4) not in holiday_dates(code="DE")
|
||||||
|
assert date(2026, 6, 4) in holiday_dates(code="DE", region="BY")
|
||||||
|
|
||||||
|
|
||||||
|
def test_de_region_by_name():
|
||||||
|
assert date(2026, 6, 4) in holiday_dates(code="DE", region="Bayern")
|
||||||
|
|
||||||
|
|
||||||
|
def test_de_assumption_is_catholic_category_in_bavaria():
|
||||||
|
assert date(2026, 8, 15) not in holiday_dates(code="DE", region="BY")
|
||||||
|
assert date(2026, 8, 15) in holiday_dates(code="DE", region="BY", categories=("public", "catholic"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_de_unity_day():
|
||||||
|
assert date(2026, 10, 3) in holiday_dates(code="DE")
|
||||||
|
|
||||||
|
|
||||||
|
# Other EU countries
|
||||||
|
|
||||||
|
|
||||||
|
def test_at_national_day_and_immaculate_conception():
|
||||||
|
dates = holiday_dates(code="AT")
|
||||||
|
assert date(2026, 10, 26) in dates
|
||||||
|
assert date(2026, 12, 8) in dates
|
||||||
|
|
||||||
|
|
||||||
|
def test_fr_alsace_moselle():
|
||||||
|
assert date(2026, 12, 26) not in holiday_dates(code="FR")
|
||||||
|
assert date(2026, 12, 26) in holiday_dates(code="FR", region="57")
|
||||||
|
assert date(2026, 4, 3) in holiday_dates(code="FR", region="57")
|
||||||
|
|
||||||
|
|
||||||
|
def test_pl_christmas_eve_since_2025():
|
||||||
|
assert date(2024, 12, 24) not in holiday_dates(code="PL", year=2024)
|
||||||
|
assert date(2026, 12, 24) in holiday_dates(code="PL", year=2026)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sk_constitution_and_uprising():
|
||||||
|
dates = holiday_dates(code="SK")
|
||||||
|
assert date(2026, 8, 29) in dates
|
||||||
|
assert date(2026, 7, 5) in dates
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_eu_country_has_holidays_in_2026():
|
||||||
|
from app.services.calendars import EU_MEMBERS
|
||||||
|
|
||||||
|
for code in EU_MEMBERS:
|
||||||
|
assert len(holiday_dates(code=code)) >= 8, code
|
||||||
|
|
||||||
|
|
||||||
|
# Financial calendar
|
||||||
|
|
||||||
|
|
||||||
|
def test_target2_2026():
|
||||||
|
assert holiday_dates(kind="market", code="XECB") == {
|
||||||
|
date(2026, 1, 1),
|
||||||
|
date(2026, 4, 3),
|
||||||
|
date(2026, 4, 6),
|
||||||
|
date(2026, 5, 1),
|
||||||
|
date(2026, 12, 25),
|
||||||
|
date(2026, 12, 26),
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""Workday arithmetic over a hand made calendar, independent of the holiday library."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.errors import OutOfRangeError
|
||||||
|
from app.services.workdays import (
|
||||||
|
WorkCalendar,
|
||||||
|
add_workdays,
|
||||||
|
count_workdays,
|
||||||
|
next_workday,
|
||||||
|
previous_workday,
|
||||||
|
)
|
||||||
|
|
||||||
|
# November and December 2026, a single fictional holiday on Friday 27.11.
|
||||||
|
HOLIDAYS = {date(2026, 11, 27): ("Testovaci svatek",)}
|
||||||
|
|
||||||
|
|
||||||
|
def make_calendar(**overrides) -> WorkCalendar:
|
||||||
|
params = {
|
||||||
|
"weekend": frozenset({5, 6}),
|
||||||
|
"min_date": date(2026, 1, 1),
|
||||||
|
"max_date": date(2026, 12, 31),
|
||||||
|
"holidays_in_year": lambda year: HOLIDAYS,
|
||||||
|
}
|
||||||
|
params.update(overrides)
|
||||||
|
return WorkCalendar(**params)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_skips_weekend_and_holiday():
|
||||||
|
outcome = add_workdays(make_calendar(), date(2026, 11, 26), 1)
|
||||||
|
assert outcome.result == date(2026, 11, 30)
|
||||||
|
assert [info.day for info in outcome.skipped] == [date(2026, 11, 27)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_zero_returns_start_even_on_weekend():
|
||||||
|
assert add_workdays(make_calendar(), date(2026, 11, 28), 0).result == date(2026, 11, 28)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_from_weekend_counts_from_next_workday():
|
||||||
|
assert add_workdays(make_calendar(), date(2026, 11, 28), 1).result == date(2026, 11, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_negative_moves_back():
|
||||||
|
assert add_workdays(make_calendar(), date(2026, 11, 30), -1).result == date(2026, 11, 26)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_and_subtract_are_symmetric_between_workdays():
|
||||||
|
calendar = make_calendar()
|
||||||
|
forward = add_workdays(calendar, date(2026, 11, 2), 17).result
|
||||||
|
assert add_workdays(calendar, forward, -17).result == date(2026, 11, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_extra_holiday_and_extra_workday():
|
||||||
|
calendar = make_calendar(
|
||||||
|
extra_holidays=frozenset({date(2026, 11, 30)}),
|
||||||
|
extra_workdays=frozenset({date(2026, 11, 28)}),
|
||||||
|
)
|
||||||
|
assert add_workdays(calendar, date(2026, 11, 26), 1).result == date(2026, 11, 28)
|
||||||
|
assert add_workdays(calendar, date(2026, 11, 26), 2).result == date(2026, 12, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_extra_workday_wins_over_holiday():
|
||||||
|
calendar = make_calendar(extra_workdays=frozenset({date(2026, 11, 27)}))
|
||||||
|
info = calendar.describe(date(2026, 11, 27))
|
||||||
|
assert info.is_workday is True
|
||||||
|
assert info.override == "extra_workday"
|
||||||
|
assert info.holidays == ("Testovaci svatek",)
|
||||||
|
|
||||||
|
|
||||||
|
def test_custom_weekend():
|
||||||
|
calendar = make_calendar(weekend=frozenset({4, 5}))
|
||||||
|
assert calendar.is_workday(date(2026, 11, 29)) is True
|
||||||
|
assert calendar.is_workday(date(2026, 11, 28)) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_and_previous():
|
||||||
|
calendar = make_calendar()
|
||||||
|
assert next_workday(calendar, date(2026, 11, 26)) == date(2026, 11, 30)
|
||||||
|
assert next_workday(calendar, date(2026, 11, 26), include_start=True) == date(2026, 11, 26)
|
||||||
|
assert next_workday(calendar, date(2026, 11, 28), include_start=True) == date(2026, 11, 30)
|
||||||
|
assert previous_workday(calendar, date(2026, 11, 30)) == date(2026, 11, 26)
|
||||||
|
|
||||||
|
|
||||||
|
def test_count_inclusive_and_signed():
|
||||||
|
calendar = make_calendar()
|
||||||
|
outcome = count_workdays(calendar, date(2026, 11, 23), date(2026, 11, 29))
|
||||||
|
assert outcome.workdays == 4
|
||||||
|
assert outcome.weekend_days == 2
|
||||||
|
assert [info.day for info in outcome.holidays_off] == [date(2026, 11, 27)]
|
||||||
|
|
||||||
|
reverse = count_workdays(calendar, date(2026, 11, 29), date(2026, 11, 23))
|
||||||
|
assert reverse.workdays == -4
|
||||||
|
assert reverse.weekend_days == -2
|
||||||
|
|
||||||
|
|
||||||
|
def test_count_single_day():
|
||||||
|
assert count_workdays(make_calendar(), date(2026, 11, 26), date(2026, 11, 26)).workdays == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_range_start():
|
||||||
|
with pytest.raises(OutOfRangeError):
|
||||||
|
add_workdays(make_calendar(), date(2025, 12, 31), 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_out_of_range_result():
|
||||||
|
with pytest.raises(OutOfRangeError):
|
||||||
|
add_workdays(make_calendar(), date(2026, 12, 30), 5)
|
||||||
Reference in New Issue
Block a user