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.
This commit is contained in:
1 parent
120ef4ee76
commit
7e83deb22f
11 files changed
+146
-27
No files matched your search
@@ -1,12 +1,13 @@
|
||||
"""`cf config account-*` — счета: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Account, CurrencyConverter
|
||||
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, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@@ -19,7 +20,10 @@ def account_add(
|
||||
"""Добавить счёт"""
|
||||
model = load_model()
|
||||
curr = currency.upper() if currency else model.base_currency
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
try:
|
||||
account = Account(name=name, balance=balance, currency=curr)
|
||||
except ValidationError as e:
|
||||
fail_validation(e)
|
||||
model.accounts.append(account)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.account_add.ok", name=name, balance=balance, currency=curr))
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""`cf config asset-*` — активы: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import Asset, CurrencyConverter
|
||||
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, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@@ -18,7 +19,10 @@ def asset_add(
|
||||
) -> None:
|
||||
"""Добавить актив"""
|
||||
model = load_model()
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
try:
|
||||
asset = Asset(name=name, value=value, growth_rate=growth_rate)
|
||||
except ValidationError as e:
|
||||
fail_validation(e)
|
||||
model.assets.append(asset)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.asset_add.ok", name=name, value=value))
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""`cf config liability-*` — обязательства: добавление, список, удаление."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter, Liability
|
||||
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, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@@ -19,7 +20,10 @@ def liability_add(
|
||||
) -> None:
|
||||
"""Добавить обязательство"""
|
||||
model = load_model()
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
try:
|
||||
liability = Liability(name=name, balance=balance, interest=interest, payment=payment)
|
||||
except ValidationError as e:
|
||||
fail_validation(e)
|
||||
model.liabilities.append(liability)
|
||||
save_model(model)
|
||||
print_ok(t("cmd.config.liability_add.ok", name=name, balance=balance))
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""`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, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@@ -20,13 +21,16 @@ def recurring_add(
|
||||
) -> None:
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
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)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""`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, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
from infrastructure.i18n import t
|
||||
|
||||
|
||||
@@ -24,13 +25,16 @@ def transaction_add(
|
||||
if not account_id:
|
||||
print_error(t("cmd.config.transaction_add.err", account=account))
|
||||
raise typer.Exit(1)
|
||||
txn = Transaction(
|
||||
date=date or "",
|
||||
account=account_id,
|
||||
category=category,
|
||||
amount=amount,
|
||||
description=description,
|
||||
)
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user