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.
111 lines
4.2 KiB
Python
111 lines
4.2 KiB
Python
"""`cf config transaction-*` — транзакции: добавление, список, удаление."""
|
|
|
|
import typer
|
|
from pydantic import ValidationError
|
|
from rich.table import Table
|
|
|
|
from domain import CurrencyConverter, Transaction
|
|
from infrastructure.cli.commands.config._app import app
|
|
from infrastructure.cli.commands.config._helpers import print_error, 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 transaction_add(
|
|
account: str = typer.Option(..., "--account", "-a", help=t("cmd.config.transaction_add.opt.account")),
|
|
amount: float = typer.Option(..., "--amount", "-m", help=t("cmd.config.transaction_add.opt.amount")),
|
|
category: str = typer.Option("", "--category", "-c", help=t("cmd.config.transaction_add.opt.category")),
|
|
description: str = typer.Option("", "--description", "-d", help=t("cmd.config.transaction_add.opt.description")),
|
|
date: str = typer.Option("", "--date", "-D", help=t("cmd.config.transaction_add.opt.date")),
|
|
) -> None:
|
|
"""Добавить транзакцию"""
|
|
model = load_model()
|
|
account_id = _resolve_account_id(model, account)
|
|
if not account_id:
|
|
print_error(t("cmd.config.transaction_add.err", account=account))
|
|
raise typer.Exit(1)
|
|
try:
|
|
txn = Transaction(
|
|
date=date or "",
|
|
account=account_id,
|
|
category=category,
|
|
amount=amount,
|
|
description=description,
|
|
)
|
|
except ValidationError as e:
|
|
fail_validation(e)
|
|
model.transactions.append(txn)
|
|
save_model(model)
|
|
kind = t("cmd.config.transaction_add.kind.income") if amount >= 0 else t("cmd.config.transaction_add.kind.expense")
|
|
amount_str = CurrencyConverter.format_money(abs(amount), _account_currency(model, account_id))
|
|
print_ok(t("cmd.config.transaction_add.ok", kind=kind, amount_str=amount_str, account=account))
|
|
|
|
|
|
@app.command(name="transaction-list")
|
|
def transaction_list() -> None:
|
|
"""Список транзакций"""
|
|
model = load_model()
|
|
if not model.transactions:
|
|
print_warning(t("cmd.config.transaction_list.empty"))
|
|
return
|
|
table = Table(title=t("table.transactions.title"))
|
|
table.add_column(t("table.accounts_config.col.id"), style="dim")
|
|
table.add_column(t("table.transactions.col.date"))
|
|
table.add_column(t("table.accounts_config.col.name"))
|
|
table.add_column(t("table.transactions.col.category"))
|
|
table.add_column(t("table.transactions.col.amount"), justify="right")
|
|
table.add_column(t("table.transactions.col.description"))
|
|
for tx in model.transactions:
|
|
account_name = _account_name(model, tx.account)
|
|
amount_str = CurrencyConverter.format_money(tx.amount, _account_currency(model, tx.account))
|
|
table.add_row(
|
|
str(tx.id)[:8],
|
|
tx.date,
|
|
account_name,
|
|
tx.category,
|
|
amount_str,
|
|
tx.description,
|
|
)
|
|
console.print(table)
|
|
|
|
|
|
@app.command(name="transaction-remove")
|
|
def transaction_remove(
|
|
identifier: str = typer.Argument(..., help=t("cmd.config.transaction_remove.arg")),
|
|
) -> None:
|
|
"""Удалить транзакцию по ID"""
|
|
model = load_model()
|
|
remove_items(
|
|
model,
|
|
"transactions",
|
|
lambda tx: str(tx.id) == identifier,
|
|
identifier=identifier,
|
|
ok_key="cmd.config.transaction_remove.ok",
|
|
err_key="cmd.config.transaction_remove.err",
|
|
)
|
|
|
|
|
|
# ── helpers ────────────────────────────────────────────────────
|
|
|
|
|
|
def _resolve_account_id(model, identifier: str) -> str | None:
|
|
for a in model.accounts:
|
|
if str(a.id) == identifier or a.name == identifier:
|
|
return str(a.id)
|
|
return None
|
|
|
|
|
|
def _account_name(model, account_id: str) -> str:
|
|
for a in model.accounts:
|
|
if str(a.id) == account_id:
|
|
return a.name
|
|
return account_id[:8]
|
|
|
|
|
|
def _account_currency(model, account_id: str) -> str:
|
|
for a in model.accounts:
|
|
if str(a.id) == account_id:
|
|
return a.currency
|
|
return model.base_currency
|