gendesign/backend/app/schemas/concept.py
Light1YT d350d27325
All checks were successful
CI / frontend-tests (pull_request) Successful in 59s
CI / openapi-codegen-check (pull_request) Successful in 1m53s
CI / backend-tests (pull_request) Successful in 10m1s
CI / changes (pull_request) Successful in 7s
feat(finmodel): financing overlay (кредит 15%) поверх unlevered DCF (epic #1881 PR-5)
Финансирование как ДОПОЛНИТЕЛЬНЫЙ overlay поверх готового unlevered cashflow:
кредитная линия покрывает накопительный кассовый разрыв, проценты капитализируются
(compound), ставка _CREDIT_RATE_ANNUAL=15% (норматив, ОТДЕЛЬНО от ставки
дисконтирования — разная семантика: стоимость долга vs требуемая доходность).

Backend (financial.py):
- _compute_financing(operating_cf, annual_rate) — чистая (READ-ONLY вход, не
  мутирует): процент на остаток на начало месяца ДО движений → капитализация;
  draw=-cf при оттоке, repay=min(cf,debt) при притоке (долг не уходит в минус).
  Возвращает peak_debt_rub / total_interest_rub / ending_debt_rub.
- compute_financial: вызов после DCF, net_profit_after_financing = net − interest.
- _build_monthly_cashflow и unlevered NPV/IRR/PBP НЕ ТРОНУТЫ → инвариант
  Σ unlevered cashflow == net_profit сохранён (регресс-тест).
- FinancialModel +6 полей (financing_enabled/annual_rate_used/peak_debt_rub/
  total_interest_rub/net_profit_after_financing_rub/financing_is_simplified).

Frontend: ParcelFinancialEstimate +6 полей; adaptFinanceDrawer + concept-каскад
показывают пиковый долг/проценты/чистую прибыль после финанс. (когда enabled).

MVP: только агрегаты, БЕЗ levered IRR (хрупко на хардкод-100%-долге — отдельный
PR). HEAVY caveat: проценты — реальная стоимость (net после < net до); 100%
покрытие разрыва (нет equity/LTC); compound; эскроу не моделируется; unlevered
headline не затронут. financing_is_simplified=True флаг.

mypy strict clean, +9 backend + 3 frontend тестов (compound точное значение,
no-mutation, инвариант-регресс, монотонность, net_after<net), api-types
регенерён авторитетно, deps не тронуты (hand-roll).

Refs #1881
2026-06-24 01:12:47 +05:00

123 lines
6.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Any, Literal
from pydantic import BaseModel, Field
class ConceptInput(BaseModel):
"""Stage 1a — input contract. Frozen interface for frontend codegen."""
parcel_geojson: dict[str, Any] = Field(
..., description="GeoJSON Polygon of the parcel (WGS84 / EPSG:4326)"
)
housing_class: Literal["econom", "comfort", "business"] = "comfort"
target_floors: int = Field(9, ge=1, le=30)
development_type: Literal["spot", "mid_rise", "high_rise"] = "mid_rise"
land_cost_rub: float | None = Field(
None, ge=0, description="Optional land cost for financial model"
)
class TEAP(BaseModel):
"""Технико-экономические показатели."""
built_area_sqm: float
total_floor_area_sqm: float
residential_area_sqm: float
apartments_count: int
density: float
parking_spaces: int
class FinancialModel(BaseModel):
"""Static developer P&L + monthly-DCF investment metrics (PR-1/PR-3, эпик #1881).
Full static cost cascade + VAT + profit tax → net profit + ROI (PR-1). On top
of that static P&L, PR-3 lays the cascade onto a **monthly cashflow schedule**
(default phase norms — ПИР → СМР → продажи) and runs a real DCF: NPV, IRR
(bisection over the monthly cashflow) and *undiscounted* cumulative payback.
See ``compute_financial`` docstring for the schedule assumptions and the
налоги/рассрочка phasing choices.
``irr`` is a **real** annualised DCF IRR when ``irr_is_proxy is False``; for a
degenerate cashflow with no sign change (e.g. always-loss) the bisection cannot
bracket a root, so we fall back to the PR-1 annualised-ROI proxy and flag
``irr_is_proxy=True``. VAT is a documented simplification (see docstring), not
exact НК РФ mechanics.
The legacy summary fields (``revenue_rub`` / ``cost_rub`` /
``gross_margin_rub`` / ``irr``) are kept for backward-compat; the new fields
expose the full cascade, the net P&L and the DCF metrics.
"""
# ── Legacy summary (backward-compat) ───────────────────────────────────────
revenue_rub: float
cost_rub: float
gross_margin_rub: float
irr: float
# ── Revenue breakdown ──────────────────────────────────────────────────────
revenue_residential_rub: float
revenue_parking_rub: float
# ── Cost cascade ───────────────────────────────────────────────────────────
construction_rub: float
pir_rub: float
networks_rub: float
developer_services_rub: float
contingency_rub: float
marketing_rub: float
land_rub: float
# ── БДР / taxes → net profit ───────────────────────────────────────────────
vat_rub: float
profit_before_tax_rub: float
profit_tax_rub: float
net_profit_rub: float
# ── Metrics ────────────────────────────────────────────────────────────────
roi: float # net profit / total cost
margin_pct: float # net profit / revenue
irr_is_proxy: bool = True # frontend caveat: True → IRR is the ROI-proxy, not DCF
# ── DCF / investment metrics (PR-3, эпик #1881) ────────────────────────────
# NPV дисконтированного помесячного cashflow по ставке ``discount_rate_used``.
npv_rub: float = 0.0
# Окупаемость (мес) по НЕдисконтированному накопительному cashflow, линейная
# интерполяция дробного месяца. ``None`` — проект не окупается на горизонте.
payback_months: float | None = None
# Годовая ставка дисконтирования, фактически применённая в NPV (норматив).
discount_rate_used: float = 0.0
# График фаз/продаж — типовые нормативные ДОПУЩЕНИЯ (не график конкретного
# проекта). True → UI/PDF показывают caveat «график — типовое допущение».
schedule_is_default: bool = True
# ── Financing overlay (PR-5, эпик #1881) ───────────────────────────────────
# OVERLAY поверх unlevered cashflow: кредит покрывает кассовый разрыв, проценты
# капитализируются (compound). Unlevered NPV/IRR (headline) НЕ затронуты.
financing_enabled: bool = False # True когда overlay посчитан
annual_rate_used: float = 0.0 # _CREDIT_RATE_ANNUAL (норматив, отдельно от дисконта)
peak_debt_rub: float = 0.0 # «задолженность по кредиту» Excel — пик долга
total_interest_rub: float = 0.0 # «поток по финдеятельности» Excel — Σ процентов
net_profit_after_financing_rub: float = 0.0 # net_profit total_interest
# honest-флаг: 100% покрытие разрыва, compound %, эскроу не моделируется точно.
financing_is_simplified: bool = True
# ── Price calibration (PR-2, эпик #1881) ───────────────────────────────────
# Цена продажи жилья, руб/кв.м, фактически использованная в выручке. Либо
# калиброванная по рынку (Objective / district reference), либо норматив класса.
# ``price_source`` honest-flag для UI/PDF: не выдавать норматив за рынок.
price_per_sqm_used: float
price_is_calibrated: bool = False
# Значения: "objective_district_median" | "district_reference" | "class_norm".
price_source: str = "class_norm"
class ConceptVariant(BaseModel):
strategy: Literal["max_area", "max_insolation", "balanced"]
buildings_geojson: dict[str, Any]
teap: TEAP
financial: FinancialModel
class ConceptOutput(BaseModel):
variants: list[ConceptVariant]