fix: counterparty template pick crashes the page (#1291)

Picking a suggestion under "Tidigare motparter" in Bokför transaktion replaced
the page with "Något gick fel". handleOpenTemplateReview built the review state
from `{ id, name_sv } as BookingTemplate`, so `template.debit_account` was
undefined, reached QuickReviewDialog's required `defaultAccount: string`, and
threw on `accountOverride.startsWith('2')` during the first render.

Typed the dialog's template prop as a narrow ReviewTemplate whose optional
fields are actually optional, so the cast disappears and the compiler owns this
class of bug. Also carries the counterparty's learned accounts and VAT (the
preview showed the category fallback, not what the server books) and decides
"is this a counterparty booking" from the template id rather than the presence
of a line_pattern (single-line templates got an account/VAT editor the
categorize route discards).

Five more page-crashes of the same shape, adversarially verified:

- suppliers/[id] and supplier-invoices/[id] passed the error envelope OBJECT as
  a toast description. The Toaster is a sibling of {children} in the ROOT
  layout, so that throw escapes both segment error boundaries onto global-error.
- components/reports/views wrote the same object into a useState<string | null>
  at 13 sites and rendered it bare.
- components/ui/toaster.tsx now coerces non-renderable values as a choke point.
- skattekonto read data.informationstext.length off Skatteverket's raw JSON,
  where the field is not required.
- TicWorkspace read profile.statuses.length off a persisted jsonb blob. 17 of 17
  prod rows predate the TIC v2 upgrade (#584) and lack the key, so that
  workspace was in the error boundary for every company that had opened it.

Plus hardening: formatCurrency coerces a null currency to SEK (prod has 0 NULL
across 28 416 transactions, so defense not a live bug) and cleanSignatory
returns [] for a missing description.

Verified by rendering the real dialog against a throwaway /sandbox route: the
pre-fix prop shape reproduces the exact error boundary, the fixed one renders
D: 6570 Bankavgifter / K: 1930 Företagskonto and the matching verifikat.

No migrations.
This commit is contained in:
Jakob Wennberg
2026-07-29 19:20:25 +02:00
committed by GitHub
parent 16f34fb214
commit 198d3092c7
20 changed files with 669 additions and 93 deletions
+49 -5
View File
@@ -32,8 +32,42 @@ import {
import { Badge } from '@/components/ui/badge'
import Link from 'next/link'
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { TICCompanyProfile } from '@/extensions/general/tic/lib/tic-types'
/**
* The profile is hydrated from a persisted `extension_data` jsonb blob, so its
* shape is whatever the TIC schema looked like when it was cached, not what
* TICCompanyProfile promises today. A blob written before the v2 upgrade (#584)
* has no `statuses` key at all, and `profile.statuses.length` on a rendered
* blob like that dropped the whole workspace into the error boundary.
*
* Normalising once at the hydration boundary keeps every list read below
* honest, including the ones a future schema change would otherwise break.
*/
function normalizeProfile(raw: unknown): TICCompanyProfile {
const p = (raw ?? {}) as Partial<TICCompanyProfile>
const list = <T,>(value: T[] | undefined | null): T[] => (Array.isArray(value) ? value : [])
return {
...(p as TICCompanyProfile),
registration: p.registration ?? { fTax: false, vat: false, payroll: false },
sniCodes: list(p.sniCodes),
bankAccounts: list(p.bankAccounts),
beneficialOwners: list(p.beneficialOwners),
financialReports: list(p.financialReports),
fiscalYearHistory: list(p.fiscalYearHistory),
signatory: list(p.signatory),
representatives: list(p.representatives),
payrolls: list(p.payrolls),
statuses: list(p.statuses),
// Declared nullable, so undefined would already read as falsy at the
// render guards; normalised anyway so the object matches its own type.
fiscalYear: p.fiscalYear ?? null,
board: p.board ?? null,
financials: p.financials ?? null,
}
}
function formatKSEK(value: number | null): string {
if (value === null) return '-'
return `${(value * 1000).toLocaleString('sv-SE')} kr`
@@ -165,8 +199,13 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
useEffect(() => {
if (isDataLoading) return
const cached = getByKey('company_profile')
if (cached?.value) {
setProfile(cached.value as unknown as TICCompanyProfile)
// Blobs written before the TIC v2 upgrade (#584) predate the statuses /
// board / payroll sections entirely. Rendering one normalized would show
// a permanently section-less profile, because the success path has no
// refresh button to repair it: leaving `profile` null instead lets the
// auto-fetch effect below pull the current shape and re-save it.
if (cached?.value && 'statuses' in cached.value) {
setProfile(normalizeProfile(cached.value))
}
setInitialLoad(false)
}, [isDataLoading, getByKey])
@@ -196,14 +235,19 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
)
if (!res.ok) {
const { error } = await res.json()
toast({ title: error ?? t('toast_profile_failed'), variant: 'destructive' })
// `error` is the canonical envelope object, not a string: as a bare
// toast title it would render an object as a React child.
const body = await res.json().catch(() => null)
toast({
title: body?.error ? getErrorMessage(body, { statusCode: res.status }) : t('toast_profile_failed'),
variant: 'destructive',
})
setFetchFailed(true)
return
}
const { data } = await res.json()
setProfile(data)
setProfile(normalizeProfile(data))
await save('company_profile', data)
} catch {
toast({ title: t('toast_unexpected_error'), variant: 'destructive' })