D16b: месячная доля recurring по frequency и учёт start_date/end_date
amount — итог за период frequency: daily /30.4, weekly /4.33, monthly /1, yearly /12 (делители — именованные константы domain/recurring.py). Платёж учитывается в месяце сетки прогноза, если start_date <= конец месяца и end_date >= начало месяца; сравнение по ISO-строкам, пустые даты — без границ. Сетка прогноза привязана к start_month (по умолчанию текущий календарный месяц), округление — только в точке отображения.
This commit is contained in:
1 parent
abcd84c0fa
commit
f50106ca96
6 files changed
+259
-32
No files matched your search
+45
-4
@@ -1,4 +1,5 @@
|
||||
from copy import deepcopy
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
|
||||
from domain import Account, FinancialModel
|
||||
@@ -14,16 +15,45 @@ _TWELVE = Decimal("12")
|
||||
_HUNDRED = Decimal("100")
|
||||
|
||||
|
||||
def _first_of_month(value: str | date | None) -> date:
|
||||
"""Первый день месяца старта сетки прогноза.
|
||||
|
||||
`None` — текущий календарный месяц. Явное значение (ISO-строка или `date`)
|
||||
нужно тестам и вызывающему коду, которому важна воспроизводимость.
|
||||
"""
|
||||
if value is None:
|
||||
today = date.today()
|
||||
return today.replace(day=1)
|
||||
if isinstance(value, date):
|
||||
return value.replace(day=1)
|
||||
return date.fromisoformat(value).replace(day=1)
|
||||
|
||||
|
||||
def _shift_month(first: date, offset: int) -> date:
|
||||
"""Первый день месяца, сдвинутого на `offset` от месяца `first`."""
|
||||
total = first.year * 12 + first.month - 1 + offset
|
||||
year, month0 = divmod(total, 12)
|
||||
return date(year, month0 + 1, 1)
|
||||
|
||||
|
||||
class ForecastService:
|
||||
"""Помесячный прогноз денежных потоков.
|
||||
|
||||
Расчёт НЕ мутирует модель: `self.model` после `forecast_cashflow()` остаётся
|
||||
байт-в-байт тем же, что до вызова, поэтому повторный прогноз на том же
|
||||
экземпляре даёт идентичный результат (D14).
|
||||
|
||||
Сетка прогноза привязана к календарю (D16b): месяц `m` (нумерация с 1) —
|
||||
это календарный месяц, отстоящий на `m - 1` месяцев от месяца старта.
|
||||
Старт задаётся `start_month` (`YYYY-MM-DD` или `date`, приводится к первому
|
||||
дню месяца); по умолчанию — текущий календарный месяц. Границы recurring
|
||||
(`start_date`/`end_date`) сравниваются с началом и концом каждого месяца
|
||||
сетки, а не с «сегодня».
|
||||
"""
|
||||
|
||||
def __init__(self, model: FinancialModel):
|
||||
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
|
||||
self.model = deepcopy(model)
|
||||
self.start_month = _first_of_month(start_month)
|
||||
|
||||
def forecast_cashflow(self, months: int = 12) -> list[dict]:
|
||||
if months < 1:
|
||||
@@ -75,6 +105,11 @@ class ForecastService:
|
||||
income = _ZERO
|
||||
expenses = _ZERO
|
||||
|
||||
# Границы месяца сетки: месяц m считается от месяца старта прогноза
|
||||
# (D16b), а не от «сегодня» и не от даты транзакции.
|
||||
month_start = _shift_month(self.start_month, m)
|
||||
month_end = _shift_month(self.start_month, m + 1) - timedelta(days=1)
|
||||
|
||||
for t in self.model.transactions:
|
||||
if t.account == str(account.id):
|
||||
if t.amount > 0:
|
||||
@@ -83,12 +118,18 @@ class ForecastService:
|
||||
expenses += abs(t.amount)
|
||||
|
||||
for r in self.model.recurring:
|
||||
# D16b: платёж учитывается только в месяцах, попадающих в
|
||||
# [start_date, end_date]; `amount` — итог за период frequency,
|
||||
# в прогноз идёт месячная доля (полная точность Decimal).
|
||||
if not r.is_active_in_month(month_start.isoformat(), month_end.isoformat()):
|
||||
continue
|
||||
share = r.monthly_amount()
|
||||
# D16a: классификация только по знаку; `category` — подпись,
|
||||
# а не правило (то же правило в ScenarioService.apply/what_if).
|
||||
if r.amount > 0:
|
||||
income += r.amount
|
||||
if share > 0:
|
||||
income += share
|
||||
else:
|
||||
expenses += abs(r.amount)
|
||||
expenses += abs(share)
|
||||
|
||||
expenses += self._liability_cost(liability_balances)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from copy import deepcopy
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from application.forecast import ForecastService
|
||||
@@ -30,8 +31,10 @@ DEFAULT_SCENARIOS = {
|
||||
|
||||
|
||||
class ScenarioService:
|
||||
def __init__(self, model: FinancialModel):
|
||||
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
|
||||
self.model = deepcopy(model)
|
||||
# Месяц старта сетки прогноза (D16b) — тот же для всех сценариев.
|
||||
self.start_month = start_month
|
||||
|
||||
def apply(self, scenario: ForecastScenario, months: int = 12) -> dict:
|
||||
model = deepcopy(self.model)
|
||||
@@ -53,7 +56,7 @@ class ScenarioService:
|
||||
for a in model.assets:
|
||||
a.growth_rate = a.growth_rate * scenario.growth_multiplier
|
||||
|
||||
service = ForecastService(model)
|
||||
service = ForecastService(model, start_month=self.start_month)
|
||||
result = service.summary(months)
|
||||
result["scenario"] = scenario.name
|
||||
result["scenario_description"] = scenario.description
|
||||
|
||||
Reference in new issue
Block a user