02db5430eb
Security - Every route now requires a login and refuses ids outside the caller's workspace with 404: plan, leave-wishes, day-overrides and vacation-days were fully anonymous; every other router trusted client-supplied workspace/child/parent ids. Scraper sessions are bound to their owner. - Invitations can no longer be created for a foreign workspace, and a redeemer who is already a member (or a full workspace) is refused. - Production refuses the default JWT secret; API docs are hidden in production; a failed migration aborts startup instead of serving. - Login and register no longer reveal whether an email exists; inactive accounts are rejected; /auth/refresh is rate limited. - The FK scraper writes debug artefacts only when explicitly enabled, logs no scraped values or page text, clears the BankID QR as soon as it is scanned and purges finished sessions after five minutes. - Real FK page captures are removed from the tree (history rewrite follows); the parser tests use a synthetic fixture. Performance and correctness - Plan apply/sync run inside one locked transaction with batched writes instead of one commit per row, so a failure mid-batch leaves nothing half-applied and concurrent syncs no longer corrupt each other. - SQLite runs in WAL mode with a busy timeout; 14 indexes cover the filters that were full scans; argon2 hashing runs off the event loop; responses are gzipped. - Frontend: a 401 now refreshes the token once and retries, so sessions no longer die silently after 15 minutes; every data hook discards stale responses; logout clears state even when the server call fails. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CsXCCcDfmV4Sps4ZQSvNEY
95 lines
4.1 KiB
Python
95 lines
4.1 KiB
Python
"""HTTP routes for the planning engine.
|
|
|
|
Routers stay thin: validate via Pydantic, call the service, map domain errors
|
|
to HTTP. All allocation logic lives in `app.services.allocation_service`, and
|
|
all bulk-apply logic (idempotency, collisions, `replace`, validation) lives in
|
|
`app.services.planning_service.PlanningService.apply_proposed_days`. See
|
|
PLANNING_ENGINE_SPEC.md §4.
|
|
"""
|
|
|
|
from fastapi import APIRouter, HTTPException, status
|
|
|
|
from app.dependencies import PlanningEngineServiceDep, PlanningServiceDep, WorkspaceScopeDep
|
|
from app.models.plan import (
|
|
PlanApplyRequest,
|
|
PlanApplyResponse,
|
|
PlanProposalResponse,
|
|
PlanProposeRequest,
|
|
PlanSyncRequest,
|
|
PlanSyncResponse,
|
|
)
|
|
from app.utils.errors import NotFoundError, ValidationError
|
|
|
|
router = APIRouter(prefix="/api/plan", tags=["plan"])
|
|
|
|
|
|
@router.post("/propose", response_model=PlanProposalResponse)
|
|
async def propose_plan(
|
|
payload: PlanProposeRequest, service: PlanningEngineServiceDep, scope: WorkspaceScopeDep
|
|
) -> PlanProposalResponse:
|
|
"""Compute a plan proposal. Read-only — persists nothing, safe to spam."""
|
|
scope.check_workspace(payload.workspace_id)
|
|
try:
|
|
proposal = await service.propose(payload.workspace_id)
|
|
except NotFoundError as exc:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
|
|
except ValidationError as exc:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
|
|
return PlanProposalResponse.from_domain(proposal)
|
|
|
|
|
|
@router.post("/apply", response_model=PlanApplyResponse)
|
|
async def apply_plan(
|
|
payload: PlanApplyRequest, service: PlanningServiceDep, scope: WorkspaceScopeDep
|
|
) -> PlanApplyResponse:
|
|
"""Accept a (possibly user-edited) set of proposed days as real plan.
|
|
|
|
Always returns 200 with `accepted: false` and a `rejections`/`collisions`
|
|
breakdown when the batch is refused — refusal (a collision without
|
|
`replace`, an invalid day type, a balance/eligibility violation) is an
|
|
expected, structured outcome for the UI to render, not an HTTP error.
|
|
A genuinely missing workspace/child (404) is the one case still raised
|
|
as an HTTP error, since that's not something the batch report can explain.
|
|
"""
|
|
scope.check_workspace(payload.workspace_id)
|
|
# Every child/parent named in the batch must belong to the caller's own
|
|
# workspace too — otherwise a forged child_id/parent_personal_data_uuid
|
|
# could write a planned_leave_day row attributed to another tenant's
|
|
# child or parent even though workspace_id itself checks out.
|
|
for child_id in {item.child_id for item in payload.days}:
|
|
await scope.check_child(child_id)
|
|
for parent_id in {item.parent_personal_data_uuid for item in payload.days}:
|
|
await scope.check_member(parent_id)
|
|
try:
|
|
result = await service.apply_proposed_days(
|
|
workspace_id=payload.workspace_id,
|
|
days=[item.to_domain() for item in payload.days],
|
|
replace=payload.replace,
|
|
)
|
|
except NotFoundError as exc:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
|
|
return PlanApplyResponse.from_domain(result)
|
|
|
|
|
|
@router.post("/sync", response_model=PlanSyncResponse)
|
|
async def sync_plan(
|
|
payload: PlanSyncRequest, service: PlanningServiceDep, scope: WorkspaceScopeDep
|
|
) -> PlanSyncResponse:
|
|
"""Recompute and persist a workspace's plan in one step.
|
|
|
|
The direct-manipulation calendar UX's one call: no separate preview
|
|
step. Runs propose then apply internally (see
|
|
`PlanningService.sync_plan`), never retyping or overwriting a day the
|
|
user has pinned, and reports exactly what changed (`changes`) so the UI
|
|
can show e.g. "Sommar 2028 flyttades 2 dagar — Ångra" instead of
|
|
silently rewriting the calendar.
|
|
"""
|
|
scope.check_workspace(payload.workspace_id)
|
|
try:
|
|
result = await service.sync_plan(payload.workspace_id)
|
|
except NotFoundError as exc:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from exc
|
|
except ValidationError as exc:
|
|
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
|
|
return PlanSyncResponse.from_domain(result)
|