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
This commit is contained in:
2026-09-14 08:21:18 +02:00
parent 249e277696
commit 87b3eb5d0c
20 changed files with 514 additions and 43 deletions
+33
View File
@@ -76,4 +76,37 @@ describe('useAnalytics', () => {
expect(api.getWorkspaceOverview).toHaveBeenCalled()
})
it('clears stale data instead of leaving it rendered when the workspace/child identity is lost', async () => {
const mockData = {
workspaceId: 'ws1',
childId: 'child1',
parentProjections: [],
combinedDaysUsed: 76,
combinedDaysLeft: 164,
combinedExpiringAtB4: 50,
}
vi.mocked(api.getWorkspaceOverview).mockResolvedValue(mockData as any)
const { result, rerender } = renderHook(
({ workspaceId, childId }: { workspaceId: string | null; childId: string | undefined }) =>
useAnalytics(workspaceId, childId),
{ initialProps: { workspaceId: 'ws1' as string | null, childId: 'child1' as string | undefined } },
)
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(result.current.data).toEqual(mockData)
// Simulate a logout clearing the workspace/child selection — this must
// not leave the previous account's figures on screen.
rerender({ workspaceId: null, childId: undefined })
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(result.current.data).toBeNull()
})
})
+8 -1
View File
@@ -15,7 +15,14 @@ export function useAnalytics(workspaceId: string | null, childId?: string): UseA
const [error, setError] = useState<string | null>(null)
const fetch = useCallback(async () => {
if (!workspaceId || !childId) return
if (!workspaceId || !childId) {
// The identity this data belongs to is gone (e.g. a logout cleared
// the workspace/child selection) — clear rather than leave the
// previous account's figures rendered until a new id arrives.
setData(null)
setError(null)
return
}
setIsLoading(true)
setError(null)
try {
@@ -47,6 +47,25 @@ describe('useCalendarDays', () => {
expect(result.current.error).toBeNull()
})
it('refetch re-runs the fetch with the current parameters', async () => {
vi.mocked(api.getCalendarDays).mockResolvedValue(mockWindow)
const { result } = renderHook(() => useCalendarDays('ws-1', 2026, 4))
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
vi.mocked(api.getCalendarDays).mockClear()
await act(async () => {
await result.current.refetch()
})
expect(api.getCalendarDays).toHaveBeenCalledWith('ws-1', 2026, 4)
expect(api.getCalendarDays).toHaveBeenCalledTimes(1)
})
it('refetches when startYear changes', async () => {
vi.mocked(api.getCalendarDays).mockResolvedValue(mockWindow)
+8 -1
View File
@@ -5,6 +5,12 @@
* Backs both the Kalender page's shading + click-to-override (§3.4/§3.6) and
* the Settings red-days list (§3.8) from the same `GET /api/calendar/days`
* endpoint — see `app/routers/calendar.py` / ARCHITECTURE.md §13.3.
*
* There is no shared cache/invalidation layer (no TanStack Query) here, so a
* day-override mutation elsewhere does not automatically make this window
* stale — callers that mutate overrides (see `useDayOverrides`) must
* explicitly call `refetch` afterwards or the calendar grid will keep
* showing the pre-mutation shading until a full reload.
*/
import { useCallback, useEffect, useState } from 'react'
@@ -15,6 +21,7 @@ interface UseCalendarDaysResult {
data: CalendarWindow | null
isLoading: boolean
error: string | null
refetch: () => Promise<void>
}
export function useCalendarDays(
@@ -44,5 +51,5 @@ export function useCalendarDays(
void fetchWindow()
}, [fetchWindow])
return { data, isLoading, error }
return { data, isLoading, error, refetch: fetchWindow }
}
@@ -78,4 +78,47 @@ describe('useParentalLeave', () => {
expect(api.getParentalLeave).toHaveBeenCalled()
})
it('clears stale data instead of leaving it rendered when the parent/child identity is lost', async () => {
const mockData = {
id: 'pf1',
personalDataUuid: 'pd1',
workspaceId: 'ws1',
childId: 'child1',
source: 'manual' as const,
fetchedAt: new Date().toISOString(),
totalDays: 300,
daysUsed: 20,
daysLeft: 280,
reservedDaysTotal: 90,
reservedDaysLeft: 80,
transferableDaysLeft: 50,
dubbeldagarLeft: 60,
tierData: { sjukpenningTotal: 390, sjukpenningUsed: 10, sjukpenningLeft: 380, lagstaNivaTotal: 90, lagstaNivaUsed: 0, lagstaNivaLeft: 90 },
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}
vi.mocked(api.getParentalLeave).mockResolvedValue(mockData as any)
const { result, rerender } = renderHook(
({ personalDataUuid, childId }: { personalDataUuid: string | null; childId: string | null }) =>
useParentalLeave(personalDataUuid, childId),
{ initialProps: { personalDataUuid: 'pd1' as string | null, childId: 'child1' as string | null } },
)
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(result.current.data).toEqual(mockData)
// Simulate a logout clearing the parent/child selection — this must not
// leave the previous account's figures on screen.
rerender({ personalDataUuid: null, childId: null })
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(result.current.data).toBeNull()
})
})
+8 -1
View File
@@ -18,7 +18,14 @@ export function useParentalLeave(
const [error, setError] = useState<string | null>(null)
const fetch = useCallback(async () => {
if (!personalDataUuid || !childId) return
if (!personalDataUuid || !childId) {
// The identity this data belongs to is gone (e.g. a logout cleared
// the parent/child selection) — clear rather than leave the previous
// account's figures rendered until a new id arrives.
setData(null)
setError(null)
return
}
setIsLoading(true)
setError(null)
try {
+8 -1
View File
@@ -18,7 +18,14 @@ export function usePlannedDays(childId?: string): UsePlannedDaysResult {
const [error, setError] = useState<string | null>(null)
const fetch = useCallback(async () => {
if (!childId) return
if (!childId) {
// The child this data belongs to is gone (e.g. a logout cleared the
// selection) — clear rather than leave the previous account's
// planned days rendered until a new childId arrives.
setData(null)
setError(null)
return
}
setIsLoading(true)
setError(null)
try {