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
This commit is contained in:
oqyude committed 2026-11-11 15:40:37 +03:00
1 parent b90ca4c282
commit cdda703b37
39 files changed
+2181 -198

No files matched your search

+43 -15
View File
@@ -1,5 +1,5 @@
from copy import deepcopy
from decimal import Decimal, ROUND_HALF_UP
from decimal import ROUND_HALF_UP, Decimal
from domain import Account, FinancialModel
@@ -16,15 +16,23 @@ _HUNDRED = Decimal("100")
class ForecastService:
def __init__(self, model: FinancialModel):
self.model = deepcopy(model)
# Источник не мутируется: каждый прогон работает на свежей копии,
# поэтому повторный вызов forecast_cashflow/summary даёт тот же результат.
self._source = deepcopy(model)
@property
def model(self) -> FinancialModel:
"""Копия исходной модели (для чтения; прогноз её не меняет)."""
return deepcopy(self._source)
def forecast_cashflow(self, months: int = 12) -> list[dict]:
if months < 1:
raise ForecastError("months must be >= 1")
model = deepcopy(self._source)
results = []
for account in self.model.accounts:
monthly = self._project_account(account, months)
for account in model.accounts:
monthly = self._project_account(model, account, months)
for m in range(months):
results.append({
"account": account.name,
@@ -38,7 +46,7 @@ class ForecastService:
for m in range(months):
total_growth = sum(
a.value * a.growth_rate / _HUNDRED / _TWELVE
for a in self.model.assets
for a in model.assets
)
month_rows = [r for r in results if r["month"] == m + 1]
total_bal = sum(r["balance"] for r in month_rows) or _ONE
@@ -48,32 +56,35 @@ class ForecastService:
r["balance"] = _q(r["balance"] + total_growth * share)
# Compound asset values for next month
for a in self.model.assets:
for a in model.assets:
a.value = a.value + a.value * a.growth_rate / _HUNDRED / _TWELVE
return results
def _project_account(self, account: Account, months: int) -> list[dict]:
def _project_account(self, model: FinancialModel, account: Account, months: int) -> list[dict]:
balance = account.balance
monthly = []
for m in range(months):
income = _ZERO
expenses = _ZERO
for t in self.model.transactions:
if t.account == str(account.id):
for t in model.transactions:
if _refers_to(t.account, account):
if t.amount > 0:
income += t.amount
else:
expenses += abs(t.amount)
for r in self.model.recurring:
for r in model.recurring:
# Пустой r.account — платёж общий для всех счетов (legacy-поведение).
if r.account and not _refers_to(r.account, account):
continue
if r.amount > 0:
income += r.amount
else:
expenses += abs(r.amount)
expenses += self._liability_cost(account)
expenses += self._liability_cost(model, account)
balance = balance + income - expenses
@@ -84,9 +95,9 @@ class ForecastService:
})
return monthly
def _liability_cost(self, account: Account) -> Decimal:
def _liability_cost(self, model: FinancialModel, account: Account) -> Decimal:
total = _ZERO
for liability in self.model.liabilities:
for liability in model.liabilities:
interest_cost = liability.balance * liability.interest / _HUNDRED / _TWELVE
total += interest_cost
liability.balance = liability.balance - (liability.payment - interest_cost)
@@ -99,11 +110,14 @@ class ForecastService:
if not results:
return {"total_balance": 0, "total_income": 0, "total_expenses": 0, "months": months}
final = results[-1]
last_month = max(r["month"] for r in results)
total_balance = sum(
(r["balance"] for r in results if r["month"] == last_month), _ZERO
)
all_income = sum(r["income"] for r in results)
all_expenses = sum(r["expenses"] for r in results)
return {
"total_balance": final["balance"],
"total_balance": _q(total_balance),
"total_income": _q(all_income),
"total_expenses": _q(all_expenses),
"months": months,
@@ -113,3 +127,17 @@ class ForecastService:
def _q(v: Decimal) -> Decimal:
"""Quantize to 2 decimal places, ROUND_HALF_UP."""
return v.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def _refers_to(ref: str, account: Account) -> bool:
"""True if `ref` points at `account` — by UUID or by (case-insensitive) name.
Excel-authored models reference accounts by name; JSON-authored and legacy
models use the account UUID string. Both are accepted.
"""
value = (ref or "").strip()
if not value:
return False
if value == str(account.id):
return True
return value.casefold() == account.name.strip().casefold()