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
@@ -263,6 +263,66 @@ describe('WorkspaceContext', () => {
expect(api.getWorkspace).not.toHaveBeenCalled()
})
it('clears identity/workspace state on logout so it cannot leak into the next session', async () => {
vi.mocked(useAuth).mockReturnValue(authenticated)
vi.mocked(api.getUserContext).mockResolvedValue(userContext)
vi.mocked(api.getWorkspace).mockResolvedValue(workspace)
const { result, rerender } = renderHook(() => useWorkspace(), { wrapper })
await waitFor(() => expect(result.current.workspace).not.toBeNull())
expect(result.current.parentName).toBe('Anna')
vi.mocked(useAuth).mockReturnValue(unauthenticated)
rerender()
await waitFor(() => expect(result.current.workspace).toBeNull())
expect(result.current.workspaceId).toBeNull()
expect(result.current.parentName).toBeNull()
expect(result.current.personalDataUuid).toBeNull()
expect(result.current.children).toEqual([])
expect(result.current.selectedChildId).toBeNull()
expect(localStorage.getItem('workspaceId')).toBeNull()
})
it('refetches on a fresh login even when stale data from a previous session is already present', async () => {
// Regression for a login-swap bug: a previous guard only refetched when
// workspaceId/children looked empty, so logging in as a *different*
// user after a previous session's data was already cached here never
// refetched at all, and the new session silently rendered the old
// account's workspace/name/children.
vi.mocked(useAuth).mockReturnValue(authenticated)
vi.mocked(api.getUserContext).mockResolvedValue(userContext)
vi.mocked(api.getWorkspace).mockResolvedValue(workspace)
const { result, rerender } = renderHook(() => useWorkspace(), { wrapper })
await waitFor(() => expect(result.current.parentName).toBe('Anna'))
vi.mocked(useAuth).mockReturnValue(unauthenticated)
rerender()
await waitFor(() => expect(result.current.workspace).toBeNull())
const otherWorkspace: Workspace = { ...workspace, id: 'ws2', name: 'Other workspace' }
const otherUserContext: api.UserContext = {
personal_data_uuid: 'pd2',
workspace_id: 'ws2',
parent_name: 'Alex',
children: [{ id: 'c3', name: 'Child Three', birth_date: '2026-01-01' }],
}
vi.mocked(api.getUserContext).mockResolvedValue(otherUserContext)
vi.mocked(api.getWorkspace).mockResolvedValue(otherWorkspace)
vi.mocked(api.getUserContext).mockClear()
vi.mocked(useAuth).mockReturnValue(authenticated)
rerender()
await waitFor(() => expect(result.current.parentName).toBe('Alex'))
expect(api.getUserContext).toHaveBeenCalled()
expect(result.current.workspaceId).toBe('ws2')
expect(result.current.personalDataUuid).toBe('pd2')
expect(result.current.selectedChildId).toBe('c3')
expect(result.current.workspace).toEqual(otherWorkspace)
})
it('throws when useWorkspace is used outside a WorkspaceProvider', () => {
vi.mocked(useAuth).mockReturnValue(unauthenticated)
+40 -3
View File
@@ -1,4 +1,4 @@
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
import * as api from '@/services/api'
import { useAuth } from '@/context/AuthContext'
import type { Workspace } from '@/types'
@@ -38,6 +38,11 @@ export function WorkspaceProvider({ children: childrenProp }: { children: React.
const [selectedChildId, setSelectedChildId] = useState<string | null>(null)
const [personalDataUuid, setPersonalDataUuid] = useState<string | null>(null)
const [parentName, setParentName] = useState<string | null>(null)
// Tracks isAuthenticated across renders so the effect below can react to
// login/logout *transitions* rather than to the mere presence (or
// absence) of cached data — see the effect for why that distinction is
// what makes a login swap actually refetch.
const wasAuthenticatedRef = useRef(false)
const fetchWorkspace = useCallback(async (id: string) => {
setIsLoading(true)
@@ -80,11 +85,43 @@ export function WorkspaceProvider({ children: childrenProp }: { children: React.
}
}, [])
// Clears every piece of identity/workspace state this provider holds,
// including the persisted workspaceId. Called on logout so stale data is
// actively wiped rather than left to be overwritten "eventually" by the
// next login's fetch — the gap between those two points is exactly where
// one account's data could otherwise flash under another account's
// session.
const clearWorkspaceState = useCallback(() => {
localStorage.removeItem('workspaceId')
setWorkspace(null)
setWorkspaceId(null)
setChildren([])
setSelectedChildId(null)
setPersonalDataUuid(null)
setParentName(null)
setError(null)
}, [])
// React to isAuthenticated *transitions*, not to whether data already
// looks present. This provider sits above the router and outlives page
// navigation, so on a logout-then-login-as-a-different-user swap,
// workspaceId/children/personalDataUuid/parentName from the previous
// session are all still sitting in state here. A guard like
// `!workspaceId || children.length === 0` would then never re-fire for
// the new session (that data isn't empty, just stale), so the new
// account would silently keep rendering the old account's context. Using
// an explicit false->true edge means a fresh login always refetches, and
// a true->false edge always clears.
useEffect(() => {
if (isAuthenticated && (!workspaceId || children.length === 0)) {
const wasAuthenticated = wasAuthenticatedRef.current
wasAuthenticatedRef.current = isAuthenticated
if (isAuthenticated && !wasAuthenticated) {
void refreshContext()
} else if (!isAuthenticated && wasAuthenticated) {
clearWorkspaceState()
}
}, [isAuthenticated, workspaceId, children.length, refreshContext])
}, [isAuthenticated, refreshContext, clearWorkspaceState])
useEffect(() => {
if (isAuthenticated && workspaceId && !workspace) {
+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 {
+1 -1
View File
@@ -78,7 +78,7 @@ export const en: Record<TranslationKey, string> = {
'dashboard.overviewTitle': 'Overview',
'dashboard.usedDays': 'Used days',
'dashboard.daysLeft': 'Days left',
'dashboard.expiringAtB4': 'Expires at age 4',
'dashboard.expiringAtB4': 'Total expiring at age 4 (all parents)',
'dashboard.plannedDaysTitle': 'Planned days',
'dashboard.remainingUntilB4Title': 'Remaining until age 4',
'dashboard.saveManualFetchError': 'Could not save the details',
+1 -1
View File
@@ -72,7 +72,7 @@ export const sv = {
'dashboard.overviewTitle': 'Översikt',
'dashboard.usedDays': 'Använda dagar',
'dashboard.daysLeft': 'Kvarvarande dagar',
'dashboard.expiringAtB4': 'Förfaller vid 4 års ålder',
'dashboard.expiringAtB4': 'Totalt förfaller vid 4 års ålder (alla föräldrar)',
'dashboard.plannedDaysTitle': 'Planerade dagar',
'dashboard.remainingUntilB4Title': 'Återstående till 4 års ålder',
'dashboard.saveManualFetchError': 'Kunde inte spara uppgifterna',
+14 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { Calendar } from './Calendar'
import { useWorkspace } from '@/context'
import { usePlannedDays, useCalendarDays, useDayOverrides } from '@/hooks'
@@ -53,6 +53,7 @@ describe('Calendar', () => {
data: { startYear: 2026, endYear: 2026, minYear: 2026, maxYear: 2035, days: [] },
isLoading: false,
error: null,
refetch: vi.fn(),
}
const mockDayOverrides = {
@@ -311,6 +312,7 @@ describe('Calendar', () => {
},
isLoading: false,
error: null,
refetch: vi.fn(),
})
render(<Calendar />)
@@ -345,6 +347,7 @@ describe('Calendar', () => {
},
isLoading: false,
error: null,
refetch: vi.fn(),
})
render(<Calendar />)
@@ -401,6 +404,7 @@ describe('Calendar', () => {
it('clicking a currently-free day in override mode marks it as a working day', async () => {
const today = todayDateString()
const upsert = vi.fn().mockResolvedValue(undefined)
const refetchCalendarWindow = vi.fn().mockResolvedValue(undefined)
;(useWorkspace as any).mockReturnValue(mockWorkspace)
;(usePlannedDays as any).mockReturnValue(mockPlannedDays)
;(useCalendarDays as any).mockReturnValue({
@@ -422,6 +426,7 @@ describe('Calendar', () => {
},
isLoading: false,
error: null,
refetch: refetchCalendarWindow,
})
;(useDayOverrides as any).mockReturnValue({ data: [], isLoading: false, error: null, upsert, remove: vi.fn() })
@@ -440,11 +445,17 @@ describe('Calendar', () => {
isWorkingDay: true,
note: null,
})
// Regression: the day cell's shading comes from a separate fetch
// (GET /api/calendar/days) than the override list, so a successful
// mutation must explicitly refetch it — otherwise the cell keeps
// showing its pre-mutation state until a full page reload.
await waitFor(() => expect(refetchCalendarWindow).toHaveBeenCalledTimes(1))
})
it('clicking an already-overridden day in override mode removes the override', async () => {
const today = todayDateString()
const removeOverride = vi.fn().mockResolvedValue(undefined)
const refetchCalendarWindow = vi.fn().mockResolvedValue(undefined)
;(useWorkspace as any).mockReturnValue(mockWorkspace)
;(usePlannedDays as any).mockReturnValue(mockPlannedDays)
;(useCalendarDays as any).mockReturnValue({
@@ -466,6 +477,7 @@ describe('Calendar', () => {
},
isLoading: false,
error: null,
refetch: refetchCalendarWindow,
})
;(useDayOverrides as any).mockReturnValue({
data: [{ id: 'ov-1', workspaceId: 'ws-1', date: today, isWorkingDay: false, note: null }],
@@ -485,6 +497,7 @@ describe('Calendar', () => {
await screen.findByTestId('calendar-override-toggle')
expect(removeOverride).toHaveBeenCalledWith('ov-1')
await waitFor(() => expect(refetchCalendarWindow).toHaveBeenCalledTimes(1))
})
})
})
+11 -1
View File
@@ -56,7 +56,11 @@ export function Calendar(): ReactNode {
const calendarMaxYear = viewMonth === 11 ? viewYear + 1 : viewYear
const calendarYearsSpan = calendarMaxYear - calendarMinYear + 1
const { data: calendarWindow } = useCalendarDays(workspace?.id ?? '', calendarMinYear, calendarYearsSpan)
const { data: calendarWindow, refetch: refetchCalendarWindow } = useCalendarDays(
workspace?.id ?? '',
calendarMinYear,
calendarYearsSpan,
)
const { data: dayOverrides, upsert: upsertDayOverride, remove: removeDayOverride } = useDayOverrides(
workspace?.id ?? '',
)
@@ -183,6 +187,12 @@ export function Calendar(): ReactNode {
note: null,
})
}
// The grid's shading/badges come from GET /api/calendar/days, a
// separate fetch from the override list above — without this
// explicit refetch the day-overrides list would be up to date but the
// calendar cell would keep showing the pre-mutation state until a
// full page reload.
await refetchCalendarWindow()
} catch (err) {
setOverrideError(err instanceof Error ? err.message : t('calendar.overrideError'))
}