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.
134 lines
6.0 KiB
Python
134 lines
6.0 KiB
Python
"""Composition root + общие хелперы для CLI-команд."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import shutil
|
||
from decimal import Decimal
|
||
from typing import NoReturn
|
||
|
||
import typer
|
||
from pydantic import ValidationError
|
||
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
|
||
from infrastructure.repositories import JsonFileRepository
|
||
|
||
console = Console()
|
||
|
||
_json_repo = JsonFileRepository()
|
||
|
||
|
||
def _validation_message(error: dict) -> str:
|
||
"""Текст одной ошибки pydantic без английского префикса.
|
||
|
||
pydantic добавляет к тексту исключения валидатора префикс
|
||
«Value error, » — пользователю он не нужен, поэтому срезается (D19).
|
||
"""
|
||
return str(error["msg"]).removeprefix("Value error, ")
|
||
|
||
|
||
def fail_validation(exc: ValidationError) -> NoReturn:
|
||
"""Показать ошибку валидации понятным сообщением и завершить команду.
|
||
|
||
Доменные модели валидируют и при присваивании (D17), поэтому «нельзя
|
||
положить отрицательный курс» — ожидаемая ошибка ввода, а не сбой
|
||
программы: пользователь получает понятное сообщение и код возврата 1
|
||
вместо traceback.
|
||
"""
|
||
details = "; ".join(
|
||
f"{'.'.join(str(part) for part in error['loc']) or t('global.value')}: {_validation_message(error)}"
|
||
for error in exc.errors()
|
||
)
|
||
console.print(f"[red]{t('global.validation_error', error=details)}[/red]")
|
||
raise typer.Exit(1)
|
||
|
||
|
||
def load_model() -> FinancialModel:
|
||
model_path = AppPaths.from_env().model_path
|
||
if model_path.exists():
|
||
return _json_repo.load(model_path)
|
||
return FinancialModel()
|
||
|
||
|
||
def save_model(model: FinancialModel) -> None:
|
||
"""Сохранить модель. Прежние поколения остаются рядом как `.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]")
|
||
_json_repo.save(model, model_path)
|
||
|
||
|
||
def build_services(
|
||
model: FinancialModel,
|
||
) -> tuple[ForecastService, ScenarioService, AssistantService, CurrencyConverter]:
|
||
"""Composition root: собрать граф сервисов с зависимостями."""
|
||
converter = CurrencyConverter(model.exchange_rates)
|
||
forecast_service = ForecastService(model, converter=converter)
|
||
scenario_service = ScenarioService(model, converter=converter)
|
||
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
|
||
return forecast_service, scenario_service, assistant_service, converter
|
||
|
||
|
||
def print_warnings(warnings: list[str]) -> None:
|
||
"""Напечатать предупреждения расчёта (нет курса, счёт не найден)."""
|
||
for warning in warnings:
|
||
console.print(f"[yellow]{warning}[/yellow]")
|
||
|
||
|
||
def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, str]:
|
||
"""Валюта вывода и её символ.
|
||
|
||
По умолчанию — валюта вывода модели (`display_currency`, а она, в свою
|
||
очередь, наследует базовую валюту), а не всегда базовая (D34).
|
||
"""
|
||
target = (currency or model.output_currency).upper()
|
||
converter = CurrencyConverter(model.exchange_rates)
|
||
symbol = converter.get_symbol(target)
|
||
return target, symbol
|
||
|
||
|
||
def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal:
|
||
"""Перевести сумму для вывода. Нет курса — сообщение вместо traceback (Н6)."""
|
||
if to_curr == from_curr:
|
||
return amount
|
||
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:
|
||
"""Format money via the canonical display rule.
|
||
|
||
`symbol` НЕ читается: символ и раскладку определяет
|
||
`CurrencyConverter.format_money` по коду валюты. Параметр оставлен только
|
||
ради совместимости с существующими вызовами
|
||
(compare.py / forecast.py / scenario.py / whatif.py), которые передают его
|
||
позиционно.
|
||
"""
|
||
return CurrencyConverter.format_money(amount, currency)
|