"""Shared building blocks of the source parsers.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from zoneinfo import ZoneInfo import httpx from app.models import Origin, ParsedRates, Rate # Dividing by the quoted amount (for example 100 JPY) must not lose precision # on small per-unit prices, while float noise from the division is rounded away. RATE_DECIMALS = 6 # Czech banks state validity in local time, some sources send it as a UTC timestamp. PRAGUE_ZONE = ZoneInfo("Europe/Prague") @dataclass(frozen=True) class Source: id: str name: str url: str # Pure function of the downloaded document. Raises ValueError when the format changed. parse: Callable[[str], ParsedRates] # When set, the source is requested with POST and this JSON body instead of GET. request_json: dict[str, Any] | None = None # When set, replaces the single request, for sources that need several of them. fetch: Callable[[httpx.AsyncClient], Awaitable[str]] | None = None # Shown in the API documentation when consumers should know something about the source. note: str | None = None def parse_comma_decimal(value: str) -> float: return float(value.replace(",", ".")) def make_rate( currency: str, amount: int, buy: float, sell: float, middle: float | None = None, buy_sell_origin: Origin = "fetched", ) -> Rate: """Converts source prices to the universal form: per 1 unit, middle always present.""" quoted_middle = middle if middle is not None else (buy + sell) / 2 return Rate( currency=currency, buy=round(buy / amount, RATE_DECIMALS), sell=round(sell / amount, RATE_DECIMALS), middle=round(quoted_middle / amount, RATE_DECIMALS), buy_sell_origin=buy_sell_origin, middle_origin="fetched" if middle is not None else "computed", )