diff --git a/infrastructure/cli/commands/config/rates.py b/infrastructure/cli/commands/config/rates.py index 32f057e..b977eed 100644 --- a/infrastructure/cli/commands/config/rates.py +++ b/infrastructure/cli/commands/config/rates.py @@ -11,6 +11,7 @@ from infrastructure.cli.commands.config._app import app from infrastructure.cli.commands.config._helpers import print_error, print_ok, print_warning from infrastructure.cli.services import console, fail_validation, load_model, save_model from infrastructure.i18n import t +from infrastructure.rates import RatesError, apply_rates, fetch_cbr_rates @app.command() @@ -77,3 +78,32 @@ def rate_remove( else: print_error(t("cmd.config.rate_remove.err", fc=fc, tc=tc)) raise typer.Exit(1) + + +@app.command(name="rate-refresh") +def rate_refresh( + dry_run: bool = typer.Option(False, "--dry-run", help=t("cmd.config.rate_refresh.opt.dry_run")), +) -> None: + """Обновить курсы валют из сети (ЦБ РФ)""" + model = load_model() + try: + snapshot = fetch_cbr_rates() + except RatesError as e: + print_error(t("cmd.config.rate_refresh.err", error=str(e))) + raise typer.Exit(1) + + report = apply_rates(model, snapshot) + console.print(t("cmd.config.rate_refresh.date", date=snapshot.date or "—")) + for line in report["added"]: + console.print(t("cmd.config.rate_refresh.added", pair=line)) + for line in report["updated"]: + console.print(t("cmd.config.rate_refresh.updated", pair=line)) + if report["unchanged"]: + console.print(t("cmd.config.rate_refresh.unchanged", count=len(report["unchanged"]))) + + if dry_run: + console.print(f"[yellow]{t('cmd.config.rate_refresh.dry_run')}[/yellow]") + return + + save_model(model) + print_ok(t("cmd.config.rate_refresh.ok", count=len(snapshot.rates))) diff --git a/infrastructure/i18n/ru.py b/infrastructure/i18n/ru.py index 6312639..d633041 100644 --- a/infrastructure/i18n/ru.py +++ b/infrastructure/i18n/ru.py @@ -142,6 +142,15 @@ MESSAGES: dict[str, str] = { "cmd.config.rate_remove.help": "Удалить курс валюты", "cmd.config.rate_remove.ok": "Курс {fc} → {tc} удалён", "cmd.config.rate_remove.err": "Курс {fc} → {tc} не найден", + "cmd.config.rate_refresh.help": "Обновить курсы валют из сети (ЦБ РФ)", + "cmd.config.rate_refresh.opt.dry_run": "Только показать, без записи в модель", + "cmd.config.rate_refresh.date": "Курсы ЦБ РФ на {date}", + "cmd.config.rate_refresh.added": "Добавлен курс: {pair}", + "cmd.config.rate_refresh.updated": "Обновлён курс: {pair}", + "cmd.config.rate_refresh.unchanged": "Без изменений: {count} курсов", + "cmd.config.rate_refresh.dry_run": "Курсы в модель не записаны (--dry-run)", + "cmd.config.rate_refresh.ok": "Курсов обновлено: {count}", + "cmd.config.rate_refresh.err": "Не удалось обновить курсы: {error}", "cmd.config.account_add.help": "Добавить счёт", "cmd.config.account_add.opt.name": "Название счёта", "cmd.config.account_add.opt.balance": "Начальный баланс", diff --git a/infrastructure/rates/__init__.py b/infrastructure/rates/__init__.py new file mode 100644 index 0000000..937a41d --- /dev/null +++ b/infrastructure/rates/__init__.py @@ -0,0 +1,19 @@ +"""Источники курсов валют из сети.""" + +from infrastructure.rates.cbr import ( + CBR_URL, + RatesError, + RatesSnapshot, + apply_rates, + fetch_cbr_rates, + parse_cbr_xml, +) + +__all__ = [ + "CBR_URL", + "RatesError", + "RatesSnapshot", + "apply_rates", + "fetch_cbr_rates", + "parse_cbr_xml", +] diff --git a/infrastructure/rates/cbr.py b/infrastructure/rates/cbr.py new file mode 100644 index 0000000..b7d2d75 --- /dev/null +++ b/infrastructure/rates/cbr.py @@ -0,0 +1,112 @@ +"""Загрузка курсов валют из сети ЦБ РФ (D37). + +Источник — ежедневные курсы Центробанка: +https://www.cbr.ru/scripts/XML_daily.asp (XML в кодировке windows-1251). + +Курсы, которые ЦБ публикует, — это «сколько рублей стоит единица валюты». +В модели они хранятся как пары ``X → RUB``, поэтому импорт обновляет именно +такие пары, а курсы между другими валютами (например, EUR → USD) не трогает. +""" + +from __future__ import annotations + +import urllib.error +import urllib.request +from dataclasses import dataclass +from decimal import Decimal +from xml.etree import ElementTree + +from domain import ExchangeRate + +CBR_URL = "https://www.cbr.ru/scripts/XML_daily.asp" +CBR_ENCODING = "windows-1251" +DEFAULT_TIMEOUT = 15 + + +class RatesError(Exception): + """Курсы не удалось получить (нет сети, битый ответ, пустой список).""" + + +@dataclass(frozen=True) +class RatesSnapshot: + """Набор курсов на одну дату.""" + + date: str + rates: tuple[ExchangeRate, ...] + + +def parse_cbr_xml(payload: bytes) -> RatesSnapshot: + """Разобрать XML ЦБ РФ. Бросает ``RatesError`` при негодном ответе.""" + try: + root = ElementTree.fromstring(payload.decode(CBR_ENCODING)) + except (ElementTree.ParseError, UnicodeDecodeError) as exc: + raise RatesError(f"не удалось разобрать ответ ЦБ РФ: {exc}") from exc + + date = root.get("Date", "") + rates: list[ExchangeRate] = [] + for valute in root.findall("Valute"): + code = (valute.findtext("CharCode") or "").strip().upper() + unit_rate = (valute.findtext("VunitRate") or valute.findtext("Value") or "").strip() + if not code or not unit_rate: + continue + if code == "RUB": + continue + try: + # VunitRate — курс за единицу валюты; Nominal в нём уже учтён. + rate = Decimal(unit_rate.replace(",", ".")) + except ArithmeticError as exc: + raise RatesError(f"некорректный курс для {code}: {unit_rate}") from exc + if rate <= 0: + continue + rates.append(ExchangeRate(from_currency=code, to_currency="RUB", rate=rate)) + + if not rates: + raise RatesError("ЦБ РФ вернул пустой список курсов") + return RatesSnapshot(date=date, rates=tuple(rates)) + + +def fetch_cbr_rates(url: str = CBR_URL, timeout: int = DEFAULT_TIMEOUT) -> RatesSnapshot: + """Скачать и разобрать курсы ЦБ РФ.""" + request = urllib.request.Request(url, headers={"User-Agent": "cashflow-forecast/1.0"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + payload = response.read() + except (urllib.error.URLError, OSError) as exc: + raise RatesError(f"не удалось получить курсы с {url}: {exc}") from exc + return parse_cbr_xml(payload) + + +def apply_rates(model, snapshot: RatesSnapshot) -> dict[str, list[str]]: + """Обновить курсы модели по снимку. Возвращает отчёт об изменениях. + + Курсы ``X → RUB`` заменяются, остальные пары (например, ``EUR → USD``) + остаются нетронутыми. Курс, который не изменился, в отчёт не попадает. + """ + updated: list[str] = [] + added: list[str] = [] + unchanged: list[str] = [] + + by_pair = {(r.from_currency, r.to_currency): r for r in model.exchange_rates} + for rate in snapshot.rates: + key = (rate.from_currency, rate.to_currency) + existing = by_pair.get(key) + if existing is None: + model.exchange_rates.append(rate) + added.append(f"{rate.from_currency} → {rate.to_currency} = {rate.rate}") + elif existing.rate != rate.rate: + existing.rate = rate.rate + updated.append(f"{rate.from_currency} → {rate.to_currency} = {rate.rate}") + else: + unchanged.append(f"{rate.from_currency} → {rate.to_currency}") + + return {"added": added, "updated": updated, "unchanged": unchanged} + + +__all__ = [ + "CBR_URL", + "RatesError", + "RatesSnapshot", + "apply_rates", + "fetch_cbr_rates", + "parse_cbr_xml", +] diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index ea39c4f..77dcede 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -40,6 +40,7 @@ EXPECTED_CONFIG_COMMANDS = { "rate-set", "rate-list", "rate-remove", + "rate-refresh", "account-add", "account-list", "account-remove", @@ -104,6 +105,7 @@ EXPECTED_CONFIG_PARAMS = { ("from_currency", ("from_currency",), None, True), ("to_currency", ("to_currency",), None, True), ], + "rate-refresh": [("dry_run", ("--dry-run",), False, False)], "account-add": [ ("name", ("--name", "-n"), None, True), ("balance", ("--balance", "-b"), 0.0, False), diff --git a/tests/test_rates.py b/tests/test_rates.py new file mode 100644 index 0000000..5e1f9e5 --- /dev/null +++ b/tests/test_rates.py @@ -0,0 +1,124 @@ +"""Тесты обновления курсов валют из сети (D37).""" + +from decimal import Decimal + +import pytest + +from domain import ExchangeRate, FinancialModel +from infrastructure.rates import RatesError, RatesSnapshot, apply_rates, parse_cbr_xml + +# Обрезанный ответ ЦБ РФ (в реальности — windows-1251). +_CBR_XML = """ + + + 840 + USD + 1 + Доллар США + 82,1516 + 82,1516 + + + 978 + EUR + 1 + Евро + 91,0322 + 91,0322 + + + 156 + CNY + 10 + Китайских юаней + 112,6667 + 11,26667 + + + 810 + RUB + 1 + Российский рубль + 1 + 1 + + +""" + + +class TestParseCbrXml: + def test_parses_rates(self): + snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251")) + assert snapshot.date == "14.11.2026" + codes = [rate.from_currency for rate in snapshot.rates] + assert codes == ["USD", "EUR", "CNY"] + + def test_rate_is_per_unit(self): + snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251")) + cny = next(rate for rate in snapshot.rates if rate.from_currency == "CNY") + # CNY публикуется за 10 юаней, VunitRate — за единицу. + assert cny.rate == Decimal("11.26667") + assert cny.to_currency == "RUB" + + def test_russian_rouble_is_skipped(self): + snapshot = parse_cbr_xml(_CBR_XML.encode("windows-1251")) + assert "RUB" not in [rate.from_currency for rate in snapshot.rates] + + def test_broken_xml_raises(self): + with pytest.raises(RatesError): + parse_cbr_xml(b"") + + def test_empty_list_raises(self): + payload = '' + with pytest.raises(RatesError): + parse_cbr_xml(payload.encode("windows-1251")) + + +class TestApplyRates: + def test_adds_new_rates(self): + model = FinancialModel() + snapshot = RatesSnapshot( + date="14.11.2026", + rates=(ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("91.03")),), + ) + report = apply_rates(model, snapshot) + assert len(report["added"]) == 1 + assert any(rate.from_currency == "EUR" for rate in model.exchange_rates) + + def test_updates_existing_rate(self): + model = FinancialModel( + exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))] + ) + snapshot = RatesSnapshot( + date="14.11.2026", + rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),), + ) + report = apply_rates(model, snapshot) + assert len(report["updated"]) == 1 + assert model.exchange_rates[0].rate == Decimal("82.15") + + def test_keeps_other_pairs(self): + model = FinancialModel( + exchange_rates=[ExchangeRate(from_currency="EUR", to_currency="USD", rate=Decimal("1.1"))] + ) + snapshot = RatesSnapshot( + date="14.11.2026", + rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),), + ) + apply_rates(model, snapshot) + pairs = {(r.from_currency, r.to_currency) for r in model.exchange_rates} + assert ("EUR", "USD") in pairs + assert ("USD", "RUB") in pairs + + def test_unchanged_rate_is_reported_separately(self): + model = FinancialModel( + exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15"))] + ) + snapshot = RatesSnapshot( + date="14.11.2026", + rates=(ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("82.15")),), + ) + report = apply_rates(model, snapshot) + assert report["unchanged"] == ["USD → RUB"] + assert not report["updated"] + assert not report["added"]