"""Прогноз денежных потоков: календарь + валюты. Правила расчёта (v2, 2026-11): - **Транзакции.** Операция с датой в прошлом уже учтена в балансе счёта — в прогноз она не попадает (иначе баланс задваивается). Операция с датой в будущем попадает в тот месяц, в который она выпадает. Операция без даты считается текущим месяцем. - **Регулярные платежи.** Разворачиваются по календарю — ``daily``/``weekly``/ ``monthly``/``yearly`` дают конкретные даты списаний (см. `domain.recurrence`). Списания в прошлом не берутся, ``end_date`` уважается. - **Валюты.** Суммы приводятся к базовой валюте модели по курсам из состояния. Баланс счёта — в валюте счёта, операция — в своей валюте (пусто = валюта счёта). Отсутствующий курс — не падение, а предупреждение: сумма не попадает в прогноз, но пользователь видит, чего не хватает. - **Активы и обязательства** не привязаны к счетам: их денежные потоки распределяются по счетам пропорционально балансу (при нулевом суммарном балансе — поровну). """ from __future__ import annotations from copy import deepcopy from datetime import date from decimal import ROUND_HALF_UP, Decimal from domain import Account, FinancialModel from domain.currency import CurrencyConverter, CurrencyError from domain.dates import month_bounds, parse_date from domain.recurrence import RecurrenceError, occurrences class ForecastError(Exception): pass _ZERO = Decimal("0") _ONE = Decimal("1") _TWELVE = Decimal("12") _HUNDRED = Decimal("100") class ForecastService: def __init__( self, model: FinancialModel, *, today: date | None = None, converter: CurrencyConverter | None = None, ) -> None: # Источник не мутируется: каждый прогон работает на свежей копии, # поэтому повторный вызов forecast_cashflow/summary даёт тот же результат. self._source = deepcopy(model) self._today = today or date.today() self._converter = converter or CurrencyConverter(self._source.exchange_rates) self.warnings: list[str] = [] @property def model(self) -> FinancialModel: """Копия исходной модели (для чтения; прогноз её не меняет).""" return deepcopy(self._source) @property def today(self) -> date: """Отправная точка прогноза (по умолчанию — сегодня).""" return self._today @property def converter(self) -> CurrencyConverter: return self._converter # -- основной расчёт --------------------------------------------------- def forecast_cashflow(self, months: int = 12) -> list[dict]: if months < 1: raise ForecastError("months must be >= 1") model = deepcopy(self._source) self.warnings = [] base = model.base_currency window_start, window_end = month_bounds(self._today, months) accounts = model.accounts count = len(accounts) balances: list[Decimal] = [] for account in accounts: converted = self._to_base(base, self._account_currency(account), account.balance) balances.append(converted if converted is not None else _ZERO) income: list[list[Decimal]] = [[_ZERO] * months for _ in range(count)] expenses: list[list[Decimal]] = [[_ZERO] * months for _ in range(count)] self._apply_transactions(model, base, window_start, months, income, expenses) self._apply_recurring(model, base, window_start, window_end, months, income, expenses) asset_values = self._asset_values(model, base) liability_state = self._liability_state(model, base) results: list[dict] = [] for month_index in range(months): month_balances = [ balances[i] + income[i][month_index] - expenses[i][month_index] for i in range(count) ] total_growth = self._grow_assets(model, asset_values) liability_cash = self._step_liabilities(model, liability_state) total = sum(month_balances, _ZERO) for i in range(count): if total > 0: share = month_balances[i] / total elif count: share = _ONE / count else: share = _ZERO growth_share = total_growth * share liability_share = liability_cash * share income[i][month_index] += growth_share expenses[i][month_index] += liability_share month_balances[i] = month_balances[i] + growth_share - liability_share for i in range(count): results.append({ "account": accounts[i].name, "month": month_index + 1, "balance": _q(month_balances[i]), "income": _q(income[i][month_index]), "expenses": _q(expenses[i][month_index]), }) balances = month_balances return results # -- транзакции --------------------------------------------------------- def _apply_transactions( self, model: FinancialModel, base: str, window_start: date, months: int, income: list[list[Decimal]], expenses: list[list[Decimal]], ) -> None: for txn in model.transactions: account_index = self._account_index(model, txn.account) if account_index is None: self.warnings.append( f"Транзакция «{txn.description or txn.category or txn.id}» — " f"счёт «{txn.account}» не найден, операция пропущена" ) continue currency = txn.currency or self._account_currency(model.accounts[account_index]) or base amount = self._to_base(base, currency, txn.amount) if amount is None: continue txn_date = parse_date(txn.date) if txn_date is None: month_index = 0 # дата не указана — считаем текущим месяцем else: if txn_date < self._today: continue # уже учтена в балансе счёта month_index = self._month_index(window_start, txn_date) if month_index < 0: continue if month_index >= months: continue if amount > 0: income[account_index][month_index] += amount else: expenses[account_index][month_index] += -amount # -- регулярные платежи ------------------------------------------------- def _apply_recurring( self, model: FinancialModel, base: str, window_start: date, window_end: date, months: int, income: list[list[Decimal]], expenses: list[list[Decimal]], ) -> None: for rec in model.recurring: if rec.account: targets = [i for i in range(len(model.accounts)) if self._account_index(model, rec.account) == i] if not targets: self.warnings.append( f"Регулярный платёж «{rec.category or rec.id}» — " f"счёт «{rec.account}» не найден, платёж пропущен" ) continue currency = rec.currency or self._account_currency(model.accounts[targets[0]]) or base else: targets = list(range(len(model.accounts))) currency = rec.currency or base amount = self._to_base(base, currency, rec.amount) if amount is None: continue try: days = occurrences( start_date=rec.start_date, end_date=rec.end_date, frequency=rec.frequency, window_start=self._today, window_end=window_end, ) except RecurrenceError as exc: self.warnings.append( f"Регулярный платёж «{rec.category or rec.id}»: {exc}" ) continue for day in days: month_index = self._month_index(window_start, day) if month_index < 0 or month_index >= months: continue for account_index in targets: if amount > 0: income[account_index][month_index] += amount else: expenses[account_index][month_index] += -amount # -- активы и обязательства --------------------------------------------- def _asset_values(self, model: FinancialModel, base: str) -> list[Decimal]: values = [] for asset in model.assets: converted = self._to_base(base, asset.currency or base, asset.value) values.append(converted if converted is not None else _ZERO) return values def _grow_assets(self, model: FinancialModel, asset_values: list[Decimal]) -> Decimal: total = _ZERO for index, asset in enumerate(model.assets): growth = asset_values[index] * asset.growth_rate / _HUNDRED / _TWELVE total += growth asset_values[index] = asset_values[index] + growth return total def _liability_state(self, model: FinancialModel, base: str) -> dict: state: dict = {} for liability in model.liabilities: balance = self._to_base(base, liability.currency or base, liability.balance) payment = self._to_base(base, liability.currency or base, liability.payment) state[liability.id] = { "balance": balance if balance is not None else _ZERO, "payment": payment if payment is not None else _ZERO, "interest": liability.interest, } return state def _step_liabilities(self, model: FinancialModel, state: dict) -> Decimal: """Списать обязательства за месяц. Возвращает денежный outflow в базовой валюте. Платёж уменьшает остаток долга на (платёж − проценты); проценты — часть платежа. Если платежа нет, проценты просто начисляются на остаток. """ cash = _ZERO for liability in model.liabilities: item = state[liability.id] balance = item["balance"] interest = balance * item["interest"] / _HUNDRED / _TWELVE payment = item["payment"] if payment > 0: cash += payment remaining = balance - (payment - interest) item["balance"] = remaining if remaining > 0 else _ZERO else: item["balance"] = balance + interest return cash # -- сводка ------------------------------------------------------------- def summary(self, months: int = 12) -> dict: results = self.forecast_cashflow(months) if not results: return { "total_balance": _ZERO, "total_income": _ZERO, "total_expenses": _ZERO, "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), _ZERO) all_expenses = sum((r["expenses"] for r in results), _ZERO) return { "total_balance": _q(total_balance), "total_income": _q(all_income), "total_expenses": _q(all_expenses), "months": months, } # -- помощники ---------------------------------------------------------- def _to_base(self, base: str, currency: str, amount: Decimal) -> Decimal | None: """Привести сумму к базовой валюте. ``None`` — курса нет.""" source = (currency or base).upper() target = (base or "RUB").upper() if source == target: return amount try: return self._converter.convert(amount, source, target) except CurrencyError: self.warnings.append( f"Нет курса {source} → {target}: сумма {amount} {source} не учтена в прогнозе" ) return None @staticmethod def _account_currency(account: Account) -> str: return (account.currency or "").upper() @staticmethod def _account_index(model: FinancialModel, reference: str) -> int | None: """Индекс счёта по UUID или по имени (регистр не важен).""" value = (reference or "").strip() if not value: return None for index, account in enumerate(model.accounts): if value == str(account.id) or value.casefold() == account.name.strip().casefold(): return index return None @staticmethod def _month_index(window_start: date, day: date) -> int: """Номер месяца (0-based) относительно начала окна; -1 — до окна.""" return (day.year - window_start.year) * 12 + (day.month - window_start.month) 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()