diff --git a/infrastructure/cli/commands/config/accounts.py b/infrastructure/cli/commands/config/accounts.py index 98ba48a..059a6f8 100644 --- a/infrastructure/cli/commands/config/accounts.py +++ b/infrastructure/cli/commands/config/accounts.py @@ -6,7 +6,7 @@ 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.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 @@ -53,6 +53,23 @@ def account_remove( ) -> None: """Удалить счёт по ID или названию""" model = load_model() + account = next((a for a in model.accounts if str(a.id) == identifier or a.name == identifier), None) + if account is not None: + # M1: удаление счёта оставляло транзакции и регулярные платежи + # висячими ссылками — прогноз молча пропускал их. Отказываем, пока + # пользователь не удалит или не переназначит ссылки. + transactions = sum(1 for t in model.transactions if _refers_to_account(account, t.account)) + recurring = sum(1 for r in model.recurring if _refers_to_account(account, r.account)) + if transactions or recurring: + print_error( + t( + "cmd.config.account_remove.in_use", + id=identifier, + transactions=transactions, + recurring=recurring, + ) + ) + raise typer.Exit(1) remove_items( model, "accounts", @@ -61,3 +78,11 @@ def account_remove( ok_key="cmd.config.account_remove.ok", err_key="cmd.config.account_remove.err", ) + + +def _refers_to_account(account: Account, reference: str) -> bool: + """Ссылается ли строка на счёт — по UUID или имени (как в прогнозе).""" + value = (reference or "").strip() + if not value: + return False + return value == str(account.id) or value.casefold() == account.name.strip().casefold() diff --git a/infrastructure/i18n/ru.py b/infrastructure/i18n/ru.py index 109e1c5..c99e152 100644 --- a/infrastructure/i18n/ru.py +++ b/infrastructure/i18n/ru.py @@ -162,6 +162,8 @@ MESSAGES: dict[str, str] = { "cmd.config.account_remove.arg": "ID или название счёта", "cmd.config.account_remove.ok": "Счёт '{id}' удалён", "cmd.config.account_remove.err": "Счёт '{id}' не найден", + "cmd.config.account_remove.in_use": "Счёт '{id}' используется: транзакции — {transactions}, " + "регулярные платежи — {recurring}. Удалите или переназначьте их и повторите", "cmd.config.transaction_add.help": "Добавить транзакцию", "cmd.config.transaction_add.opt.account": "ID или название счёта", "cmd.config.transaction_add.opt.amount": "Сумма (доход/расход)", diff --git a/tests/test_cli.py b/tests/test_cli.py index 970a152..5a60cf2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -70,6 +70,25 @@ class TestCli: lst2 = runner.invoke(app, ["config", "account-list"]) assert "Тестовый" not in lst2.stdout + def test_account_remove_refuses_while_transactions_reference_it(self): + import json + + runner.invoke(app, ["init"]) + runner.invoke(app, ["config", "account-add", "--name", "A"]) + model_path = Path("data") / "model.json" + runner.invoke(app, ["config", "transaction-add", "--account", "A", "--amount", "100"]) + + result = runner.invoke(app, ["config", "account-remove", "A"]) + assert result.exit_code == 1 + assert "используется" in result.stdout + assert len(json.loads(model_path.read_text(encoding="utf-8"))["accounts"]) == 1 + + transaction_id = json.loads(model_path.read_text(encoding="utf-8"))["transactions"][0]["id"] + runner.invoke(app, ["config", "transaction-remove", transaction_id]) + result = runner.invoke(app, ["config", "account-remove", "A"]) + assert result.exit_code == 0 + assert json.loads(model_path.read_text(encoding="utf-8"))["accounts"] == [] + def test_config_transaction_crud(self): runner.invoke(app, ["init"]) runner.invoke(app, ["config", "account-add", "--name", "Счёт", "--balance", "0"])