- расчёт ведётся в базовой валюте модели: баланс счёта переводится из валюты счёта, операция — из своей валюты (пусто = валюта счёта), актив и обязательство — из своей (пусто = базовая); - нет курса — не падение, а предупреждение: сумма не попадает в прогноз, но пользователь видит, чего не хватает (нет курса USD → RUB); - FinancialModel.display_currency — валюта вывода по умолчанию; новая команда cf config display-currency; cf forecast/scenario/compare печатают предупреждения расчёта; cf info показывает обе валюты и суммы в валюте их владельца; - рост активов при нулевых балансах теперь делится поровну — раньше он делился по доле от единицы и просто исчезал. Тесты: 296 → 302 (класс TestForecastCurrency: конвертация баланса, операции, актива, регулярного платежа, предупреждение об отсутствии курса).
106 lines
4.4 KiB
Python
106 lines
4.4 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.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:
|
||
_json_repo.save(model, AppPaths.from_env().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:
|
||
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)
|