perf(reference-data): sweep the remaining raw reads onto the session cache, ratchet to 0 (#1941)

Final consumer migration of the responsiveness plan: the 35 files still
fetching fiscal periods, settings, accounts, cash accounts, dimensions or
templates on their own now read lib/reference-data, and every client
write site invalidates the shared cache instead of refetching locally.

Settings and registries: FiscalYearsManager, FiscalPeriodEditor (period
snapshotted once per company so a revalidation cannot reset dates being
edited), BookingTemplatesPanel, ChartOfAccounts, ChartOfAccountsManager,
EditAccountDialog, CorrectionEntryDialog, StrikeLinesDialog,
InvoicePaymentAccountsSettings; the dimensions registry (DimensionsManager,
DimensionCombobox, LineDimensionFields, DimensionFilter, bookkeeping/[id])
reads useDimensions and the ad-hoc fetchDimensions/fetchDimensionsCached
helpers are deleted.

Pages and pickers: CashAccountSelector (FyPicker-shaped restore, once per
company load), use-account-names, FiscalYearGapNotice,
OpeningBalancePeriodStep, BankFileConfirmStep, ImportReviewStep, the import
page (invalidates accounts + periods after a SIE execute), customers list,
invoices list + detail, pending, salary employee, asset dispose, year-end
and periodisering pages (invalidate periods after closing), reports
DimensionPnlView (its pivot picker read the wrong payload key and was
always empty; it now populates), SkatteverketPanel, TemplatePicker,
ArticleForm (vat_registered).

Invoice dialogs and extensions: SendInvoiceDialog, PaymentBookingDialog
(init reduced to the credit-note lookup + catalogue, proposal and voucher
preview fire on open when cached; a local getSession replaces the network
getUser for the fallback CC), InvoiceInboxWorkspace, TicWorkspace,
ArcimMigrationWorkspace (invalidates after each SIE import step),
enable-banking AccountPickerDialog.

raw-reference-fetch ratchet: 35 -> 0 files.

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-26 14:56:37 +02:00
committed by GitHub
co-authored by Jakob Wennberg Claude Fable 5
parent 4560ccbfc9
commit 3ee3565d6d
41 changed files with 636 additions and 977 deletions
@@ -1,6 +1,8 @@
'use client'
import { useState, useCallback, useEffect, useReducer, useRef } from 'react'
import { useAccounts } from '@/lib/reference-data/hooks'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import { useTranslations } from 'next-intl'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
@@ -2039,6 +2041,10 @@ export default function ArcimMigrationWorkspace({
// SIE data state (held between mapping and execution steps)
const [sieData, setSieData] = useState<SIEData | null>(null)
const companyAccountsForVatRef = useRef<BASAccount[]>([])
// Chart of accounts incl. inactive, from the session cache
// (lib/reference-data). Re-read when the mapping step opens because the
// preview may have created accounts; the SIE import invalidates it too.
const { refresh: refreshCompanyAccounts } = useAccounts(false)
// Options state
const [migrationOptions, setMigrationOptions] = useState<MigrationOptions>(DEFAULT_OPTIONS)
@@ -2619,16 +2625,10 @@ export default function ArcimMigrationWorkspace({
}
const data = await res.json() as SIEData
const accountsRes = await fetch('/api/bookkeeping/accounts?active=false')
const accountsBody = await accountsRes.json().catch(() => ({})) as {
data?: BASAccount[]
error?: unknown
}
if (!accountsRes.ok) {
throw apiError(accountsBody, `HTTP ${accountsRes.status}`)
}
companyAccountsForVatRef.current = accountsBody.data ?? []
const enrichedMappings = enrichAccountMappingsWithVat(data.mappings, accountsBody.data ?? [])
// Bound SWR mutate resolves with the revalidated list.
const companyAccounts = ((await refreshCompanyAccounts()) ?? []) as BASAccount[]
companyAccountsForVatRef.current = companyAccounts
const enrichedMappings = enrichAccountMappingsWithVat(data.mappings, companyAccounts)
setSieData({ ...data, mappings: enrichedMappings })
// If all SIE files are already imported, disable SIE import by default
@@ -2648,7 +2648,7 @@ export default function ArcimMigrationWorkspace({
} finally {
setIsLoading(false)
}
}, [consentId])
}, [consentId, refreshCompanyAccounts])
const handlePreviewContinue = useCallback(() => {
if (preview?.sieAvailable) {
@@ -2781,6 +2781,9 @@ export default function ArcimMigrationWorkspace({
const result = await res.json() as ImportResult
setSieImportResults(prev => [...prev, result])
// The import creates accounts and a räkenskapsår: every cached
// picker must see them.
void invalidateReferenceData(['ref:accounts', 'ref:fiscal-periods'])
// The endpoint returns HTTP 200 with success:false when the import
// itself failed (e.g. räkenskapsår mismatch). Stop here: continuing
@@ -1,6 +1,7 @@
'use client'
import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
import { useCompanySettings } from '@/lib/reference-data/hooks'
import { useTranslations } from 'next-intl'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
@@ -391,7 +392,11 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
// Cash method users see "Bokför direkt" as the primary CTA; accrual users
// see "Skapa leverantörsfaktura". Defaults to 'accrual' until we've read
// the company settings so we don't flicker the CTA order on first paint.
const [accountingMethod, setAccountingMethod] = useState<AccountingMethod>('accrual')
// The company's bookkeeping method drives the CTA hierarchy; read from the
// session-cached settings row (lib/reference-data), no request of its own.
const { settings: companySettings } = useCompanySettings()
const accountingMethod: AccountingMethod =
companySettings?.accounting_method === 'cash' ? 'cash' : 'accrual'
// ── Data loading ───────────────────────────────────────────
@@ -451,16 +456,6 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
useEffect(() => {
fetchItems()
fetchInboxAddress()
// Resolve the company's bookkeeping method: drives CTA hierarchy.
fetch('/api/settings')
.then((r) => (r.ok ? r.json() : null))
.then((body) => {
const method = body?.data?.accounting_method
if (method === 'cash' || method === 'accrual') {
setAccountingMethod(method)
}
})
.catch(() => { /* keep 'accrual' default */ })
}, [fetchItems, fetchInboxAddress])
// Realtime: refetch when any invoice_inbox_items row changes for this
@@ -1,6 +1,7 @@
'use client'
import { useState, useCallback, useEffect } from 'react'
import { useCompanySettings } from '@/lib/reference-data/hooks'
import { useTranslations } from 'next-intl'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
@@ -188,6 +189,9 @@ function ProfileSkeleton() {
export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
const { getByKey, save, isLoading: isDataLoading } = useExtensionData('general', 'tic')
const { toast } = useToast()
// org_number from the session-cached settings row (lib/reference-data):
// the profile fetch no longer pays a /api/settings round trip first.
const { settings: companySettings, error: settingsError } = useCompanySettings()
const t = useTranslations('tic_workspace')
const [profile, setProfile] = useState<TICCompanyProfile | null>(null)
const [isFetching, setIsFetching] = useState(false)
@@ -216,14 +220,13 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
setFetchFailed(false)
try {
// Get org_number from company settings
const settingsRes = await fetch('/api/settings')
if (!settingsRes.ok) {
// Get org_number from company settings (settled without a row = the
// same failure the old fetch reported).
if (settingsError) {
toast({ title: t('toast_settings_failed'), variant: 'destructive' })
return
}
const { data: settings } = await settingsRes.json()
const orgNumber = settings?.org_number
const orgNumber = companySettings?.org_number
if (!orgNumber) {
setNoOrgNumber(true)
@@ -255,7 +258,7 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
} finally {
setIsFetching(false)
}
}, [save, toast, t])
}, [save, toast, t, companySettings, settingsError])
// Auto-fetch on first visit when no cached data
useEffect(() => {