Files
nifodea/infrastructure/cli/services.py
T
oqyude cdda703b37 T9: Excel as the model authoring surface
- ExcelRepository: canonical columns with ru/en aliases, date/number normalization
  (Excel dates, DD.MM.YYYY, '1 234,56', currency symbols, parentheses), account
  name->UUID resolution, per-row errors with sheet!row, warnings for formulas
  without cached values, duplicate names and default exchange rates
- ExcelTemplate: skeleton generator (number/date formats, dropdowns for currency,
  frequency en/ru and account, 'Инструкция' sheet); ship data/model_template.xlsx
- CLI: cf template-xlsx [--force]; cf import-xlsx --dry-run with rich error table,
  import writes nothing when the file has errors
- RecurringCashflow.account (empty = all accounts) + name/UUID matching in forecast;
  cf config recurring-add --account, account column in info/recurring-list
- Forecast: runs are idempotent, 'Итог: Баланс' sums all accounts of the last month
- README: 'Сборка модели в Excel' section
- ruff check . clean (9 pre-existing import/line-length findings fixed)
- MetaAgent: T9 archived, req-T9 approved, manifest/checkpoints/state synced

118 tests pass
2026-11-11 15:40:37 +03:00

77 lines
2.7 KiB
Python

"""Composition root + общие хелперы для CLI-команд."""
from __future__ import annotations
from decimal import Decimal
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 MODEL_PATH
from infrastructure.repositories import JsonFileRepository
console = Console()
_json_repo = JsonFileRepository()
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 account_label(model: FinancialModel, ref: str, *, empty: str = "") -> str:
"""Человекочитаемое имя счёта по ссылке (UUID или имя); пусто → `empty`."""
value = (ref or "").strip()
if not value:
return empty
for account in model.accounts:
if value == str(account.id) or value.casefold() == account.name.strip().casefold():
return account.name
return value
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` is retained as a positional parameter for backward compatibility with
existing callers (compare.py / forecast.py / scenario.py / whatif.py); the
symbol/layout decision is centralised in `CurrencyConverter.format_money`.
"""
return CurrencyConverter.format_money(amount, currency)