1a41119682
* perf(bundle): drop the BAS chart and the Node crypto polyfill from the shared client baseline
Two chunks rode along in the first-load JS of almost every dashboard route:
the full BAS 2026 chart (315 KB uncompressed, in 81 route manifests) and
the browser polyfill for Node's crypto/vm/Buffer (327 KB, in 26 routes
incl. login and register). Neither was needed on first paint; both got
there through static imports of helpers that happen to live next to code
that needs the data or the builtin.
Node polyfill (4 pure splits, behaviour unchanged, re-exported from the
original modules for server callers):
- lib/auth/bankid-flags.ts: isBankIdEnabled (login, register, security
settings imported it from bankid.ts, which imports crypto).
- lib/import/bank-file/formats.ts: the format registry + detection (the
import history imported getFormat from parser.ts, which hashes).
- lib/salary/personnummer-format.ts: parsing/validation/formatting (the
employee forms reached the encrypting personnummer.ts via tax-column).
- lib/auth/api-key-scopes.ts: scope catalogue, groups, tool map, helpers
(the API key panel imported STAGING_SCOPES from the key generator).
BAS chart:
- lib/bookkeeping/bas-lazy.ts + use-bas-reference.ts: the chart becomes a
dynamic import, fetched once per session after first paint; components
that show BAS names/descriptions call useBasReference() and re-render
when it lands. Until then (and on the server) only the hardcoded
account-descriptions answer, so SSR and hydration agree.
- lib/bookkeeping/bas-labels.ts: class/group labels out of bas-reference.ts
(account-descriptions needed a label and paid for the whole chart).
- lib/bookkeeping/bas-account-numbers.ts (generated, ~11 KB) +
scripts/generate-bas-account-numbers.ts (--check) + parity test:
isStandardBASAccountNumber for AddAccountDialog/ChartOfAccountsManager.
- lib/bookkeeping/account-classifier-{heuristic,client}.ts: the BAS-aligned
heuristic shared by the server classifier and a client variant that uses
the lazy chart.
- lib/bookkeeping/invoice-accounts.ts: INVOICE_FX_RATE_MISSING,
InvoiceFxRateMissingError, getRevenueAccount, getOutputVatAccount out of
invoice-entries.ts, whose engine import pulled account-backfill and the
chart into SendInvoiceDialog/PaymentBookingDialog.
- CorrectOpeningBalanceDialog re-seeds names when the chart lands;
OpeningBalanceRowEditor builds its Fuse indexes lazily; the
ChartOfAccountsManager BAS-katalog tab awaits the chunk.
Tooling:
- scripts/perf/client-import-closure.mjs: static import closure of every
'use client' module with the shortest chain to a target (file or bare
specifier); found every path above without a build.
- scripts/checks/client-node-builtin.mjs wired into check:guards: a client
module reaching a Node builtin is a hard failure (0 today).
Left as is: invoices/[id], its credit page and SendInvoiceDialog still
reach the chart through lib/invoices/issue-credit-note -> invoice-entries
-> engine -> account-backfill; splitting the engine is out of scope here.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(perf): unambiguous import-edge regex in the closure walker (CodeQL js/redos)
One quantifier per span: a greedy [^'"]* up to the specifier quote, which it
cannot cross, so a run of whitespace has a single parse. Same edges as
before (multi-line named imports, re-exports, side-effect imports; type-only
imports still skipped).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
166 lines
5.9 KiB
TypeScript
166 lines
5.9 KiB
TypeScript
'use client'
|
|
|
|
import { useMemo, useState, useCallback } from 'react'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
} from '@/components/ui/dialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { AlertTriangle } from 'lucide-react'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
|
import { getBasLoadedByNumber } from '@/lib/bookkeeping/bas-lazy'
|
|
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
|
|
import OpeningBalanceRowEditor, {
|
|
type EditableRow,
|
|
type OpeningBalanceEditorState,
|
|
} from '@/components/import/OpeningBalanceRowEditor'
|
|
import type { JournalEntry, JournalEntryLine } from '@/types'
|
|
|
|
interface Props {
|
|
/** The currently-linked, posted opening-balance verifikat being corrected. */
|
|
entry: JournalEntry
|
|
open: boolean
|
|
onOpenChange: (open: boolean) => void
|
|
onCorrected: () => void
|
|
}
|
|
|
|
let seedIdCounter = 0
|
|
|
|
// Map the booked IB's lines into editable rows. account_name isn't stored on
|
|
// the line, so resolve it from BAS for display (cosmetic: only account_number
|
|
// + amounts are sent on save). The chart is a lazily loaded chunk: the
|
|
// caller re-seeds once it has arrived.
|
|
function seedRowsFromEntry(entry: JournalEntry): EditableRow[] {
|
|
const lines = ((entry.lines || []) as JournalEntryLine[])
|
|
.slice()
|
|
.sort((a, b) => a.sort_order - b.sort_order)
|
|
|
|
return lines.map((l) => {
|
|
const bas = getBasLoadedByNumber(l.account_number)
|
|
return {
|
|
id: l.id || `seed_${++seedIdCounter}`,
|
|
account_number: l.account_number,
|
|
account_name: bas?.account_name ?? '',
|
|
debit_amount: Number(l.debit_amount) || 0,
|
|
credit_amount: Number(l.credit_amount) || 0,
|
|
validation_errors: [],
|
|
bas_match: bas?.account_name ?? null,
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Inline correction of an already-booked opening-balance verifikat. The user
|
|
* edits the IB's lines directly; on save we POST to
|
|
* /api/import/opening-balance/correct, which (BFL-compliant) stornoes the old
|
|
* IB, books a corrected one, and relinks the period to it. Works regardless of
|
|
* how the IB was created (SIE import, CSV/Excel import, or year-end carry).
|
|
*/
|
|
export default function CorrectOpeningBalanceDialog({
|
|
entry,
|
|
open,
|
|
onOpenChange,
|
|
onCorrected,
|
|
}: Props) {
|
|
const { toast } = useToast()
|
|
const basReady = useBasReference()
|
|
// basReady is a re-seed trigger: names fill in once the chart chunk lands.
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
const initialRows = useMemo(() => seedRowsFromEntry(entry), [entry, basReady])
|
|
const [state, setState] = useState<OpeningBalanceEditorState | null>(null)
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
|
|
const handleSubmit = useCallback(async () => {
|
|
if (!state?.canSubmit || isSubmitting) return
|
|
|
|
setIsSubmitting(true)
|
|
try {
|
|
const lines = state.rows
|
|
.filter((r) => r.debit_amount > 0 || r.credit_amount > 0)
|
|
.map((r) => ({
|
|
account_number: r.account_number,
|
|
debit_amount: r.debit_amount,
|
|
credit_amount: r.credit_amount,
|
|
}))
|
|
|
|
const res = await fetch('/api/import/opening-balance/correct', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ fiscal_period_id: entry.fiscal_period_id, lines }),
|
|
})
|
|
|
|
const result = await res.json()
|
|
|
|
if (!res.ok) {
|
|
const err = new Error('Failed to correct opening balances') as Error & {
|
|
body?: unknown
|
|
status?: number
|
|
}
|
|
err.body = result
|
|
err.status = res.status
|
|
throw err
|
|
}
|
|
|
|
toast({
|
|
title: 'Ingående balanser korrigerade',
|
|
description: 'Den gamla IB-verifikationen stornades och en ny bokfördes.',
|
|
})
|
|
onOpenChange(false)
|
|
onCorrected()
|
|
} catch (err) {
|
|
const anyErr = err as { body?: unknown; status?: number }
|
|
toast({
|
|
title: 'Kunde inte korrigera ingående balanser',
|
|
description: getErrorMessage(anyErr.body ?? err, {
|
|
context: 'journal_entry',
|
|
statusCode: anyErr.status,
|
|
}),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsSubmitting(false)
|
|
}
|
|
}, [state, isSubmitting, entry.fiscal_period_id, toast, onOpenChange, onCorrected])
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
|
<DialogHeader>
|
|
<DialogTitle>Korrigera ingående balanser</DialogTitle>
|
|
<DialogDescription>
|
|
Ändra beloppen nedan och spara. Den befintliga IB-verifikationen (
|
|
<span data-ph-mask="">{formatVoucher(entry)}</span>) makuleras och en ny bokförs med
|
|
de korrigerade beloppen.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{/* Storno explanation: a booked verifikat can't be edited in place */}
|
|
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
|
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
|
<p className="text-sm text-warning">
|
|
En bokförd verifikation kan inte ändras direkt (Bokföringslagen). När du sparar stornas
|
|
den gamla IB-verifikationen och en ny bokförs: båda sparas som en spårbar rättelse.
|
|
</p>
|
|
</div>
|
|
|
|
<OpeningBalanceRowEditor initialRows={initialRows} onChange={setState} />
|
|
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
|
Avbryt
|
|
</Button>
|
|
<Button onClick={handleSubmit} disabled={!state?.canSubmit || isSubmitting}>
|
|
{isSubmitting ? 'Sparar...' : 'Korrigera ingående balanser'}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|