Files
F-r-ldraledigplannerare/backend/app/models/plan.py
T
jacobh2 014503e89b Spend vacation on the days worth having, and name the ones about to expire
The planner knew exactly how many semesterdagar a parent was about to
forfeit and never placed a single day to prevent it. It also had no
weekend-wrap logic at all: REASON_VACATION_WRAP_WEEKEND was stamped on
every tier-3 interior vacation day, including a lone Tuesday in February.

Two changes.

Spend better. A workday adjacent to a free stretch, or in the middle of a
gap of three or fewer fenced by free days, now takes vacation --
_vacation_bridge_reason, consulted for every parent type. This departs
from spec 6.1's "wrapping suppressed for hourly": the FP-preservation
argument is salary-type independent, only the pay argument was hourly-moot.
In a both-parents window, both now take vacation on such a date rather
than one paying with FP. After funding, reallocate_vacation_by_value swaps
vacation onto higher-ranked dates 1-for-1 with FP days, so which dates hold
vacation improves while how many never drops -- greedy first, re-timed
after, never withheld. An invariant test asserts the count can only rise.

Name the losses. A new pass proposes concrete dates for vacation that would
otherwise expire, current year only, ranked red-day bridge then weekend
bridge then interior, later dates first. They ride on
PlanProposal.rescue_days, kept off `days` so nothing downstream commits
them, and surface on the Dashboard with accept-one, accept-all (one
batched /api/plan/apply, not N) and dismiss. Dismissal reuses the
tip_dismissal table, keyed on (parent, year) identity rather than the
group's dates -- those are recomputed from the whole plan's residual on
every propose, so date-hashing made dismissal self-defeating. Dismiss does
not bump the plan version; it changes no data and must not trigger a write.

Measured on the seeded demo: 12 forfeiting days for one parent now yield 12
proposed dates, all Fridays or Mondays. Total vacation placed is unchanged
at 203 days, confirming the reallocation only re-times.

Three defects here were found by driving a browser, while 2273 unit tests
passed -- all three lived in the seam between layers that unit tests mock
away. Adds API-level tests over the real request sequence. Rate limiting is
now off in tests (one file consumed the whole registration budget) with the
suite's first real 429 assertion.

PROPOSE_VS_SYNC_BUG.md documents a pre-existing, unfixed issue found along
the way: Dashboard figures swing on the first sync with no user action.

Backend 946 tests, frontend 1341, coverage above all gates.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YZaX6xbuMEMXuyKA1fq2Mm
2026-09-21 07:00:18 +02:00

550 lines
19 KiB
Python

"""API schemas (Pydantic) for the planning-engine endpoints.
See PLANNING_ENGINE_SPEC.md §4. `POST /api/plan/propose` is read-only and
persists nothing — it just runs `PlanningEngineService.propose()` and shapes
the resulting (pure) `PlanProposal` for the wire.
`POST /api/plan/apply` is the other half: it takes a (possibly user-edited)
subset of a proposal's `days` and turns it into real `planned_leave_day`
rows via `PlanningService.apply_proposed_days`. See that method's docstring
for the idempotency/collision/`replace` semantics.
"""
from datetime import date
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, Field
from app.models.planned_leave import PlannedLeaveDayResponse
from app.services.allocation_service import PlanProposal
from app.services.planning_service import (
DayCollision,
EvictionCandidate,
EvictionPreview,
PlanApplyResult,
PlanChange,
PlanSyncResult,
ProposedDayInput,
Rejection,
ResourceShortage,
)
# Wire-level mirror of `PlanningService`'s `EVICTION_CHOICE_*` constants —
# kept as a `Literal` here (rather than importing the string constants) so
# an invalid value 422s at the Pydantic boundary instead of silently
# reaching the service as a no-op "do nothing".
EvictionChoice = Literal["drop_future_pl", "drop_latest_vacation_this_year"]
class PlanProposeRequest(BaseModel):
workspace_id: UUID
class ProposedDayResponse(BaseModel):
date: date
parent_personal_data_uuid: UUID
child_id: UUID | None
day_type: str
is_dubbeldag: bool
wish_id: UUID
reason: str
class ShortfallRemedyResponse(BaseModel):
kind: str
message_key: str
data: dict[str, object]
days_freed: int
class SurplusAdviceResponse(BaseModel):
"""§9.2 — the mirror of `ShortfallRemedyResponse`: a concrete suggestion
for a parent forecast to *forfeit* FP days at the age-4 boundary, rather
than run short. Same (kind, message_key/data, day-count) shape as the
remedy; `data` mirrors `PlanWarningResponse.data` for the (parent, child)
scope.
"""
kind: str
message_key: str
days_involved: int
data: dict[str, object]
class RescueDayResponse(BaseModel):
"""§vacation-rescue — a suggest-only concrete date to spend a vacation
day that would otherwise expire this year — see `RescueDay`
(app/services/allocation_service.py) for why this rides on its own
`PlanProposalResponse.rescue_days` field rather than joining `days`: it
has no wish behind it and must never be picked up by anything that
iterates the proposal's `days` before the user explicitly accepts it.
"""
date: date
parent_personal_data_uuid: UUID
child_id: UUID
year: int
reason: str
class WindowOutcomeResponse(BaseModel):
wish_id: UUID
wish_name: str
# i18n provenance of `wish_name` — see `WindowOutcome.wish_name_message_key`
# (app/services/allocation_service.py). `None` for a free-typed/user-renamed
# wish, or any row predating this field.
wish_name_message_key: str | None
year: int
start_date: date
end_date: date
weeks_wished: int
weeks_funded: float
shortfall_days: int
strategy: str
requested_strategy: str
strategy_degraded: bool
dubbeldagar_legally_available: bool
message_key: str
data: dict[str, object]
cost_breakdown: dict[str, int]
remedies: list[ShortfallRemedyResponse]
# Mirrors `WindowOutcome.shift_gain_days` (app/services/allocation_service.py)
# — spendable days the flexible placement search saved versus the naive
# bound-start placement. 0 for a fixed window or a reused flexible one.
shift_gain_days: int = 0
class PlanWarningResponse(BaseModel):
kind: str
message_key: str
data: dict[str, object]
class PoolBalanceResponse(BaseModel):
parent_personal_data_uuid: UUID
child_id: UUID
sjukpenning_left: int
lagsta_left: int
dubbeldagar_left: int
class VacationBalanceResponse(BaseModel):
parent_personal_data_uuid: UUID
year: int
total_days: int
saved_days_in: int
already_used: int
# True when no `vacation_days` row existed for this (parent, year) and the
# loader defaulted `total_days` to the statutory entitlement rather than
# an entered value — see `VacationBudget.is_assumed`. The UI should use
# this to prompt the user to confirm/override the assumed year instead of
# silently treating it as a real entry.
is_assumed: bool
class Age4ProjectionResponse(BaseModel):
"""§3.3 part 2 — plan-aware age-4 projection: what this *proposed* plan
(not yet applied) implies at the child's 4th birthday, per (parent,
child). Always present, unlike `surplus_advice` which is only emitted
when there's a surplus to advise on.
"""
parent_personal_data_uuid: UUID
child_id: UUID
fourth_birthday: date
projected_left_at_b4: int
savable_after_b4: int
expiring_at_b4: int
savable_cap_at_b4: int
class PlanProposalResponse(BaseModel):
days: list[ProposedDayResponse]
outcomes: list[WindowOutcomeResponse]
warnings: list[PlanWarningResponse]
pool_balances: list[PoolBalanceResponse]
vacation_balances: list[VacationBalanceResponse]
surplus_advice: list[SurplusAdviceResponse]
age4_projections: list[Age4ProjectionResponse]
rescue_days: list[RescueDayResponse]
@classmethod
def from_domain(cls, proposal: PlanProposal) -> "PlanProposalResponse":
return cls(
days=[
ProposedDayResponse(
date=d.date,
parent_personal_data_uuid=d.parent_personal_data_uuid,
child_id=d.child_id,
day_type=d.day_type,
is_dubbeldag=d.is_dubbeldag,
wish_id=d.wish_id,
reason=d.reason,
)
for d in proposal.days
],
outcomes=[
WindowOutcomeResponse(
wish_id=o.wish_id,
wish_name=o.wish_name,
wish_name_message_key=o.wish_name_message_key,
year=o.year,
start_date=o.start_date,
end_date=o.end_date,
weeks_wished=o.weeks_wished,
weeks_funded=o.weeks_funded,
shortfall_days=o.shortfall_days,
strategy=o.strategy,
requested_strategy=o.requested_strategy,
strategy_degraded=o.strategy_degraded,
dubbeldagar_legally_available=o.dubbeldagar_legally_available,
message_key=o.message_key,
data=o.data,
cost_breakdown=o.cost_breakdown,
remedies=[
ShortfallRemedyResponse(
kind=r.kind,
message_key=r.message_key,
data=r.data,
days_freed=r.days_freed,
)
for r in o.remedies
],
shift_gain_days=o.shift_gain_days,
)
for o in proposal.outcomes
],
warnings=[
PlanWarningResponse(kind=w.kind, message_key=w.message_key, data=w.data)
for w in proposal.warnings
],
pool_balances=[
PoolBalanceResponse(
parent_personal_data_uuid=parent_id,
child_id=child_id,
sjukpenning_left=pool.sjukpenning_left,
lagsta_left=pool.lagsta_left,
dubbeldagar_left=pool.dubbeldagar_left,
)
for (parent_id, child_id), pool in proposal.balances_after.pools_after.items()
],
vacation_balances=[
VacationBalanceResponse(
parent_personal_data_uuid=parent_id,
year=year,
total_days=budget.total_days,
saved_days_in=budget.saved_days_in,
already_used=budget.already_used,
is_assumed=budget.is_assumed,
)
for (parent_id, year), budget in proposal.balances_after.vacation_after.items()
],
surplus_advice=[
SurplusAdviceResponse(
kind=a.kind,
message_key=a.message_key,
days_involved=a.days_involved,
data=a.data,
)
for a in proposal.surplus_advice
],
age4_projections=[
Age4ProjectionResponse(
parent_personal_data_uuid=p.parent_personal_data_uuid,
child_id=p.child_id,
fourth_birthday=p.fourth_birthday,
projected_left_at_b4=p.projected_left_at_b4,
savable_after_b4=p.savable_after_b4,
expiring_at_b4=p.expiring_at_b4,
savable_cap_at_b4=p.savable_cap_at_b4,
)
for p in proposal.age4_projections
],
rescue_days=[
RescueDayResponse(
date=r.date,
parent_personal_data_uuid=r.parent_personal_data_uuid,
child_id=r.child_id,
year=r.year,
reason=r.reason,
)
for r in proposal.rescue_days
],
)
# ---------------------------------------------------------------------------
# POST /api/plan/apply
# ---------------------------------------------------------------------------
class ProposedDayApplyItem(BaseModel):
"""One day to persist. Same shape as `ProposedDayResponse` minus the
explain-only `reason` (harmless if a caller sends it anyway — a frontend
can hand back `ProposedDayResponse` entries from `/propose` verbatim;
extra fields are ignored). `wish_id` DOES carry persistence meaning here
(unlike `reason`): it links the persisted row back to the wish that
produced it, so a client handing back a `/propose` day verbatim gets that
attribution persisted for free.
`day_type` additionally accepts 'free' (an automatic weekend/red-day
entry from a proposal) purely so a client doesn't have to filter those
out itself — they are always skipped, never persisted, see
`PlanApplyResponse.skipped_free_count`.
"""
date: date
parent_personal_data_uuid: UUID
child_id: UUID
day_type: str = Field(pattern="^(sjukpenning|lagsta|vacation|free)$")
is_dubbeldag: bool = False
wish_id: UUID | None = None
is_pinned: bool = False
def to_domain(self) -> ProposedDayInput:
return ProposedDayInput(
date=self.date,
parent_personal_data_uuid=self.parent_personal_data_uuid,
child_id=self.child_id,
day_type=self.day_type,
is_dubbeldag=self.is_dubbeldag,
wish_id=self.wish_id,
is_pinned=self.is_pinned,
)
class PlanApplyRequest(BaseModel):
workspace_id: UUID
days: list[ProposedDayApplyItem]
replace: bool = False
class DayCollisionResponse(BaseModel):
date: date
parent_personal_data_uuid: UUID
child_id: UUID
existing_day_type: str
proposed_day_type: str
@classmethod
def from_domain(cls, collision: DayCollision) -> "DayCollisionResponse":
return cls(
date=collision.date,
parent_personal_data_uuid=collision.parent_personal_data_uuid,
child_id=collision.child_id,
existing_day_type=collision.existing_day_type,
proposed_day_type=collision.proposed_day_type,
)
class RejectionResponse(BaseModel):
"""§3.5 — a single reason a batch (or part of it) was refused, i18n-ready:
`message_key` + `data` (the `tips_service.Tip` shape) instead of a
pre-rendered string, so `PlanResults.tsx` can render it in the caller's
active locale.
"""
message_key: str
data: dict[str, object]
@classmethod
def from_domain(cls, rejection: Rejection) -> "RejectionResponse":
return cls(message_key=rejection.message_key, data=rejection.data)
class PlanApplyResponse(BaseModel):
accepted: bool
created_count: int
skipped_identical_count: int
skipped_free_count: int
replaced_count: int
deleted_count: int
collisions: list[DayCollisionResponse]
rejections: list[RejectionResponse]
created_days: list[PlannedLeaveDayResponse]
@classmethod
def from_domain(cls, result: PlanApplyResult) -> "PlanApplyResponse":
return cls(
accepted=result.accepted,
created_count=result.created_count,
skipped_identical_count=result.skipped_identical_count,
skipped_free_count=result.skipped_free_count,
replaced_count=result.replaced_count,
deleted_count=result.deleted_count,
collisions=[DayCollisionResponse.from_domain(c) for c in result.collisions],
rejections=[RejectionResponse.from_domain(r) for r in result.rejections],
created_days=[PlannedLeaveDayResponse.from_entity(d) for d in result.created],
)
# ---------------------------------------------------------------------------
# POST /api/plan/sync
# ---------------------------------------------------------------------------
class PlanSyncRequest(BaseModel):
workspace_id: UUID
# Which of the three user-facing options resolves a would-evict save
# (§ eviction preview). Omitted/`None` — the default — means "do
# nothing": the save is refused and nothing is mutated, exactly as if
# the user picked the explicit cancel option. Only meaningful when the
# response's `eviction_preview.would_evict` was `True` on a prior call
# with the same edit already persisted upstream (e.g. via the leave-wish
# endpoints) — a plain sync that fits within budget ignores this field
# entirely (never asked for a choice in the first place).
eviction_choice: EvictionChoice | None = None
class PlanChangeResponse(BaseModel):
"""One (child, parent, date) slot's delta from a `sync` call — see
`PlanChange`'s docstring for the `kind` vocabulary. Structured data only;
the frontend composes the toast copy ("Sommar 2028 flyttades 2 dagar —
Ångra") itself.
"""
kind: str
date: date
parent_personal_data_uuid: UUID
child_id: UUID
old_day_type: str | None
new_day_type: str | None
old_is_dubbeldag: bool | None
new_is_dubbeldag: bool | None
old_wish_id: UUID | None
new_wish_id: UUID | None
@classmethod
def from_domain(cls, change: PlanChange) -> "PlanChangeResponse":
return cls(
kind=change.kind,
date=change.date,
parent_personal_data_uuid=change.parent_personal_data_uuid,
child_id=change.child_id,
old_day_type=change.old_day_type,
new_day_type=change.new_day_type,
old_is_dubbeldag=change.old_is_dubbeldag,
new_is_dubbeldag=change.new_is_dubbeldag,
old_wish_id=change.old_wish_id,
new_wish_id=change.new_wish_id,
)
class EvictionCandidateResponse(BaseModel):
"""One previously-persisted day a fresh sync would otherwise silently
delete — see `EvictionCandidate`'s docstring. `wish_name` is `None` when
the owning wish's name couldn't be resolved (never a reason to hide the
day itself).
"""
date: date
parent_personal_data_uuid: UUID
child_id: UUID
day_type: str
is_dubbeldag: bool
wish_id: UUID
wish_name: str | None
@classmethod
def from_domain(cls, candidate: EvictionCandidate) -> "EvictionCandidateResponse":
return cls(
date=candidate.date,
parent_personal_data_uuid=candidate.parent_personal_data_uuid,
child_id=candidate.child_id,
day_type=candidate.day_type,
is_dubbeldag=candidate.is_dubbeldag,
wish_id=candidate.wish_id,
wish_name=candidate.wish_name,
)
class ResourceShortageResponse(BaseModel):
"""One exhausted resource behind an eviction preview — see
`ResourceShortage`'s docstring. `resource_kind == 'parental_leave'`
carries `tier`/`child_id` (`year` is `None`); `resource_kind ==
'vacation'` carries `year` instead (`tier`/`child_id` are `None`).
Structured on purpose — the frontend composes the warning text itself,
never a backend-rendered string.
"""
resource_kind: str
parent_personal_data_uuid: UUID
tier: str | None
child_id: UUID | None
year: int | None
days_evicted: int
@classmethod
def from_domain(cls, shortage: ResourceShortage) -> "ResourceShortageResponse":
return cls(
resource_kind=shortage.resource_kind,
parent_personal_data_uuid=shortage.parent_personal_data_uuid,
tier=shortage.tier,
child_id=shortage.child_id,
year=shortage.year,
days_evicted=shortage.days_evicted,
)
class EvictionPreviewResponse(BaseModel):
"""Always present on `PlanSyncResponse`; `would_evict: false` with empty
lists in the common (fits-within-budget) case — see
`EvictionPreview`'s docstring.
"""
would_evict: bool
candidates: list[EvictionCandidateResponse]
shortages: list[ResourceShortageResponse]
@classmethod
def from_domain(cls, preview: EvictionPreview) -> "EvictionPreviewResponse":
return cls(
would_evict=preview.would_evict,
candidates=[EvictionCandidateResponse.from_domain(c) for c in preview.candidates],
shortages=[ResourceShortageResponse.from_domain(s) for s in preview.shortages],
)
# ---------------------------------------------------------------------------
# POST /api/plan/rescue-days/dismiss
# ---------------------------------------------------------------------------
class RescueDayDismissRequest(BaseModel):
"""Dismiss one (parent, year) group of suggested vacation-rescue days —
see `PlanningEngineService.dismiss_rescue_days`. No `date`/`reason` list
here on purpose: the service recomputes the currently-suggested group
itself rather than trusting a client-supplied date list (same shape as
`TipDismissalCreate`/`TipsService.dismiss`).
"""
workspace_id: UUID
parent_personal_data_uuid: UUID
year: int
class PlanSyncResponse(BaseModel):
proposal: PlanProposalResponse
apply_result: PlanApplyResponse
changes: list[PlanChangeResponse]
eviction_preview: EvictionPreviewResponse
@classmethod
def from_domain(cls, result: PlanSyncResult) -> "PlanSyncResponse":
return cls(
proposal=PlanProposalResponse.from_domain(result.proposal),
apply_result=PlanApplyResponse.from_domain(result.apply_result),
changes=[PlanChangeResponse.from_domain(c) for c in result.changes],
eviction_preview=EvictionPreviewResponse.from_domain(result.eviction_preview),
)