Files
nifodea/infrastructure/cli/commands/config/rates.py
T

80 lines
3.2 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
@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)