Files
nifodea/infrastructure/cli/commands/config/rates.py
T
oqyude ebcc78be3a D37: обновление курсов валют из сети (ЦБ РФ)
- infrastructure/rates/cbr.py — загрузка ежедневных курсов ЦБ РФ
  (XML, windows-1251) и разбор их в пары X → RUB; разбор вынесен в
  чистую функцию, поэтому тестируется без сети;
- cf config rate-refresh [--dry-run] — обновляет курсы в модели: пары
  X → RUB обновляются, остальные (например, EUR → USD) не трогаются,
  неизменившиеся курсы перечисляются отдельно;
- нет сети или битый ответ — понятное сообщение, модель не меняется.

Тесты: 333 → 342 (tests/test_rates.py: разбор XML, применение курсов).
2026-11-15 06:15:21 +03:00

110 lines
4.3 KiB
Python

"""`cf config rate-*` — курсы валют: добавление, список, удаление."""
from decimal import Decimal
import typer
from pydantic import ValidationError
from rich.table import Table
from domain import ExchangeRate
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()
def rate_set(
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
rate: float = typer.Argument(..., help=t("cmd.config.rate_set.arg.rate")),
) -> None:
"""Добавить или обновить курс валюты"""
model = load_model()
fc, tc = from_currency.upper(), to_currency.upper()
# Курс пишем Decimal: поле объявлено как Decimal, а float в него класть
# нельзя (D17).
rate_value = Decimal(str(rate))
existing = [r for r in model.exchange_rates if r.from_currency == fc and r.to_currency == tc]
try:
if existing:
existing[0].rate = rate_value
else:
model.exchange_rates.append(
ExchangeRate(
from_currency=fc,
to_currency=tc,
rate=rate_value,
)
)
except ValidationError as e:
# Отрицательный или нулевой курс отклоняет валидатор модели —
# показываем понятное сообщение вместо traceback (D17).
fail_validation(e)
save_model(model)
print_ok(t("cmd.config.rate_set.ok", fc=fc, tc=tc, rate=rate_value))
@app.command(name="rate-list")
def rate_list() -> None:
"""Список курсов валют"""
model = load_model()
if not model.exchange_rates:
print_warning(t("cmd.config.rate_list.empty"))
return
table = Table(title=t("table.rates.title"))
table.add_column(t("table.rates.col.from"), style="cyan")
table.add_column(t("table.rates.col.to"), style="cyan")
table.add_column(t("table.rates.col.rate"), justify="right")
for r in model.exchange_rates:
table.add_row(r.from_currency, r.to_currency, str(r.rate))
console.print(table)
@app.command(name="rate-remove")
def rate_remove(
from_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.from")),
to_currency: str = typer.Argument(..., help=t("cmd.config.rate_set.arg.to")),
) -> None:
"""Удалить курс валюты"""
model = load_model()
fc, tc = from_currency.upper(), to_currency.upper()
initial = len(model.exchange_rates)
model.exchange_rates = [r for r in model.exchange_rates if not (r.from_currency == fc and r.to_currency == tc)]
if len(model.exchange_rates) < initial:
save_model(model)
print_ok(t("cmd.config.rate_remove.ok", fc=fc, tc=tc))
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)))