fix: counterparty template pick crashes the page (#1291)
Picking a suggestion under "Tidigare motparter" in Bokför transaktion replaced
the page with "Något gick fel". handleOpenTemplateReview built the review state
from `{ id, name_sv } as BookingTemplate`, so `template.debit_account` was
undefined, reached QuickReviewDialog's required `defaultAccount: string`, and
threw on `accountOverride.startsWith('2')` during the first render.
Typed the dialog's template prop as a narrow ReviewTemplate whose optional
fields are actually optional, so the cast disappears and the compiler owns this
class of bug. Also carries the counterparty's learned accounts and VAT (the
preview showed the category fallback, not what the server books) and decides
"is this a counterparty booking" from the template id rather than the presence
of a line_pattern (single-line templates got an account/VAT editor the
categorize route discards).
Five more page-crashes of the same shape, adversarially verified:
- suppliers/[id] and supplier-invoices/[id] passed the error envelope OBJECT as
a toast description. The Toaster is a sibling of {children} in the ROOT
layout, so that throw escapes both segment error boundaries onto global-error.
- components/reports/views wrote the same object into a useState<string | null>
at 13 sites and rendered it bare.
- components/ui/toaster.tsx now coerces non-renderable values as a choke point.
- skattekonto read data.informationstext.length off Skatteverket's raw JSON,
where the field is not required.
- TicWorkspace read profile.statuses.length off a persisted jsonb blob. 17 of 17
prod rows predate the TIC v2 upgrade (#584) and lack the key, so that
workspace was in the error boundary for every company that had opened it.
Plus hardening: formatCurrency coerces a null currency to SEK (prod has 0 NULL
across 28 416 transactions, so defense not a live bug) and cleanSignatory
returns [] for a missing description.
Verified by rendering the real dialog against a throwaway /sandbox route: the
pre-fix prop shape reproduces the exact error boundary, the fixed one renders
D: 6570 Bankavgifter / K: 1930 Företagskonto and the matching verifikat.
No migrations.
This commit is contained in:
@@ -12,7 +12,9 @@ import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { linkDocuments, formatFailedDocumentNames } from '@/lib/documents/link-documents'
|
||||
import { ArrowUpRight, ArrowDownRight, Check, Paperclip, ChevronDown, ChevronUp, AlertTriangle } from 'lucide-react'
|
||||
import { getDefaultAccountForCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import type { BookingTemplate } from '@/lib/bookkeeping/booking-templates'
|
||||
import { isCounterpartyTemplateId } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { getVatRate } from '@/lib/bookkeeping/vat-entries'
|
||||
import type { ReviewTemplate } from '@/lib/transactions/quick-review-defaults'
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import JournalEntryPreview from './JournalEntryPreview'
|
||||
@@ -33,10 +35,11 @@ interface QuickReviewDialogProps {
|
||||
transaction: TransactionWithInvoice | null
|
||||
category: TransactionCategory | null
|
||||
categoryLabel: string
|
||||
/** Empty string when there is no sensible default: never undefined. */
|
||||
defaultAccount: string
|
||||
defaultVat: VatTreatment | 'none'
|
||||
entityType?: EntityType
|
||||
template?: BookingTemplate | null
|
||||
template?: ReviewTemplate | null
|
||||
templateId?: string
|
||||
counterpartyLinePattern?: LinePatternEntry[] | null
|
||||
/**
|
||||
@@ -76,7 +79,12 @@ export default function QuickReviewDialog({
|
||||
const tCat = useTranslations('tx_categories')
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const [accountOverride, setAccountOverride] = useState(defaultAccount)
|
||||
// `?? ''` is deliberate belt-and-braces: the prop is a required string, but
|
||||
// a caller that hands over a template-shaped object missing debit_account
|
||||
// used to make this undefined and take the whole page down on the
|
||||
// .startsWith() below. An empty account disables the confirm button; it
|
||||
// never throws.
|
||||
const [accountOverride, setAccountOverride] = useState(defaultAccount ?? '')
|
||||
const [vatTreatment, setVatTreatment] = useState<VatTreatment | 'none'>(defaultVat)
|
||||
const [accounts, setAccounts] = useState<BASAccount[]>([])
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
@@ -103,8 +111,8 @@ export default function QuickReviewDialog({
|
||||
|
||||
// Handle account changes: clear VAT for liability/equity accounts (class 2)
|
||||
const handleAccountChange = useCallback((account: string) => {
|
||||
setAccountOverride(account)
|
||||
if (account.startsWith('2')) {
|
||||
setAccountOverride(account ?? '')
|
||||
if (account?.startsWith('2')) {
|
||||
setVatTreatment('none')
|
||||
}
|
||||
}, [])
|
||||
@@ -200,9 +208,17 @@ export default function QuickReviewDialog({
|
||||
|
||||
const tx = enrichedTx ?? transaction
|
||||
const isIncome = tx.amount > 0
|
||||
const isCounterpartyTemplate = !!(counterpartyLinePattern && counterpartyLinePattern.length > 0)
|
||||
// Keyed off the template ID, not off the presence of a line pattern: a
|
||||
// *learned* counterparty (one business line, no pattern) is still booked
|
||||
// server-side from counterparty_template_id, so its accounts and VAT come
|
||||
// from the stored template. Deciding this from counterparties that happen
|
||||
// to have a multi-line pattern made single-line ones fall through to the
|
||||
// category branch, which previewed the wrong accounts and offered an
|
||||
// account/VAT editor whose values the categorize route discards.
|
||||
const isCounterpartyTemplate = !!template?.id && isCounterpartyTemplateId(template.id)
|
||||
const hasCounterpartyPattern = !!(counterpartyLinePattern && counterpartyLinePattern.length > 0)
|
||||
const isTemplateBooking = !!templateId || isCounterpartyTemplate
|
||||
const isLiabilityAccount = accountOverride.startsWith('2')
|
||||
const isLiabilityAccount = accountOverride?.startsWith('2') ?? false
|
||||
// For non-SEK transactions, the verifikation and the headline must show
|
||||
// the SEK-converted total: the mall/category booking always posts in SEK.
|
||||
const sekAmount = resolveSekAmount(
|
||||
@@ -399,7 +415,7 @@ export default function QuickReviewDialog({
|
||||
{patternDimsLabel}
|
||||
</Badge>
|
||||
)}
|
||||
{onChangeTemplate && !isCounterpartyTemplate && (
|
||||
{onChangeTemplate && !hasCounterpartyPattern && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-primary hover:underline"
|
||||
@@ -409,7 +425,10 @@ export default function QuickReviewDialog({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{template && !isCounterpartyTemplate && (
|
||||
{/* Only when there IS a single debit/credit pair to show: a
|
||||
multi-line counterparty pattern has none, and a template that
|
||||
never carried accounts would render "D: → K: ". */}
|
||||
{!hasCounterpartyPattern && template?.debit_account && template?.credit_account && (
|
||||
<p className="mt-1.5 text-xs font-mono text-muted-foreground">
|
||||
D: {formatAccountWithName(template.debit_account)} → K: {formatAccountWithName(template.credit_account)}
|
||||
</p>
|
||||
@@ -452,15 +471,26 @@ export default function QuickReviewDialog({
|
||||
<JournalEntryPreview
|
||||
amount={tx.amount}
|
||||
amountSek={sekAmount}
|
||||
{...(isCounterpartyTemplate
|
||||
{...(hasCounterpartyPattern
|
||||
? { linePattern: counterpartyLinePattern ?? undefined }
|
||||
: templateId && template
|
||||
: isTemplateBooking && template?.debit_account && template?.credit_account
|
||||
? {
|
||||
templateDebitAccount: template.debit_account,
|
||||
templateCreditAccount: template.credit_account,
|
||||
templateVatRate: template.vat_rate,
|
||||
templateVatTreatment: template.vat_treatment,
|
||||
templateSupplierType: template.reverse_charge_supplier_type,
|
||||
// A counterparty template carries a treatment but no rate,
|
||||
// and its legacy booking path emits an input-VAT leg from
|
||||
// that treatment only (no basbelopp pair), so it gets the
|
||||
// rate alone: passing the treatment too would preview
|
||||
// reverse-charge lines the engine never books.
|
||||
templateVatRate: isCounterpartyTemplate
|
||||
? (template.vat_treatment ? getVatRate(template.vat_treatment) : 0)
|
||||
: template.vat_rate,
|
||||
...(isCounterpartyTemplate
|
||||
? {}
|
||||
: {
|
||||
templateVatTreatment: template.vat_treatment,
|
||||
templateSupplierType: template.reverse_charge_supplier_type,
|
||||
}),
|
||||
}
|
||||
: { category, vatTreatment: isLiabilityAccount ? 'none' : vatTreatment, accountOverride, entityType }
|
||||
)}
|
||||
@@ -518,7 +548,7 @@ export default function QuickReviewDialog({
|
||||
library-template and legacy counterparty bookings. Multi-line
|
||||
counterparty patterns are excluded: their per-line bags are
|
||||
authoritative server-side and an edit here would be ignored. */}
|
||||
{dimensionsEnabled && !isCounterpartyTemplate && (
|
||||
{dimensionsEnabled && !hasCounterpartyPattern && (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">{t('label_dimensions')}</label>
|
||||
<div className="mt-1">
|
||||
|
||||
Reference in New Issue
Block a user