Files
accounted/components/import/OpeningBalancePeriodStep.tsx
T
Jakob Wennberg 3ee3565d6d 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>
2026-08-26 14:56:37 +02:00

203 lines
8.0 KiB
TypeScript

'use client'
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'
interface EditableRow {
id: string
account_number: string
account_name: string
debit_amount: number
credit_amount: number
}
interface OpeningBalancePeriodStepProps {
rows: EditableRow[]
/** `replace` is true when the selected period already has opening balances
* (the existing IB verifikat will be stornoed and replaced). */
onExecute: (fiscalPeriodId: string, replace: boolean) => void
onBack: () => void
isLoading: boolean
error: string | null
}
export default function OpeningBalancePeriodStep({
rows,
onExecute,
onBack,
isLoading,
error,
}: OpeningBalancePeriodStepProps) {
// Session-cached period list (lib/reference-data).
const { periods, isLoading: loadingPeriods } = useFiscalPeriods()
const [selectedPeriodId, setSelectedPeriodId] = useState<string>('')
// 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
let totalCredit = 0
for (const row of rows) {
totalDebit = Math.round((totalDebit + row.debit_amount) * 100) / 100
totalCredit = Math.round((totalCredit + row.credit_amount) * 100) / 100
}
// Compare in whole öre, mirroring the engine's validateBalance: a float
// epsilon like (< 0.01) would misclassify exact 1-öre imbalances as
// balanced, since e.g. 0.03 - 0.02 evaluates to just under 0.01.
const balanceDiff = Math.round((totalDebit - totalCredit) * 100) / 100
const isBalanced = Math.round((totalDebit - totalCredit) * 100) === 0
useEffect(() => {
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
const periodIsClosed = selectedPeriod?.is_closed
const periodIsLocked = !!selectedPeriod?.locked_at
// A period that already has IB can still be corrected, as long as it is open
// and unlocked: the existing IB verifikat is stornoed and replaced.
const canExecute =
!!selectedPeriodId &&
!periodIsClosed &&
!periodIsLocked &&
isBalanced &&
!isLoading
const handleExecute = useCallback(() => {
if (canExecute) {
onExecute(selectedPeriodId, periodHasOB)
}
}, [canExecute, selectedPeriodId, periodHasOB, onExecute])
return (
<Card>
<CardHeader>
<CardTitle>Välj räkenskapsperiod</CardTitle>
<CardDescription>
Välj vilken räkenskapsperiod de ingående balanserna ska bokföras .
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Period selector */}
<div className="space-y-2">
<Label>Räkenskapsperiod</Label>
{loadingPeriods ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
<Loader2 className="h-4 w-4 animate-spin" />
Hämtar perioder...
</div>
) : periods.length === 0 ? (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
<AlertCircle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
<p className="text-sm text-warning">
Inga räkenskapsperioder hittades. Skapa en räkenskapsperiod under Bokföring först.
</p>
</div>
) : (
<Select value={selectedPeriodId} onValueChange={setSelectedPeriodId}>
<SelectTrigger>
<SelectValue placeholder="Välj period" />
</SelectTrigger>
<SelectContent>
{periods.map((p) => (
<SelectItem key={p.id} value={p.id} disabled={p.is_closed || !!p.locked_at}>
{p.name} ({p.period_start} till {p.period_end})
{p.opening_balances_set && ', har redan IB'}
{p.is_closed && ', stängd'}
{p.locked_at && !p.is_closed && ', låst'}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
{/* Replace notice: selecting a period that already has IB corrects it */}
{periodHasOB && !periodIsClosed && !periodIsLocked && (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
<AlertCircle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
<p className="text-sm text-warning">
Denna period har redan ingående balanser. Om du fortsätter makuleras (stornas) den
befintliga IB-verifikationen och en ny bokförs med beloppen nedan.
</p>
</div>
)}
{/* Summary */}
<div className="rounded-lg border bg-muted/30 p-4 space-y-3">
<h4 className="text-sm font-medium">Sammanfattning</h4>
<div className="grid grid-cols-2 gap-y-2 text-sm">
<span className="text-muted-foreground">Antal konton:</span>
<span className="tabular-nums text-right">{rows.length}</span>
<span className="text-muted-foreground">Total debet:</span>
<span className="tabular-nums text-right">
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK
</span>
<span className="text-muted-foreground">Total kredit:</span>
<span className="tabular-nums text-right">
{totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK
</span>
</div>
{isBalanced ? (
<div className="flex items-center gap-2 pt-1 border-t text-sm">
<CheckCircle2 className="h-4 w-4 text-success" />
<span className="text-success font-medium">Balanserar</span>
</div>
) : (
<div className="flex items-center gap-2 pt-1 border-t text-sm">
<AlertCircle className="h-4 w-4 text-destructive shrink-0" />
<span className="text-destructive font-medium">
Balanserar inte (differens{' '}
<span className="tabular-nums">
{balanceDiff.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>{' '}
SEK)
</span>
</div>
)}
</div>
{/* Error */}
{error && (
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
<AlertCircle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
<p className="text-sm text-destructive">{error}</p>
</div>
)}
{/* Actions */}
<div className="flex justify-between pt-2">
<Button variant="ghost" onClick={onBack} disabled={isLoading}>
Tillbaka
</Button>
<Button onClick={handleExecute} disabled={!canExecute}>
{isLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
{periodHasOB ? 'Ersätter...' : 'Bokför...'}
</>
) : periodHasOB ? (
'Ersätt ingående balanser'
) : (
'Bokför ingående balanser'
)}
</Button>
</div>
</CardContent>
</Card>
)
}