fire-planner/fire_planner/api/income_streams.py
Viktor Barzin 9cc781a8d6
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
fire-planner: ProjectionLab parity Wave 1 — tabbed shell, year stats, goals,
income streams, Sankey cashflow, progress overlay, settings sub-pages

Wave 1 (9 features across 4 streams):

Stream A — dashboard skeleton
  1.A.1 ScenarioShell with top tabs (Plan/Cash Flow/Tax Analytics/Compare/
        Reports/Estate/Settings) + left Sidebar with Plans switcher.
  1.A.2 GET /scenarios/{id}/year-stats?year=N returning per-year metrics
        (NW, Δ NW, taxable income, taxes, eff. rate, spending, contribs,
        investment growth). YearScrubber + YearStatsPanel render the
        right-hand sidebar; URL ?year= preserves selection.
  1.A.3 FanChart gains optional `milestones` prop (lib/milestone.ts maps
        life_event.kind → emoji) + selectedYear marker line.

Stream B — goals + progress
  1.B.1 New goals_eval module: target_nw_by_year / never_run_out /
        target_real_income probability evaluation. Wired into POST
        /simulate (exact, per-path) and GET /scenarios/{id}/projection
        (approximated from persisted fan via percentile interpolation).
        GoalsSection renders pass/fail badges.
  1.B.2 GET /scenarios/{id}/progress overlays AccountSnapshot totals on
        the projection fan; ProgressPage shows variance side-panel.

Stream C — income + cashflow
  1.C.1 New IncomeStream model + alembic 0003 + CRUD endpoints. Engine
        aggregates streams into per-year inflows + taxable arrays;
        income tax routes through the jurisdiction tax engine.
        IncomeStreamsSection on Plan tab.
  1.C.2 GET /scenarios/{id}/cashflow?year=N returns sources/sinks for
        an ECharts Sankey (sums conserve). CashflowTab body.

Stream D — settings
  1.D.1 SettingsTab + sub-nav (Milestones/Rates/Dividends/Bonds/Tax/
        Metrics/Other/Notes); placeholder cards for unbuilt sub-pages.
  1.D.2 LifeEventsSection relocated to /scenarios/:id/settings.
  1.D.3 RatesSettings (Fixed/Historical/Advanced segmented + per-asset
        cards). SimulateRequest gains rates_mode, inflation_pct,
        stocks/bonds growth + dividend, stocks_allocation. New
        build_fixed_paths() in simulator. Real-return arithmetic
        verified against (1+g+d)/(1+i)−1 ≈ 5.4%.
  1.D.4 NotesSettings — markdown textarea, save-on-blur, stored in
        scenario.config_json.notes.

Backend: 238 pytest pass (+19 new), mypy + ruff clean.
Frontend: typecheck + 7 unit tests + production build clean.

Roadmap for Wave 2-N is documented in the implementation plan.
2026-05-10 12:49:44 +00:00

98 lines
3.2 KiB
Python

"""Income-stream CRUD nested under a scenario.
Streams are typed (salary / dividend / rental / pension / social_security
/ rsu / other) so the simulator can route the after-tax cash through the
jurisdiction tax engine using `tax_treatment` as the bucket.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from fire_planner.api.dependencies import get_session
from fire_planner.api.schemas import (
IncomeStreamCreate,
IncomeStreamOut,
IncomeStreamPatch,
)
from fire_planner.db import IncomeStream, Scenario
router = APIRouter(tags=["income-streams"])
@router.get(
"/scenarios/{scenario_id}/income-streams",
response_model=list[IncomeStreamOut],
)
async def list_streams(
scenario_id: int,
session: AsyncSession = Depends(get_session),
) -> list[IncomeStream]:
scen = await session.get(Scenario, scenario_id)
if scen is None:
raise HTTPException(status_code=404, detail="Scenario not found")
rows = (await session.execute(
select(IncomeStream).where(IncomeStream.scenario_id == scenario_id).order_by(
IncomeStream.start_year, IncomeStream.id))).scalars().all()
return list(rows)
@router.post(
"/scenarios/{scenario_id}/income-streams",
response_model=IncomeStreamOut,
status_code=201,
)
async def create_stream(
scenario_id: int,
payload: IncomeStreamCreate,
session: AsyncSession = Depends(get_session),
) -> IncomeStream:
scen = await session.get(Scenario, scenario_id)
if scen is None:
raise HTTPException(status_code=404, detail="Scenario not found")
if payload.end_year is not None and payload.end_year < payload.start_year:
raise HTTPException(status_code=400, detail="end_year < start_year")
stream = IncomeStream(scenario_id=scenario_id, **payload.model_dump())
session.add(stream)
await session.commit()
await session.refresh(stream)
return stream
@router.patch(
"/income-streams/{stream_id}",
response_model=IncomeStreamOut,
)
async def patch_stream(
stream_id: int,
payload: IncomeStreamPatch,
session: AsyncSession = Depends(get_session),
) -> IncomeStream:
stream = await session.get(IncomeStream, stream_id)
if stream is None:
raise HTTPException(status_code=404, detail="Income stream not found")
updates = payload.model_dump(exclude_unset=True)
for k, v in updates.items():
setattr(stream, k, v)
if stream.end_year is not None and stream.end_year < stream.start_year:
raise HTTPException(status_code=400, detail="end_year < start_year")
await session.commit()
await session.refresh(stream)
return stream
@router.delete(
"/income-streams/{stream_id}",
status_code=204,
response_model=None,
)
async def delete_stream(
stream_id: int,
session: AsyncSession = Depends(get_session),
) -> None:
stream = await session.get(IncomeStream, stream_id)
if stream is None:
raise HTTPException(status_code=404, detail="Income stream not found")
await session.execute(delete(IncomeStream).where(IncomeStream.id == stream_id))
await session.commit()