Files
F-r-ldraledigplannerare/backend/tests/unit/test_services/test_allocation_input_loader.py
T
jacobh2 76b1e712b9 Complete NextSteps roadmap: planning engine UI, calendar cluster, flexible wishes
Works through every numbered item in NextSteps260913.md section 3, plus the
three known verification issues in section 4.1.

Surface what the backend already computed:
- 3.1 render surplus_advice in PlanResults, mirroring the shortfall remedies
- 3.2 surface VacationBalance.is_assumed so assumed statutory years are visible
- 3.3 age-4 expiry given the proposed plan, via a new Age4Projection reusing
  the existing _age4_projections arithmetic (Dashboard stat verified, not rebuilt)

Calendar cluster (one pass over the holiday data):
- new GET /api/calendar/days exposing roda dagar, klamdagar and day overrides,
  paginated four years at a time
- 3.4 shade roda dagar/klamdagar, with R/K badges so colour is not the only signal
- 3.6 click-to-override behind an explicit mode toggle, leaving drag multi-select intact
- 3.7 click month/year to advance
- 3.8 per-year red-days list in Settings, statutory days plus overrides

i18n:
- 3.5 five backend-generated Swedish surfaces converted to message_key + data,
  following the tips_service pattern; old string fields replaced, not kept

Flexible wishes (3.9):
- PLANNING_ENGINE_SPEC section 10: window_mode, candidate search, cost function,
  deterministic tie-break, two-pass ordering, test matrix rows 15-24
- backend: entity, migration 006, _FULL_SCHEMA sync, repository, allocator
- frontend: season-preset toggle in WishEditor, unplaced outcome rendering

Fixes (4.1):
- pin typecheck to the local tsc rather than npx resolving a newer TypeScript
- ignore generated coverage/ and dist/ in the ESLint flat config
- fix the flaky usePlanApply test properly, with waitFor rather than a retry

Tests: backend 361 -> 404, frontend 540 -> 704. Coverage 89.47% -> 96.52% lines.

Not yet verified in a browser.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RXMhc9nT6sNz1SL4j8dznL
2026-09-14 02:33:03 +02:00

394 lines
15 KiB
Python

"""Tests for `AllocationInputLoader` — the only I/O-touching half of the
planning engine (see app.services.allocation_service module docstring).
Uses the same sqlite-backed fixtures as the rest of the service test suite
(tests/conftest.py) to seed a realistic workspace and verify the loader nets
out already-committed `planned_leave_day` rows, falls back to default
entitlement when no FK snapshot exists, and reads `planning_mode` /
`planning_goal` off the workspace.
"""
from datetime import date, datetime
from uuid import uuid4
import pytest
from app.entities.child import Child
from app.entities.day_override import DayOverride
from app.entities.parental_leave import ParentalLeaveFetch, TierData
from app.entities.personal_data import PersonalData
from app.entities.planned_leave import PlannedLeaveDay
from app.entities.vacation_days import VacationDays
from app.entities.workspace import Workspace
from app.repositories_impl.sqlite.child_repository import SQLiteChildRepository
from app.repositories_impl.sqlite.day_override_repository import SQLiteDayOverrideRepository
from app.repositories_impl.sqlite.leave_wish_repository import SQLiteLeaveWishRepository
from app.repositories_impl.sqlite.parental_leave_repository import SQLiteParentalLeaveRepository
from app.repositories_impl.sqlite.personal_data_repository import SQLitePersonalDataRepository
from app.repositories_impl.sqlite.planned_leave_repository import SQLitePlannedLeaveRepository
from app.repositories_impl.sqlite.vacation_days_repository import SQLiteVacationDaysRepository
from app.repositories_impl.sqlite.workspace_repository import SQLiteWorkspaceRepository
from app.services.allocation_service import AllocationInputLoader, Allocator, PlanningEngineService
from app.utils.errors import NotFoundError
def _make_loader(
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> AllocationInputLoader:
return AllocationInputLoader(
workspace_repo=workspace_repo,
child_repo=child_repo,
personal_data_repo=personal_data_repo,
parental_leave_repo=parental_leave_repo,
vacation_repo=vacation_repo,
planned_leave_repo=planned_leave_repo,
leave_wish_repo=leave_wish_repo,
)
class TestAllocationInputLoader:
async def test_workspace_not_found_raises(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
loader = _make_loader(
workspace_repo,
child_repo,
personal_data_repo,
parental_leave_repo,
vacation_repo,
planned_leave_repo,
leave_wish_repo,
)
with pytest.raises(NotFoundError):
await loader.load(uuid4(), today=date(2027, 1, 1))
async def test_load_nets_out_committed_days_and_defaults_entitlement(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
now = datetime.now()
ws = await workspace_repo.create(
Workspace(
id=uuid4(),
name="Familj",
planning_goal="max_money",
planning_mode="couple",
created_at=now,
)
)
parent_with_fetch = await personal_data_repo.create(
PersonalData(
uuid=uuid4(),
workspace_id=ws.id,
name="Parent1",
salary_type="monthly",
employment_status="employed",
created_at=now,
)
)
parent_without_fetch = await personal_data_repo.create(
PersonalData(
uuid=uuid4(),
workspace_id=ws.id,
name="Parent2",
salary_type="hourly",
employment_status="employed",
created_at=now,
)
)
child = await child_repo.create(
Child(
id=uuid4(),
workspace_id=ws.id,
name="Barn",
birth_date=date(2026, 1, 1),
created_at=now,
)
)
tier = TierData(
sjukpenning_total=390,
sjukpenning_used=100,
sjukpenning_left=290,
lagsta_niva_total=90,
lagsta_niva_used=0,
lagsta_niva_left=90,
)
await parental_leave_repo.create(
ParentalLeaveFetch(
id=uuid4(),
personal_data_uuid=parent_with_fetch.uuid,
workspace_id=ws.id,
child_id=child.id,
source="manual",
fetched_at=now,
total_days=240,
days_used=100,
days_left=140,
reserved_days_total=90,
reserved_days_left=90,
transferable_days_left=50,
dubbeldagar_left=60,
tier_data=tier,
created_at=now,
updated_at=now,
)
)
# Two already-committed FP days for parent_with_fetch that the FK
# snapshot above does not know about yet -> must be netted out.
for i in range(2):
await planned_leave_repo.create(
PlannedLeaveDay(
id=uuid4(),
workspace_id=ws.id,
child_id=child.id,
parent_personal_data_uuid=parent_with_fetch.uuid,
date=date(2027, 3, 1 + i),
day_type="sjukpenning",
)
)
# A committed vacation day for the same parent, in 2027.
await planned_leave_repo.create(
PlannedLeaveDay(
id=uuid4(),
workspace_id=ws.id,
child_id=child.id,
parent_personal_data_uuid=parent_with_fetch.uuid,
date=date(2027, 4, 1),
day_type="vacation",
)
)
await vacation_repo.create(
VacationDays(
id=uuid4(),
personal_data_uuid=parent_with_fetch.uuid,
workspace_id=ws.id,
year=2027,
total_days=25,
saved_days_in=0,
)
)
loader = _make_loader(
workspace_repo,
child_repo,
personal_data_repo,
parental_leave_repo,
vacation_repo,
planned_leave_repo,
leave_wish_repo,
)
alloc_input = await loader.load(ws.id, today=date(2027, 1, 1))
assert alloc_input.planning_mode == "couple"
assert alloc_input.planning_goal == "max_money"
assert alloc_input.today == date(2027, 1, 1)
pool_with_fetch = alloc_input.pools[(parent_with_fetch.uuid, child.id)]
assert pool_with_fetch.sjukpenning_left == 288 # 290 - 2 committed
assert pool_with_fetch.lagsta_left == 90
# No FK snapshot at all for parent_without_fetch -> default entitlement.
pool_defaulted = alloc_input.pools[(parent_without_fetch.uuid, child.id)]
assert pool_defaulted.sjukpenning_left == 390
assert pool_defaulted.lagsta_left == 90
vac = alloc_input.vacation[(parent_with_fetch.uuid, 2027)]
assert vac.total_days == 25
assert vac.already_used == 1 # the committed vacation day
assert len(alloc_input.existing_planned) == 3
assert alloc_input.horizon_end >= date(2030, 1, 1) # at least the child's 4th birthday
assert date(2027, 6, 6) in alloc_input.holidays # Sweden's national day
# Task 1: PersonalData.min_vacation_days_per_year (default 20) must be
# plumbed onto ParentFacts so the pure Allocator can enforce it without
# touching a repository.
parent_facts_by_uuid = {p.uuid: p for p in alloc_input.parents}
assert parent_facts_by_uuid[parent_with_fetch.uuid].min_vacation_days_per_year == 20
assert parent_facts_by_uuid[parent_without_fetch.uuid].min_vacation_days_per_year == 20
async def test_load_reflects_a_custom_minimum_vacation_days(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
"""A parent whose employer sets a higher-than-statutory floor (Task 1)
must have that reflected on `ParentFacts`, not the seeded default."""
now = datetime.now()
ws = await workspace_repo.create(Workspace(id=uuid4(), name="Familj", created_at=now))
parent = await personal_data_repo.create(
PersonalData(
uuid=uuid4(),
workspace_id=ws.id,
name="Parent",
min_vacation_days_per_year=25,
created_at=now,
)
)
loader = _make_loader(
workspace_repo,
child_repo,
personal_data_repo,
parental_leave_repo,
vacation_repo,
planned_leave_repo,
leave_wish_repo,
)
alloc_input = await loader.load(ws.id, today=date(2027, 1, 1))
assert len(alloc_input.parents) == 1
assert alloc_input.parents[0].uuid == parent.uuid
assert alloc_input.parents[0].min_vacation_days_per_year == 25
async def test_planning_engine_service_glues_loader_and_allocator(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
now = datetime.now()
ws = await workspace_repo.create(
Workspace(id=uuid4(), name="Solo", planning_goal="balanced", created_at=now)
)
await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Solo Parent", created_at=now)
)
loader = _make_loader(
workspace_repo,
child_repo,
personal_data_repo,
parental_leave_repo,
vacation_repo,
planned_leave_repo,
leave_wish_repo,
)
service = PlanningEngineService(loader, Allocator())
proposal = await service.propose(ws.id, today=date(2027, 1, 1))
assert proposal.days == []
assert proposal.outcomes == []
async def test_day_overrides_default_to_empty_without_a_repo(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
"""`day_override_repo` is optional (backward compatible) — omitting it
must not crash the loader, just leave `day_overrides` empty."""
ws = await workspace_repo.create(
Workspace(id=uuid4(), name="No overrides", created_at=datetime.now())
)
await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Parent", created_at=datetime.now())
)
loader = _make_loader(
workspace_repo,
child_repo,
personal_data_repo,
parental_leave_repo,
vacation_repo,
planned_leave_repo,
leave_wish_repo,
)
alloc_input = await loader.load(ws.id, today=date(2027, 1, 1))
assert alloc_input.day_overrides == {}
async def test_day_overrides_loaded_from_repository(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
day_override_repo: SQLiteDayOverrideRepository,
) -> None:
"""When a `DayOverrideRepository` is wired in, its rows land in
`AllocationInput.day_overrides` as {date: is_working_day}."""
now = datetime.now()
ws = await workspace_repo.create(
Workspace(id=uuid4(), name="With overrides", created_at=now)
)
await personal_data_repo.create(
PersonalData(uuid=uuid4(), workspace_id=ws.id, name="Parent", created_at=now)
)
await day_override_repo.create(
DayOverride(
id=uuid4(),
workspace_id=ws.id,
date=date(2027, 12, 24),
is_working_day=True,
created_at=now,
updated_at=now,
)
)
await day_override_repo.create(
DayOverride(
id=uuid4(),
workspace_id=ws.id,
date=date(2027, 2, 2),
is_working_day=False,
created_at=now,
updated_at=now,
)
)
loader = AllocationInputLoader(
workspace_repo=workspace_repo,
child_repo=child_repo,
personal_data_repo=personal_data_repo,
parental_leave_repo=parental_leave_repo,
vacation_repo=vacation_repo,
planned_leave_repo=planned_leave_repo,
leave_wish_repo=leave_wish_repo,
day_override_repo=day_override_repo,
)
alloc_input = await loader.load(ws.id, today=date(2027, 1, 1))
assert alloc_input.day_overrides == {
date(2027, 12, 24): True,
date(2027, 2, 2): False,
}