Files
F-r-ldraledigplannerare/backend/tests/unit/test_services/test_analytics_service.py
T
jacobh2 87b3eb5d0c Fix four bugs found by browser verification
First real browser walkthrough of the app, against seeded demo data. All 1140
tests were passing; none of these four were visible to them.

Age-4 entitlement (high severity, domain bug). The no-snapshot fallback gave a
single parent rules.sjukpenning_days + rules.lagsta_niva_days = 390 + 90 = 480
days, but those config values are the whole CHILD's combined tier totals across
both parents, not one parent's share. The correct fallback is days_per_parent
(240 = 195 + 45), which only AnalyticsService used. So a parent without an FK
snapshot was credited with roughly double their real entitlement, and the
Dashboard and Plan tab disagreed about expiring_at_b4 for the same committed
state. The wrong default existed in three places; allocation_service.py and
planning_service.py are corrected, and analytics_service.py now calls the shared
pure days_left_at_age_4_projection instead of re-deriving the arithmetic, so
there is one source of truth. A test that had encoded the buggy 390/90 default
as expected behaviour is corrected too.

The Dashboard stat is workspace-wide while the Plan tab breaks down per parent,
which is legitimate but was unlabelled and contributed to the confusion; the
dashboard label now says it is a combined all-parents total.

Nonsensical remedy text. lower_priority_wish computed
max(other.target_weeks // 2, 1), which for a 1-week wish clamped back to 1 and
rendered "Lowering Var from 1 to 1 weeks frees up 32 days". target_weeks has a
domain floor of 1 and the planner works in whole days, so there is no smaller
whole-week suggestion to make: the remedy is now suppressed for 1-week wishes.
Wishes of 2+ weeks still get a genuine, strictly smaller suggestion.

Day override invisible until reload. Calendar refetched the overrides list but
not GET /api/calendar/days, which backs the grid's shading and badges, so a
just-applied override did not render. useCalendarDays now exposes refetch and
Calendar calls it after a successful upsert or remove.

Dashboard showed the previous user's data after a login swap. WorkspaceContext
sits above the router and outlives login/logout, and its refetch was gated on
!workspaceId || children.length === 0 - so precisely because the old session's
data was still present, the guard blocked the refetch. It now keys off an
explicit isAuthenticated transition and clears state on the logout edge itself,
including the persisted localStorage workspaceId, so one account's figures can
never be briefly visible under another's session. useAnalytics, useParentalLeave
and usePlannedDays clear cached data on identity loss as defence in depth.

Backend 435 -> 439 tests, frontend 705 -> 710.

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

407 lines
16 KiB
Python

"""Tests for the core calculation engine (days-left-at-age-4).
These tests cover the headline feature and must cover edge cases:
leap years, unborn child (due date), no FK data yet, full planned calendar.
"""
from datetime import date, datetime
from uuid import uuid4
import pytest
from dateutil.relativedelta import relativedelta
from app.entities.child import Child
from app.entities.parental_leave import ParentalLeaveFetch, TierData
from app.repositories_impl.sqlite.child_repository import SQLiteChildRepository
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.leave_wish_repository import SQLiteLeaveWishRepository
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.analytics_service import AnalyticsService
from tests.conftest import SeededIds
def _make_child(workspace_id, birth_date: date) -> Child:
return Child(
id=uuid4(),
workspace_id=workspace_id,
name="TestChild",
birth_date=birth_date,
created_at=datetime.now(),
)
def _make_fetch(
personal_data_uuid, workspace_id, child_id, total=240, used=100
) -> ParentalLeaveFetch:
now = datetime.now()
tier = TierData(
sjukpenning_total=390,
sjukpenning_used=used,
sjukpenning_left=390 - used,
lagsta_niva_total=90,
lagsta_niva_used=0,
lagsta_niva_left=90,
)
return ParentalLeaveFetch(
id=uuid4(),
personal_data_uuid=personal_data_uuid,
workspace_id=workspace_id,
child_id=child_id,
source="manual",
fetched_at=now,
total_days=total,
days_used=used,
days_left=total - used,
reserved_days_total=90,
reserved_days_left=90,
transferable_days_left=50,
dubbeldagar_left=60,
tier_data=tier,
created_at=now,
updated_at=now,
)
async def _make_service(
child_repo: SQLiteChildRepository,
leave_repo: SQLiteParentalLeaveRepository,
planned_repo: SQLitePlannedLeaveRepository,
pd_repo: SQLitePersonalDataRepository,
) -> AnalyticsService:
return AnalyticsService(leave_repo, planned_repo, child_repo, pd_repo)
class TestAge4Projection:
async def test_no_planned_days_projection(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
# Use a birth date far in the future so today < B4
birth = date.today() + relativedelta(years=2)
child = _make_child(ws, birth)
await child_repo.create(child)
fetch = _make_fetch(pd_uuid, ws, child.id, total=240, used=100)
await parental_leave_repo.create(fetch)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
proj = await service.get_days_left_at_age_4(pd_uuid, child.id)
assert proj.days_used == 100
assert proj.planned_days_before_b4 == 0
assert proj.projected_left_at_b4 == 140 # 240 - 100
assert proj.savable_after_b4 == 96
assert proj.expiring_at_b4 == 44 # 140 - 96
async def test_no_fetch_data_assumes_full_entitlement(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
birth = date.today() + relativedelta(years=2)
child = _make_child(ws, birth)
await child_repo.create(child)
# No FK data entered
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
proj = await service.get_days_left_at_age_4(pd_uuid, child.id)
assert proj.total_days == 240 # default entitlement
assert proj.days_used == 0
assert proj.projected_left_at_b4 == 240
assert proj.savable_after_b4 == 96
assert proj.expiring_at_b4 == 144 # 240 - 96
async def test_leap_year_birthday(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
# Child born 2024-02-29 (leap day); 4th birthday must be 2028-02-29
birth = date(2024, 2, 29)
child = _make_child(ws, birth)
await child_repo.create(child)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
proj = await service.get_days_left_at_age_4(pd_uuid, child.id)
# dateutil.relativedelta gives 2028-02-29 (2028 is a leap year)
assert proj.fourth_birthday == date(2028, 2, 29)
async def test_all_days_used_nothing_left(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
birth = date.today() + relativedelta(years=2)
child = _make_child(ws, birth)
await child_repo.create(child)
fetch = _make_fetch(pd_uuid, ws, child.id, total=240, used=240)
await parental_leave_repo.create(fetch)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
proj = await service.get_days_left_at_age_4(pd_uuid, child.id)
assert proj.projected_left_at_b4 == 0
assert proj.savable_after_b4 == 0
assert proj.expiring_at_b4 == 0
async def test_child_not_found_raises(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
) -> None:
from app.utils.errors import NotFoundError
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
with pytest.raises(NotFoundError):
await service.get_days_left_at_age_4(uuid4(), uuid4())
class TestValidateDubbeldagar:
async def test_child_not_found_raises(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
) -> None:
from app.utils.errors import NotFoundError
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
with pytest.raises(NotFoundError):
await service.validate_dubbeldagar(uuid4(), date.today())
async def test_outside_window_raises(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
from app.utils.errors import DubbeldagError
ws = seeded_ids.workspace_id
birth = date(2024, 1, 1)
child = _make_child(ws, birth)
await child_repo.create(child)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
# Date beyond the 15-month window
beyond_window = birth + relativedelta(months=16)
with pytest.raises(DubbeldagError):
await service.validate_dubbeldagar(child.id, beyond_window)
async def test_quota_exceeded_raises(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
from app.config import settings
from app.entities.planned_leave import PlannedLeaveDay
from app.utils.errors import DubbeldagError
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
birth = date(2024, 1, 1)
child = _make_child(ws, birth)
await child_repo.create(child)
# Fill up the dubbeldagar quota
for i in range(settings.rules.max_dubbeldagar):
day = birth + relativedelta(days=i)
await planned_leave_repo.create(
PlannedLeaveDay(
id=uuid4(),
workspace_id=ws,
child_id=child.id,
parent_personal_data_uuid=pd_uuid,
date=day,
day_type="sjukpenning",
is_dubbeldag=True,
)
)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
within_window = birth + relativedelta(months=1)
with pytest.raises(DubbeldagError):
await service.validate_dubbeldagar(child.id, within_window)
class TestGetOverview:
async def test_overview_single_parent(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
seeded_ids: SeededIds,
) -> None:
ws = seeded_ids.workspace_id
pd_uuid = seeded_ids.personal_data_uuid
birth = date.today() + relativedelta(years=2)
child = _make_child(ws, birth)
await child_repo.create(child)
fetch = _make_fetch(pd_uuid, ws, child.id, total=240, used=80)
await parental_leave_repo.create(fetch)
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
overview = await service.get_overview(ws, child.id)
assert overview.workspace_id == ws
assert len(overview.parent_projections) == 1
assert overview.combined_days_used == 80
assert overview.combined_days_left == 160 # 240 - 80
assert overview.combined_expiring_at_b4 == 64 # 160 - 96
async def test_overview_no_parents_raises(
self,
child_repo: SQLiteChildRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
personal_data_repo: SQLitePersonalDataRepository,
) -> None:
from app.utils.errors import NotFoundError
service = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
with pytest.raises(NotFoundError):
await service.get_overview(uuid4(), uuid4())
class TestAgreesWithPlanProposalForTheSameCommittedState:
"""Bug A regression: the Dashboard (`AnalyticsService`) and the Plan tab's
propose-time projection (`allocation_service._Ledger.build_age4_projections`,
via `Allocator`/`AllocationInputLoader`) must compute the same
`expiring_at_b4` for a parent with no FK snapshot yet and no leave wishes
(so the proposal adds nothing new) — i.e. the *committed* state.
Before the fix, `AllocationInputLoader`'s no-snapshot fallback assumed a
single parent was entitled to the WHOLE child's combined tier totals
(`rules.sjukpenning_days` + `rules.lagsta_niva_days` == 390 + 90 == 480)
instead of that parent's fair half-share (195 + 45 == 240, matching
`AnalyticsService`'s own fallback, `rules.days_per_parent`). That made the
Plan tab report roughly double what the Dashboard showed for the exact
same (empty) committed plan — this test pins the two together.
"""
async def test_no_snapshot_no_wishes_matches_dashboard(
self,
workspace_repo: SQLiteWorkspaceRepository,
child_repo: SQLiteChildRepository,
personal_data_repo: SQLitePersonalDataRepository,
parental_leave_repo: SQLiteParentalLeaveRepository,
planned_leave_repo: SQLitePlannedLeaveRepository,
vacation_repo: SQLiteVacationDaysRepository,
leave_wish_repo: SQLiteLeaveWishRepository,
) -> None:
from app.entities.personal_data import PersonalData
from app.entities.workspace import Workspace
from app.services.allocation_service import AllocationInputLoader, Allocator
now = datetime.now()
ws = await workspace_repo.create(
Workspace(id=uuid4(), name="Familj", planning_mode="couple", created_at=now)
)
parent = await personal_data_repo.create(
PersonalData(
uuid=uuid4(),
workspace_id=ws.id,
name="Sam",
salary_type="monthly",
employment_status="employed",
created_at=now,
)
)
birth = date.today() + relativedelta(years=2)
child = _make_child(ws.id, birth)
await child_repo.create(child)
# Deliberately no ParentalLeaveFetch and no leave wishes for `parent`
# -> both surfaces must fall back to default entitlement.
# -- Dashboard side --
analytics = await _make_service(
child_repo, parental_leave_repo, planned_leave_repo, personal_data_repo
)
dashboard_proj = await analytics.get_days_left_at_age_4(parent.uuid, child.id)
# -- Plan-tab side --
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,
)
alloc_input = await loader.load(ws.id, today=date.today())
proposal = Allocator().propose(alloc_input)
assert proposal.days == [] # no wishes -> nothing new proposed
plan_proj = next(
p
for p in proposal.age4_projections
if p.parent_personal_data_uuid == parent.uuid and p.child_id == child.id
)
assert dashboard_proj.projected_left_at_b4 == plan_proj.projected_left_at_b4
assert dashboard_proj.savable_after_b4 == plan_proj.savable_after_b4
assert dashboard_proj.expiring_at_b4 == plan_proj.expiring_at_b4
# Pin the actual figures too, so a future regression of either
# fallback (240 vs. 480) fails loudly rather than merely disagreeing.
assert dashboard_proj.projected_left_at_b4 == 240
assert dashboard_proj.expiring_at_b4 == 144