diff --git a/infrastructure/cli/commands/config/accounts.py b/infrastructure/cli/commands/config/accounts.py index abc79d6..98ba48a 100644 --- a/infrastructure/cli/commands/config/accounts.py +++ b/infrastructure/cli/commands/config/accounts.py @@ -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)) diff --git a/infrastructure/cli/commands/config/assets.py b/infrastructure/cli/commands/config/assets.py index 37888a1..653bb85 100644 --- a/infrastructure/cli/commands/config/assets.py +++ b/infrastructure/cli/commands/config/assets.py @@ -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)) diff --git a/infrastructure/cli/commands/config/liabilities.py b/infrastructure/cli/commands/config/liabilities.py index c018382..0d6360f 100644 --- a/infrastructure/cli/commands/config/liabilities.py +++ b/infrastructure/cli/commands/config/liabilities.py @@ -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)) diff --git a/infrastructure/cli/commands/config/recurring.py b/infrastructure/cli/commands/config/recurring.py index 398d6a9..a73f529 100644 --- a/infrastructure/cli/commands/config/recurring.py +++ b/infrastructure/cli/commands/config/recurring.py @@ -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) diff --git a/infrastructure/cli/commands/config/transactions.py b/infrastructure/cli/commands/config/transactions.py index e52fd71..1a37dcc 100644 --- a/infrastructure/cli/commands/config/transactions.py +++ b/infrastructure/cli/commands/config/transactions.py @@ -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") diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index dc34bbf..d3a1d8f 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import shutil from decimal import Decimal from typing import NoReturn @@ -13,6 +14,7 @@ from rich.console import Console from application.forecast import ForecastService from application.scenarios import ScenarioService from domain import CurrencyConverter, FinancialModel +from domain.currency import CurrencyError from infrastructure.ai.assistant import AssistantService from infrastructure.cli.paths import AppPaths from infrastructure.i18n import t @@ -56,16 +58,23 @@ def load_model() -> FinancialModel: def save_model(model: FinancialModel) -> None: - """Сохранить модель. Прежний файл остаётся рядом как `.bak` (D35). + """Сохранить модель. Прежние поколения остаются рядом как `.bak` (D35). + `.bak` — состояние до этой записи, `.bak.1` — поколение до него (R8): + после двух команд подряд есть куда откатиться на две версии назад. Импорт из Excel заменяет модель целиком — если файл оказался не тем, - прежнее состояние можно вернуть одной командой копирования. + прежнее состояние можно вернуть копированием. """ model_path = AppPaths.from_env().model_path if model_path.exists(): backup_path = model_path.with_suffix(model_path.suffix + ".bak") + previous_path = model_path.with_suffix(model_path.suffix + ".bak.1") try: + if backup_path.exists(): + shutil.copy2(backup_path, previous_path) + os.chmod(previous_path, 0o600) shutil.copy2(model_path, backup_path) + os.chmod(backup_path, 0o600) console.print(f"[dim]{t('cmd.import.backup', path=backup_path)}[/dim]") except OSError as exc: console.print(f"[yellow]{t('cmd.import.backup_failed', error=exc)}[/yellow]") @@ -102,9 +111,14 @@ def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal: + """Перевести сумму для вывода. Нет курса — сообщение вместо traceback (Н6).""" if to_curr == from_curr: return amount - return converter.convert(amount, from_curr, to_curr) + try: + return converter.convert(amount, from_curr, to_curr) + except CurrencyError: + console.print(f"[red]{t('global.no_rate', from_currency=from_curr, to_currency=to_curr)}[/red]") + raise typer.Exit(1) def fmt_amount(amount: Decimal | float, currency: str, symbol: str = "") -> str: diff --git a/infrastructure/i18n/ru.py b/infrastructure/i18n/ru.py index 91579ff..109e1c5 100644 --- a/infrastructure/i18n/ru.py +++ b/infrastructure/i18n/ru.py @@ -217,6 +217,7 @@ MESSAGES: dict[str, str] = { "global.ok": "OK", "global.value": "значение", "global.validation_error": "Ошибка валидации данных: {error}", + "global.no_rate": "Нет курса {from_currency} → {to_currency} — обновите курсы: cf config rate-refresh", "prompt.analyze": "Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n" "\n" "### Модель (JSON):\n" diff --git a/infrastructure/repositories/json_file_repository.py b/infrastructure/repositories/json_file_repository.py index 79d5593..78e93a2 100644 --- a/infrastructure/repositories/json_file_repository.py +++ b/infrastructure/repositories/json_file_repository.py @@ -1,6 +1,8 @@ """JsonFileRepository — хранит FinancialModel в .json (включая version).""" import json +import os +import tempfile from pathlib import Path from application.repositories.model_repository import ModelRepository @@ -15,7 +17,26 @@ class JsonFileRepository(ModelRepository): return FinancialModel.from_dict(data) def save(self, model: FinancialModel, path: str | Path) -> None: + """Атомарно записать модель и закрыть файл правами 0600 (Н9). + + Пишем во временный файл рядом и подменяем через `os.replace`: + обрыв записи не оставит обрезанный `model.json` (R7). Файл с + финансовыми данными не должен быть читаем всем пользователям + системы — на POSIX выставляем `0600`. + """ p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) - with open(p, "w", encoding="utf-8") as f: - json.dump(model.to_dict(), f, indent=2, ensure_ascii=False) + fd, tmp_name = tempfile.mkstemp(dir=p.parent, prefix=f".{p.name}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(model.to_dict(), f, indent=2, ensure_ascii=False) + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp_name, 0o600) + os.replace(tmp_name, p) + except BaseException: + try: + os.unlink(tmp_name) + except FileNotFoundError: + pass + raise diff --git a/tests/test_cli.py b/tests/test_cli.py index ce9a68b..970a152 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -242,6 +242,58 @@ class TestValidationErrors: assert result.exit_code == 0 assert "Traceback" not in result.stdout + def test_config_account_add_with_negative_balance_fails_cleanly(self): + result = runner.invoke(app, ["config", "account-add", "--name", "A", "--balance", "-1"]) + assert result.exit_code == 1 + assert "Ошибка валидации" in result.stdout + assert "баланс не может быть отрицательным" in result.stdout + assert "Traceback" not in result.stdout + + def test_config_transaction_add_with_zero_amount_fails_cleanly(self): + runner.invoke(app, ["config", "account-add", "--name", "A"]) + result = runner.invoke(app, ["config", "transaction-add", "--account", "A", "--amount", "0"]) + assert result.exit_code == 1 + assert "Ошибка валидации" in result.stdout + assert "сумма не может быть нулевой" in result.stdout + assert "Traceback" not in result.stdout + + def test_config_recurring_add_with_unknown_frequency_fails_cleanly(self): + result = runner.invoke(app, ["config", "recurring-add", "--amount", "-1", "--frequency", "hourly"]) + assert result.exit_code == 1 + assert "Ошибка валидации" in result.stdout + assert "Traceback" not in result.stdout + + def test_config_liability_add_with_negative_interest_fails_cleanly(self): + result = runner.invoke(app, ["config", "liability-add", "--name", "L", "--interest", "-1"]) + assert result.exit_code == 1 + assert "Ошибка валидации" in result.stdout + assert "Traceback" not in result.stdout + + def test_forecast_with_currency_without_rate_fails_cleanly(self): + # Н6: нет курса для валюты вывода — сообщение, а не traceback. + runner.invoke(app, ["init"]) + result = runner.invoke(app, ["forecast", "--months", "1", "--currency", "EUR"]) + assert result.exit_code == 1 + assert "Нет курса RUB → EUR" in result.stdout + assert "Traceback" not in result.stdout + + +class TestBackups: + """R8: два поколения отката — `.bak` и `.bak.1`.""" + + def test_two_previous_generations_are_kept(self): + import json + + runner.invoke(app, ["init"]) + runner.invoke(app, ["config", "account-add", "--name", "A"]) + runner.invoke(app, ["config", "account-add", "--name", "B"]) + + data_dir = Path("data") + backup = json.loads((data_dir / "model.json.bak").read_text(encoding="utf-8")) + previous = json.loads((data_dir / "model.json.bak.1").read_text(encoding="utf-8")) + assert len(backup["accounts"]) == 1 + assert len(previous["accounts"]) == 0 + class TestFilesystemIsolation: """Регрессии D10: CLI-тесты не пишут в дерево репозитория.""" diff --git a/tests/test_language.py b/tests/test_language.py index 783fc8c..bfee078 100644 --- a/tests/test_language.py +++ b/tests/test_language.py @@ -34,6 +34,7 @@ ALLOWED_PLACEHOLDERS = ("{error}",) # листов Excel, коды выхода). Сравниваются как подстроки. ALLOWED_LATIN_RUNS = ( "CashFlow Forecast", # имя продукта в app.help + "cf config rate-refresh", # команда, которой пользователь обновляет курсы ) _PRINT_FUNCS = {"print", "console.print", "typer.echo", "print_ok", "print_error", "print_warning"} diff --git a/tests/test_repositories.py b/tests/test_repositories.py index 5e867c6..b3bb26e 100644 --- a/tests/test_repositories.py +++ b/tests/test_repositories.py @@ -1,3 +1,5 @@ +import os +import stat from decimal import Decimal from pathlib import Path @@ -45,6 +47,14 @@ class TestJsonFileRepository: repo = JsonFileRepository() assert isinstance(repo, ModelRepository) + def test_saved_model_has_private_permissions(self, tmp_path: Path): + if os.name != "posix": + return + repo = JsonFileRepository() + p = tmp_path / "private.json" + repo.save(FinancialModel(), p) + assert stat.S_IMODE(p.stat().st_mode) == 0o600 + def test_decimal_preserved(self, tmp_path: Path): repo = JsonFileRepository() model = FinancialModel(assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))])