D33: транзакции попадают в месяц своей даты
- транзакция из прошлого уже учтена в балансе счёта — в прогноз не попадает; транзакция будущего попадает в месяц своей даты; без даты — в первый месяц сетки; за горизонтом — игнорируется; - счёт ищется и по UUID, и по имени: операция, заполненная в Excel по имени счёта, больше не выпадает из расчёта молча; - ForecastService.warnings — предупреждения расчёта (счёт не найден). Числа изменились (было → стало, sample_model, 12 мес.): - доход 52149.97 → 19149.96 (зарплата и аренда учитывались в каждом месяце, теперь — только в январе); - итоговый баланс 13087.98 → 13184.84. Тесты: 289 → 296 (новый класс TestTransactionDates, характеристики прогноза и сценариев пересчитаны и проверены вручную).
This commit is contained in:
1 parent
6b8d508c4f
commit
289f039ed8
3 files changed
+238
-67
No files matched your search
+118
-41
@@ -3,7 +3,7 @@ from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from application.forecast import ForecastError, ForecastService
|
||||
from domain import Account, FinancialModel, RecurringCashflow
|
||||
from domain import Account, FinancialModel, RecurringCashflow, Transaction
|
||||
from domain.recurrence import FREQUENCIES, normalize_frequency
|
||||
|
||||
_MAIN_ACCOUNT = "Основной счёт"
|
||||
@@ -103,31 +103,34 @@ class TestForecastCharacterization:
|
||||
|
||||
# Порядок строк: сначала все 12 месяцев «Основного счёта»,
|
||||
# затем все 12 месяцев «Сбережений».
|
||||
#
|
||||
# D33: транзакции попадают в месяц своей даты — зарплата 01.01 и
|
||||
# аренда 05.01 учитываются только в январ��, а не в каждом месяце.
|
||||
expected = [
|
||||
(_MAIN_ACCOUNT, 1, Decimal("7152.22"), Decimal("3635.55"), Decimal("1483.33")),
|
||||
(_MAIN_ACCOUNT, 2, Decimal("9190.44"), Decimal("3655.37"), Decimal("1481.60")),
|
||||
(_MAIN_ACCOUNT, 3, Decimal("11226.72"), Decimal("3671.50"), Decimal("1479.85")),
|
||||
(_MAIN_ACCOUNT, 4, Decimal("13262.08"), Decimal("3684.97"), Decimal("1478.10")),
|
||||
(_MAIN_ACCOUNT, 5, Decimal("15297.25"), Decimal("3696.48"), Decimal("1476.35")),
|
||||
(_MAIN_ACCOUNT, 6, Decimal("17332.67"), Decimal("3706.48"), Decimal("1474.58")),
|
||||
(_MAIN_ACCOUNT, 7, Decimal("19368.69"), Decimal("3715.31"), Decimal("1472.81")),
|
||||
(_MAIN_ACCOUNT, 8, Decimal("21405.57"), Decimal("3723.22"), Decimal("1471.03")),
|
||||
(_MAIN_ACCOUNT, 9, Decimal("23443.48"), Decimal("3730.37"), Decimal("1469.24")),
|
||||
(_MAIN_ACCOUNT, 10, Decimal("25482.59"), Decimal("3736.92"), Decimal("1467.45")),
|
||||
(_MAIN_ACCOUNT, 11, Decimal("27522.98"), Decimal("3742.96"), Decimal("1465.64")),
|
||||
(_MAIN_ACCOUNT, 12, Decimal("29564.76"), Decimal("3748.57"), Decimal("1463.83")),
|
||||
(_MAIN_ACCOUNT, 2, Decimal("7372.13"), Decimal("637.06"), Decimal("281.60")),
|
||||
(_MAIN_ACCOUNT, 3, Decimal("7593.78"), Decimal("638.56"), Decimal("279.85")),
|
||||
(_MAIN_ACCOUNT, 4, Decimal("7817.16"), Decimal("640.05"), Decimal("278.10")),
|
||||
(_MAIN_ACCOUNT, 5, Decimal("8042.30"), Decimal("641.53"), Decimal("276.35")),
|
||||
(_MAIN_ACCOUNT, 6, Decimal("8269.19"), Decimal("643.00"), Decimal("274.58")),
|
||||
(_MAIN_ACCOUNT, 7, Decimal("8497.85"), Decimal("644.47"), Decimal("272.81")),
|
||||
(_MAIN_ACCOUNT, 8, Decimal("8728.28"), Decimal("645.93"), Decimal("271.03")),
|
||||
(_MAIN_ACCOUNT, 9, Decimal("8960.49"), Decimal("647.38"), Decimal("269.24")),
|
||||
(_MAIN_ACCOUNT, 10, Decimal("9194.50"), Decimal("648.83"), Decimal("267.45")),
|
||||
(_MAIN_ACCOUNT, 11, Decimal("9430.29"), Decimal("650.27"), Decimal("265.64")),
|
||||
(_MAIN_ACCOUNT, 12, Decimal("9667.90"), Decimal("651.71"), Decimal("263.83")),
|
||||
(_SAVINGS_ACCOUNT, 1, Decimal("10435.76"), Decimal("697.78"), Decimal("262.02")),
|
||||
(_SAVINGS_ACCOUNT, 2, Decimal("10657.97"), Decimal("680.18"), Decimal("260.19")),
|
||||
(_SAVINGS_ACCOUNT, 3, Decimal("10885.72"), Decimal("666.29"), Decimal("258.36")),
|
||||
(_SAVINGS_ACCOUNT, 4, Decimal("11117.99"), Decimal("655.07"), Decimal("256.52")),
|
||||
(_SAVINGS_ACCOUNT, 5, Decimal("11354.08"), Decimal("645.83"), Decimal("254.67")),
|
||||
(_SAVINGS_ACCOUNT, 6, Decimal("11593.54"), Decimal("638.11"), Decimal("252.81")),
|
||||
(_SAVINGS_ACCOUNT, 7, Decimal("11836.06"), Decimal("631.58"), Decimal("250.95")),
|
||||
(_SAVINGS_ACCOUNT, 8, Decimal("12081.39"), Decimal("625.99"), Decimal("249.08")),
|
||||
(_SAVINGS_ACCOUNT, 9, Decimal("12329.36"), Decimal("621.16"), Decimal("247.20")),
|
||||
(_SAVINGS_ACCOUNT, 10, Decimal("12579.84"), Decimal("616.96"), Decimal("245.32")),
|
||||
(_SAVINGS_ACCOUNT, 11, Decimal("12832.74"), Decimal("613.28"), Decimal("243.42")),
|
||||
(_SAVINGS_ACCOUNT, 12, Decimal("13087.98"), Decimal("610.04"), Decimal("241.52")),
|
||||
(_SAVINGS_ACCOUNT, 2, Decimal("10676.28"), Decimal("698.49"), Decimal("260.19")),
|
||||
(_SAVINGS_ACCOUNT, 3, Decimal("10918.66"), Decimal("699.23"), Decimal("258.36")),
|
||||
(_SAVINGS_ACCOUNT, 4, Decimal("11162.91"), Decimal("699.99"), Decimal("256.52")),
|
||||
(_SAVINGS_ACCOUNT, 5, Decimal("11409.03"), Decimal("700.78"), Decimal("254.67")),
|
||||
(_SAVINGS_ACCOUNT, 6, Decimal("11657.02"), Decimal("701.59"), Decimal("252.81")),
|
||||
(_SAVINGS_ACCOUNT, 7, Decimal("11906.90"), Decimal("702.42"), Decimal("250.95")),
|
||||
(_SAVINGS_ACCOUNT, 8, Decimal("12158.68"), Decimal("703.28"), Decimal("249.08")),
|
||||
(_SAVINGS_ACCOUNT, 9, Decimal("12412.35"), Decimal("704.15"), Decimal("247.20")),
|
||||
(_SAVINGS_ACCOUNT, 10, Decimal("12667.93"), Decimal("705.05"), Decimal("245.32")),
|
||||
(_SAVINGS_ACCOUNT, 11, Decimal("12925.42"), Decimal("705.96"), Decimal("243.42")),
|
||||
(_SAVINGS_ACCOUNT, 12, Decimal("13184.84"), Decimal("706.90"), Decimal("241.52")),
|
||||
]
|
||||
|
||||
actual = [(r["account"], r["month"], r["balance"], r["income"], r["expenses"]) for r in results]
|
||||
@@ -137,35 +140,34 @@ class TestForecastCharacterization:
|
||||
def test_summary_6_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert service.summary(months=6) == {
|
||||
"total_balance": Decimal("11527.64"),
|
||||
"total_income": Decimal("26033.66"),
|
||||
"total_expenses": Decimal("10483.81"),
|
||||
"total_balance": Decimal("11591.11"),
|
||||
"total_income": Decimal("11033.65"),
|
||||
"total_expenses": Decimal("4483.81"),
|
||||
"months": 6,
|
||||
}
|
||||
|
||||
def test_summary_12_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert service.summary(months=12) == {
|
||||
"total_balance": Decimal("13087.98"),
|
||||
"total_income": Decimal("52149.97"),
|
||||
"total_expenses": Decimal("20705.87"),
|
||||
"total_balance": Decimal("13184.84"),
|
||||
"total_income": Decimal("19149.96"),
|
||||
"total_expenses": Decimal("7505.87"),
|
||||
"months": 12,
|
||||
}
|
||||
|
||||
def test_repeated_forecast_is_idempotent(self, sample_model):
|
||||
# D14: движок больше не мутирует свои assets/liabilities, поэтому
|
||||
# повторный forecast_cashflow на ТОМ ЖЕ экземпляре сервиса даёт
|
||||
# идентичный результат. До D14 второй вызов давал 13649.62 вместо
|
||||
# 13087.98 (сумма 368465.98 вместо 361041.88).
|
||||
# идентичный результат.
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
first = service.forecast_cashflow(months=12)
|
||||
second = service.forecast_cashflow(months=12)
|
||||
|
||||
assert first == second
|
||||
assert first[-1]["balance"] == Decimal("13087.98")
|
||||
assert second[-1]["balance"] == Decimal("13087.98")
|
||||
assert sum(r["balance"] for r in first) == Decimal("361041.88")
|
||||
assert sum(r["balance"] for r in second) == Decimal("361041.88")
|
||||
assert first[-1]["balance"] == Decimal("13184.84")
|
||||
assert second[-1]["balance"] == Decimal("13184.84")
|
||||
assert sum(r["balance"] for r in first) == Decimal("242241.87")
|
||||
assert sum(r["balance"] for r in second) == Decimal("242241.87")
|
||||
|
||||
def test_forecast_does_not_mutate_model(self, sample_model):
|
||||
# D14: модель сервиса после прогноза байт-в-байт та же, что до.
|
||||
@@ -190,15 +192,15 @@ class TestForecastCharacterization:
|
||||
service.forecast_cashflow(months=12)
|
||||
summary = service.summary(months=12)
|
||||
assert summary == {
|
||||
"total_balance": Decimal("13087.98"),
|
||||
"total_income": Decimal("52149.97"),
|
||||
"total_expenses": Decimal("20705.87"),
|
||||
"total_balance": Decimal("13184.84"),
|
||||
"total_income": Decimal("19149.96"),
|
||||
"total_expenses": Decimal("7505.87"),
|
||||
"months": 12,
|
||||
}
|
||||
|
||||
# На свежем экземпляре — те же числа.
|
||||
fresh = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert fresh.summary(months=12)["total_balance"] == Decimal("13087.98")
|
||||
assert fresh.summary(months=12)["total_balance"] == Decimal("13184.84")
|
||||
|
||||
def test_summary_total_balance_is_last_table_row(self, sample_model):
|
||||
# D14: «Итог» в CLI обязан совпадать с последней строкой таблицы —
|
||||
@@ -233,8 +235,83 @@ class TestForecastCharacterization:
|
||||
six = ForecastService(sample_model, start_month=_GRID_START).summary(months=6)
|
||||
twelve = ForecastService(sample_model, start_month=_GRID_START).summary(months=12)
|
||||
|
||||
assert six["total_balance"] == Decimal("11527.64")
|
||||
assert twelve["total_balance"] == Decimal("13087.98")
|
||||
assert six["total_balance"] == Decimal("11591.11")
|
||||
assert twelve["total_balance"] == Decimal("13184.84")
|
||||
|
||||
|
||||
class TestTransactionDates:
|
||||
"""D33: транзакция попадает в месяц своей даты, а не в каждый месяц."""
|
||||
|
||||
_GRID = "2026-01-01"
|
||||
|
||||
@staticmethod
|
||||
def _model(*transactions) -> FinancialModel:
|
||||
return FinancialModel(
|
||||
accounts=[Account(name="Счёт", balance=Decimal("0"))],
|
||||
transactions=list(transactions),
|
||||
)
|
||||
|
||||
def _balances(self, model: FinancialModel, months: int = 6) -> list[Decimal]:
|
||||
rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months)
|
||||
return [row["balance"] for row in rows]
|
||||
|
||||
def test_future_transaction_lands_in_its_own_month(self):
|
||||
model = self._model(
|
||||
Transaction(date="2026-03-10", account="Счёт", category="income", amount=Decimal("1000"))
|
||||
)
|
||||
assert self._balances(model) == [
|
||||
Decimal("0.00"),
|
||||
Decimal("0.00"),
|
||||
Decimal("1000.00"),
|
||||
Decimal("1000.00"),
|
||||
Decimal("1000.00"),
|
||||
Decimal("1000.00"),
|
||||
]
|
||||
|
||||
def test_past_transaction_does_not_move_the_forecast(self):
|
||||
# Операция до начала сетки уже учтена в балансе счёта.
|
||||
model = self._model(
|
||||
Transaction(date="2025-12-01", account="Счёт", category="income", amount=Decimal("1000"))
|
||||
)
|
||||
assert self._balances(model) == [Decimal("0.00")] * 6
|
||||
|
||||
def test_transaction_without_date_goes_to_the_first_month(self):
|
||||
# Баланс накапливается: операция без даты попадает в первый месяц
|
||||
# сетки и дальше просто лежит на балансе.
|
||||
model = self._model(Transaction(account="Счёт", category="income", amount=Decimal("500")))
|
||||
assert self._balances(model) == [Decimal("500.00")] * 6
|
||||
|
||||
def test_transaction_after_horizon_is_ignored(self):
|
||||
model = self._model(
|
||||
Transaction(date="2027-01-10", account="Счёт", category="income", amount=Decimal("1000"))
|
||||
)
|
||||
assert self._balances(model) == [Decimal("0.00")] * 6
|
||||
|
||||
def test_transaction_is_found_by_account_name(self):
|
||||
# Excel-автор пишет в ячейке имя счёта, а не UUID.
|
||||
model = self._model(
|
||||
Transaction(date="2026-01-05", account="Счёт", category="income", amount=Decimal("700"))
|
||||
)
|
||||
assert self._balances(model)[0] == Decimal("700.00")
|
||||
|
||||
def test_transaction_is_found_by_account_uuid(self):
|
||||
account = Account(name="Счёт", balance=Decimal("0"))
|
||||
model = FinancialModel(
|
||||
accounts=[account],
|
||||
transactions=[
|
||||
Transaction(date="2026-01-05", account=str(account.id), category="income", amount=Decimal("700"))
|
||||
],
|
||||
)
|
||||
assert self._balances(model)[0] == Decimal("700.00")
|
||||
|
||||
def test_unknown_account_produces_warning(self):
|
||||
service = ForecastService(
|
||||
self._model(Transaction(date="2026-01-05", account="Нет такого", amount=Decimal("700"))),
|
||||
start_month=self._GRID,
|
||||
)
|
||||
service.forecast_cashflow(6)
|
||||
assert service.warnings
|
||||
assert "не найден" in service.warnings[0]
|
||||
|
||||
|
||||
class TestRecurringSchedule:
|
||||
|
||||
+13
-13
@@ -87,9 +87,9 @@ class TestScenarioCharacterization:
|
||||
|
||||
def test_default_scenarios_numbers_6_months(self, sample_model):
|
||||
expected = {
|
||||
"baseline": (Decimal("11527.64"), Decimal("26033.66"), Decimal("10483.81")),
|
||||
"optimistic": (Decimal("12051.96"), Decimal("30048.49"), Decimal("10003.81")),
|
||||
"pessimistic": (Decimal("10943.69"), Decimal("22021.49"), Decimal("11443.81")),
|
||||
"baseline": (Decimal("11591.11"), Decimal("11033.65"), Decimal("4483.81")),
|
||||
"optimistic": (Decimal("12135.36"), Decimal("12798.52"), Decimal("4303.81")),
|
||||
"pessimistic": (Decimal("10986.41"), Decimal("9271.49"), Decimal("4843.81")),
|
||||
}
|
||||
|
||||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||||
@@ -106,9 +106,9 @@ class TestScenarioCharacterization:
|
||||
|
||||
def test_default_scenarios_numbers_12_months(self, sample_model):
|
||||
expected = {
|
||||
"baseline": (Decimal("13087.98"), Decimal("52149.97"), Decimal("20705.87")),
|
||||
"optimistic": (Decimal("14119.08"), Decimal("60216.93"), Decimal("19745.87")),
|
||||
"pessimistic": (Decimal("11938.83"), Decimal("44095.56"), Decimal("22625.87")),
|
||||
"baseline": (Decimal("13184.84"), Decimal("19149.96"), Decimal("7505.87")),
|
||||
"optimistic": (Decimal("14241.99"), Decimal("22266.93"), Decimal("7205.87")),
|
||||
"pessimistic": (Decimal("12008.32"), Decimal("16045.55"), Decimal("8105.87")),
|
||||
}
|
||||
|
||||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||||
@@ -130,9 +130,9 @@ class TestScenarioCharacterization:
|
||||
income_mult=1.2, expense_mult=0.9, months=6
|
||||
)
|
||||
assert six == {
|
||||
_BALANCE: Decimal("12231.75"),
|
||||
_INCOME: Decimal("30833.63"),
|
||||
_EXPENSES: Decimal("9523.81"),
|
||||
_BALANCE: Decimal("12302.52"),
|
||||
_INCOME: Decimal("12833.63"),
|
||||
_EXPENSES: Decimal("4123.81"),
|
||||
"months": 6,
|
||||
"scenario": "what-if",
|
||||
"scenario_description": description,
|
||||
@@ -142,9 +142,9 @@ class TestScenarioCharacterization:
|
||||
income_mult=1.2, expense_mult=0.9, months=12
|
||||
)
|
||||
assert twelve == {
|
||||
_BALANCE: Decimal("14514.02"),
|
||||
_INCOME: Decimal("61749.97"),
|
||||
_EXPENSES: Decimal("18785.87"),
|
||||
_BALANCE: Decimal("14616.08"),
|
||||
_INCOME: Decimal("22149.98"),
|
||||
_EXPENSES: Decimal("6905.87"),
|
||||
"months": 12,
|
||||
"scenario": "what-if",
|
||||
"scenario_description": description,
|
||||
@@ -168,7 +168,7 @@ class TestScenarioCharacterization:
|
||||
second = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
||||
|
||||
assert first == second
|
||||
assert first[_BALANCE] == Decimal("11527.64")
|
||||
assert first[_BALANCE] == Decimal("11591.11")
|
||||
|
||||
|
||||
class TestRecurringScheduleInScenarios:
|
||||
|
||||
Reference in new issue
Block a user