feat(reconciliation): match migrated bank history against imported SIE verifikat (#1598)
* feat(reconciliation): match migrated bank history against imported SIE verifikat A first-class Fortnox/SIE migrator path: after SIE import plus bank connect or bank CSV upload, historical bank rows are auto-matched (>= 0.9) or suggestion-matched (0.75-0.89, persisted for review) against the imported verifikat, with a guided review surface, instead of landing as anonymous "Att bokfora" rows. Phase 0: per-cash-account unattended sweep (fixes #1298 cross-account pooling); widen payment_match_log action CHECK with linked_to_existing_voucher (silently unlogged since March). Phase 1: potential_journal_entry_id/method/confidence on transactions with CHECK + invalidation triggers; persistSuggestions in runReconciliation; sweep after bank CSV import with SIE overlap (suppressing auto-categorization); sweep summaries stamped on bank_connections and bank_file_imports; POST /api/reconciliation/bank/confirm-suggestions with per-pair server-side revalidation (voucher consumption + bank-leg amount and direction). Phase 2: "Granska forslag" review tab on Transactions with chunked bulk confirm, per-row fallbacks, "Kor matchning igen" (all_accounts sweep mode, mutually exclusive with dry_run), attn line, pre-migration row marker. Phase 3: ImportResultStep dual CTA (bank connect + CSV), migrator variant of the account-picker #917 nudge, sweep outcome on the onboarding checklist bank step. Non-selection apply runs on /api/reconciliation/bank/run now floor at 0.9 and persist the review band instead of auto-committing fuzzy matches. Migrations already applied to staging under the same versions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): resolve PR review findings in one pass Swedish accounting review (both previously-deferred holes closed): - runReconciliation's >= 0.9 auto-apply now writes 'matched' to payment_match_log (behandlingshistorik, BFNAR 2013:2 kap 8); the bus event alone lands in the 30-day event_log and is not an audit record. - The three match-route storno-conflict branches detach reconciliation links via unlinkReconciliation instead of storno-reversing the linked verifikat: a reconciliation link points at an independent verifikat that may evidence other affarshandelser, and a wholesale reversal is an over-broad rattelse (BFL 5 kap 5 §). - Historical gap quantified on prod (read-only, recorded in DECISIONS): 762 unlogged manual links across 52 companies since 2026-03-23. CodeRabbit: - confirm-suggestions route: maxDuration 300 for full 500-item batches. - AccountPickerDialog: migrator-nudge buttons set lookbackTouched so the async gap-fill probe cannot override an explicit choice. - enable-banking post-backfill sweep: persistSuggestions so the review band is not dropped. - bank-file execute: sie_sweep stamp errors are logged, not swallowed. - ImportResultStep: sandbox keeps the CSV CTA (file import works there). - payment_match_log CHECK swap: NOT VALID + VALIDATE, no table scan under ACCESS EXCLUSIVE. - logMatchEvent calls awaited (serverless can freeze unawaited work). - DECISIONS.md stale version reference annotated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): defer reconciliation-link detach until the match commits Round-2 review findings: - CodeRabbit: the eager unlinkReconciliation call could orphan a transaction if the match flow failed after it. All three match routes now persist NOTHING up front: the final transaction update overwrites journal_entry_id and clears reconciliation_method in the same write, so any failure in between leaves the existing link intact. The release is logged as 'unmatched' after the commit. - Swedish review: the auto_suggested logMatchEvent in runReconciliation is now awaited like every other audit write. - DECISIONS entry split into compliance/CodeRabbit lines and updated to describe the deferred detach. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): literal reconciliation_method payloads for the phantom-column scanner The conditional spreads introduced with the deferred detach pushed the scanner's unresolvable-expression count past its ceiling (380 > 378). reconciliation_method: null is correct unconditionally on a confirmed invoice/supplier match (null is already the value on every row that was not reconciliation-linked), so the payloads become plain literals the guard can verify. No behavior change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
07e89d9b52
commit
08440fed94
@@ -59,7 +59,7 @@ export default async function DashboardPage() {
|
||||
supabase.from('customers').select('*', { count: 'exact', head: true }).eq('company_id', companyId),
|
||||
supabase.from('invoices').select('*', { count: 'exact', head: true }).eq('company_id', companyId),
|
||||
supabase.from('transactions').select('*', { count: 'exact', head: true }).eq('company_id', companyId),
|
||||
supabase.from('bank_connections').select('id, status, consent_expires, bank_name').eq('company_id', companyId).eq('status', 'active'),
|
||||
supabase.from('bank_connections').select('id, status, consent_expires, bank_name, last_sie_sweep').eq('company_id', companyId).eq('status', 'active'),
|
||||
supabase.from('sie_imports').select('*', { count: 'exact', head: true }).eq('company_id', companyId).eq('status', 'completed'),
|
||||
// Skatteverket tokens are user-scoped (one BankID identity per user) but
|
||||
// carry the active company_id; either filter would work: we use user_id
|
||||
@@ -158,6 +158,37 @@ export default async function DashboardPage() {
|
||||
|
||||
const userFirstName = profile?.full_name?.trim().split(/\s+/)[0] ?? null
|
||||
|
||||
// Latest SIE reconciliation-sweep summary across both history sources
|
||||
// (PSD2 sync stamps bank_connections.last_sie_sweep; a bank-file import
|
||||
// stamps bank_file_imports.sie_sweep). Feeds the checklist's bank step with
|
||||
// "X matchade, Y att granska" so a migrator sees the sweep outcome without
|
||||
// hunting for it. Best-effort: absent rows just render no note.
|
||||
type SieSweepSummaryLite = {
|
||||
auto_linked?: number
|
||||
suggested?: number
|
||||
unmatched?: number
|
||||
errors?: number
|
||||
ran_at?: string
|
||||
}
|
||||
const { data: latestFileSweep } = await supabase
|
||||
.from('bank_file_imports')
|
||||
.select('sie_sweep')
|
||||
.eq('company_id', companyId)
|
||||
.not('sie_sweep', 'is', null)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
const sweepCandidates: SieSweepSummaryLite[] = [
|
||||
...(bankConnections || [])
|
||||
.map((c) => c.last_sie_sweep as SieSweepSummaryLite | null)
|
||||
.filter((s): s is SieSweepSummaryLite => Boolean(s)),
|
||||
...(latestFileSweep?.sie_sweep ? [latestFileSweep.sie_sweep as SieSweepSummaryLite] : []),
|
||||
]
|
||||
const sieSweep =
|
||||
sweepCandidates.length > 0
|
||||
? sweepCandidates.reduce((a, b) => ((a.ran_at ?? '') >= (b.ran_at ?? '') ? a : b))
|
||||
: null
|
||||
|
||||
return (
|
||||
<DashboardContent
|
||||
companyId={companyId}
|
||||
@@ -176,6 +207,16 @@ export default async function DashboardPage() {
|
||||
}}
|
||||
vatLine={vatLine}
|
||||
emptyLedger={emptyLedger}
|
||||
sieSweep={
|
||||
sieSweep
|
||||
? {
|
||||
auto_linked: sieSweep.auto_linked ?? 0,
|
||||
suggested: sieSweep.suggested ?? 0,
|
||||
unmatched: sieSweep.unmatched ?? 0,
|
||||
errors: sieSweep.errors ?? 0,
|
||||
}
|
||||
: null
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,9 @@ import type {
|
||||
ViewMode,
|
||||
SourceFilter,
|
||||
CategorizeHandler,
|
||||
PotentialVoucher,
|
||||
} from '@/components/transactions/transaction-types'
|
||||
import { SuggestionReviewList } from '@/components/transactions/SuggestionReviewList'
|
||||
import type {
|
||||
SkattekontoBatchResult,
|
||||
SkattekontoBatchRowResult,
|
||||
@@ -182,7 +184,11 @@ function buildSupplierInvoiceMap(
|
||||
// prod schema cache (see DECISIONS.md 2026-07-06).
|
||||
async function fetchPotentialMatches(
|
||||
supabase: SupabaseClient,
|
||||
rows: { potential_invoice_id: string | null; potential_supplier_invoice_id: string | null }[],
|
||||
rows: {
|
||||
potential_invoice_id: string | null
|
||||
potential_supplier_invoice_id: string | null
|
||||
potential_journal_entry_id?: string | null
|
||||
}[],
|
||||
) {
|
||||
const potentialInvoiceIds = Array.from(
|
||||
new Set(rows.flatMap((t) => (t.potential_invoice_id ? [t.potential_invoice_id] : []))),
|
||||
@@ -190,6 +196,9 @@ async function fetchPotentialMatches(
|
||||
const potentialSupplierInvoiceIds = Array.from(
|
||||
new Set(rows.flatMap((t) => (t.potential_supplier_invoice_id ? [t.potential_supplier_invoice_id] : []))),
|
||||
)
|
||||
const potentialJournalEntryIds = Array.from(
|
||||
new Set(rows.flatMap((t) => (t.potential_journal_entry_id ? [t.potential_journal_entry_id] : []))),
|
||||
)
|
||||
|
||||
// Chunked .in() lists (PostgREST .in() URL-length convention, same 150 as
|
||||
// the underlag-status effect below): the caller may pass the full pending
|
||||
@@ -206,7 +215,7 @@ async function fetchPotentialMatches(
|
||||
// an unmatchable candidate must not reach the row or the match dialog, which
|
||||
// would otherwise compare the transaction against a 0 kr remaining balance
|
||||
// and call it a partial payment.
|
||||
const [invoiceResults, supplierInvoiceResults] = await Promise.all([
|
||||
const [invoiceResults, supplierInvoiceResults, voucherResults] = await Promise.all([
|
||||
Promise.all(
|
||||
chunks(potentialInvoiceIds).map((ids) =>
|
||||
supabase
|
||||
@@ -227,6 +236,19 @@ async function fetchPotentialMatches(
|
||||
.gt('remaining_amount', 0),
|
||||
),
|
||||
),
|
||||
// Journal-entry match suggestions (the sweep's 0.75-0.89 band). DB
|
||||
// triggers clear the pointer when the entry is consumed or reversed, but
|
||||
// the posted-status filter revalidates anyway: a suggestion that no
|
||||
// longer resolves to a live verifikat must not reach the review surface.
|
||||
Promise.all(
|
||||
chunks(potentialJournalEntryIds).map((ids) =>
|
||||
supabase
|
||||
.from('journal_entries')
|
||||
.select('id, voucher_series, voucher_number, entry_date, description')
|
||||
.in('id', ids)
|
||||
.eq('status', 'posted'),
|
||||
),
|
||||
),
|
||||
])
|
||||
|
||||
// Non-fatal: the transaction list still renders without match hints, but
|
||||
@@ -237,10 +259,31 @@ async function fetchPotentialMatches(
|
||||
for (const r of supplierInvoiceResults) {
|
||||
if (r.error) console.error('[fetchPotentialMatches] supplier_invoices query failed', r.error)
|
||||
}
|
||||
for (const r of voucherResults) {
|
||||
if (r.error) console.error('[fetchPotentialMatches] journal_entries query failed', r.error)
|
||||
}
|
||||
|
||||
const voucherMap: Record<string, PotentialVoucher> = {}
|
||||
for (const je of voucherResults.flatMap((r) => (r.data ?? []) as Array<{
|
||||
id: string
|
||||
voucher_series: string
|
||||
voucher_number: number
|
||||
entry_date: string
|
||||
description: string | null
|
||||
}>)) {
|
||||
voucherMap[je.id] = {
|
||||
journal_entry_id: je.id,
|
||||
voucher_series: je.voucher_series,
|
||||
voucher_number: je.voucher_number,
|
||||
entry_date: je.entry_date,
|
||||
description: je.description,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
invoiceMap: buildInvoiceMap(invoiceResults.flatMap((r) => r.data ?? [])),
|
||||
supplierInvoiceMap: buildSupplierInvoiceMap(supplierInvoiceResults.flatMap((r) => r.data ?? [])),
|
||||
voucherMap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,6 +543,39 @@ export default function TransactionsPage() {
|
||||
const refreshTransactionsInFlightRef = useRef(false)
|
||||
const refreshTransactionsQueuedRef = useRef(false)
|
||||
|
||||
// "Kör matchning igen" in the review surface.
|
||||
const [rerunningMatch, setRerunningMatch] = useState(false)
|
||||
|
||||
// End of the company's completed SIE-import coverage (latest
|
||||
// fiscal_year_end). Drives the quiet "från perioden före din migrering"
|
||||
// marker on inbox rows: period-based on purpose, it labels which period a
|
||||
// row belongs to, it never suggests a sync skip date (that was #917).
|
||||
const [sieCoverageEnd, setSieCoverageEnd] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (!companyId) {
|
||||
setSieCoverageEnd(null)
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
const { data } = await supabase
|
||||
.from('sie_imports')
|
||||
.select('fiscal_year_end')
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'completed')
|
||||
.not('fiscal_year_end', 'is', null)
|
||||
.order('fiscal_year_end', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (!cancelled) {
|
||||
setSieCoverageEnd((data as { fiscal_year_end?: string } | null)?.fiscal_year_end || null)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [companyId, supabase])
|
||||
|
||||
// Computed lists
|
||||
const uncategorizedTransactions = useMemo(
|
||||
() => transactions
|
||||
@@ -513,6 +589,18 @@ export default function TransactionsPage() {
|
||||
[exitingIds, transactions],
|
||||
)
|
||||
|
||||
// Journal-entry match suggestions awaiting review (the migrator surface).
|
||||
// potential_voucher is already revalidated (posted-only) at enrichment time,
|
||||
// and DB triggers clear consumed/reversed suggestions, so this list is
|
||||
// honest without extra queries.
|
||||
const suggestionItems = useMemo(
|
||||
() =>
|
||||
transactions.filter(
|
||||
(t) => t.potential_voucher && !t.journal_entry_id && !t.is_ignored && !exitingIds.has(t.id),
|
||||
),
|
||||
[exitingIds, transactions],
|
||||
)
|
||||
|
||||
// Merged inbox: bank tx + SKV rows interleaved by date. Source filter
|
||||
// narrows to one side. SKV rows always go after bank rows on the same
|
||||
// date: bank tx tend to have invoice-match suggestions and we'd rather
|
||||
@@ -891,7 +979,7 @@ export default function TransactionsPage() {
|
||||
const windowIds = new Set(rows.map((r) => r.id))
|
||||
const olderPending = (pendingRows ?? []).filter((r) => !windowIds.has(r.id))
|
||||
const allRows = [...rows, ...olderPending].sort((a, b) => b.date.localeCompare(a.date))
|
||||
const { invoiceMap, supplierInvoiceMap } = await fetchPotentialMatches(supabase, allRows)
|
||||
const { invoiceMap, supplierInvoiceMap, voucherMap } = await fetchPotentialMatches(supabase, allRows)
|
||||
|
||||
// Re-check after the second await: a scope change during the match
|
||||
// enrichment must also discard this response.
|
||||
@@ -903,6 +991,9 @@ export default function TransactionsPage() {
|
||||
potential_supplier_invoice: t.potential_supplier_invoice_id
|
||||
? supplierInvoiceMap[t.potential_supplier_invoice_id]
|
||||
: undefined,
|
||||
potential_voucher: t.potential_journal_entry_id
|
||||
? voucherMap[t.potential_journal_entry_id]
|
||||
: undefined,
|
||||
}))
|
||||
|
||||
setTransactions(transactionsWithInvoices)
|
||||
@@ -973,7 +1064,7 @@ export default function TransactionsPage() {
|
||||
setPagedThroughDate(txData.length >= PAGE_SIZE ? txData[txData.length - 1].date : null)
|
||||
setHasMore(txData.length >= PAGE_SIZE)
|
||||
|
||||
const { invoiceMap, supplierInvoiceMap } = await fetchPotentialMatches(supabase, txData)
|
||||
const { invoiceMap, supplierInvoiceMap, voucherMap } = await fetchPotentialMatches(supabase, txData)
|
||||
|
||||
// Same staleness rule after the enrichment await: the offsets above were
|
||||
// written under this generation, but a newer fetch has already reset them.
|
||||
@@ -988,6 +1079,9 @@ export default function TransactionsPage() {
|
||||
potential_supplier_invoice: t.potential_supplier_invoice_id
|
||||
? supplierInvoiceMap[t.potential_supplier_invoice_id]
|
||||
: undefined,
|
||||
potential_voucher: t.potential_journal_entry_id
|
||||
? voucherMap[t.potential_journal_entry_id]
|
||||
: undefined,
|
||||
}))
|
||||
|
||||
// The page may overlap pending rows already merged into state: keep the
|
||||
@@ -1939,6 +2033,132 @@ export default function TransactionsPage() {
|
||||
}, 350)
|
||||
}
|
||||
|
||||
// "Granska migrerad historik": confirm/reject persisted journal-entry match
|
||||
// suggestions through the server-side revalidating bulk endpoint. Stale
|
||||
// pairs come back as skipped, never as a failed batch: the toast reports
|
||||
// both numbers honestly and the refresh re-derives the list from DB truth.
|
||||
// Chunked at the schema's 500-id cap (same as BankReconciliationView's
|
||||
// apply): a migrator's review list can exceed it, and one unchunked POST
|
||||
// would 400 with zero progress on exactly the flagship bulk action.
|
||||
const SUGGESTION_CHUNK_SIZE = 500
|
||||
|
||||
const confirmSuggestions = useCallback(
|
||||
async (transactionIds: string[]) => {
|
||||
let confirmed = 0
|
||||
let skipped = 0
|
||||
try {
|
||||
for (let i = 0; i < transactionIds.length; i += SUGGESTION_CHUNK_SIZE) {
|
||||
const chunk = transactionIds.slice(i, i + SUGGESTION_CHUNK_SIZE)
|
||||
const response = await fetch('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transaction_ids: chunk, action: 'confirm' }),
|
||||
})
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
// Report the partial progress alongside the failure: chunks that
|
||||
// already committed stay committed.
|
||||
toast({
|
||||
title: t('review_confirm_failed'),
|
||||
description: getErrorMessage(payload, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
confirmed += (payload.data?.confirmed ?? []).length
|
||||
skipped += (payload.data?.skipped ?? []).length
|
||||
}
|
||||
toast({
|
||||
title: t('review_confirm_done_title', { count: confirmed }),
|
||||
description:
|
||||
skipped > 0
|
||||
? t('review_confirm_done_skipped', { count: skipped })
|
||||
: t('review_confirm_done_description'),
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('review_confirm_failed'),
|
||||
description: getErrorMessage(error, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
await refreshTransactions()
|
||||
}
|
||||
},
|
||||
[refreshTransactions, t, toast],
|
||||
)
|
||||
|
||||
const rejectSuggestions = useCallback(
|
||||
async (transactionIds: string[]) => {
|
||||
try {
|
||||
for (let i = 0; i < transactionIds.length; i += SUGGESTION_CHUNK_SIZE) {
|
||||
const chunk = transactionIds.slice(i, i + SUGGESTION_CHUNK_SIZE)
|
||||
const response = await fetch('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transaction_ids: chunk, action: 'reject' }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const payload = await response.json()
|
||||
toast({
|
||||
title: t('review_reject_failed'),
|
||||
description: getErrorMessage(payload, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('review_reject_failed'),
|
||||
description: getErrorMessage(error, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
await refreshTransactions()
|
||||
}
|
||||
},
|
||||
[refreshTransactions, t, toast],
|
||||
)
|
||||
|
||||
// "Kör matchning igen": full per-account sweep over all history. New >= 0.9
|
||||
// matches auto-link; the review band lands back here as fresh suggestions.
|
||||
const rerunMatching = useCallback(async () => {
|
||||
setRerunningMatch(true)
|
||||
try {
|
||||
const response = await fetch('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ all_accounts: true }),
|
||||
})
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('review_rerun_failed'),
|
||||
description: getErrorMessage(payload, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: t('review_rerun_done_title'),
|
||||
description: t('review_rerun_done_description', {
|
||||
applied: payload.data?.applied ?? 0,
|
||||
suggested: payload.data?.suggested ?? 0,
|
||||
}),
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('review_rerun_failed'),
|
||||
description: getErrorMessage(error, { context: 'transaction' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setRerunningMatch(false)
|
||||
await refreshTransactions()
|
||||
}
|
||||
}, [refreshTransactions, t, toast])
|
||||
|
||||
async function handleMatchInvoice(transactionId: string, invoiceId: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`/api/transactions/${transactionId}/match-invoice`, {
|
||||
@@ -2940,11 +3160,19 @@ export default function TransactionsPage() {
|
||||
<TransactionStatusBar onOpenCreateDialog={() => setIsDialogOpen(true)} />
|
||||
|
||||
|
||||
{skvNeedsReconnect && (
|
||||
{skvNeedsReconnect ? (
|
||||
<AttnLine action={{ label: t('skv_reconnect_cta'), href: '/settings/tax' }}>
|
||||
{t('skv_reconnect_body')}
|
||||
</AttnLine>
|
||||
)}
|
||||
) : suggestionItems.length > 0 && mode !== 'review' ? (
|
||||
// Migrated-history review nudge. Max one attn line per page
|
||||
// (convention 6): the SKV reconnect line wins when both apply.
|
||||
<AttnLine
|
||||
action={{ label: t('review_attn_cta'), onClick: () => setMode('review') }}
|
||||
>
|
||||
{t('review_attn_body', { count: suggestionItems.length })}
|
||||
</AttnLine>
|
||||
) : null}
|
||||
|
||||
{/* Toolbar (concept order): [Att bokföra/Alla-seg] [sök] [Välj flera]
|
||||
... [source ContextPicker far right] */}
|
||||
@@ -2981,6 +3209,29 @@ export default function TransactionsPage() {
|
||||
>
|
||||
{t('mode_all')}
|
||||
</button>
|
||||
{/* Review tab exists only while suggestions do (or while the user is
|
||||
standing in it after emptying the list): a permanent third tab
|
||||
would advertise a migrator surface most companies never need. */}
|
||||
{(suggestionItems.length > 0 || mode === 'review') && (
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === 'review'}
|
||||
onClick={() => setMode('review')}
|
||||
className={`inline-flex items-center gap-1.5 rounded-md px-3.5 py-[5px] text-[12.5px] transition-colors duration-150 ${
|
||||
mode === 'review'
|
||||
? 'border border-border bg-card font-medium text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{t('mode_review')}
|
||||
{suggestionItems.length > 0 && (
|
||||
<span className="rounded-full bg-secondary px-1.5 text-[10px] font-medium tabular-nums">
|
||||
{suggestionItems.length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative min-w-[220px] max-w-xs flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
@@ -3034,6 +3285,15 @@ export default function TransactionsPage() {
|
||||
</div>
|
||||
))}
|
||||
</DataList>
|
||||
) : mode === 'review' ? (
|
||||
<SuggestionReviewList
|
||||
items={suggestionItems}
|
||||
onConfirm={confirmSuggestions}
|
||||
onReject={rejectSuggestions}
|
||||
onOpenMatchVoucher={openMatchVoucherDialog}
|
||||
onRerunMatching={rerunMatching}
|
||||
rerunning={rerunningMatch}
|
||||
/>
|
||||
) : mode === 'inbox' ? (
|
||||
inboxItems.length === 0 ? (
|
||||
searchTerm || sourceFilter !== 'all' || periodBounds ? (
|
||||
@@ -3059,8 +3319,12 @@ export default function TransactionsPage() {
|
||||
is usually a migration/import whose counterpart vouchers
|
||||
already exist, and the only match affordance here is per-row.
|
||||
Static text + count (no probe): the reconciliation preview is
|
||||
the honest source of how many actually match. */}
|
||||
{selectableInboxIds.length >= 5 && (
|
||||
the honest source of how many actually match.
|
||||
Yields to the review-suggestions attn at the top of the page
|
||||
(max one ochre sentence per page): when the sweep has already
|
||||
persisted suggestions, "Granska förslagen" is the more precise
|
||||
destination for the same backlog. */}
|
||||
{selectableInboxIds.length >= 5 && suggestionItems.length === 0 && (
|
||||
<AttnLine
|
||||
className="px-1 pb-3"
|
||||
action={{
|
||||
@@ -3190,6 +3454,7 @@ export default function TransactionsPage() {
|
||||
onMoveCashAccount={openMoveAccountDialog}
|
||||
cashAccounts={cashAccounts}
|
||||
onToggleSelect={toggleBatchSelect}
|
||||
preMigrationCutoff={sieCoverageEnd}
|
||||
/>
|
||||
) : (
|
||||
<SkattekontoInboxCard
|
||||
|
||||
@@ -2,9 +2,9 @@ import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
|
||||
import {
|
||||
runReconciliation,
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
} from '@/lib/reconciliation/bank-reconciliation'
|
||||
runUnattendedReconciliationSweep,
|
||||
toSweepSummary,
|
||||
} from '@/lib/reconciliation/unattended-sweep'
|
||||
import {
|
||||
isConsentExpiringSoon,
|
||||
getDaysUntilExpiry,
|
||||
@@ -261,22 +261,36 @@ export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
|
||||
const totalDuplicates = syncResults.reduce((sum, r) => sum + r.duplicates, 0)
|
||||
const totalErrors = syncResults.reduce((sum, r) => sum + r.errors, 0)
|
||||
|
||||
// Batch reconciliation sweep when SIE overlap detected
|
||||
// Batch reconciliation sweep when SIE overlap detected. One scoped run
|
||||
// per enabled cash account (issue #1298): a pooled run matched every
|
||||
// same-currency account's transactions against 1930's GL lines and could
|
||||
// persist a cross-account journal_entry_id.
|
||||
if (sieOverlap && totalImported > 0) {
|
||||
try {
|
||||
const reconResult = await runReconciliation(supabase, connection.company_id, connection.user_id, {
|
||||
dateFrom: fromDate,
|
||||
dateTo: toDate,
|
||||
// Unattended run: nobody reviews a dry-run first, so never commit
|
||||
// low-confidence (fuzzy / date-range) matches automatically.
|
||||
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
})
|
||||
const reconResult = await runUnattendedReconciliationSweep(
|
||||
supabase,
|
||||
connection.company_id,
|
||||
connection.user_id,
|
||||
{ dateFrom: fromDate, dateTo: toDate },
|
||||
)
|
||||
// Stamp the outcome so the UI can render "Vi matchade X av Y" and the
|
||||
// review surface knows there is something to granska.
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
last_sie_sweep: toSweepSummary(reconResult, { dateFrom: fromDate, dateTo: toDate }),
|
||||
})
|
||||
.eq('id', connection.id)
|
||||
if (reconResult.applied > 0 || reconResult.skippedBelowThreshold > 0) {
|
||||
ctx.log.info('batch reconciliation after sync', {
|
||||
companyId: connection.company_id,
|
||||
applied: reconResult.applied,
|
||||
skippedBelowThreshold: reconResult.skippedBelowThreshold,
|
||||
total: reconResult.matches.length,
|
||||
accounts: reconResult.accounts.map((a) => ({
|
||||
accountNumber: a.accountNumber,
|
||||
applied: a.applied,
|
||||
skippedBelowThreshold: a.skippedBelowThreshold,
|
||||
})),
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Tests for POST /api/import/bank-file/execute, focused on the SIE-overlap
|
||||
* behavior: a bank file covering a period a completed SIE import already
|
||||
* booked must (a) suppress auto-categorization to prevent double-booking and
|
||||
* (b) trigger the per-account reconciliation sweep and stamp its summary,
|
||||
* because CSV is how a migrator gets pre-PSD2 history into the system.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const getCompanyRoleMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const ingestMock = vi.fn()
|
||||
vi.mock('@/lib/transactions/ingest', () => ({
|
||||
ingestTransactions: (...args: unknown[]) => ingestMock(...args),
|
||||
}))
|
||||
|
||||
const sweepMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/unattended-sweep', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/reconciliation/unattended-sweep')>()
|
||||
return {
|
||||
...actual,
|
||||
runUnattendedReconciliationSweep: (...args: unknown[]) => sweepMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
|
||||
function makeBody(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
transactions: [
|
||||
{ date: '2025-03-10', description: 'Hyra mars', amount: -12000, currency: 'SEK' },
|
||||
{ date: '2025-01-05', description: 'Kundbetalning', amount: 25000, currency: 'SEK' },
|
||||
],
|
||||
format: 'seb',
|
||||
filename: 'kontoutdrag.csv',
|
||||
file_hash: 'abc123',
|
||||
skip_duplicates: true,
|
||||
auto_categorize: true,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function emptyIngestResult(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
imported: 2,
|
||||
duplicates: 0,
|
||||
reconciled: 0,
|
||||
auto_categorized: 0,
|
||||
auto_matched_invoices: 0,
|
||||
errors: 0,
|
||||
transaction_ids: ['t-1', 't-2'],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function emptySweepResult(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
accounts: [],
|
||||
applied: 1,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 1,
|
||||
suggested: 1,
|
||||
unmatched: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST /api/import/bank-file/execute (SIE overlap)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' })
|
||||
ingestMock.mockResolvedValue(emptyIngestResult())
|
||||
sweepMock.mockResolvedValue(emptySweepResult())
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/import/bank-file/execute', {
|
||||
method: 'POST',
|
||||
body: makeBody(),
|
||||
})
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('suppresses auto-categorization, runs the sweep over the file window, and stamps the summary on SIE overlap', async () => {
|
||||
enqueue({ data: { id: 'import-1' } }) // bank_file_imports upsert
|
||||
enqueue({ data: { id: 'sie-1' } }) // sie_imports overlap: found
|
||||
enqueue({ data: null }) // bank_file_imports status update
|
||||
enqueue({ data: null }) // sie_sweep stamp update
|
||||
enqueue({ data: [{ id: 't-1' }, { id: 't-2' }] }) // imported tx for event
|
||||
|
||||
const request = createMockRequest('/api/import/bank-file/execute', {
|
||||
method: 'POST',
|
||||
body: makeBody(),
|
||||
})
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// Ingest was told to skip auto-categorization (double-booking guard).
|
||||
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
|
||||
expect(ingestOptions.skipAutoCategorization).toBe(true)
|
||||
// Sweep ran over the file's own date window (min/max of its rows).
|
||||
expect(sweepMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', {
|
||||
dateFrom: '2025-01-05',
|
||||
dateTo: '2025-03-10',
|
||||
})
|
||||
})
|
||||
|
||||
it('runs no sweep and keeps categorization when there is no SIE overlap', async () => {
|
||||
enqueue({ data: { id: 'import-1' } }) // upsert
|
||||
enqueue({ data: null }) // sie_imports overlap: none
|
||||
enqueue({ data: null }) // status update
|
||||
enqueue({ data: [{ id: 't-1' }] }) // imported tx for event
|
||||
|
||||
const request = createMockRequest('/api/import/bank-file/execute', {
|
||||
method: 'POST',
|
||||
body: makeBody(),
|
||||
})
|
||||
const response = await POST(request, emptyParams)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
|
||||
expect(ingestOptions.skipAutoCategorization).toBeUndefined()
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never sweeps for a viewer (raw insert only)', async () => {
|
||||
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'viewer', companyId: 'company-1' })
|
||||
enqueue({ data: { id: 'import-1' } }) // upsert
|
||||
enqueue({ data: { id: 'sie-1' } }) // overlap found
|
||||
enqueue({ data: null }) // status update
|
||||
enqueue({ data: [{ id: 't-1' }] }) // imported tx for event
|
||||
|
||||
const request = createMockRequest('/api/import/bank-file/execute', {
|
||||
method: 'POST',
|
||||
body: makeBody(),
|
||||
})
|
||||
const response = await POST(request, emptyParams)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
|
||||
expect(ingestOptions.rawInsertOnly).toBe(true)
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,10 @@ import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { ParsedBankTransaction, BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
import type { Transaction } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
runUnattendedReconciliationSweep,
|
||||
toSweepSummary,
|
||||
} from '@/lib/reconciliation/unattended-sweep'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -102,9 +106,30 @@ export const POST = withRouteContext(
|
||||
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
|
||||
}))
|
||||
|
||||
// Detect SIE overlap, mirroring the enable-banking sync paths: a bank
|
||||
// file covering a period a completed SIE import already booked must be
|
||||
// matched against the imported verifikat, not re-booked. CSV is the only
|
||||
// way a migrator gets deep history (PSD2 windows stop at ~90 days), so
|
||||
// this path is the primary one for the Fortnox/SIE migrator journey.
|
||||
const fileDateFrom = transactions.map((t) => t.date).sort()[0] || undefined
|
||||
const fileDateTo = transactions.map((t) => t.date).sort().reverse()[0] || undefined
|
||||
let sieOverlap: { id: string } | null = null
|
||||
if (fileDateFrom) {
|
||||
const { data } = await supabase
|
||||
.from('sie_imports')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'completed')
|
||||
.gte('fiscal_year_end', fileDateFrom)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
sieOverlap = data ?? null
|
||||
}
|
||||
|
||||
const ingestOptions: IngestOptions = {}
|
||||
if (settlement_account) ingestOptions.settlementAccount = settlement_account
|
||||
if (role === 'viewer') ingestOptions.rawInsertOnly = true
|
||||
if (sieOverlap) ingestOptions.skipAutoCategorization = true
|
||||
const ingestResult = await ingestTransactions(supabase, companyId, user.id, rawTransactions, ingestOptions)
|
||||
|
||||
if (ingestResult.errors > 0 && ingestResult.first_error) {
|
||||
@@ -133,6 +158,44 @@ export const POST = withRouteContext(
|
||||
})
|
||||
.eq('id', importRecord.id)
|
||||
|
||||
// SIE-overlap-gated reconciliation sweep (issue: no sweep fired after a
|
||||
// bank CSV import, yet CSV is how a migrator gets pre-PSD2 history). One
|
||||
// scoped run per enabled cash account; >= 0.9 auto-links, the 0.75-0.89
|
||||
// band persists as reviewable suggestions. Viewers skip it: the sweep
|
||||
// updates transactions, which viewers cannot do.
|
||||
if (sieOverlap && ingestResult.imported > 0 && role !== 'viewer') {
|
||||
try {
|
||||
const sweepResult = await runUnattendedReconciliationSweep(supabase, companyId, user.id, {
|
||||
dateFrom: fileDateFrom,
|
||||
dateTo: fileDateTo,
|
||||
})
|
||||
const { error: stampError } = await supabase
|
||||
.from('bank_file_imports')
|
||||
.update({
|
||||
sie_sweep: toSweepSummary(sweepResult, {
|
||||
dateFrom: fileDateFrom,
|
||||
dateTo: fileDateTo,
|
||||
}),
|
||||
})
|
||||
.eq('id', importRecord.id)
|
||||
if (stampError) {
|
||||
// The links/suggestions are already written; only the UI summary
|
||||
// is missing. Say so instead of letting the sweep look unrun.
|
||||
opLog.warn('failed to stamp sie_sweep summary on bank_file_imports', stampError)
|
||||
}
|
||||
if (sweepResult.applied > 0 || sweepResult.suggested > 0) {
|
||||
opLog.info('post-import SIE reconciliation sweep', {
|
||||
applied: sweepResult.applied,
|
||||
suggested: sweepResult.suggested,
|
||||
unmatched: sweepResult.unmatched,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
// Non-critical: rows stay in "Att bokföra" for manual matching.
|
||||
opLog.warn('post-import SIE reconciliation sweep failed', err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
|
||||
try {
|
||||
const { data: importedTransactions } = await supabase
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/confirm-suggestions.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company/write dependencies plus the suggestions service. Covers:
|
||||
* 401, 403 viewer, validation (400), and both actions' happy paths.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const confirmMock = vi.fn()
|
||||
const rejectMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/suggestions', () => ({
|
||||
confirmJournalEntrySuggestions: (...args: unknown[]) => confirmMock(...args),
|
||||
rejectJournalEntrySuggestions: (...args: unknown[]) => rejectMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const TX_1 = '11111111-1111-4111-8111-111111111111'
|
||||
const TX_2 = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
describe('POST /api/reconciliation/bank/confirm-suggestions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
confirmMock.mockResolvedValue({ confirmed: [TX_1], rejected: [], skipped: [] })
|
||||
rejectMock.mockResolvedValue({ confirmed: [], rejected: [TX_1], skipped: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an empty transaction_ids array with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an unknown action with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'maybe' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('confirms suggestions and reports skipped pairs in snake_case', async () => {
|
||||
confirmMock.mockResolvedValue({
|
||||
confirmed: [TX_1],
|
||||
rejected: [],
|
||||
skipped: [{ transactionId: TX_2, reason: 'voucher_consumed' }],
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1, TX_2], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: {
|
||||
confirmed: string[]
|
||||
skipped: Array<{ transaction_id: string; reason: string }>
|
||||
}
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.confirmed).toEqual([TX_1])
|
||||
expect(body.data.skipped).toEqual([
|
||||
{ transaction_id: TX_2, reason: 'voucher_consumed', message: undefined },
|
||||
])
|
||||
expect(confirmMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', [TX_1, TX_2])
|
||||
expect(rejectMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('routes action=reject to the reject service', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'reject' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { rejected: string[] } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.rejected).toEqual([TX_1])
|
||||
expect(rejectMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', [TX_1])
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { ConfirmJeSuggestionsSchema } from '@/lib/api/schemas'
|
||||
import {
|
||||
confirmJournalEntrySuggestions,
|
||||
rejectJournalEntrySuggestions,
|
||||
} from '@/lib/reconciliation/suggestions'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
// A full 500-item batch runs sequentially with several queries per pair
|
||||
// (revalidation is the point), which can exceed the platform's default
|
||||
// function budget. Same 5-minute allowance as the bank-file and SIE imports.
|
||||
export const maxDuration = 300
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/bank/confirm-suggestions
|
||||
*
|
||||
* Bulk confirm (or reject) journal-entry match suggestions written by the
|
||||
* SIE reconciliation sweep. Confirming links each transaction to its suggested
|
||||
* verifikat via the ordinary manual-link path with full server-side
|
||||
* revalidation per pair; pairs that went stale between suggestion and click
|
||||
* (entry reversed, verifikat consumed by another row, row booked elsewhere)
|
||||
* are skipped and reported rather than failing the batch.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.confirm_suggestions',
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, ConfirmJeSuggestionsSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { transaction_ids, action } = validation.data
|
||||
|
||||
const result =
|
||||
action === 'confirm'
|
||||
? await confirmJournalEntrySuggestions(supabase, companyId, user.id, transaction_ids)
|
||||
: await rejectJournalEntrySuggestions(supabase, companyId, user.id, transaction_ids)
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
confirmed: result.confirmed,
|
||||
rejected: result.rejected,
|
||||
skipped: result.skipped.map((s) => ({
|
||||
transaction_id: s.transactionId,
|
||||
reason: s.reason,
|
||||
message: s.message,
|
||||
})),
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -31,6 +31,12 @@ vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
const runReconciliationMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/bank-reconciliation', () => ({
|
||||
runReconciliation: (...args: unknown[]) => runReconciliationMock(...args),
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD: 0.9,
|
||||
}))
|
||||
|
||||
const sweepMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/unattended-sweep', () => ({
|
||||
runUnattendedReconciliationSweep: (...args: unknown[]) => sweepMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
@@ -135,7 +141,11 @@ describe('POST /api/reconciliation/bank/run', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('omits the confidence threshold when the client does not send one', async () => {
|
||||
it('defaults a no-selection apply to the 0.9 unattended floor when the client sends no threshold', async () => {
|
||||
// Merged semantics (#1571 x bank-and-sie-match): an explicit
|
||||
// confidence_threshold always wins; WITHOUT one, an apply with no
|
||||
// selected_matches is effectively unattended, so it floors at 0.9 and
|
||||
// persists the review band instead of auto-committing fuzzy matches.
|
||||
// cash_accounts lookup: no row, '1930' default is exempt.
|
||||
enqueue({ data: null })
|
||||
|
||||
@@ -150,7 +160,7 @@ describe('POST /api/reconciliation/bank/run', () => {
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ confidenceThreshold: undefined }),
|
||||
expect.objectContaining({ confidenceThreshold: 0.9, persistSuggestions: true }),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -211,7 +221,117 @@ describe('POST /api/reconciliation/bank/run', () => {
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ accountNumber: '1930', currency: 'SEK', dryRun: false }),
|
||||
// A no-selection apply run persists the review band as suggestions
|
||||
// behind the unattended confidence floor ("Kör matchning igen").
|
||||
expect.objectContaining({
|
||||
accountNumber: '1930',
|
||||
currency: 'SEK',
|
||||
dryRun: false,
|
||||
confidenceThreshold: 0.9,
|
||||
persistSuggestions: true,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the legacy no-threshold behavior for a reviewed selected_matches apply', async () => {
|
||||
// cash_accounts lookup: no row, '1930' exempt.
|
||||
enqueue({ data: null })
|
||||
runReconciliationMock.mockResolvedValue({
|
||||
matches: [],
|
||||
applied: 0,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 0,
|
||||
suggested: 0,
|
||||
candidates: 0,
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
selected_matches: [
|
||||
{
|
||||
transaction_id: '11111111-1111-4111-8111-111111111111',
|
||||
journal_entry_id: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
const options = runReconciliationMock.mock.calls[0][3] as Record<string, unknown>
|
||||
expect(options.applyOnly).toHaveLength(1)
|
||||
// The user already reviewed these pairs in the dry-run preview: no floor,
|
||||
// no suggestion persistence.
|
||||
expect(options.confidenceThreshold).toBeUndefined()
|
||||
expect(options.persistSuggestions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('routes all_accounts to the per-account sweep ("Kör matchning igen")', async () => {
|
||||
sweepMock.mockResolvedValue({
|
||||
accounts: [
|
||||
{ accountNumber: '1930', applied: 3, suggested: 1 },
|
||||
{ accountNumber: '1931', applied: 1, suggested: 0 },
|
||||
],
|
||||
applied: 4,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 1,
|
||||
suggested: 1,
|
||||
unmatched: 2,
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { all_accounts: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { applied: number; suggested: number; unmatched: number }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.applied).toBe(4)
|
||||
expect(body.data.suggested).toBe(1)
|
||||
expect(body.data.unmatched).toBe(2)
|
||||
expect(sweepMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', {
|
||||
dateFrom: undefined,
|
||||
dateTo: undefined,
|
||||
})
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects all_accounts combined with dry_run: the sweep has no preview form and must never apply on a requested preview', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { all_accounts: true, dry_run: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects all_accounts combined with account_number or selected_matches', async () => {
|
||||
for (const body of [
|
||||
{ all_accounts: true, account_number: '1930' },
|
||||
{ all_accounts: true, confidence_threshold: 0.85 },
|
||||
{
|
||||
all_accounts: true,
|
||||
selected_matches: [
|
||||
{
|
||||
transaction_id: '11111111-1111-4111-8111-111111111111',
|
||||
journal_entry_id: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
},
|
||||
]) {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', { method: 'POST', body })
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
}
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { runReconciliation } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import {
|
||||
runReconciliation,
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
} from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { runUnattendedReconciliationSweep } from '@/lib/reconciliation/unattended-sweep'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RunReconciliationSchema } from '@/lib/api/schemas'
|
||||
|
||||
@@ -12,8 +16,60 @@ export const POST = withRouteContext(
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, RunReconciliationSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { date_from, date_to, account_number, dry_run, selected_matches, confidence_threshold } =
|
||||
validation.data
|
||||
const {
|
||||
date_from,
|
||||
date_to,
|
||||
account_number,
|
||||
dry_run,
|
||||
selected_matches,
|
||||
confidence_threshold,
|
||||
all_accounts,
|
||||
} = validation.data
|
||||
|
||||
// "Kör matchning igen": the per-account sweep across every enabled cash
|
||||
// account, exactly what the unattended post-sync path runs. New >= 0.9
|
||||
// matches auto-link; the 0.75-0.89 band persists as suggestions.
|
||||
//
|
||||
// The sweep ALWAYS writes at its own fixed floor: there is no dry-run form
|
||||
// of it, and silently ignoring dry_run (or a client-sent floor) here would
|
||||
// turn a requested preview into applied links (the documented
|
||||
// dry-run-gotcha P0 class). Enforce the mutual exclusion instead of just
|
||||
// documenting it.
|
||||
if (
|
||||
all_accounts &&
|
||||
(dry_run !== undefined ||
|
||||
account_number ||
|
||||
selected_matches ||
|
||||
confidence_threshold !== undefined)
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'all_accounts kan inte kombineras med dry_run, account_number, selected_matches eller confidence_threshold',
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
if (all_accounts) {
|
||||
const sweep = await runUnattendedReconciliationSweep(supabase, companyId, user.id, {
|
||||
dateFrom: date_from,
|
||||
dateTo: date_to,
|
||||
})
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
applied: sweep.applied,
|
||||
errors: sweep.errors,
|
||||
suggested: sweep.suggested,
|
||||
unmatched: sweep.unmatched,
|
||||
skipped_below_threshold: sweep.skippedBelowThreshold,
|
||||
accounts: sweep.accounts.map((a) => ({
|
||||
account_number: a.accountNumber,
|
||||
applied: a.applied,
|
||||
suggested: a.suggested,
|
||||
})),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const accountNumber = account_number ?? '1930'
|
||||
|
||||
@@ -52,9 +108,17 @@ export const POST = withRouteContext(
|
||||
transactionId: m.transaction_id,
|
||||
journalEntryId: m.journal_entry_id,
|
||||
})),
|
||||
// Server-side floor on the apply path (mirrors the v1 route): pairs the
|
||||
// fresh re-run scores below it are skipped, not applied.
|
||||
confidenceThreshold: confidence_threshold,
|
||||
// Server-side floor on the apply path. A client-sent confidence_threshold
|
||||
// always wins (mirrors the v1 route: pairs the fresh re-run scores below
|
||||
// it are skipped, not applied). Without one: a no-selection apply run is
|
||||
// effectively unattended, so it floors at 0.9 and persists the 0.75-0.89
|
||||
// band as reviewable suggestions instead of auto-committing fuzzy
|
||||
// matches; applyOnly runs keep the legacy no-floor behavior (the user
|
||||
// already reviewed the pairs in the dry-run preview). Ignored on dry runs.
|
||||
confidenceThreshold:
|
||||
confidence_threshold ??
|
||||
(selected_matches ? undefined : DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD),
|
||||
...(selected_matches ? {} : { persistSuggestions: true }),
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
@@ -74,6 +138,8 @@ export const POST = withRouteContext(
|
||||
})),
|
||||
applied: result.applied,
|
||||
errors: result.errors,
|
||||
suggested: result.suggested,
|
||||
skipped_below_threshold: result.skippedBelowThreshold,
|
||||
dry_run: dry_run ?? false,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -334,9 +334,26 @@ export const POST = withRouteContext(
|
||||
})
|
||||
}
|
||||
|
||||
// A RECONCILIATION link (reconciliation_method set) is not a conflicting
|
||||
// booking: the entry it points at is an independent verifikat (SIE import,
|
||||
// salary run, manual booking) that may evidence OTHER affärshändelser, and
|
||||
// reversing it wholesale as a side effect of matching one payment would be
|
||||
// an over-broad rättelse (BFL 5 kap 5 §: a correction is scoped to the
|
||||
// actual error). Nothing is detached HERE: the final transaction update
|
||||
// below overwrites the pointer and clears reconciliation_method in the
|
||||
// same write, so a failure anywhere in between leaves the existing link
|
||||
// fully intact instead of orphaning the row.
|
||||
const priorReconciliationLink =
|
||||
transaction.journal_entry_id && transaction.reconciliation_method
|
||||
? {
|
||||
journalEntryId: transaction.journal_entry_id as string,
|
||||
method: transaction.reconciliation_method as string,
|
||||
}
|
||||
: null
|
||||
|
||||
// Storno conflicting auto-categorization JE before any other state change.
|
||||
// If storno fails, return immediately: nothing else has been modified.
|
||||
if (transaction.journal_entry_id) {
|
||||
if (transaction.journal_entry_id && !priorReconciliationLink) {
|
||||
try {
|
||||
await reverseEntry(supabase, companyId, user.id, transaction.journal_entry_id)
|
||||
|
||||
@@ -730,6 +747,13 @@ export const POST = withRouteContext(
|
||||
journal_entry_id: journalEntryId,
|
||||
is_business: true,
|
||||
category: 'income_services',
|
||||
// The invoice match supersedes any prior reconciliation link: the
|
||||
// stale method label must not survive the re-pointed journal_entry_id
|
||||
// (deferred detach, see the priorReconciliationLink block above).
|
||||
// Unconditional literal on purpose: null is already the value on every
|
||||
// non-reconciliation-linked row, and a literal payload keeps the
|
||||
// phantom-column scanner able to verify the column set.
|
||||
reconciliation_method: null,
|
||||
})
|
||||
.eq('id', transactionId)
|
||||
|
||||
@@ -738,6 +762,20 @@ export const POST = withRouteContext(
|
||||
return errorResponseFromCode('MATCH_INVOICE_LINK_TX_FAILED', txLog, { requestId })
|
||||
}
|
||||
|
||||
// The deferred detach committed with the update above: record the release
|
||||
// of the prior reconciliation link so the append-only trail shows the full
|
||||
// transition (behandlingshistorik, BFNAR 2013:2 kap 8).
|
||||
if (priorReconciliationLink) {
|
||||
await logMatchEvent(supabase, user.id, transactionId, 'unmatched', {
|
||||
invoiceId: invoice_id,
|
||||
previousState: {
|
||||
journal_entry_id: priorReconciliationLink.journalEntryId,
|
||||
reconciliation_method: priorReconciliationLink.method,
|
||||
},
|
||||
newState: { journal_entry_id: journalEntryId, reconciliation_method: null },
|
||||
})
|
||||
}
|
||||
|
||||
logMatchEvent(supabase, user.id, transactionId, 'matched', {
|
||||
invoiceId: invoice_id,
|
||||
matchConfidence: 1.0,
|
||||
|
||||
@@ -412,7 +412,21 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
const { newPaidAmount, newRemaining, isFullyPaid, newStatus } = payment.plan
|
||||
const paidAt = isFullyPaid ? paidAtFromDate(transaction.date) : null
|
||||
|
||||
if (transaction.journal_entry_id) {
|
||||
// A RECONCILIATION link (reconciliation_method set) is not a conflicting
|
||||
// booking: the entry is an independent verifikat that may evidence OTHER
|
||||
// affärshändelser; reversing it wholesale would be an over-broad rättelse
|
||||
// (BFL 5 kap 5 §). Nothing is detached here: the final transaction update
|
||||
// overwrites the pointer and clears reconciliation_method in the same
|
||||
// write, so a failure in between leaves the existing link intact.
|
||||
const priorReconciliationLink =
|
||||
transaction.journal_entry_id && transaction.reconciliation_method
|
||||
? {
|
||||
journalEntryId: transaction.journal_entry_id as string,
|
||||
method: transaction.reconciliation_method as string,
|
||||
}
|
||||
: null
|
||||
|
||||
if (transaction.journal_entry_id && !priorReconciliationLink) {
|
||||
try {
|
||||
await reverseEntry(ctx.supabase, ctx.companyId!, ctx.userId, transaction.journal_entry_id)
|
||||
const { error: clearErr } = await ctx.supabase
|
||||
@@ -762,6 +776,10 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
potential_invoice_id: null,
|
||||
journal_entry_id: journalEntryId,
|
||||
is_business: true,
|
||||
// The invoice match supersedes any prior reconciliation link (deferred
|
||||
// detach, see the priorReconciliationLink block above). Unconditional:
|
||||
// null is already the value on every non-reconciliation-linked row.
|
||||
reconciliation_method: null,
|
||||
}
|
||||
if (existingTxCategory) txUpdate.category = existingTxCategory
|
||||
|
||||
@@ -777,6 +795,19 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
// Record the release of the prior reconciliation link now that the
|
||||
// re-point has committed (behandlingshistorik, BFNAR 2013:2 kap 8).
|
||||
if (priorReconciliationLink) {
|
||||
await logMatchEvent(ctx.supabase, ctx.userId, txId, 'unmatched', {
|
||||
invoiceId: invoice_id,
|
||||
previousState: {
|
||||
journal_entry_id: priorReconciliationLink.journalEntryId,
|
||||
reconciliation_method: priorReconciliationLink.method,
|
||||
},
|
||||
newState: { journal_entry_id: journalEntryId, reconciliation_method: null },
|
||||
})
|
||||
}
|
||||
|
||||
logMatchEvent(ctx.supabase, ctx.userId, txId, 'matched', {
|
||||
invoiceId: invoice_id,
|
||||
matchConfidence: 1.0,
|
||||
|
||||
@@ -244,7 +244,21 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
// 2440/1930 supplier-invoice payment entry: two verifikationer for
|
||||
// one affärshändelse violates BFL 5 kap 6 §. If storno fails, abort
|
||||
// before any further state change.
|
||||
if (transaction.journal_entry_id) {
|
||||
// A RECONCILIATION link (reconciliation_method set) is not a conflicting
|
||||
// booking: the entry is an independent verifikat that may evidence OTHER
|
||||
// affärshändelser; reversing it wholesale would be an over-broad rättelse
|
||||
// (BFL 5 kap 5 §). Nothing is detached here: the final transaction update
|
||||
// overwrites the pointer and clears reconciliation_method in the same
|
||||
// write, so a failure in between leaves the existing link intact.
|
||||
const priorReconciliationLink =
|
||||
transaction.journal_entry_id && transaction.reconciliation_method
|
||||
? {
|
||||
journalEntryId: transaction.journal_entry_id as string,
|
||||
method: transaction.reconciliation_method as string,
|
||||
}
|
||||
: null
|
||||
|
||||
if (transaction.journal_entry_id && !priorReconciliationLink) {
|
||||
try {
|
||||
await reverseEntry(
|
||||
ctx.supabase,
|
||||
@@ -508,6 +522,12 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
potential_supplier_invoice_id: null,
|
||||
journal_entry_id: journalEntryId,
|
||||
is_business: true,
|
||||
// The supplier-invoice match supersedes any prior reconciliation link
|
||||
// (deferred detach, see the priorReconciliationLink block above).
|
||||
// Unconditional literal on purpose: null is already the value on every
|
||||
// non-reconciliation-linked row, and a literal payload keeps the
|
||||
// phantom-column scanner able to verify the column set.
|
||||
reconciliation_method: null,
|
||||
})
|
||||
.eq('id', txId)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
@@ -517,6 +537,19 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
// Record the release of the prior reconciliation link now that the
|
||||
// re-point has committed (behandlingshistorik, BFNAR 2013:2 kap 8).
|
||||
if (priorReconciliationLink) {
|
||||
await logMatchEvent(ctx.supabase, ctx.userId, txId, 'unmatched', {
|
||||
supplierInvoiceId: supplier_invoice_id,
|
||||
previousState: {
|
||||
journal_entry_id: priorReconciliationLink.journalEntryId,
|
||||
reconciliation_method: priorReconciliationLink.method,
|
||||
},
|
||||
newState: { journal_entry_id: journalEntryId, reconciliation_method: null },
|
||||
})
|
||||
}
|
||||
|
||||
// Propagate a document pinned to the transaction onto the payment
|
||||
// verifikat, mirroring the dashboard route (BFL 5 kap 6 §). Guarded to
|
||||
// unlinked current-version docs only: a doc already serving another
|
||||
|
||||
Reference in New Issue
Block a user