from decimal import Decimal import pytest from application.forecast import ForecastError, ForecastService from domain import ( Account, Asset, ExchangeRate, FinancialModel, Liability, RecurringCashflow, Transaction, ) from domain.recurrence import FREQUENCIES, normalize_frequency _MAIN_ACCOUNT = "Основной счёт" _SAVINGS_ACCOUNT = "Сбережения" # Месяц старта сетки прогноза для D11-характеристики: он совпадает с # `start_date` recurring в `sample_model`, поэтому числа не зависят от того, # когда именно запущены тесты (D16b). _GRID_START = "2026-01-01" class TestForecastService: def test_forecast_returns_results(self, sample_model): service = ForecastService(sample_model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) assert len(results) > 0 assert "balance" in results[0] assert "month" in results[0] def test_forecast_12_months(self, sample_model): service = ForecastService(sample_model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) months = set(r["month"] for r in results) assert max(months) == 12 def test_invalid_months(self, sample_model): service = ForecastService(sample_model, start_month=_GRID_START) with pytest.raises(ForecastError): service.forecast_cashflow(months=0) def test_summary(self, sample_model): service = ForecastService(sample_model, start_month=_GRID_START) s = service.summary(months=6) assert "total_balance" in s assert "total_income" in s assert "total_expenses" in s assert s["months"] == 6 def test_empty_model(self, empty_model): service = ForecastService(empty_model) results = service.forecast_cashflow(months=3) assert results == [] class TestRecurringClassificationBySign: """D16a: recurring классифицируется только по знаку, `category` — подпись.""" @staticmethod def _model(*recurring: RecurringCashflow) -> FinancialModel: return FinancialModel( accounts=[Account(name="Счёт", balance=Decimal("0"))], recurring=list(recurring), ) def test_negative_amount_with_income_category_is_expense(self): model = self._model(RecurringCashflow(amount=Decimal("-500"), category="income")) summary = ForecastService(model).summary(months=1) assert summary["total_income"] == Decimal("0") assert summary["total_expenses"] == Decimal("500") assert summary["total_balance"] == Decimal("-500") def test_positive_amount_with_expense_category_is_income(self): model = self._model(RecurringCashflow(amount=Decimal("500"), category="expense")) summary = ForecastService(model).summary(months=1) assert summary["total_income"] == Decimal("500") assert summary["total_expenses"] == Decimal("0") assert summary["total_balance"] == Decimal("500") def test_category_does_not_affect_classification(self): # Оба платежа противоположны своим категориям: по знаку это # доход 500 и расход 500, а не наоборот. model = self._model( RecurringCashflow(amount=Decimal("-500"), category="income"), RecurringCashflow(amount=Decimal("500"), category="expense"), ) summary = ForecastService(model).summary(months=1) assert summary["total_income"] == Decimal("500") assert summary["total_expenses"] == Decimal("500") assert summary["total_balance"] == Decimal("0") class TestForecastCharacterization: """Фиксация текущих чисел движка прогноза. Это характеристика существующего поведения, а не спецификация: числа меняются только вместе с изменением самого движка. Движок мутирует свои assets/liabilities (известная проблема Tier 2, D14), поэтому все проверки ниже выполняются на СВЕЖЕМ экземпляре ForecastService. """ def test_forecast_cashflow_12_months_exact_values(self, sample_model): service = ForecastService(sample_model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) # Порядок строк: сначала все 12 месяцев «Основного счёта», # затем все 12 месяцев «Сбережений». # # D33: транзакции попадают в месяц своей даты — зарплата 01.01 и # аренда 05.01 учитываются только в январ��, а не в каждом месяце. # D39: общий регулярный платёж и стоимость обязательства считаются # один раз на модель и раскладываются по счетам — раньше зарплата # попадала в каждый счёт целиком. expected = [ (_MAIN_ACCOUNT, 1, Decimal("6853.97"), Decimal("3337.30"), Decimal("1483.33")), (_MAIN_ACCOUNT, 2, Decimal("6773.92"), Decimal("338.20"), Decimal("283.33")), (_MAIN_ACCOUNT, 3, Decimal("6693.87"), Decimal("339.11"), Decimal("283.33")), (_MAIN_ACCOUNT, 4, Decimal("6613.83"), Decimal("340.02"), Decimal("283.33")), (_MAIN_ACCOUNT, 5, Decimal("6533.79"), Decimal("340.93"), Decimal("283.33")), (_MAIN_ACCOUNT, 6, Decimal("6453.77"), Decimal("341.86"), Decimal("283.33")), (_MAIN_ACCOUNT, 7, Decimal("6373.74"), Decimal("342.79"), Decimal("283.33")), (_MAIN_ACCOUNT, 8, Decimal("6293.72"), Decimal("343.72"), Decimal("283.33")), (_MAIN_ACCOUNT, 9, Decimal("6213.72"), Decimal("344.67"), Decimal("283.33")), (_MAIN_ACCOUNT, 10, Decimal("6133.72"), Decimal("345.62"), Decimal("283.33")), (_MAIN_ACCOUNT, 11, Decimal("6053.71"), Decimal("346.57"), Decimal("283.33")), (_MAIN_ACCOUNT, 12, Decimal("5973.72"), Decimal("347.53"), Decimal("283.33")), (_SAVINGS_ACCOUNT, 1, Decimal("10079.36"), Decimal("496.03"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 2, Decimal("9961.64"), Decimal("497.36"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 3, Decimal("9843.93"), Decimal("498.69"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 4, Decimal("9726.22"), Decimal("500.03"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 5, Decimal("9608.52"), Decimal("501.38"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 6, Decimal("9490.83"), Decimal("502.74"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 7, Decimal("9373.15"), Decimal("504.10"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 8, Decimal("9255.48"), Decimal("505.48"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 9, Decimal("9137.81"), Decimal("506.86"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 10, Decimal("9020.16"), Decimal("508.26"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 11, Decimal("8902.52"), Decimal("509.66"), Decimal("416.67")), (_SAVINGS_ACCOUNT, 12, Decimal("8784.89"), Decimal("511.08"), Decimal("416.67")), ] actual = [(r["account"], r["month"], r["balance"], r["income"], r["expenses"]) for r in results] assert len(results) == 24 assert actual == expected 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("15944.60"), "total_income": Decimal("8033.65"), "total_expenses": Decimal("5400.00"), "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("14758.61"), "total_income": Decimal("13149.99"), "total_expenses": Decimal("9600.00"), "months": 12, } def test_repeated_forecast_is_idempotent(self, sample_model): # D14: движок больше не мутирует свои assets/liabilities, поэтому # повторный forecast_cashflow на ТОМ ЖЕ экземпляре сервиса даёт # идентичный результат. 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("8784.89") assert second[-1]["balance"] == Decimal("8784.89") assert sum(r["balance"] for r in first) == Decimal("190149.99") assert sum(r["balance"] for r in second) == Decimal("190149.99") def test_forecast_does_not_mutate_model(self, sample_model): # D14: модель сервиса после прогноза байт-в-байт та же, что до. service = ForecastService(sample_model, start_month=_GRID_START) before = service.model.model_dump_json() service.forecast_cashflow(months=12) service.summary(months=12) assert service.model.model_dump_json() == before # И модель, переданная в сервис, тоже не меняется (сервис работает # на копии — и не трогает оригинал). original = sample_model.model_dump_json() ForecastService(sample_model, start_month=_GRID_START).forecast_cashflow(months=12) assert sample_model.model_dump_json() == original def test_summary_after_forecast_matches_summary_alone(self, sample_model): # D14: сводка больше не расходится с прогнозом. До D14 после двух # прогнозов summary давал 13730.60 / 52867.46 / 19200.00 вместо # 13087.98 / 52149.97 / 20705.87. service = ForecastService(sample_model, start_month=_GRID_START) service.forecast_cashflow(months=12) service.forecast_cashflow(months=12) summary = service.summary(months=12) assert summary == { "total_balance": Decimal("14758.61"), "total_income": Decimal("13149.99"), "total_expenses": Decimal("9600.00"), "months": 12, } # На свежем экземпляре — те же числа. fresh = ForecastService(sample_model, start_month=_GRID_START) assert fresh.summary(months=12)["total_balance"] == Decimal("14758.61") def test_summary_total_balance_sums_all_accounts(self, sample_model): # D39: «Итог» в CLI — сумма балансов всех счетов за последний месяц. # Раньше бралась последняя строка, то есть баланс последнего счёта: # при двух счетах «Итог» показывал 8784.89 вместо 14758.61. service = ForecastService(sample_model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) summary = service.summary(months=12, results=results) last_month = results[-1]["month"] expected = sum(r["balance"] for r in results if r["month"] == last_month) assert summary["total_balance"] == expected assert summary["total_balance"] != results[-1]["balance"] # Сводка без переданных результатов даёт то же самое (расчёт идемпотентен). assert service.summary(months=12) == summary def test_summary_of_single_account_equals_last_row(self, sample_model): # D14 + D39: при одном счёте «Итог» — это последняя строка таблицы. model = sample_model.model_copy(deep=True) model.accounts = model.accounts[:1] service = ForecastService(model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) assert service.summary(months=12, results=results)["total_balance"] == results[-1]["balance"] def test_forecast_output_is_quantized_to_two_decimals(self, sample_model): # D15: округление в прогнозе осталось только в точке сериализации # (`_q()`), поэтому JSON-вывод стабилен: все денежные значения — # ровно два знака после запятой. service = ForecastService(sample_model, start_month=_GRID_START) results = service.forecast_cashflow(months=12) assert results for row in results: for key in ("balance", "income", "expenses"): assert row[key].as_tuple().exponent == -2 summary = service.summary(months=12) for key in ("total_balance", "total_income", "total_expenses"): assert summary[key].as_tuple().exponent == -2 def test_horizon_changes_numbers(self, sample_model): # Стоимость обязательства амортизируется по одному разу на месяц (D39), # поэтому суммарное число начислений зависит от горизонта — это # текущее поведение (Tier 2, D16). 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("15944.60") assert twelve["total_balance"] == Decimal("14758.61") 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 TestForecastCurrency: """D34: расчёт ведётся в базовой валюте, суммы переводятся по курсам.""" _GRID = "2026-01-01" @staticmethod def _model(**kwargs) -> FinancialModel: defaults = dict( base_currency="RUB", accounts=[Account(name="Счёт", currency="RUB", balance=Decimal("0"))], exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))], ) defaults.update(kwargs) return FinancialModel(**defaults) def test_account_balance_is_converted_to_base_currency(self): model = self._model( accounts=[Account(name="Доллары", currency="USD", balance=Decimal("1000"))], ) service = ForecastService(model, start_month=self._GRID) rows = service.forecast_cashflow(1) assert rows[0]["balance"] == Decimal("80000.00") def test_transaction_uses_its_own_currency(self): account = Account(name="Счёт", currency="RUB", balance=Decimal("0")) model = self._model( accounts=[account], transactions=[ Transaction( date="2026-01-05", account=str(account.id), category="income", amount=Decimal("10"), currency="USD", ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1) assert rows[0]["income"] == Decimal("800.00") def test_transaction_without_currency_inherits_account_currency(self): account = Account(name="Доллары", currency="USD", balance=Decimal("0")) model = self._model( accounts=[account], transactions=[ Transaction(date="2026-01-05", account=str(account.id), category="income", amount=Decimal("10")) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1) assert rows[0]["income"] == Decimal("800.00") def test_asset_value_is_converted_to_base_currency(self): model = self._model( assets=[Asset(name="Акции", value=Decimal("100"), growth_rate=Decimal("8"), currency="USD")], ) service = ForecastService(model, start_month=self._GRID) rows = service.forecast_cashflow(1) # 100 USD = 8000 RUB, рост 8% годовых → 8000 × 0.08 / 12 = 53.33. assert rows[0]["income"] == Decimal("53.33") def test_missing_rate_produces_warning_and_skips_amount(self): model = self._model( base_currency="EUR", accounts=[Account(name="Доллары", currency="USD", balance=Decimal("1000"))], exchange_rates=[], ) service = ForecastService(model, start_month=self._GRID) rows = service.forecast_cashflow(1) assert rows[0]["balance"] == Decimal("0.00") assert service.warnings assert "нет курса USD → EUR" in service.warnings[0] def test_liability_payment_is_converted_to_base_currency(self): # Н2: платёж в валюте обязательства переводится в базовую валюту так # же, как остаток долга. Иначе 100 USD вычитались бы из 80 000 ₽. model = self._model( liabilities=[ Liability( name="Кредит", balance=Decimal("1000"), interest=Decimal("12"), payment=Decimal("100"), currency="USD", ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1) # 100 USD = 8000 ₽; проценты (800 ₽) — часть платежа, а не весь расход. assert sum(r["expenses"] for r in rows) == Decimal("8000.00") def test_recurring_amount_is_converted_to_base_currency(self): model = self._model( recurring=[ RecurringCashflow( start_date="2026-01-01", frequency="monthly", amount=Decimal("-100"), category="rent", currency="USD", ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(1) assert rows[0]["expenses"] == Decimal("8000.00") class TestRecurringSchedule: """D32: периодичность recurring считается по календарю. `amount` — сумма ОДНОГО списания. Сколько списаний выпадает в месяц сетки прогноза, решает календарь: daily — по числу дней месяца, weekly — по 7-дневным интервалам от якоря, monthly — одно в месяц, yearly — в месяц якорной даты. `start_date`/`end_date` ограничивают окно списаний. """ _GRID = "2026-01-01" @staticmethod def _model(amount: str, frequency: str = "monthly", start_date: str = "", end_date: str = "") -> FinancialModel: return FinancialModel( accounts=[Account(name="Счёт", balance=Decimal("0"))], recurring=[ RecurringCashflow( amount=Decimal(amount), frequency=frequency, start_date=start_date, end_date=end_date, ) ], ) def _incomes(self, model: FinancialModel, months: int = 6) -> list[Decimal]: rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months) return [row["income"] for row in rows] def test_frequency_divisors_cover_exactly_the_allowed_frequencies(self): assert set(FREQUENCIES) == {"daily", "weekly", "monthly", "yearly"} assert normalize_frequency("daily") == "daily" assert normalize_frequency("weekly") == "weekly" assert normalize_frequency("monthly") == "monthly" assert normalize_frequency("yearly") == "yearly" def test_russian_frequency_synonyms_are_normalized(self): # Автор Excel-файла пишет «ежемесячно» — модель хранит канон. assert normalize_frequency("ежемесячно") == "monthly" assert normalize_frequency("ЕЖЕГОДНО") == "yearly" assert RecurringCashflow(amount=Decimal("1"), frequency="ежедневно").frequency == "daily" def test_monthly_without_bounds_pays_every_month(self): # Как было до D16b: monthly без границ — вся сумма в каждом месяце. assert self._incomes(self._model("500")) == [Decimal("500.00")] * 6 def test_empty_start_date_means_from_the_beginning(self): assert self._incomes(self._model("500", start_date="")) == [Decimal("500.00")] * 6 def test_monthly_start_date_inside_horizon(self): # Старт 10 апреля: январь–март без платежа, апрель–июнь — платёж. incomes = self._incomes(self._model("500", start_date="2026-04-10")) assert incomes == [Decimal("0.00")] * 3 + [Decimal("500.00")] * 3 def test_monthly_start_date_exactly_on_month_start(self): # Граница включительная: start_date == начало марта → март уже платит. incomes = self._incomes(self._model("500", start_date="2026-03-01")) assert incomes == [Decimal("0.00")] * 2 + [Decimal("500.00")] * 4 def test_monthly_start_date_exactly_on_month_end(self): # start_date == конец февраля → февраль уже платит (start ≤ конец месяца). incomes = self._incomes(self._model("500", start_date="2026-02-28")) assert incomes == [Decimal("0.00")] + [Decimal("500.00")] * 5 def test_monthly_end_date_stops_payments(self): incomes = self._incomes(self._model("500", end_date="2026-03-15")) assert incomes == [Decimal("500.00")] * 3 + [Decimal("0.00")] * 3 def test_monthly_end_date_exactly_on_month_start(self): # Граница включительная: end_date == начало марта → март ещё платит. incomes = self._incomes(self._model("500", end_date="2026-03-01")) assert incomes == [Decimal("500.00")] * 3 + [Decimal("0.00")] * 3 def test_end_date_before_grid_pays_nothing(self): incomes = self._incomes(self._model("500", end_date="2025-12-31")) assert incomes == [Decimal("0.00")] * 6 def test_yearly_amount_is_charged_once_in_the_anchor_month(self): # D32: годовой платёж списывается ЦЕЛИКОМ в месяц якорной даты, # а не по 1/12 каждый месяц (как было в D16b). model = self._model("1200", frequency="yearly") assert self._incomes(model, months=12) == [Decimal("1200.00")] + [Decimal("0.00")] * 11 # Итог за год сохраняется: 1200. assert ForecastService(model, start_month=self._GRID).summary(months=12)["total_income"] == Decimal("1200.00") def test_yearly_anchor_month_follows_start_date(self): # Якорь 10 марта — списание в марте, а не в первом месяце сетки. assert self._incomes(self._model("1200", frequency="yearly", start_date="2026-03-10")) == [ Decimal("0.00"), Decimal("0.00"), Decimal("1200.00"), Decimal("0.00"), Decimal("0.00"), Decimal("0.00"), ] def test_weekly_amount_is_charged_by_calendar_weeks(self): # Якорь 01.01.2026 — четверг; в январе списания 1, 8, 15, 22, 29 (5 шт.), # в феврале — 5, 12, 19, 26 (4 шт.), и так далее по календарю. assert self._incomes(self._model("100", frequency="weekly")) == [ Decimal("500.00"), Decimal("400.00"), Decimal("400.00"), Decimal("500.00"), Decimal("400.00"), Decimal("400.00"), ] def test_daily_amount_is_charged_by_days_in_month(self): # daily: списание в каждый день месяца — сумма равна числу дней. assert self._incomes(self._model("1", frequency="daily")) == [ Decimal("31.00"), Decimal("28.00"), Decimal("31.00"), Decimal("30.00"), Decimal("31.00"), Decimal("30.00"), ] def test_monthly_anchor_on_31st_skips_short_months(self): # Календарная точность: 31-го числа нет в феврале, апреле и июне — # в этих месяцах списания нет. assert self._incomes(self._model("500", start_date="2026-01-31")) == [ Decimal("500.00"), Decimal("0.00"), Decimal("500.00"), Decimal("0.00"), Decimal("500.00"), Decimal("0.00"), ] def test_weekly_share_keeps_full_decimal_precision(self): # Сумма списаний считается умножением на КОЛИЧЕСТВО списаний — # дробной части у календарного платежа нет. item = RecurringCashflow(amount=Decimal("100"), frequency="weekly") assert item.amount_in_month("2026-01-01", "2026-01-31") == Decimal("500") assert self._incomes(self._model("100", frequency="weekly"), months=1) == [Decimal("500.00")] def test_rounding_happens_only_on_display(self): # daily amount=0.01: за календарный год списаний 365 (2026 — не # високосный), баланс 3.65. Округление — только на выводе, поэтому # дробные суммы не накапливают ошибку. rows = ForecastService(self._model("0.01", frequency="daily"), start_month=self._GRID).forecast_cashflow(12) assert rows[-1]["balance"] == Decimal("3.65") class TestMultipleAccounts: """D39: несколько счетов — общие платежи и обязательства считаются один раз. До D39 регулярный платёж без привязки к счёту попадал в каждый счёт целиком (зарплата на двух счетах удваивалась), а стоимость обязательства начислялась на каждый счёт: проценты по кредиту — дважды в месяц, а тело кредита гасилось вдвое быстрее. """ _GRID = "2026-01-01" @staticmethod def _model(*, accounts, recurring=(), liabilities=()): return FinancialModel( base_currency="RUB", accounts=list(accounts), recurring=list(recurring), liabilities=list(liabilities), ) def test_shared_recurring_is_counted_once(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], recurring=[RecurringCashflow(amount=Decimal("1000"), frequency="monthly", start_date="2026-01-01")], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) # 1000 — а не 2000: платёж общий, он один на модель. assert sum(r["income"] for r in rows) == Decimal("1000.00") def test_shared_recurring_is_split_by_balance(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], recurring=[RecurringCashflow(amount=Decimal("1000"), frequency="monthly", start_date="2026-01-01")], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) # Доли — по балансам: 1000 / 4000 и 3000 / 4000. assert rows[0]["income"] == Decimal("250.00") assert rows[1]["income"] == Decimal("750.00") def test_shared_expense_is_counted_once(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], recurring=[RecurringCashflow(amount=Decimal("-200"), frequency="monthly", start_date="2026-01-01")], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) assert sum(r["expenses"] for r in rows) == Decimal("200.00") def test_recurring_bound_to_account_goes_only_to_it(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], recurring=[ RecurringCashflow( amount=Decimal("1000"), frequency="monthly", start_date="2026-01-01", account="A", ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) assert rows[0]["income"] == Decimal("1000.00") assert rows[1]["income"] == Decimal("0.00") def test_liability_cost_is_charged_once_per_month(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], liabilities=[ Liability( name="Кредит", balance=Decimal("12000"), interest=Decimal("12"), payment=Decimal("200"), ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) # Н1: в денежный поток попадает весь платёж (200), а не только # проценты (120) — и ровно один раз на модель, а не на каждый счёт. assert sum(r["expenses"] for r in rows) == Decimal("200.00") def test_liability_is_amortized_once_per_month(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], liabilities=[ Liability( name="Кредит", balance=Decimal("100"), interest=Decimal("0"), payment=Decimal("200"), ) ], ) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=2) # Тело кредита гасится один раз на модель: долг 100 закрывается первым # платежом (100, а не 200 из-за двух счетов), во втором месяце платить # уже нечего. При двойной амортизации (было до D39) списалось бы 200. month_one = [r for r in rows if r["month"] == 1] month_two = [r for r in rows if r["month"] == 2] assert sum(r["expenses"] for r in month_one) == Decimal("100.00") assert sum(r["expenses"] for r in month_two) == Decimal("0.00") def test_transaction_stays_on_its_own_account(self): model = self._model( accounts=[ Account(name="A", balance=Decimal("1000")), Account(name="B", balance=Decimal("3000")), ], ) model.transactions.append(Transaction(date="2026-01-05", account="A", amount=Decimal("500"))) rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months=1) assert rows[0]["income"] == Decimal("500.00") assert rows[1]["income"] == Decimal("0.00")