Files
oqyude 7e83deb22f fix(cli,storage): обработка ошибок и атомарное сохранение модели (R5–R8)
R5 (Н5). `config account-add/transaction-add/recurring-add/asset-add/
liability-add` больше не роняют необработанный pydantic ValidationError:
создание модели обёрнуто в try/except → `fail_validation`, поэтому
пользователь видит русское сообщение и код 1 вместо traceback.

R6 (Н6). `convert_value` ловит CurrencyError: `cf forecast --currency EUR`
без курса печатает «Нет курса RUB → EUR — обновите курсы: cf config
rate-refresh» и завершается с кодом 1, а не rich-трейсбеком.

R7 (Н9). `JsonFileRepository.save` пишет во временный файл рядом,
сбрасывает на диск и подменяет через `os.replace`; итоговый `model.json`
получает права 0600. Обрыв записи больше не оставляет обрезанный файл.

R8 (Н9). `save_model` хранит два поколения: `.bak` — состояние до
текущей записи, `.bak.1` — поколение до него; оба с правами 0600.

Тесты: +10 (5 команд/ошибок ввода, отсутствие курса, права файла,
ротация бэкапов). Значения прогноза не менялись.

Refs: review/2026-11-29-review.md §3 Н5, Н6, Н9, §6 R5–R8.
2026-12-01 21:13:58 +03:00

75 lines
3.0 KiB
Python

"""`cf config recurring-*` — регулярные платежи: добавление, список, удаление."""
import typer
from pydantic import ValidationError
from rich.table import Table
from domain import CurrencyConverter, RecurringCashflow
from infrastructure.cli.commands.config._app import app
from infrastructure.cli.commands.config._helpers import print_ok, print_warning, remove_items
from infrastructure.cli.services import console, fail_validation, load_model, save_model
from infrastructure.i18n import t
@app.command()
def recurring_add(
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.recurring_add.opt.amount")),
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.recurring_add.opt.category")),
frequency: str = typer.Option("monthly", "--frequency", "-f", help=t("cmd.config.recurring_add.opt.frequency")),
start_date: str = typer.Option("", "--start", "-s", help=t("cmd.config.recurring_add.opt.start")),
end_date: str = typer.Option("", "--end", "-e", help=t("cmd.config.recurring_add.opt.end")),
) -> None:
"""Добавить регулярный платёж"""
model = load_model()
try:
rc = RecurringCashflow(
start_date=start_date or "",
end_date=end_date or "",
frequency=frequency,
amount=amount,
category=category,
)
except ValidationError as e:
fail_validation(e)
model.recurring.append(rc)
save_model(model)
amount_str = CurrencyConverter.format_money(abs(amount), model.base_currency)
print_ok(t("cmd.config.recurring_add.ok", amount_str=amount_str, frequency=frequency))
@app.command(name="recurring-list")
def recurring_list() -> None:
"""Список регулярных платежей"""
model = load_model()
if not model.recurring:
print_warning(t("cmd.config.recurring_list.empty"))
return
table = Table(title=t("table.recurring.title"))
table.add_column(t("table.recurring.col.id"), style="dim")
table.add_column(t("table.recurring.col.start"))
table.add_column(t("table.recurring.col.end"))
table.add_column(t("table.recurring.col.period"))
table.add_column(t("table.recurring.col.amount"), justify="right")
table.add_column(t("table.recurring.col.category"))
for r in model.recurring:
amount_str = CurrencyConverter.format_money(r.amount, model.base_currency)
row = (str(r.id)[:8], r.start_date, r.end_date, r.frequency, amount_str, r.category)
table.add_row(*row)
console.print(table)
@app.command(name="recurring-remove")
def recurring_remove(
identifier: str = typer.Argument(..., help=t("cmd.config.recurring_remove.arg")),
) -> None:
"""Удалить регулярный платёж по ID"""
model = load_model()
remove_items(
model,
"recurring",
lambda r: str(r.id) == identifier,
identifier=identifier,
ok_key="cmd.config.recurring_remove.ok",
err_key="cmd.config.recurring_remove.err",
)