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:
co-authored by
Jakob Wennberg
Claude Fable 5
parent
4560ccbfc9
commit
3ee3565d6d
@@ -6,9 +6,10 @@ import { Input } from '@/components/ui/input'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
DIMENSION_CODE_PATTERN,
|
||||
fetchDimensions,
|
||||
type DimensionValueDto,
|
||||
} from '@/components/dimensions/types'
|
||||
import { useDimensions } from '@/lib/reference-data/hooks'
|
||||
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
|
||||
|
||||
interface DimensionComboboxProps {
|
||||
/** SIE dimension number as a string ('1' = kostnadsställe, '6' = projekt). */
|
||||
@@ -47,9 +48,23 @@ export default function DimensionCombobox({
|
||||
const [search, setSearch] = useState(value ?? '')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||
const [loadState, setLoadState] = useState<'idle' | 'loading' | 'loaded' | 'error'>('idle')
|
||||
const [dimensionId, setDimensionId] = useState<string | null>(null)
|
||||
const [values, setValues] = useState<DimensionValueDto[]>([])
|
||||
// Registry from the session cache (lib/reference-data): every combobox on
|
||||
// the page shares one entry, so opening a picker costs no request.
|
||||
const { dimensions, isLoading: registryLoading, error: registryError } = useDimensions()
|
||||
const loadState: 'loading' | 'loaded' | 'error' = registryLoading
|
||||
? 'loading'
|
||||
: registryError
|
||||
? 'error'
|
||||
: 'loaded'
|
||||
const dimension = useMemo(
|
||||
() => dimensions.find((d) => String(d.sie_dim_no) === sieDimNo) ?? null,
|
||||
[dimensions, sieDimNo],
|
||||
)
|
||||
const dimensionId = dimension?.id ?? null
|
||||
const values = useMemo(
|
||||
() => dimension?.values.filter((v) => v.is_active) ?? [],
|
||||
[dimension],
|
||||
)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
@@ -72,24 +87,10 @@ export default function DimensionCombobox({
|
||||
valuesRef.current = values
|
||||
}, [values])
|
||||
|
||||
const loadValues = useCallback(async () => {
|
||||
setLoadState('loading')
|
||||
try {
|
||||
const dims = await fetchDimensions()
|
||||
const dim = dims.find((d) => String(d.sie_dim_no) === sieDimNo)
|
||||
setDimensionId(dim?.id ?? null)
|
||||
setValues(dim?.values.filter((v) => v.is_active) ?? [])
|
||||
setLoadState('loaded')
|
||||
} catch {
|
||||
setLoadState('error')
|
||||
}
|
||||
}, [sieDimNo])
|
||||
|
||||
const openDropdown = useCallback(() => {
|
||||
setIsOpen(true)
|
||||
setCreateError(null)
|
||||
if (loadState === 'idle') void loadValues()
|
||||
}, [loadState, loadValues])
|
||||
}, [])
|
||||
|
||||
const filteredValues = useMemo(() => {
|
||||
const term = search.trim().toLowerCase()
|
||||
@@ -169,7 +170,8 @@ export default function DimensionCombobox({
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
}
|
||||
setValues((prev) => [...prev, created].sort((a, b) => a.code.localeCompare(b.code, 'sv')))
|
||||
// Refresh the shared registry so every picker offers the new value.
|
||||
await invalidateReferenceData('ref:dimensions')
|
||||
selectValue(created.code)
|
||||
} finally {
|
||||
setIsCreating(false)
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { useDimensions } from '@/lib/reference-data/hooks'
|
||||
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -44,7 +46,6 @@ import DimensionValueForm, {
|
||||
type DimensionValueFormInput,
|
||||
} from '@/components/dimensions/DimensionValueForm'
|
||||
import {
|
||||
fetchDimensions,
|
||||
PROJECT_DIM_NO,
|
||||
type DimensionDto,
|
||||
type DimensionValueDto,
|
||||
@@ -76,10 +77,21 @@ export default function DimensionsManager() {
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
|
||||
const [dimensions, setDimensions] = useState<DimensionDto[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [activeDimId, setActiveDimId] = useState<string | null>(null)
|
||||
// The register renders the same session-cached registry the pickers use
|
||||
// (lib/reference-data); every write below invalidates it.
|
||||
const { dimensions: registry, isLoading, error: loadError, refresh: refreshDimensions } = useDimensions()
|
||||
const dimensions = useMemo(
|
||||
() => [...registry].sort((a, b) => a.sort_order - b.sort_order || a.sie_dim_no - b.sie_dim_no),
|
||||
[registry],
|
||||
)
|
||||
const loadFailed = !!loadError
|
||||
// The requested tab, validated against the current registry: a dimension
|
||||
// that disappears falls back to the first one.
|
||||
const [requestedDimId, setActiveDimId] = useState<string | null>(null)
|
||||
const activeDimId =
|
||||
requestedDimId && dimensions.some((d) => d.id === requestedDimId)
|
||||
? requestedDimId
|
||||
: (dimensions[0]?.id ?? null)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [sortColumn, setSortColumn] = useState<SortColumn>('code')
|
||||
const [sortDir, setSortDir] = useState<SortDir>('asc')
|
||||
@@ -88,37 +100,17 @@ export default function DimensionsManager() {
|
||||
const [newDimDialogOpen, setNewDimDialogOpen] = useState(false)
|
||||
const [isCreatingDimension, setIsCreatingDimension] = useState(false)
|
||||
|
||||
const loadDimensions = useCallback(
|
||||
async (showSpinner: boolean) => {
|
||||
if (showSpinner) setIsLoading(true)
|
||||
try {
|
||||
const dims = await fetchDimensions()
|
||||
const sorted = [...dims].sort(
|
||||
(a, b) => a.sort_order - b.sort_order || a.sie_dim_no - b.sie_dim_no,
|
||||
)
|
||||
setDimensions(sorted)
|
||||
setLoadFailed(false)
|
||||
setActiveDimId((prev) =>
|
||||
prev && sorted.some((d) => d.id === prev) ? prev : (sorted[0]?.id ?? null),
|
||||
)
|
||||
} catch (err) {
|
||||
setLoadFailed(true)
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: getErrorMessage(err, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
},
|
||||
[toast, t, errorLocale],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void loadDimensions(true)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
if (!loadError) return
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: getErrorMessage(loadError, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}, [loadError, toast, t, errorLocale])
|
||||
|
||||
/** After a write: refresh the shared registry (this list and every picker). */
|
||||
const loadDimensions = useCallback(() => invalidateReferenceData('ref:dimensions'), [])
|
||||
|
||||
const activeDim = useMemo(
|
||||
() => dimensions.find((d) => d.id === activeDimId) ?? null,
|
||||
@@ -227,7 +219,7 @@ export default function DimensionsManager() {
|
||||
})
|
||||
}
|
||||
setDialog(null)
|
||||
await loadDimensions(false)
|
||||
await loadDimensions()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('save_failed_title'),
|
||||
@@ -262,7 +254,7 @@ export default function DimensionsManager() {
|
||||
const createdId = (json?.data?.dimension as { id?: string } | undefined)?.id
|
||||
toast({ title: t('dim_created_title') })
|
||||
setNewDimDialogOpen(false)
|
||||
await loadDimensions(false)
|
||||
await loadDimensions()
|
||||
if (createdId) {
|
||||
setActiveDimId(createdId)
|
||||
setSearchTerm('')
|
||||
@@ -300,7 +292,7 @@ export default function DimensionsManager() {
|
||||
}
|
||||
toast({ title: t('deleted_title') })
|
||||
setDialog(null)
|
||||
await loadDimensions(false)
|
||||
await loadDimensions()
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
@@ -359,7 +351,7 @@ export default function DimensionsManager() {
|
||||
title={t('load_failed_title')}
|
||||
description={t('load_failed_description')}
|
||||
actionLabel={t('retry')}
|
||||
onAction={() => void loadDimensions(true)}
|
||||
onAction={() => void refreshDimensions()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import DimensionCombobox from '@/components/dimensions/DimensionCombobox'
|
||||
import {
|
||||
fetchDimensionsCached,
|
||||
type DimensionDto,
|
||||
} from '@/components/dimensions/types'
|
||||
import { useDimensions } from '@/lib/reference-data/hooks'
|
||||
|
||||
interface LineDimensionFieldsProps {
|
||||
/** Current dimensions map ({sie_dim_no: object_code}), a line's map or the header default. */
|
||||
@@ -46,24 +43,13 @@ export default function LineDimensionFields({
|
||||
stacked,
|
||||
inputClassName,
|
||||
}: LineDimensionFieldsProps) {
|
||||
const [registry, setRegistry] = useState<DimensionDto[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetchDimensionsCached()
|
||||
.then((dims) => {
|
||||
if (!cancelled) setRegistry(dims)
|
||||
})
|
||||
.catch(() => {
|
||||
/* keep the hardcoded 1/6 fallback */
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
// Registry from the session cache (lib/reference-data): one entry shared
|
||||
// by every line picker on the page; empty while loading or on failure,
|
||||
// which keeps the hardcoded 1/6 fallback below.
|
||||
const { dimensions: registry } = useDimensions()
|
||||
|
||||
const fields = useMemo(() => {
|
||||
const active = registry?.filter((d) => d.is_active) ?? []
|
||||
const active = registry.filter((d) => d.is_active)
|
||||
if (active.length === 0) return FALLBACK_FIELDS
|
||||
return [...active]
|
||||
.sort((a, b) => a.sort_order - b.sort_order || a.sie_dim_no - b.sie_dim_no)
|
||||
|
||||
@@ -61,36 +61,3 @@ export const PROJECT_DIM_NO = 6
|
||||
*/
|
||||
export const DIMENSION_CODE_PATTERN = /^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$/
|
||||
|
||||
/**
|
||||
* Load the company's dimension registry. The handler lazily seeds system dims
|
||||
* 1/6 via ensure_company_dimensions, so the result always contains at least
|
||||
* Kostnadsställe + Projekt. Throws the parsed error envelope on failure so
|
||||
* callers can hand it straight to getErrorMessage().
|
||||
*/
|
||||
export async function fetchDimensions(): Promise<DimensionDto[]> {
|
||||
const res = await fetch('/api/dimensions')
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
throw json ?? new Error('Failed to load dimensions')
|
||||
}
|
||||
return (json?.dimensions ?? []) as DimensionDto[]
|
||||
}
|
||||
|
||||
let cachedDimensionsPromise: Promise<DimensionDto[]> | null = null
|
||||
|
||||
/**
|
||||
* Module-level cached variant of fetchDimensions for high-mount-count
|
||||
* consumers (one registry fetch per page load instead of one per line
|
||||
* picker). A failed fetch clears the cache so the next mount retries.
|
||||
* Registry mutations are rare enough that staleness within a page visit
|
||||
* is acceptable — the register UI uses the uncached fetch.
|
||||
*/
|
||||
export function fetchDimensionsCached(): Promise<DimensionDto[]> {
|
||||
if (!cachedDimensionsPromise) {
|
||||
cachedDimensionsPromise = fetchDimensions().catch((err) => {
|
||||
cachedDimensionsPromise = null
|
||||
throw err
|
||||
})
|
||||
}
|
||||
return cachedDimensionsPromise
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user