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,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
|
||||
from fastapi import FastAPI
|
||||
"""Service entry point.
|
||||
|
||||
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(
|
||||
title=APP_NAME,
|
||||
version=APP_VERSION,
|
||||
root_path=ROOT_PATH
|
||||
title=settings.app_name,
|
||||
version=settings.app_version,
|
||||
description=DESCRIPTION,
|
||||
root_path=settings.root_path,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/version")
|
||||
def version():
|
||||
return {
|
||||
"app": APP_NAME,
|
||||
"version": APP_VERSION,
|
||||
"language": "python",
|
||||
"root_path": ROOT_PATH
|
||||
}
|
||||
@app.exception_handler(ServiceError)
|
||||
async def service_error_handler(request: Request, exc: ServiceError) -> JSONResponse:
|
||||
logger.info(
|
||||
"Request rejected",
|
||||
extra={"error_code": exc.error_code, "path": request.url.path, "status_code": exc.status_code},
|
||||
)
|
||||
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),
|
||||
)
|
||||
Reference in New Issue
Block a user