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
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { useAccounts } from '@/lib/reference-data/hooks'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -18,8 +19,6 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { summarizeByCurrency } from '@/lib/import/bank-file/currency-summary'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { BankFileParseResult, BankFileDuplicateInfo } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankAccount {
|
||||
@@ -54,32 +53,26 @@ export default function BankFileConfirmStep({
|
||||
// automatically rather than promising an exact final number.
|
||||
const duplicateCount = Math.min(Math.max(duplicateInfo?.duplicate_count ?? 0, 0), stats.parsed_rows)
|
||||
|
||||
const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([])
|
||||
const [selectedAccount, setSelectedAccount] = useState('1930')
|
||||
const { company } = useCompany()
|
||||
|
||||
// Active 19xx accounts from the session-cached chart (lib/reference-data):
|
||||
// the account select is populated on the first paint.
|
||||
const { accounts } = useAccounts()
|
||||
const bankAccounts = useMemo<BankAccount[]>(
|
||||
() =>
|
||||
accounts
|
||||
.filter((a) => a.account_number >= '1900' && a.account_number <= '1999')
|
||||
.sort((a, b) => a.account_number.localeCompare(b.account_number))
|
||||
.map((a) => ({ account_number: a.account_number, account_name: a.account_name })),
|
||||
[accounts],
|
||||
)
|
||||
// Default to 1930 if available, otherwise the first account (once).
|
||||
const defaultedRef = useRef(false)
|
||||
useEffect(() => {
|
||||
if (!company?.id) return
|
||||
async function fetchBankAccounts(companyId: string) {
|
||||
const supabase = createClient()
|
||||
const { data } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number, account_name')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.gte('account_number', '1900')
|
||||
.lte('account_number', '1999')
|
||||
.order('account_number')
|
||||
|
||||
if (data && data.length > 0) {
|
||||
setBankAccounts(data)
|
||||
// Default to 1930 if available, otherwise first account
|
||||
const has1930 = data.some(a => a.account_number === '1930')
|
||||
if (!has1930) setSelectedAccount(data[0].account_number)
|
||||
}
|
||||
}
|
||||
fetchBankAccounts(company.id)
|
||||
}, [company?.id])
|
||||
if (defaultedRef.current || bankAccounts.length === 0) return
|
||||
defaultedRef.current = true
|
||||
const has1930 = bankAccounts.some((a) => a.account_number === '1930')
|
||||
if (!has1930) setSelectedAccount(bankAccounts[0].account_number)
|
||||
}, [bankAccounts])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AlertCircle } from 'lucide-react'
|
||||
@@ -16,24 +17,10 @@ import { findFiscalYearGaps, type FiscalYearGap, type PeriodLike } from '@/lib/b
|
||||
*/
|
||||
export function FiscalYearGapNotice() {
|
||||
const t = useTranslations('fiscal_year_gaps')
|
||||
const [gaps, setGaps] = useState<FiscalYearGap[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/bookkeeping/fiscal-periods')
|
||||
.then(async (res) => {
|
||||
if (!res.ok) return
|
||||
const json = await res.json()
|
||||
const periods = (Array.isArray(json) ? json : (json.data ?? [])) as PeriodLike[]
|
||||
if (!cancelled) setGaps(findFiscalYearGaps(periods))
|
||||
})
|
||||
.catch(() => {
|
||||
// Advisory only.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
// Session-cached period list (lib/reference-data): refreshed by the import
|
||||
// flow's invalidation, so the notice reflects the years just imported.
|
||||
const { periods } = useFiscalPeriods()
|
||||
const gaps = useMemo<FiscalYearGap[]>(() => findFiscalYearGaps(periods as PeriodLike[]), [periods])
|
||||
|
||||
if (gaps.length === 0) return null
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useCompanySettings } from '@/lib/reference-data/hooks'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -72,6 +73,8 @@ export default function ImportReviewStep({
|
||||
}: ImportReviewStepProps) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { company } = useCompany()
|
||||
const { settings: companySettings } = useCompanySettings()
|
||||
const companyDefaultVoucherSeries = companySettings?.default_voucher_series || null
|
||||
const t = useTranslations('import')
|
||||
const [options, setOptions] = useState<ImportExecuteOptions>({
|
||||
createFiscalPeriod: true,
|
||||
@@ -116,15 +119,9 @@ export default function ImportReviewStep({
|
||||
: Promise.resolve({ count: 0, error: null })
|
||||
|
||||
const [
|
||||
{ data: settingsData, error: settingsError },
|
||||
{ data: sequencesData, error: sequencesError },
|
||||
{ count: ibCount, error: ibCountError },
|
||||
] = await Promise.all([
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('default_voucher_series')
|
||||
.eq('company_id', company.id)
|
||||
.maybeSingle(),
|
||||
supabase
|
||||
.from('voucher_sequences')
|
||||
.select('voucher_series')
|
||||
@@ -134,9 +131,6 @@ export default function ImportReviewStep({
|
||||
|
||||
if (cancelled) return
|
||||
|
||||
if (settingsError) {
|
||||
console.error('Failed to load company settings for voucher series', settingsError)
|
||||
}
|
||||
if (sequencesError) {
|
||||
console.error('Failed to load voucher sequences', sequencesError)
|
||||
}
|
||||
@@ -144,7 +138,8 @@ export default function ImportReviewStep({
|
||||
console.error('Failed to check for existing opening-balance vouchers', ibCountError)
|
||||
}
|
||||
|
||||
const companyDefault = settingsData?.default_voucher_series || null
|
||||
// From the session-cached settings row (lib/reference-data).
|
||||
const companyDefault = companyDefaultVoucherSeries
|
||||
const sequences = new Set<string>((sequencesData || []).map((row) => row.voucher_series))
|
||||
const existingIb = ibCountError ? 0 : (ibCount ?? 0)
|
||||
|
||||
@@ -176,7 +171,7 @@ export default function ImportReviewStep({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [company?.id, preview.fiscalYearStart, preview.fiscalYearEnd, preview.openingBalanceTotal])
|
||||
}, [company?.id, companyDefaultVoucherSeries, preview.fiscalYearStart, preview.fiscalYearEnd, preview.openingBalanceTotal])
|
||||
|
||||
// Block browser close/refresh during import
|
||||
useUnsavedChanges(isLoading)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { AlertCircle, Loader2, CheckCircle2 } from 'lucide-react'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
|
||||
interface EditableRow {
|
||||
id: string
|
||||
@@ -33,9 +33,12 @@ export default function OpeningBalancePeriodStep({
|
||||
isLoading,
|
||||
error,
|
||||
}: OpeningBalancePeriodStepProps) {
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
// Session-cached period list (lib/reference-data).
|
||||
const { periods, isLoading: loadingPeriods } = useFiscalPeriods()
|
||||
const [selectedPeriodId, setSelectedPeriodId] = useState<string>('')
|
||||
const [loadingPeriods, setLoadingPeriods] = useState(true)
|
||||
// Auto-select the first open period without OB once per load, never again
|
||||
// on a background refresh of the list (that would override a user pick).
|
||||
const autoSelectedRef = useRef(false)
|
||||
|
||||
// Compute totals
|
||||
let totalDebit = 0
|
||||
@@ -51,31 +54,13 @@ export default function OpeningBalancePeriodStep({
|
||||
const isBalanced = Math.round((totalDebit - totalCredit) * 100) === 0
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPeriods() {
|
||||
setLoadingPeriods(true)
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
const allPeriods: FiscalPeriod[] = data.data || []
|
||||
setPeriods(allPeriods)
|
||||
|
||||
// Auto-select first open period without OB
|
||||
const openPeriod = allPeriods.find(
|
||||
(p) => !p.is_closed && !p.locked_at && !p.opening_balances_set,
|
||||
)
|
||||
if (openPeriod) {
|
||||
setSelectedPeriodId(openPeriod.id)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silent, user can still select period
|
||||
} finally {
|
||||
setLoadingPeriods(false)
|
||||
}
|
||||
}
|
||||
fetchPeriods()
|
||||
}, [])
|
||||
if (loadingPeriods || autoSelectedRef.current) return
|
||||
autoSelectedRef.current = true
|
||||
const openPeriod = periods.find(
|
||||
(p) => !p.is_closed && !p.locked_at && !p.opening_balances_set,
|
||||
)
|
||||
if (openPeriod) setSelectedPeriodId(openPeriod.id)
|
||||
}, [periods, loadingPeriods])
|
||||
|
||||
const selectedPeriod = periods.find((p) => p.id === selectedPeriodId)
|
||||
const periodHasOB = !!selectedPeriod?.opening_balances_set
|
||||
|
||||
Reference in New Issue
Block a user