- domain/*: на всех моделях домена (FinancialModel, Account, Transaction,
RecurringCashflow, Asset, Liability, ForecastScenario, ExchangeRate)
включён model_config = ConfigDict(validate_assignment=True). Раньше
присваивание шло мимо валидаторов: `r.rate = -5` принимался, а
config_cmd.py писал в поле Decimal значение типа float.
- infrastructure/cli/commands/config_cmd.py: rate_set пишет
Decimal(str(rate)) вместо float.
- infrastructure/cli/services.py: хелпер fail_validation() — печатает
понятное сообщение (t("global.validation_error")) и завершает команду
кодом 1 вместо traceback.
- infrastructure/cli/i18n.py: добавлен ключ global.validation_error.
- infrastructure/cli/commands/{whatif,scenario,compare}.py: тот же обработчик
для случая «множитель 0 обнуляет сумму» — иначе D17 вводил бы новый traceback.
- tests/test_model.py: +9 тестов (отклонение отрицательного/нулевого курса,
float в поле Decimal не остаётся float, отклонение по всем валидаторам).
- tests/test_cli.py: +4 теста (ненулевой код без traceback, модель не
сохраняется, курс сохраняется строкой-Decimal, валидный курс проходит).
Было → стало:
cf config rate-set USD RUB -- -5 принимался, «OK Курс USD → RUB = -5.0»,
курс сохранялся float (-5.0) + warning
→ «Ошибка валидации данных: rate: Value error,
rate must be positive», код 1, без traceback
cf whatif --income 0 работал (суммы обнулялись молча)
→ «Ошибка валидации данных: amount: Value error,
amount must be non-zero», код 1
84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
"""Composition root + общие хелперы для CLI-команд."""
|
|
|
|
from __future__ import annotations
|
|
|
|
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 infrastructure.ai.assistant import AssistantService
|
|
from infrastructure.cli.i18n import t
|
|
from infrastructure.cli.paths import MODEL_PATH
|
|
from infrastructure.repositories import JsonFileRepository
|
|
|
|
console = Console()
|
|
|
|
_json_repo = JsonFileRepository()
|
|
|
|
|
|
def fail_validation(exc: ValidationError) -> NoReturn:
|
|
"""Показать ошибку валидации понятным сообщением и завершить команду.
|
|
|
|
Доменные модели валидируют и при присваивании (D17), поэтому «нельзя
|
|
положить отрицательный курс» — ожидаемая ошибка ввода, а не сбой
|
|
программы: пользователь получает понятное сообщение и код возврата 1
|
|
вместо traceback.
|
|
"""
|
|
details = "; ".join(
|
|
f"{'.'.join(str(part) for part in error['loc']) or 'значение'}: {error['msg']}" for error in exc.errors()
|
|
)
|
|
console.print(f"[red]{t('global.validation_error', error=details)}[/red]")
|
|
raise typer.Exit(1)
|
|
|
|
|
|
def load_model() -> FinancialModel:
|
|
if MODEL_PATH.exists():
|
|
return _json_repo.load(MODEL_PATH)
|
|
return FinancialModel()
|
|
|
|
|
|
def save_model(model: FinancialModel) -> None:
|
|
_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)
|
|
scenario_service = ScenarioService(model)
|
|
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
|
|
return forecast_service, scenario_service, assistant_service, converter
|
|
|
|
|
|
def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, str]:
|
|
target = currency or model.base_currency
|
|
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:
|
|
if to_curr == from_curr:
|
|
return amount
|
|
return converter.convert(amount, from_curr, to_curr)
|
|
|
|
|
|
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)
|