Parse transferable days from FK instead of deriving them

The scraper never read "överlåtbara dagar" from Försäkringskassan. It only
visited ansok-och-planera-foraldrapenning#/valjdagar and derived the
reserved/transferable split in build_snapshot, assuming transferable days
are spent before reserved ones. On real data that gave 49 for the user and
0 for the partner where FK states 129 and 71.

The assumption cannot be repaired: reserved-first, transferable-first,
proportional and cap-based models were all checked against real figures and
none reproduces FK's accounting (reserved-first fits the partner but is 10
days off for the user). FK publishes the real numbers per parent per tier on
the min-foraldrapenning page, which the scraper had never visited.

- Scrape the "Dagar ni kan föra över" panel after the valjdagar extraction,
  summing sjukpenningnivå + lägstanivå per parent. The totals are not
  literals on the page. Parse only direct-child <p> elements: the first
  group embeds a tooltip with decoy "45 dagar"/"90 dagar" text.
- build_snapshot accepts the reported value and derives reserved days from
  it; the old arithmetic remains only as a fallback. An implausible FK value
  degrades to that fallback rather than failing the fetch.
- Record provenance in transferable_days_reported (migration 006) and badge
  derived values as estimates in the dashboard breakdown. Drop the footnote's
  claim that at most 150 days are transferable — real data contradicts it as
  a per-family figure.
- Select the child's section by name when FK lists several; never guess.

Verified against a live BankID scrape: scraped 240/101/139 with 129
transferable, deduced partner 240/169/71 with 71, both flagged as reported.

Incidental fixes found along the way:

- The fetch router never forwarded the partner's transferable figure to
  persist_partner_deduction, so the partner's stored snapshot would have kept
  the flawed split even once the parse landed.
- 'deduced' snapshots were labelled "Manually entered" by a two-way ternary
  over a three-value union. Replaced with a compiler-checked exhaustive map.
- Alembic resolved its database from alembic.ini alone, ignoring
  APP_SQLITE_PATH, so migrations silently targeted the developer's real
  database even when pointed elsewhere. env.py now resolves it, preferring
  -x sqlalchemy.url, then a real APP_SQLITE_PATH, then the ini value.
- backend/captures/ was not ignored: the root pattern was anchored as
  /captures/ despite a comment saying scraper dumps must never be tracked.
- CLAUDE.md quoted test counts and coverage percentages that had gone stale,
  which made a correct verification report look suspect. Gate thresholds kept.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DXPBfr1v7F71t6QcbHCaaT
This commit is contained in:
2026-09-20 09:11:53 +02:00
parent 3eb8511eb6
commit 97a7200c1a
29 changed files with 1422 additions and 45 deletions
@@ -53,8 +53,25 @@ describe('ParentalLeaveBreakdown', () => {
render(<ParentalLeaveBreakdown parents={[alex, samWithout]} />)
const notes = screen.getAllByTestId('reserved-days-note')
expect(notes).toHaveLength(1)
expect(notes[0]).toHaveTextContent(`${LEAVE_RULES.reservedDaysPerParent} av varje förälders dagar är reserverade`)
expect(notes[0]).toHaveTextContent(`max ${LEAVE_RULES.transferableDaysPerParent} dagar kan överlåtas`)
expect(notes[0]).toHaveTextContent(
`${LEAVE_RULES.reservedDaysPerParent} av varje förälders dagar är reserverade och kan inte överlåtas till den andra föräldern.`,
)
})
it('renders the transferable-days value plain when it was reported by FK', () => {
render(<ParentalLeaveBreakdown parents={[alex]} />)
const cell = screen.getByTestId('breakdown-transferable-pd-a')
expect(cell).toHaveTextContent('50')
expect(cell.querySelector('.badge')).not.toBeInTheDocument()
})
it('marks the transferable-days value as an estimate when it was derived, not reported by FK', () => {
const derived = { ...alex, data: { ...alexData, transferableDaysReported: false } }
render(<ParentalLeaveBreakdown parents={[derived]} />)
const cell = screen.getByTestId('breakdown-transferable-pd-a')
expect(cell).toHaveTextContent('Antaget')
expect(cell).toHaveTextContent('50')
expect(cell.querySelector('.badge')).toBeInTheDocument()
})
it('shows the scraped source and date per parent', () => {
@@ -67,6 +84,13 @@ describe('ParentalLeaveBreakdown', () => {
expect(screen.getByTestId('breakdown-provenance-pd-a')).toHaveTextContent('Manuellt angiven')
})
it('shows the deduced source label', () => {
render(<ParentalLeaveBreakdown parents={[{ ...alex, data: { ...alexData, source: 'deduced' } }]} />)
const provenance = screen.getByTestId('breakdown-provenance-pd-a')
expect(provenance).toHaveTextContent('Härlett från Försäkringskassan')
expect(provenance).not.toHaveTextContent('Manuellt angiven')
})
it('formats the provenance date using the en-US locale when the language is English', () => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
vi.stubGlobal('localStorage', {
@@ -1,7 +1,7 @@
import { ReactNode } from 'react'
import type { ParentalLeaveFetch } from '@/types'
import type { ParentalLeaveFetch, ParentalLeaveSource } from '@/types'
import { LEAVE_RULES } from '@/utils/constants'
import { useTranslation } from '@/i18n'
import { useTranslation, type TranslationKey } from '@/i18n'
/** One parent's balance snapshot — `data` is `null` when nothing has been
* fetched or entered for them yet. */
@@ -15,6 +15,13 @@ export interface ParentalLeaveBreakdownProps {
parents: ParentalLeaveBreakdownParent[]
}
/** Map parental leave source values to their i18n translation keys. */
const SOURCE_LABEL_KEYS: Record<ParentalLeaveSource, TranslationKey> = {
scraped: 'parentalLeaveBreakdown.sourceScraped',
manual: 'parentalLeaveBreakdown.sourceManual',
deduced: 'parentalLeaveBreakdown.sourceDeduced',
}
/**
* The raw balance snapshot per parent (one column each): what is left of
* each tier, transferable and double days, and where the figures came from.
@@ -74,7 +81,18 @@ export function ParentalLeaveBreakdown({ parents }: ParentalLeaveBreakdownProps)
</tr>
<tr data-testid="breakdown-transferable">
<th scope="row">{t('parentalLeaveBreakdown.transferableDays')}</th>
{parents.map((parent) => cell(parent, 'breakdown-transferable', (d) => d.transferableDaysLeft))}
{parents.map((parent) =>
cell(parent, 'breakdown-transferable', (d) => (
<>
{!d.transferableDaysReported && (
<span className="badge badge--muted parental-leave-breakdown__badge">
{t('parentalLeaveBreakdown.estimatedBadge')}
</span>
)}
{d.transferableDaysLeft}
</>
)),
)}
</tr>
<tr data-testid="breakdown-dubbeldagar">
<th scope="row">{t('parentalLeaveBreakdown.dubbeldagarLeft')}</th>
@@ -88,11 +106,7 @@ export function ParentalLeaveBreakdown({ parents }: ParentalLeaveBreakdownProps)
<li key={parent.personalDataUuid} data-testid={`breakdown-provenance-${parent.personalDataUuid}`}>
<span className="parental-leave-breakdown__provenance-name">{parent.name}</span>{' '}
{parent.data
? `${
parent.data.source === 'scraped'
? t('parentalLeaveBreakdown.sourceScraped')
: t('parentalLeaveBreakdown.sourceManual')
} ${formatDate(parent.data.fetchedAt)}`
? `${t(SOURCE_LABEL_KEYS[parent.data.source])} ${formatDate(parent.data.fetchedAt)}`
: t('parentalLeaveBreakdown.noBalance')}
</li>
))}
@@ -101,7 +115,6 @@ export function ParentalLeaveBreakdown({ parents }: ParentalLeaveBreakdownProps)
<p className="parental-leave-breakdown__reserved-note" data-testid="reserved-days-note">
{t('parentalLeaveBreakdown.reservedNote', {
reserved: LEAVE_RULES.reservedDaysPerParent,
transferable: LEAVE_RULES.transferableDaysPerParent,
})}
</p>
</div>
+1 -5
View File
@@ -106,11 +106,7 @@ describe('LanguageContext', () => {
})
it('interpolates multiple params', () => {
expect(
translate('en', 'parentalLeaveBreakdown.reservedNote', { reserved: 90, transferable: 45 }),
).toBe(
'90 of each parent\'s days are reserved and cannot be transferred to the other parent (up to 45 days can be transferred).',
)
expect(translate('en', 'balance.statusLine', { left: 90, total: 240 })).toBe('90 of 240 days left')
})
it('leaves an unmatched placeholder untouched', () => {
+3 -1
View File
@@ -25,11 +25,13 @@ export const dashboard = {
'overviewMetrics.defaultTitle': 'Overview',
'parentalLeaveBreakdown.dubbeldagarLeft': 'Double days left',
'parentalLeaveBreakdown.empty': 'No balances fetched yet.',
'parentalLeaveBreakdown.estimatedBadge': 'Assumed',
'parentalLeaveBreakdown.lagstaNiva': 'Minimum rate',
'parentalLeaveBreakdown.leftOfTotal': '{left} of {total}',
'parentalLeaveBreakdown.noBalance': 'No balance yet',
'parentalLeaveBreakdown.reservedNote': '{reserved} of each parent\'s days are reserved and cannot be transferred to the other parent (up to {transferable} days can be transferred).',
'parentalLeaveBreakdown.reservedNote': '{reserved} of each parent\'s days are reserved and cannot be transferred to the other parent.',
'parentalLeaveBreakdown.sjukpenning': 'Sjukpenningnivå (income-based)',
'parentalLeaveBreakdown.sourceDeduced': 'Derived from Försäkringskassan',
'parentalLeaveBreakdown.sourceManual': 'Manually entered',
'parentalLeaveBreakdown.sourceScraped': 'Fetched from Försäkringskassan',
'parentalLeaveBreakdown.transferableDays': 'Transferable days',
+3 -1
View File
@@ -25,11 +25,13 @@ export const dashboard = {
'overviewMetrics.defaultTitle': 'Översikt',
'parentalLeaveBreakdown.dubbeldagarLeft': 'Dubbeldagar kvar',
'parentalLeaveBreakdown.empty': 'Inga saldon hämtade än.',
'parentalLeaveBreakdown.estimatedBadge': 'Antaget',
'parentalLeaveBreakdown.lagstaNiva': 'Lägstanivå',
'parentalLeaveBreakdown.leftOfTotal': '{left} av {total}',
'parentalLeaveBreakdown.noBalance': 'Inget saldo än',
'parentalLeaveBreakdown.reservedNote': '{reserved} av varje förälders dagar är reserverade och kan inte överlåtas till den andra föräldern (max {transferable} dagar kan överlåtas).',
'parentalLeaveBreakdown.reservedNote': '{reserved} av varje förälders dagar är reserverade och kan inte överlåtas till den andra föräldern.',
'parentalLeaveBreakdown.sjukpenning': 'Sjukpenningnivå',
'parentalLeaveBreakdown.sourceDeduced': 'Härlett från Försäkringskassan',
'parentalLeaveBreakdown.sourceManual': 'Manuellt angiven',
'parentalLeaveBreakdown.sourceScraped': 'Hämtad från Försäkringskassan',
'parentalLeaveBreakdown.transferableDays': 'Överlåtbara dagar',
+3
View File
@@ -117,6 +117,7 @@ describe('API response mappers (snake_case → camelCase)', () => {
reserved_days_total: 90,
reserved_days_left: 80,
transferable_days_left: 100,
transferable_days_reported: false,
dubbeldagar_left: 60,
tier_data: {
sjukpenning_total: 390,
@@ -149,6 +150,7 @@ describe('API response mappers (snake_case → camelCase)', () => {
expect(result.reservedDaysTotal).toBe(90)
expect(result.reservedDaysLeft).toBe(80)
expect(result.transferableDaysLeft).toBe(100)
expect(result.transferableDaysReported).toBe(false)
expect(result.dubbeldagarLeft).toBe(60)
expect(result.createdAt).toBe('2026-06-14T17:09:47')
expect(result.updatedAt).toBe('2026-06-14T17:09:47')
@@ -1068,6 +1070,7 @@ describe('endpoint functions (representative coverage)', () => {
reserved_days_total: 90,
reserved_days_left: 90,
transferable_days_left: 100,
transferable_days_reported: false,
dubbeldagar_left: 60,
tier_data: {
sjukpenning_total: 390,
+2
View File
@@ -83,6 +83,7 @@ export interface RawParentalLeaveFetch {
reserved_days_total: number
reserved_days_left: number
transferable_days_left: number
transferable_days_reported: boolean
dubbeldagar_left: number
tier_data: RawTierData
created_at: string
@@ -103,6 +104,7 @@ function toParentalLeaveFetch(raw: RawParentalLeaveFetch): ParentalLeaveFetch {
reservedDaysTotal: raw.reserved_days_total,
reservedDaysLeft: raw.reserved_days_left,
transferableDaysLeft: raw.transferable_days_left,
transferableDaysReported: raw.transferable_days_reported,
dubbeldagarLeft: raw.dubbeldagar_left,
tierData: toTierData(raw.tier_data),
createdAt: raw.created_at,
+4
View File
@@ -603,6 +603,10 @@
color: var(--c-text);
}
.parental-leave-breakdown__badge {
margin-right: var(--sp-1);
}
.parental-leave-breakdown__reserved-note {
margin: 0;
max-width: 64ch;
+9 -1
View File
@@ -127,7 +127,7 @@ export interface ParentalLeaveFetch {
personalDataUuid: string
workspaceId: string
childId: string
source: 'scraped' | 'manual' | 'deduced'
source: ParentalLeaveSource
fetchedAt: string
totalDays: number
daysUsed: number
@@ -135,6 +135,12 @@ export interface ParentalLeaveFetch {
reservedDaysTotal: number
reservedDaysLeft: number
transferableDaysLeft: number
// True when `transferableDaysLeft` came straight from Försäkringskassan's
// own figure (a scraped snapshot); false when it's derived from the
// statutory reserved-days assumption (a manually-entered balance) — see
// `LEAVE_RULES.transferableDaysPerParent`. The UI must not present the
// derived figure as fact.
transferableDaysReported: boolean
dubbeldagarLeft: number
tierData: TierData
createdAt: string
@@ -201,6 +207,8 @@ export interface PlannedDayExclusion {
// avoid colliding with the `CalendarDay` component.
export type CalendarDayType = 'red_day' | 'klamdag' | 'weekend' | 'working_day'
export type ParentalLeaveSource = 'scraped' | 'manual' | 'deduced'
export interface CalendarDayEntry {
date: string // ISO-8601 date
/** Exact holiday name (may be the combined "X; Söndag" form); null unless dayType === 'red_day'. */