- 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
144 lines
5.1 KiB
Python
144 lines
5.1 KiB
Python
from copy import deepcopy
|
|
from decimal import ROUND_HALF_UP, Decimal
|
|
|
|
from domain import Account, FinancialModel
|
|
|
|
|
|
class ForecastError(Exception):
|
|
pass
|
|
|
|
|
|
_ZERO = Decimal("0")
|
|
_ONE = Decimal("1")
|
|
_TWELVE = Decimal("12")
|
|
_HUNDRED = Decimal("100")
|
|
|
|
|
|
class ForecastService:
|
|
def __init__(self, model: FinancialModel):
|
|
# Источник не мутируется: каждый прогон работает на свежей копии,
|
|
# поэтому повторный вызов 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 model.accounts:
|
|
monthly = self._project_account(model, account, months)
|
|
for m in range(months):
|
|
results.append({
|
|
"account": account.name,
|
|
"month": m + 1,
|
|
"balance": monthly[m]["balance"],
|
|
"income": monthly[m]["income"],
|
|
"expenses": monthly[m]["expenses"],
|
|
})
|
|
|
|
# Asset growth — once per month, distributed across accounts proportionally
|
|
for m in range(months):
|
|
total_growth = sum(
|
|
a.value * a.growth_rate / _HUNDRED / _TWELVE
|
|
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
|
|
for r in month_rows:
|
|
share = r["balance"] / total_bal
|
|
r["income"] = _q(r["income"] + total_growth * share)
|
|
r["balance"] = _q(r["balance"] + total_growth * share)
|
|
|
|
# Compound asset values for next month
|
|
for a in model.assets:
|
|
a.value = a.value + a.value * a.growth_rate / _HUNDRED / _TWELVE
|
|
|
|
return results
|
|
|
|
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 model.transactions:
|
|
if _refers_to(t.account, account):
|
|
if t.amount > 0:
|
|
income += t.amount
|
|
else:
|
|
expenses += abs(t.amount)
|
|
|
|
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(model, account)
|
|
|
|
balance = balance + income - expenses
|
|
|
|
monthly.append({
|
|
"balance": _q(balance),
|
|
"income": _q(income),
|
|
"expenses": _q(expenses),
|
|
})
|
|
return monthly
|
|
|
|
def _liability_cost(self, model: FinancialModel, account: Account) -> Decimal:
|
|
total = _ZERO
|
|
for liability in model.liabilities:
|
|
interest_cost = liability.balance * liability.interest / _HUNDRED / _TWELVE
|
|
total += interest_cost
|
|
liability.balance = liability.balance - (liability.payment - interest_cost)
|
|
if liability.balance < 0:
|
|
liability.balance = _ZERO
|
|
return total
|
|
|
|
def summary(self, months: int = 12) -> dict:
|
|
results = self.forecast_cashflow(months)
|
|
if not results:
|
|
return {"total_balance": 0, "total_income": 0, "total_expenses": 0, "months": months}
|
|
|
|
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": _q(total_balance),
|
|
"total_income": _q(all_income),
|
|
"total_expenses": _q(all_expenses),
|
|
"months": months,
|
|
}
|
|
|
|
|
|
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()
|