* fix(transactions): abort supplier-invoice match when payment voucher fails The match route caught a payment-JE creation failure and proceeded anyway: invoice marked paid with payment_journal_entry_id NULL, a payments row with no voucher, and the bank line linked but unbooked. That half-state is unrecoverable from the UI — mark-paid rejects 'paid' invoices and the match route rejects already-linked transactions (the "user can re-book" comment was wrong). The v1 route was already strict; this aligns the cookie route. A failed voucher now fails the whole match before any state mutation, with bookkeeping errors mapped to their structured codes and a new MATCH_SI_JE_FAILED fallback. Incident: Arcim 2026-06-11 — invoice 20250928 marked paid with no payment voucher because account 3740 was missing from the chart. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): bank-sync supplier-invoice match is a suggestion, not a hard link A high-confidence (>=0.85, unambiguous) supplier-invoice hit at sync time set transactions.supplier_invoice_id directly — without booking a payment or touching the invoice. The half-link then BLOCKED the match route (MATCH_SI_TX_ALREADY_LINKED), stranding the bank line with no path to a payment voucher and the invoice stuck on 'registered'. Sync now always writes potential_supplier_invoice_id; the hard link is reserved for completed matches where the payment voucher is booked. High-confidence hits still drain the matching pool and skip the mapping engine. Incident: Arcim 2026-06-11 — RosholmDell 18299 (29 890 kr) auto-linked at sync, unmatchable afterwards. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): seed standard BAS accounts on demand in the engine A minimal company chart routinely lacks accounts that legitimate engine flows reach — 3740 (öres- och kronutjämning) the first time a Bankgiro payment lands a sub-krona off the invoice, 6580 on a first legal invoice. createDraftEntry threw AccountsNotInChartError and turned a standard account into a dead end. The engine now backfills missing accounts from BAS_REFERENCE (full metadata incl. SRU code) before failing. Conservative by design: unknown numbers still throw, and deactivated accounts are never resurrected — deactivation is a deliberate user choice. Concurrent seeding (23505) counts as success. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(supplier-invoices): require explicit expense account, drop the 5010 seed Every new line item (and every AI-prefilled line) was silently seeded with account 5010 Lokalhyra. AI extraction deliberately never suggests accounts, so any invoice saved without touching the field was misbooked as premises rent — legally wrong verifikat that need rättelse to fix. Lines now start with an empty account: the supplier's default_expense_account fills empty rows when set, and submit blocks with a clear toast until every row has an account. Incident: Arcim 2026-06-11 — a legal-services invoice (should be 6580) and a SaaS subscription (should be 5420) both posted to 5010. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(bookkeeping): clarify voucher description suffix to (ankomstnr N) "(ankomst 2)" read as "arrived twice" / a duplicate marker; it is the company-internal sequential arrival counter for supplier invoices. "(ankomstnr 2)" says what the number is. Existing posted vouchers keep their old description (immutable). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): cancel orphaned payment voucher when match loses the CAS race When the payment JE posts but the invoice CAS update matches 0 rows (a concurrent request settled it first), both match routes returned MATCH_SI_NOT_OPEN and left the voucher orphaned in the ledger. mark-paid has always compensated for exactly this case; the compensation is now a shared helper (cancelOrphanedPaymentEntry: cancel + voucher-gap explanation per BFNAR 2013:2) used by all three routes. Flagged by the compliance swarm and the Swedish compliance review on PR #711 — the one finding both converged on. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bookkeeping): next_voucher_number user_id fallback for service-role contexts Mirrors 20260421170500 (commit_journal_entry got this fix; its twin did not). Under a service-role client auth.uid() is NULL and the voucher_sequences upsert fails its user_id NOT NULL check before ON CONFLICT can arbitrate — even when the sequence row exists. Every non-interactive caller of the storno/correction path (getNextVoucherNumber → correctEntry) was broken. Fallback: companies.created_by (same source seed_chart_of_accounts uses). Interactive flows still record auth.uid(); DO UPDATE never touches user_id on existing rows. Also restores SET search_path = public, lost when 20260330 recreated the function after the 20260304 hardening. pg-real: new test exercises the RPC on the superuser connection (auth.uid() IS NULL) and asserts sequential numbers + owner attribution. Found live: the Arcim repair script booked payment vouchers fine (commit_journal_entry) but failed on corrections (next_voucher_number). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bookkeeping): harden cancelOrphanedPaymentEntry — never throw, breadcrumb before mutating Two hardenings from the PR #711 review round: - Whole body wrapped in try/catch: the caller is returning the correct CAS-conflict response, so an unexpected client rejection must not replace it with a 500 (best-effort is now a hard guarantee). - The gap-recovery data (series, number, period, explanation) is logged BEFORE the cancel: the cancel and gap insert are separate statements, and a crash between them would otherwise leave a cancelled voucher with no BFNAR 2013:2 gap explanation and no way to reconstruct it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
96 lines
3.7 KiB
TypeScript
96 lines
3.7 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { createLogger } from '@/lib/logger'
|
|
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
|
import { computeSRUCode } from '@/lib/bookkeeping/bas-data/sru-mapping'
|
|
|
|
const log = createLogger('account-backfill')
|
|
|
|
/**
|
|
* Seed missing standard BAS accounts into a company's chart on demand.
|
|
*
|
|
* A company chart starts minimal, and legitimate engine flows routinely reach
|
|
* accounts that exist in BAS 2026 but were never added — öresavrundning on
|
|
* 3740 the first time a Bankgiro payment lands a sub-krona off, a first legal
|
|
* invoice on 6580. Failing the whole entry for that (AccountsNotInChartError)
|
|
* turns a standard account into a dead end, so the engine backfills instead.
|
|
*
|
|
* Deliberately conservative:
|
|
* - Only accounts present in BAS_REFERENCE are seeded — unknown numbers stay
|
|
* missing and surface as AccountsNotInChartError in the caller.
|
|
* - An account that exists but is INACTIVE is never touched: deactivation is
|
|
* a deliberate user choice, and silently reactivating would override it.
|
|
* - A concurrent insert (unique violation) counts as success.
|
|
*
|
|
* Returns the account numbers that are now present and active.
|
|
*/
|
|
export async function backfillStandardBASAccounts(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
userId: string,
|
|
accountNumbers: string[],
|
|
): Promise<string[]> {
|
|
if (accountNumbers.length === 0) return []
|
|
|
|
// Only standard BAS accounts qualify.
|
|
const candidates = accountNumbers
|
|
.map((num) => ({ num, basRef: getBASReference(num) }))
|
|
.filter((c): c is { num: string; basRef: NonNullable<ReturnType<typeof getBASReference>> } =>
|
|
Boolean(c.basRef),
|
|
)
|
|
if (candidates.length === 0) return []
|
|
|
|
// Never resurrect rows that already exist (active or inactive) — the caller
|
|
// saw them as missing because they are inactive, and that stays their state.
|
|
const { data: existing, error: existingError } = await supabase
|
|
.from('chart_of_accounts')
|
|
.select('account_number')
|
|
.eq('company_id', companyId)
|
|
.in('account_number', candidates.map((c) => c.num))
|
|
if (existingError) {
|
|
log.error('failed to check existing accounts before backfill', existingError, { companyId })
|
|
return []
|
|
}
|
|
const existingNumbers = new Set((existing ?? []).map((r) => r.account_number))
|
|
const toInsert = candidates.filter((c) => !existingNumbers.has(c.num))
|
|
if (toInsert.length === 0) return []
|
|
|
|
const rows = toInsert.map(({ num, basRef }) => ({
|
|
user_id: userId,
|
|
company_id: companyId,
|
|
account_number: num,
|
|
account_name: basRef.account_name,
|
|
account_class: basRef.account_class,
|
|
account_group: basRef.account_group,
|
|
account_type: basRef.account_type,
|
|
normal_balance: basRef.normal_balance,
|
|
sru_code: basRef.sru_code ?? computeSRUCode(num),
|
|
k2_excluded: basRef.k2_excluded,
|
|
plan_type: 'full_bas' as const,
|
|
is_active: true,
|
|
is_system_account: false,
|
|
description: basRef.description,
|
|
sort_order: /^\d+$/.test(num) ? parseInt(num, 10) : null,
|
|
}))
|
|
|
|
const { error: insertError } = await supabase.from('chart_of_accounts').insert(rows)
|
|
if (insertError) {
|
|
// Unique violation = another request seeded it concurrently — that's fine,
|
|
// the account exists now. Anything else: log and let the caller's
|
|
// re-resolution decide what is still missing.
|
|
if (insertError.code !== '23505' && !insertError.message?.includes('duplicate')) {
|
|
log.error('failed to backfill standard BAS accounts', insertError, {
|
|
companyId,
|
|
accountNumbers: toInsert.map((c) => c.num),
|
|
})
|
|
return []
|
|
}
|
|
} else {
|
|
log.info('seeded standard BAS accounts on demand', {
|
|
companyId,
|
|
accountNumbers: toInsert.map((c) => c.num),
|
|
})
|
|
}
|
|
|
|
return toInsert.map((c) => c.num)
|
|
}
|