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
@@ -2207,6 +2207,13 @@ export const MarkOpeningBalanceSchema = z.object({
|
||||
export const RunReconciliationSchema = z.object({
|
||||
date_from: isoDate.optional(),
|
||||
date_to: isoDate.optional(),
|
||||
// Run the per-cash-account unattended sweep over every enabled cash account
|
||||
// ("Kör matchning igen" in the review surface) instead of one account. The
|
||||
// sweep always applies at the unattended threshold and persists suggestions;
|
||||
// there is no dry-run form. The route REJECTS (400) any combination with
|
||||
// dry_run, account_number or selected_matches rather than silently ignoring
|
||||
// them: a request that asked for a preview must never apply writes.
|
||||
all_accounts: z.boolean().optional(),
|
||||
// BAS settlement account to reconcile against (e.g. '1930', '1932'). Defaults
|
||||
// to '1930' server-side so existing clients stay correct.
|
||||
account_number: accountNumber.optional(),
|
||||
@@ -2231,6 +2238,14 @@ export const RunReconciliationSchema = z.object({
|
||||
confidence_threshold: z.number().min(0).max(1).optional(),
|
||||
})
|
||||
|
||||
// Confirm or reject persisted journal-entry match suggestions
|
||||
// (transactions.potential_journal_entry_id). Each pair is revalidated
|
||||
// server-side at confirm time; stale pairs are skipped, never failing the batch.
|
||||
export const ConfirmJeSuggestionsSchema = z.object({
|
||||
transaction_ids: z.array(uuid).min(1).max(500),
|
||||
action: z.enum(['confirm', 'reject']),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Report query schemas
|
||||
// ============================================================
|
||||
|
||||
@@ -605,6 +605,59 @@ describe('runReconciliation', () => {
|
||||
expect(result.errors).toBe(0)
|
||||
})
|
||||
|
||||
it('persists the below-threshold band as suggestions when persistSuggestions is set', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
|
||||
// Fuzzy match: amount off by 1 öre on the exact date → 0.75 confidence,
|
||||
// below the 0.9 unattended floor.
|
||||
const tx = makeTransaction({ id: 'tx-1', amount: 1000.01, date: '2024-06-15', currency: 'SEK' })
|
||||
const glLine: UnlinkedGLLine = makeGLLine({
|
||||
line_id: 'line-1',
|
||||
journal_entry_id: 'je-1',
|
||||
debit_amount: 1000,
|
||||
entry_date: '2024-06-15',
|
||||
})
|
||||
|
||||
enqueue({ data: [glLine] }) // RPC: GL lines
|
||||
enqueue({ data: [tx] }) // transactions
|
||||
enqueue({ data: [{ id: 'tx-1' }] }) // suggestion update .select('id')
|
||||
|
||||
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
|
||||
confidenceThreshold: 0.9,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
|
||||
expect(result.applied).toBe(0)
|
||||
expect(result.skippedBelowThreshold).toBe(1)
|
||||
expect(result.suggested).toBe(1)
|
||||
expect(result.candidates).toBe(1)
|
||||
})
|
||||
|
||||
it('does not count a suggestion whose optimistic-lock update matched zero rows', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
|
||||
const tx = makeTransaction({ id: 'tx-1', amount: 1000.01, date: '2024-06-15', currency: 'SEK' })
|
||||
const glLine: UnlinkedGLLine = makeGLLine({
|
||||
line_id: 'line-1',
|
||||
journal_entry_id: 'je-1',
|
||||
debit_amount: 1000,
|
||||
entry_date: '2024-06-15',
|
||||
})
|
||||
|
||||
enqueue({ data: [glLine] })
|
||||
enqueue({ data: [tx] })
|
||||
// A concurrent writer booked the row: .is('journal_entry_id', null) → 0 rows.
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
|
||||
confidenceThreshold: 0.9,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
|
||||
expect(result.suggested).toBe(0)
|
||||
expect(result.skippedBelowThreshold).toBe(1)
|
||||
})
|
||||
|
||||
it('counts a conflicted apply (0 rows updated) as an error, not applied', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
/**
|
||||
* Tests for confirm/reject of persisted journal-entry match suggestions.
|
||||
*
|
||||
* The contract under test: every pair is revalidated server-side at confirm
|
||||
* time (row state, voucher consumption, and the voucher's bank-leg amount and
|
||||
* direction), stale pairs are skipped (never failing the batch), and a
|
||||
* verifikat cannot be consumed twice within one bulk confirm.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { manualLinkMock } = vi.hoisted(() => ({ manualLinkMock: vi.fn() }))
|
||||
|
||||
vi.mock('../bank-reconciliation', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../bank-reconciliation')>()
|
||||
return { ...actual, manualLink: manualLinkMock }
|
||||
})
|
||||
|
||||
const { logMatchEventMock } = vi.hoisted(() => ({ logMatchEventMock: vi.fn() }))
|
||||
vi.mock('@/lib/invoices/match-log', () => ({
|
||||
logMatchEvent: (...args: unknown[]) => logMatchEventMock(...args),
|
||||
}))
|
||||
|
||||
import {
|
||||
confirmJournalEntrySuggestions,
|
||||
rejectJournalEntrySuggestions,
|
||||
} from '../suggestions'
|
||||
|
||||
/** Queue-based chainable supabase stub, same pattern as the reconciliation
|
||||
* suite: each awaited chain consumes the next queued result. */
|
||||
function createQueueMockSupabase() {
|
||||
const resultQueue: { data: unknown; error: unknown }[] = []
|
||||
const enqueue = (...results: { data?: unknown; error?: unknown }[]) => {
|
||||
for (const r of results) {
|
||||
resultQueue.push({ data: r.data ?? null, error: r.error ?? null })
|
||||
}
|
||||
}
|
||||
const buildChain = (): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
const next = resultQueue.shift() ?? { data: null, error: null }
|
||||
return (resolve: (v: unknown) => void) => resolve(next)
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain()
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
const supabase = {
|
||||
from: vi.fn().mockImplementation(() => buildChain()),
|
||||
rpc: vi.fn().mockImplementation(() => buildChain()),
|
||||
}
|
||||
return { supabase, enqueue }
|
||||
}
|
||||
|
||||
const TX_1 = 'tx-1'
|
||||
const TX_2 = 'tx-2'
|
||||
const JE_1 = 'je-1'
|
||||
const CA_ID = 'ca-1'
|
||||
|
||||
function suggestionRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: TX_1,
|
||||
amount: -1000,
|
||||
currency: 'SEK',
|
||||
journal_entry_id: null,
|
||||
potential_journal_entry_id: JE_1,
|
||||
potential_match_method: 'auto_date_range',
|
||||
potential_match_confidence: '0.85',
|
||||
cash_account_id: CA_ID,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** A voucher bank leg agreeing with suggestionRow's -1000 (credit = money out). */
|
||||
function matchingLegs() {
|
||||
return [{ debit_amount: 0, credit_amount: 1000, currency: null, amount_in_currency: null }]
|
||||
}
|
||||
|
||||
describe('confirmJournalEntrySuggestions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
manualLinkMock.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('confirms a valid suggestion via manualLink against the row\'s own settlement account', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow() }) // fetch tx
|
||||
enqueue({ data: [] }) // consumers of JE_1: none
|
||||
enqueue({ data: { ledger_account: '1932' } }) // cash account resolve
|
||||
enqueue({ data: matchingLegs() }) // amount revalidation legs
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([TX_1])
|
||||
expect(result.skipped).toEqual([])
|
||||
expect(manualLinkMock).toHaveBeenCalledWith(supabase, 'company-1', TX_1, JE_1, 'user-1', '1932')
|
||||
expect(logMatchEventMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
TX_1,
|
||||
'linked_to_existing_voucher',
|
||||
expect.objectContaining({ matchMethod: 'auto_date_range', matchConfidence: 0.85 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('skips a transaction whose suggested verifikat is already consumed', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow() })
|
||||
enqueue({ data: [{ id: 'other-tx' }] }) // someone already settles JE_1
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([])
|
||||
expect(result.skipped).toEqual([{ transactionId: TX_1, reason: 'voucher_consumed' }])
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never fails the batch: second row suggesting the same verifikat is skipped after the first consumes it', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
// Row 1: full happy path.
|
||||
enqueue({ data: suggestionRow() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: { ledger_account: '1930' } })
|
||||
enqueue({ data: matchingLegs() })
|
||||
// Row 2 (fetched AFTER row 1 linked): the sibling-clear trigger has wiped
|
||||
// its suggestion, so it reads as no_suggestion.
|
||||
enqueue({ data: suggestionRow({ id: TX_2, potential_journal_entry_id: null, potential_match_method: null, potential_match_confidence: null }) })
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
TX_2,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([TX_1])
|
||||
expect(result.skipped).toEqual([{ transactionId: TX_2, reason: 'no_suggestion' }])
|
||||
expect(manualLinkMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports manualLink refusals as link_failed with the service message', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: { ledger_account: '1930' } })
|
||||
enqueue({ data: matchingLegs() })
|
||||
manualLinkMock.mockResolvedValue({ success: false, error: 'Verifikationen är inte bokförd ännu.' })
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([])
|
||||
expect(result.skipped).toEqual([
|
||||
{ transactionId: TX_1, reason: 'link_failed', message: 'Verifikationen är inte bokförd ännu.' },
|
||||
])
|
||||
})
|
||||
|
||||
it('skips not-found and already-linked rows', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: null }) // TX_1 not found
|
||||
enqueue({ data: suggestionRow({ id: TX_2, journal_entry_id: 'je-existing' }) })
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
TX_2,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([])
|
||||
expect(result.skipped).toEqual([
|
||||
{ transactionId: TX_1, reason: 'not_found' },
|
||||
{ transactionId: TX_2, reason: 'already_linked' },
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves NULL-cash_account_id rows via the PRIMARY cash account, falling back to 1930', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow({ cash_account_id: null }) })
|
||||
enqueue({ data: [] })
|
||||
// Primary lookup: the company's primary account is 1920, so the unassigned
|
||||
// row must validate against 1920 (the sweep created the suggestion under
|
||||
// the primary's scope), never a hard-coded 1930.
|
||||
enqueue({ data: { ledger_account: '1920' } })
|
||||
enqueue({ data: matchingLegs() })
|
||||
|
||||
await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [TX_1])
|
||||
|
||||
expect(manualLinkMock).toHaveBeenCalledWith(supabase, 'company-1', TX_1, JE_1, 'user-1', '1920')
|
||||
})
|
||||
|
||||
it('falls back to 1930 when no primary cash account exists', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow({ cash_account_id: null }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null }) // no primary row
|
||||
enqueue({ data: matchingLegs() })
|
||||
|
||||
await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [TX_1])
|
||||
|
||||
expect(manualLinkMock).toHaveBeenCalledWith(supabase, 'company-1', TX_1, JE_1, 'user-1', '1930')
|
||||
})
|
||||
|
||||
it('skips with amount_mismatch when the voucher bank leg no longer agrees with the transaction', async () => {
|
||||
// Inline rattelse re-priced the voucher's bank leg from 1000 to 500 after
|
||||
// the suggestion was computed: status stays posted, so no invalidation
|
||||
// trigger fired. Confirm must refuse instead of asserting a false
|
||||
// correspondence (BFL 5 kap 7 §).
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: { ledger_account: '1930' } })
|
||||
enqueue({ data: [{ debit_amount: 0, credit_amount: 500, currency: null, amount_in_currency: null }] })
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.confirmed).toEqual([])
|
||||
expect(result.skipped).toHaveLength(1)
|
||||
expect(result.skipped[0]).toMatchObject({ transactionId: TX_1, reason: 'amount_mismatch' })
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips with amount_mismatch when the direction flipped', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow({ amount: 1000 }) }) // money IN
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: { ledger_account: '1930' } })
|
||||
enqueue({ data: matchingLegs() }) // credit leg = money OUT
|
||||
|
||||
const result = await confirmJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.skipped[0]).toMatchObject({ transactionId: TX_1, reason: 'amount_mismatch' })
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('rejectJournalEntrySuggestions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('clears the suggestion and logs suggestion_cleared with the previous state', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow() })
|
||||
enqueue({ data: null }) // clear update
|
||||
|
||||
const result = await rejectJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.rejected).toEqual([TX_1])
|
||||
expect(logMatchEventMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
TX_1,
|
||||
'suggestion_cleared',
|
||||
expect.objectContaining({
|
||||
previousState: expect.objectContaining({ potential_journal_entry_id: JE_1 }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('skips rows without a suggestion', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
enqueue({ data: suggestionRow({ potential_journal_entry_id: null }) })
|
||||
|
||||
const result = await rejectJournalEntrySuggestions(supabase as never, 'company-1', 'user-1', [
|
||||
TX_1,
|
||||
])
|
||||
|
||||
expect(result.rejected).toEqual([])
|
||||
expect(result.skipped).toEqual([{ transactionId: TX_1, reason: 'no_suggestion' }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* Tests for the per-cash-account unattended reconciliation sweep (issue #1298).
|
||||
*
|
||||
* The sweep is the shared entry point for every unattended caller (EB cron,
|
||||
* manual EB sync, bank-file import). What matters here is the fan-out contract:
|
||||
* one scoped runReconciliation call per enabled cash account, the legacy
|
||||
* 1930/SEK fallback for companies with no cash_accounts rows, per-account
|
||||
* failure isolation, and honest aggregation.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { runReconciliationMock } = vi.hoisted(() => ({
|
||||
runReconciliationMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../bank-reconciliation', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../bank-reconciliation')>()
|
||||
return {
|
||||
...actual,
|
||||
runReconciliation: runReconciliationMock,
|
||||
}
|
||||
})
|
||||
|
||||
import { runUnattendedReconciliationSweep, toSweepSummary } from '../unattended-sweep'
|
||||
import { DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD } from '../bank-reconciliation'
|
||||
|
||||
function emptyRunResult(overrides: Partial<{
|
||||
applied: number
|
||||
errors: number
|
||||
skippedBelowThreshold: number
|
||||
suggested: number
|
||||
candidates: number
|
||||
matches: unknown[]
|
||||
}> = {}) {
|
||||
return {
|
||||
matches: overrides.matches ?? [],
|
||||
applied: overrides.applied ?? 0,
|
||||
errors: overrides.errors ?? 0,
|
||||
skippedBelowThreshold: overrides.skippedBelowThreshold ?? 0,
|
||||
suggested: overrides.suggested ?? 0,
|
||||
candidates: overrides.candidates ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** Chainable stub for the cash_accounts lookup: every method returns the chain,
|
||||
* awaiting it resolves the configured result. */
|
||||
function makeSupabase(result: { data: unknown; error: unknown }) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(result)
|
||||
}
|
||||
return () => new Proxy(chain, handler)
|
||||
},
|
||||
}
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => new Proxy(chain, handler)),
|
||||
}
|
||||
}
|
||||
|
||||
const CA_1930 = {
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
ledger_account: '1930',
|
||||
currency: 'SEK',
|
||||
is_primary: true,
|
||||
}
|
||||
const CA_1931 = {
|
||||
id: '22222222-2222-4222-8222-222222222222',
|
||||
ledger_account: '1931',
|
||||
currency: 'SEK',
|
||||
is_primary: false,
|
||||
}
|
||||
const CA_1932_EUR = {
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
ledger_account: '1932',
|
||||
currency: 'EUR',
|
||||
is_primary: false,
|
||||
}
|
||||
|
||||
describe('runUnattendedReconciliationSweep', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('runs once per enabled cash account with that account\'s scope', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930, CA_1931, CA_1932_EUR], error: null })
|
||||
runReconciliationMock.mockResolvedValue(emptyRunResult())
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(
|
||||
supabase as never,
|
||||
'company-1',
|
||||
'user-1',
|
||||
{ dateFrom: '2026-01-01', dateTo: '2026-06-30' },
|
||||
)
|
||||
|
||||
expect(runReconciliationMock).toHaveBeenCalledTimes(3)
|
||||
|
||||
// Primary 1930: claims unassigned NULL-cash_account_id rows.
|
||||
expect(runReconciliationMock).toHaveBeenNthCalledWith(1, supabase, 'company-1', 'user-1', {
|
||||
dateFrom: '2026-01-01',
|
||||
dateTo: '2026-06-30',
|
||||
accountNumber: '1930',
|
||||
currency: 'SEK',
|
||||
cashAccountId: CA_1930.id,
|
||||
includeUnassigned: true,
|
||||
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
// Non-primary same-currency 1931: strict scope, never claims NULL rows.
|
||||
expect(runReconciliationMock).toHaveBeenNthCalledWith(2, supabase, 'company-1', 'user-1', {
|
||||
dateFrom: '2026-01-01',
|
||||
dateTo: '2026-06-30',
|
||||
accountNumber: '1931',
|
||||
currency: 'SEK',
|
||||
cashAccountId: CA_1931.id,
|
||||
includeUnassigned: false,
|
||||
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
// Foreign account reconciles in its own currency.
|
||||
expect(runReconciliationMock).toHaveBeenNthCalledWith(3, supabase, 'company-1', 'user-1', {
|
||||
dateFrom: '2026-01-01',
|
||||
dateTo: '2026-06-30',
|
||||
accountNumber: '1932',
|
||||
currency: 'EUR',
|
||||
cashAccountId: CA_1932_EUR.id,
|
||||
includeUnassigned: false,
|
||||
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
|
||||
expect(result.accounts).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('falls back to a single legacy 1930/SEK run when the company has no cash_accounts rows', async () => {
|
||||
const supabase = makeSupabase({ data: [], error: null })
|
||||
runReconciliationMock.mockResolvedValue(emptyRunResult({ applied: 2 }))
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1')
|
||||
|
||||
expect(runReconciliationMock).toHaveBeenCalledTimes(1)
|
||||
expect(runReconciliationMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', {
|
||||
dateFrom: undefined,
|
||||
dateTo: undefined,
|
||||
accountNumber: '1930',
|
||||
currency: 'SEK',
|
||||
cashAccountId: undefined,
|
||||
includeUnassigned: true,
|
||||
confidenceThreshold: DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
persistSuggestions: true,
|
||||
})
|
||||
expect(result.applied).toBe(2)
|
||||
expect(result.accounts[0].cashAccountId).toBeNull()
|
||||
})
|
||||
|
||||
it('aggregates per-account results into sweep totals', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930, CA_1931], error: null })
|
||||
runReconciliationMock
|
||||
.mockResolvedValueOnce(
|
||||
emptyRunResult({ applied: 3, skippedBelowThreshold: 2, matches: [1, 2, 3, 4, 5] }),
|
||||
)
|
||||
.mockResolvedValueOnce(emptyRunResult({ applied: 1, errors: 1, matches: [1, 2] }))
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1')
|
||||
|
||||
expect(result.applied).toBe(4)
|
||||
expect(result.errors).toBe(1)
|
||||
expect(result.skippedBelowThreshold).toBe(2)
|
||||
expect(result.accounts[0]).toMatchObject({ accountNumber: '1930', applied: 3, proposed: 5 })
|
||||
expect(result.accounts[1]).toMatchObject({ accountNumber: '1931', applied: 1, proposed: 2 })
|
||||
})
|
||||
|
||||
it('aggregates suggested and derives unmatched from the candidate pool', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930, CA_1931], error: null })
|
||||
runReconciliationMock
|
||||
.mockResolvedValueOnce(
|
||||
emptyRunResult({ applied: 5, suggested: 2, candidates: 10, matches: [1, 2, 3, 4, 5, 6, 7] }),
|
||||
)
|
||||
.mockResolvedValueOnce(emptyRunResult({ applied: 1, suggested: 0, candidates: 3, matches: [1] }))
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1')
|
||||
|
||||
expect(result.applied).toBe(6)
|
||||
expect(result.suggested).toBe(2)
|
||||
// 13 candidates, 6 auto-linked, 2 suggested: 5 rows left for the backstop.
|
||||
expect(result.unmatched).toBe(5)
|
||||
})
|
||||
|
||||
it('one account failing does not abort the others; the failure counts as one error', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930, CA_1931], error: null })
|
||||
runReconciliationMock
|
||||
.mockRejectedValueOnce(new Error('transient'))
|
||||
.mockResolvedValueOnce(emptyRunResult({ applied: 2, matches: [1, 2] }))
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1')
|
||||
|
||||
expect(runReconciliationMock).toHaveBeenCalledTimes(2)
|
||||
expect(result.errors).toBe(1)
|
||||
expect(result.applied).toBe(2)
|
||||
expect(result.accounts[0]).toMatchObject({ accountNumber: '1930', applied: 0, errors: 1 })
|
||||
expect(result.accounts[1]).toMatchObject({ accountNumber: '1931', applied: 2, errors: 0 })
|
||||
})
|
||||
|
||||
it('throws when the cash_accounts lookup fails (never degrades to the pooled run)', async () => {
|
||||
const supabase = makeSupabase({ data: null, error: { message: 'rls denied' } })
|
||||
|
||||
await expect(
|
||||
runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1'),
|
||||
).rejects.toThrow('Kunde inte hämta kassakonton')
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('carries errors into the stamped summary so a crashed account never reads as "all done"', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930, CA_1931], error: null })
|
||||
runReconciliationMock
|
||||
.mockResolvedValueOnce(emptyRunResult({ applied: 5, candidates: 5, matches: [1, 2, 3, 4, 5] }))
|
||||
// 1931 throws: its candidates never enter the pool, so unmatched: 0
|
||||
// would be a lie without the errors field.
|
||||
.mockRejectedValueOnce(new Error('transient'))
|
||||
|
||||
const result = await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1', {
|
||||
dateFrom: '2026-01-01',
|
||||
dateTo: '2026-06-30',
|
||||
})
|
||||
const summary = toSweepSummary(result, { dateFrom: '2026-01-01', dateTo: '2026-06-30' })
|
||||
|
||||
expect(summary.auto_linked).toBe(5)
|
||||
expect(summary.unmatched).toBe(0)
|
||||
expect(summary.errors).toBe(1)
|
||||
expect(summary.date_from).toBe('2026-01-01')
|
||||
})
|
||||
|
||||
it('honors an explicit confidenceThreshold override', async () => {
|
||||
const supabase = makeSupabase({ data: [CA_1930], error: null })
|
||||
runReconciliationMock.mockResolvedValue(emptyRunResult())
|
||||
|
||||
await runUnattendedReconciliationSweep(supabase as never, 'company-1', 'user-1', {
|
||||
confidenceThreshold: 0.95,
|
||||
})
|
||||
|
||||
expect(runReconciliationMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ confidenceThreshold: 0.95 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -67,6 +67,19 @@ export interface ReconciliationRunResult {
|
||||
* for human review. Always 0 on dry runs and when no threshold was given.
|
||||
*/
|
||||
skippedBelowThreshold: number
|
||||
/**
|
||||
* Below-threshold matches persisted as suggestions on the transaction
|
||||
* (potential_journal_entry_id + method + confidence) for the review surface.
|
||||
* Always 0 unless persistSuggestions was set on a non-dry apply run with a
|
||||
* confidence threshold.
|
||||
*/
|
||||
suggested: number
|
||||
/**
|
||||
* Unmatched, non-ignored transactions the run considered (the candidate pool
|
||||
* on the bank side). Lets callers report "X av Y matchade" without a second
|
||||
* count query.
|
||||
*/
|
||||
candidates: number
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,6 +211,18 @@ export interface ReconciliationOptions {
|
||||
* committed without human review.
|
||||
*/
|
||||
confidenceThreshold?: number
|
||||
/**
|
||||
* Persist below-threshold matches (the 0.75-0.89 band: auto_fuzzy,
|
||||
* auto_date_range) onto the transaction's potential_journal_entry_id /
|
||||
* potential_match_method / potential_match_confidence columns instead of
|
||||
* dropping them, so the review surface can offer them for confirmation.
|
||||
* Only meaningful together with confidenceThreshold on a non-dry apply run;
|
||||
* ignored otherwise. Suggestions are soft data: the same optimistic
|
||||
* `.is('journal_entry_id', null)` guard as the apply path, plus DB triggers
|
||||
* that clear them when the row is booked/ignored or the entry is consumed
|
||||
* or reversed.
|
||||
*/
|
||||
persistSuggestions?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -417,6 +442,7 @@ export async function runReconciliation(
|
||||
includeUnassigned = true,
|
||||
applyOnly,
|
||||
confidenceThreshold,
|
||||
persistSuggestions = false,
|
||||
} = options
|
||||
|
||||
// Fetch unlinked GL lines via RPC
|
||||
@@ -451,14 +477,28 @@ export async function runReconciliation(
|
||||
})
|
||||
|
||||
if (transactions.length === 0 || glLines.length === 0) {
|
||||
return { matches: [], applied: 0, errors: 0, skippedBelowThreshold: 0 }
|
||||
return {
|
||||
matches: [],
|
||||
applied: 0,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 0,
|
||||
suggested: 0,
|
||||
candidates: transactions.length,
|
||||
}
|
||||
}
|
||||
|
||||
// Run greedy matching, highest confidence first
|
||||
let matches = greedyMatch(transactions, glLines, currency)
|
||||
|
||||
if (dryRun) {
|
||||
return { matches, applied: 0, errors: 0, skippedBelowThreshold: 0 }
|
||||
return {
|
||||
matches,
|
||||
applied: 0,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 0,
|
||||
suggested: 0,
|
||||
candidates: transactions.length,
|
||||
}
|
||||
}
|
||||
|
||||
// When the caller reviewed a dry-run and ticked a subset, apply ONLY pairs
|
||||
@@ -477,12 +517,13 @@ export async function runReconciliation(
|
||||
// counted separately. This is the server-side guardrail for unattended
|
||||
// callers (nightly sync / cron), where nobody reviews a dry-run first.
|
||||
let toApply = matches
|
||||
let skippedBelowThreshold = 0
|
||||
let belowThresholdMatches: ReconciliationMatch[] = []
|
||||
if (confidenceThreshold !== undefined) {
|
||||
const floor = Math.max(0, Math.min(1, confidenceThreshold))
|
||||
toApply = matches.filter((m) => m.confidence >= floor)
|
||||
skippedBelowThreshold = matches.length - toApply.length
|
||||
belowThresholdMatches = matches.filter((m) => m.confidence < floor)
|
||||
}
|
||||
const skippedBelowThreshold = belowThresholdMatches.length
|
||||
|
||||
// Apply matches
|
||||
let applied = 0
|
||||
@@ -511,6 +552,18 @@ export async function runReconciliation(
|
||||
errors++
|
||||
} else {
|
||||
applied++
|
||||
// Behandlingshistorik (BFNAR 2013:2 kap 8, BFL 7:1): every auto-applied
|
||||
// link is a match event and must land in the append-only log, exactly
|
||||
// like the invoice-match and confirm-suggestion paths. The bus event
|
||||
// below goes to event_log (30-day TTL) and is NOT an audit record.
|
||||
await logMatchEvent(supabase, userId, match.transaction.id, 'matched', {
|
||||
matchConfidence: match.confidence,
|
||||
matchMethod: match.method,
|
||||
newState: {
|
||||
journal_entry_id: match.glLine.journal_entry_id,
|
||||
reconciliation_method: match.method,
|
||||
},
|
||||
})
|
||||
try {
|
||||
eventBus.emit({
|
||||
type: 'transaction.reconciled',
|
||||
@@ -531,7 +584,51 @@ export async function runReconciliation(
|
||||
}
|
||||
}
|
||||
|
||||
return { matches, applied, errors, skippedBelowThreshold }
|
||||
// Persist the below-threshold band as reviewable suggestions instead of
|
||||
// dropping it. Same optimistic-lock guard as the apply loop: a row that got
|
||||
// booked or linked between the read and this write matches zero rows, and
|
||||
// the DB trigger clears any suggestion the moment a link lands, so a stale
|
||||
// suggestion can never shadow a real link.
|
||||
let suggested = 0
|
||||
if (persistSuggestions) {
|
||||
for (const match of belowThresholdMatches) {
|
||||
try {
|
||||
const { data: suggestedRows, error } = await supabase
|
||||
.from('transactions')
|
||||
.update({
|
||||
potential_journal_entry_id: match.glLine.journal_entry_id,
|
||||
potential_match_method: match.method,
|
||||
potential_match_confidence: match.confidence,
|
||||
})
|
||||
.eq('id', match.transaction.id)
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.select('id')
|
||||
|
||||
if (!error && suggestedRows && suggestedRows.length > 0) {
|
||||
suggested++
|
||||
// Awaited: an unawaited promise can be frozen on serverless when the
|
||||
// response returns, silently dropping the audit row.
|
||||
await logMatchEvent(supabase, userId, match.transaction.id, 'auto_suggested', {
|
||||
matchConfidence: match.confidence,
|
||||
matchMethod: match.method,
|
||||
newState: { potential_journal_entry_id: match.glLine.journal_entry_id },
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Suggestions are best-effort: never fail the run over one row.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
matches,
|
||||
applied,
|
||||
errors,
|
||||
skippedBelowThreshold,
|
||||
suggested,
|
||||
candidates: transactions.length,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { manualLink, ledgerLineAmountIn } from './bank-reconciliation'
|
||||
import { logMatchEvent } from '@/lib/invoices/match-log'
|
||||
|
||||
/**
|
||||
* Confirm / reject persisted journal-entry match suggestions
|
||||
* (transactions.potential_journal_entry_id, written by the reconciliation
|
||||
* sweep's 0.75-0.89 band).
|
||||
*
|
||||
* Confirming is a reconciliation LINK, never a booking. Revalidated per pair
|
||||
* at click time, in this order: row still exists and is unlinked, suggestion
|
||||
* still present, suggested verifikat not already settled by another
|
||||
* transaction, the voucher's net movement on the settlement account still
|
||||
* agrees with the transaction's amount and direction (a suggestion computed
|
||||
* before an inline rattelse re-priced the bank leg must die here, not link),
|
||||
* and finally manualLink's own checks (entry posted, line on the settlement
|
||||
* account, optimistic lock on the row). Stale pairs are skipped and reported,
|
||||
* never failing the batch.
|
||||
*
|
||||
* The consumption check is read-then-act per request; two CONCURRENT requests
|
||||
* confirming different rows against the same verifikat can both pass it. The
|
||||
* sibling-clear trigger closes the window after the first commit, and a
|
||||
* double-settled voucher still surfaces as a non-zero difference on the
|
||||
* Bankavstamning status card, but within a single request the sequential
|
||||
* re-fetch is the real guarantee.
|
||||
*/
|
||||
|
||||
export type SuggestionSkipReason =
|
||||
| 'not_found'
|
||||
| 'no_suggestion'
|
||||
| 'already_linked'
|
||||
| 'voucher_consumed'
|
||||
| 'amount_mismatch'
|
||||
| 'link_failed'
|
||||
|
||||
export interface SuggestionActionResult {
|
||||
confirmed: string[]
|
||||
rejected: string[]
|
||||
skipped: Array<{ transactionId: string; reason: SuggestionSkipReason; message?: string }>
|
||||
}
|
||||
|
||||
interface SuggestionRow {
|
||||
id: string
|
||||
amount: number | string | null
|
||||
currency: string | null
|
||||
journal_entry_id: string | null
|
||||
potential_journal_entry_id: string | null
|
||||
potential_match_method: string | null
|
||||
potential_match_confidence: number | string | null
|
||||
cash_account_id: string | null
|
||||
}
|
||||
|
||||
async function fetchSuggestionRow(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
transactionId: string,
|
||||
): Promise<SuggestionRow | null> {
|
||||
const { data } = await supabase
|
||||
.from('transactions')
|
||||
.select(
|
||||
'id, amount, currency, journal_entry_id, potential_journal_entry_id, potential_match_method, potential_match_confidence, cash_account_id',
|
||||
)
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
return (data as SuggestionRow | null) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the settlement account manualLink must validate the voucher line
|
||||
* against. Rows with a cash_account_id use that account's ledger_account. Rows
|
||||
* WITHOUT one were swept under the PRIMARY cash account's scope
|
||||
* (includeUnassigned), so confirmation must resolve the same way: hard-coding
|
||||
* '1930' made every unassigned-row suggestion unconfirmable in a company whose
|
||||
* primary account is e.g. 1920 Plusgiro. '1930' remains only the final
|
||||
* fallback for companies with no cash_accounts rows at all.
|
||||
*/
|
||||
async function resolveSettlementAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
cashAccountId: string | null,
|
||||
): Promise<string> {
|
||||
const query = supabase.from('cash_accounts').select('ledger_account').eq('company_id', companyId)
|
||||
const { data } = cashAccountId
|
||||
? await query.eq('id', cashAccountId).maybeSingle()
|
||||
: await query.eq('is_primary', true).maybeSingle()
|
||||
return (data?.ledger_account as string | undefined) ?? '1930'
|
||||
}
|
||||
|
||||
/** Fuzzy band tolerance: the widest amount slack any persisted suggestion was
|
||||
* created under (auto_fuzzy, +-0.01), plus float headroom. */
|
||||
const CONFIRM_AMOUNT_TOLERANCE = 0.011
|
||||
|
||||
/**
|
||||
* The suggested voucher's net movement on the settlement account must still
|
||||
* agree with the transaction, in the transaction's own currency. Returns null
|
||||
* when it does; a skip reason message when it does not or cannot be verified
|
||||
* (no comparable amount = no honest link, per the determinism rule).
|
||||
*/
|
||||
async function verifySuggestedAmount(
|
||||
supabase: SupabaseClient,
|
||||
tx: SuggestionRow,
|
||||
accountNumber: string,
|
||||
): Promise<string | null> {
|
||||
const { data: lines } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('debit_amount, credit_amount, currency, amount_in_currency')
|
||||
.eq('journal_entry_id', tx.potential_journal_entry_id)
|
||||
.eq('account_number', accountNumber)
|
||||
|
||||
if (!lines || lines.length === 0) {
|
||||
return `Verifikationen saknar rad på ${accountNumber}`
|
||||
}
|
||||
const txCurrency = tx.currency ?? 'SEK'
|
||||
let movement = 0
|
||||
for (const line of lines) {
|
||||
const amount = ledgerLineAmountIn(line, txCurrency)
|
||||
if (amount === null) {
|
||||
return 'Verifikationens belopp kan inte jämföras i transaktionens valuta'
|
||||
}
|
||||
movement += amount
|
||||
}
|
||||
const txAmount = Number(tx.amount)
|
||||
if (!Number.isFinite(txAmount)) return 'Transaktionens belopp kunde inte läsas'
|
||||
if (Math.abs(Math.abs(txAmount) - Math.abs(movement)) > CONFIRM_AMOUNT_TOLERANCE) {
|
||||
return 'Beloppet stämmer inte längre med verifikationen'
|
||||
}
|
||||
if (Math.sign(txAmount) !== Math.sign(movement)) {
|
||||
return 'Riktningen stämmer inte längre med verifikationen'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export async function confirmJournalEntrySuggestions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
transactionIds: string[],
|
||||
): Promise<SuggestionActionResult> {
|
||||
const result: SuggestionActionResult = { confirmed: [], rejected: [], skipped: [] }
|
||||
|
||||
// Sequential on purpose: each pair is re-fetched at its turn, so when two
|
||||
// batch rows suggest the SAME verifikat the first confirm consumes it and the
|
||||
// second reads its (trigger-cleared) suggestion as gone instead of racing.
|
||||
for (const transactionId of transactionIds) {
|
||||
const tx = await fetchSuggestionRow(supabase, companyId, transactionId)
|
||||
if (!tx) {
|
||||
result.skipped.push({ transactionId, reason: 'not_found' })
|
||||
continue
|
||||
}
|
||||
if (tx.journal_entry_id) {
|
||||
result.skipped.push({ transactionId, reason: 'already_linked' })
|
||||
continue
|
||||
}
|
||||
if (!tx.potential_journal_entry_id) {
|
||||
result.skipped.push({ transactionId, reason: 'no_suggestion' })
|
||||
continue
|
||||
}
|
||||
|
||||
// Explicit consumption check on top of the invalidation trigger: a
|
||||
// verifikat another transaction already settles is not offered twice.
|
||||
// (manualLink deliberately allows N:1 for the manual instalments case;
|
||||
// bulk-confirming a suggestion is not that case.)
|
||||
const { data: consumers } = await supabase
|
||||
.from('transactions')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('journal_entry_id', tx.potential_journal_entry_id)
|
||||
.limit(1)
|
||||
if (consumers && consumers.length > 0) {
|
||||
result.skipped.push({ transactionId, reason: 'voucher_consumed' })
|
||||
continue
|
||||
}
|
||||
|
||||
const accountNumber = await resolveSettlementAccount(supabase, companyId, tx.cash_account_id)
|
||||
|
||||
// Amount/direction revalidation: a suggestion is a snapshot, and the
|
||||
// voucher's bank leg can legally change after it was computed (inline
|
||||
// rattelse strike-and-replace keeps status 'posted', so no invalidation
|
||||
// trigger fires). Never link on a stale snapshot.
|
||||
const amountProblem = await verifySuggestedAmount(supabase, tx, accountNumber)
|
||||
if (amountProblem) {
|
||||
result.skipped.push({ transactionId, reason: 'amount_mismatch', message: amountProblem })
|
||||
continue
|
||||
}
|
||||
|
||||
const linkResult = await manualLink(
|
||||
supabase,
|
||||
companyId,
|
||||
transactionId,
|
||||
tx.potential_journal_entry_id,
|
||||
userId,
|
||||
accountNumber,
|
||||
)
|
||||
if (!linkResult.success) {
|
||||
result.skipped.push({
|
||||
transactionId,
|
||||
reason: 'link_failed',
|
||||
message: linkResult.error,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
result.confirmed.push(transactionId)
|
||||
// Awaited: on serverless an unawaited promise can be frozen when the
|
||||
// response returns, silently dropping the audit row. logMatchEvent itself
|
||||
// never throws.
|
||||
await logMatchEvent(supabase, userId, transactionId, 'linked_to_existing_voucher', {
|
||||
matchMethod: tx.potential_match_method ?? undefined,
|
||||
matchConfidence:
|
||||
tx.potential_match_confidence !== null
|
||||
? Number(tx.potential_match_confidence)
|
||||
: undefined,
|
||||
newState: {
|
||||
journal_entry_id: tx.potential_journal_entry_id,
|
||||
reconciliation_method: 'manual',
|
||||
confirmed_suggestion: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function rejectJournalEntrySuggestions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
transactionIds: string[],
|
||||
): Promise<SuggestionActionResult> {
|
||||
const result: SuggestionActionResult = { confirmed: [], rejected: [], skipped: [] }
|
||||
|
||||
for (const transactionId of transactionIds) {
|
||||
const tx = await fetchSuggestionRow(supabase, companyId, transactionId)
|
||||
if (!tx) {
|
||||
result.skipped.push({ transactionId, reason: 'not_found' })
|
||||
continue
|
||||
}
|
||||
if (!tx.potential_journal_entry_id) {
|
||||
result.skipped.push({ transactionId, reason: 'no_suggestion' })
|
||||
continue
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from('transactions')
|
||||
.update({
|
||||
potential_journal_entry_id: null,
|
||||
potential_match_method: null,
|
||||
potential_match_confidence: null,
|
||||
})
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (error) {
|
||||
result.skipped.push({ transactionId, reason: 'link_failed', message: error.message })
|
||||
continue
|
||||
}
|
||||
|
||||
result.rejected.push(transactionId)
|
||||
await logMatchEvent(supabase, userId, transactionId, 'suggestion_cleared', {
|
||||
previousState: {
|
||||
potential_journal_entry_id: tx.potential_journal_entry_id,
|
||||
potential_match_method: tx.potential_match_method,
|
||||
potential_match_confidence: tx.potential_match_confidence,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
runReconciliation,
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
type ReconciliationOptions,
|
||||
} from './bank-reconciliation'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('reconciliation.unattended-sweep')
|
||||
|
||||
/** Per-account outcome of one unattended sweep. */
|
||||
export interface SweepAccountResult {
|
||||
/** null on the legacy fallback run for companies with no cash_accounts rows. */
|
||||
cashAccountId: string | null
|
||||
accountNumber: string
|
||||
currency: string
|
||||
/** Matches auto-linked at or above the unattended confidence floor. */
|
||||
applied: number
|
||||
/** Apply failures (optimistic-lock conflicts, DB errors) plus a whole-account
|
||||
* run failure, which counts as 1 without aborting the other accounts. */
|
||||
errors: number
|
||||
/** Matches proposed below the floor: candidate suggestions for human review. */
|
||||
skippedBelowThreshold: number
|
||||
/** Below-floor matches persisted onto potential_journal_entry_id. */
|
||||
suggested: number
|
||||
/** Unmatched transactions the run considered on this account. */
|
||||
candidates: number
|
||||
/** Total matches the matcher proposed for this account. */
|
||||
proposed: number
|
||||
}
|
||||
|
||||
export interface UnattendedSweepResult {
|
||||
accounts: SweepAccountResult[]
|
||||
applied: number
|
||||
errors: number
|
||||
skippedBelowThreshold: number
|
||||
suggested: number
|
||||
/** Candidate transactions the sweep left neither linked nor suggested. */
|
||||
unmatched: number
|
||||
}
|
||||
|
||||
export interface UnattendedSweepOptions {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
/**
|
||||
* Confidence floor for auto-apply. Defaults to
|
||||
* DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD: these sweeps run with nobody
|
||||
* reviewing a dry-run first, so fuzzy / date-range matches must never be
|
||||
* committed automatically.
|
||||
*/
|
||||
confidenceThreshold?: number
|
||||
/**
|
||||
* Persist the below-floor band as reviewable suggestions (default true:
|
||||
* every unattended caller feeds the "Granska migrerad historik" surface).
|
||||
*/
|
||||
persistSuggestions?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The JSONB stamped on bank_connections.last_sie_sweep /
|
||||
* bank_file_imports.sie_sweep so the UI can render the sweep outcome without
|
||||
* recomputing. snake_case: it lives in the DB and crosses the API boundary.
|
||||
*/
|
||||
export interface SieSweepSummary {
|
||||
auto_linked: number
|
||||
suggested: number
|
||||
unmatched: number
|
||||
/**
|
||||
* Apply/run failures across the sweep. NOT decoration: a whole-account run
|
||||
* that threw contributes 0 candidates, so its transactions are absent from
|
||||
* `unmatched` too. errors > 0 means the other three numbers describe an
|
||||
* INCOMPLETE sweep, and any UI reading this summary must not present it as
|
||||
* "all done".
|
||||
*/
|
||||
errors: number
|
||||
date_from: string | null
|
||||
date_to: string | null
|
||||
ran_at: string
|
||||
}
|
||||
|
||||
export function toSweepSummary(
|
||||
result: UnattendedSweepResult,
|
||||
options: { dateFrom?: string; dateTo?: string } = {},
|
||||
): SieSweepSummary {
|
||||
return {
|
||||
auto_linked: result.applied,
|
||||
suggested: result.suggested,
|
||||
unmatched: result.unmatched,
|
||||
errors: result.errors,
|
||||
date_from: options.dateFrom ?? null,
|
||||
date_to: options.dateTo ?? null,
|
||||
ran_at: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the unattended post-sync reconciliation sweep once per cash account
|
||||
* instead of once per company (issue #1298).
|
||||
*
|
||||
* The pooled form (`runReconciliation` with no cashAccountId) filtered the
|
||||
* transaction side by currency alone while the GL side stayed on '1930', so a
|
||||
* company with two same-currency accounts (checking 1930 + savings 1931) could
|
||||
* auto-link a savings transaction to an unlinked 1930 voucher and persist a
|
||||
* wrong journal_entry_id. Only a log warning guarded it
|
||||
* (warnIfUnscopedAcrossCashAccounts). Here every enabled cash account gets its
|
||||
* own scoped run: its BAS code on the GL side, its cash_account_id on the
|
||||
* transaction side, and NULL-cash_account_id rows claimed only by the primary
|
||||
* account (same rule as Bankavstamning).
|
||||
*
|
||||
* Companies with no cash_accounts rows at all keep the legacy single
|
||||
* 1930/SEK run: with no rows there is no per-account scope to apply, and
|
||||
* scopeTransactionsToAccount's currency-only path is the supported mode there.
|
||||
*
|
||||
* One account's run failing (thrown) is counted as one error on that account
|
||||
* and the sweep continues: an unattended sweep must not let one broken account
|
||||
* block matching on the others. The initial cash_accounts lookup failing throws
|
||||
* instead: silently degrading to the pooled run would re-create exactly the
|
||||
* cross-linking this helper exists to remove (same fail-closed contract as
|
||||
* resolveCashAccountScope).
|
||||
*/
|
||||
export async function runUnattendedReconciliationSweep(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
options: UnattendedSweepOptions = {},
|
||||
): Promise<UnattendedSweepResult> {
|
||||
const { dateFrom, dateTo, persistSuggestions = true } = options
|
||||
const confidenceThreshold =
|
||||
options.confidenceThreshold ?? DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD
|
||||
|
||||
const { data: cashAccounts, error } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, ledger_account, currency, is_primary')
|
||||
.eq('company_id', companyId)
|
||||
.eq('enabled', true)
|
||||
.order('ledger_account')
|
||||
|
||||
if (error) {
|
||||
throw new Error('Kunde inte hämta kassakonton för avstämningssvepet')
|
||||
}
|
||||
|
||||
type Scope = {
|
||||
cashAccountId: string | null
|
||||
accountNumber: string
|
||||
currency: string
|
||||
includeUnassigned: boolean
|
||||
}
|
||||
|
||||
const rows = (cashAccounts ?? []) as Array<{
|
||||
id: string
|
||||
ledger_account: string
|
||||
currency: string | null
|
||||
is_primary: boolean | null
|
||||
}>
|
||||
|
||||
const scopes: Scope[] =
|
||||
rows.length > 0
|
||||
? rows.map((row) => ({
|
||||
cashAccountId: row.id,
|
||||
accountNumber: row.ledger_account,
|
||||
currency: row.currency ?? 'SEK',
|
||||
includeUnassigned: Boolean(row.is_primary),
|
||||
}))
|
||||
: [
|
||||
{
|
||||
cashAccountId: null,
|
||||
accountNumber: '1930',
|
||||
currency: 'SEK',
|
||||
includeUnassigned: true,
|
||||
},
|
||||
]
|
||||
|
||||
const accounts: SweepAccountResult[] = []
|
||||
|
||||
for (const scope of scopes) {
|
||||
const runOptions: ReconciliationOptions = {
|
||||
dateFrom,
|
||||
dateTo,
|
||||
accountNumber: scope.accountNumber,
|
||||
currency: scope.currency,
|
||||
cashAccountId: scope.cashAccountId ?? undefined,
|
||||
includeUnassigned: scope.includeUnassigned,
|
||||
confidenceThreshold,
|
||||
persistSuggestions,
|
||||
}
|
||||
try {
|
||||
const result = await runReconciliation(supabase, companyId, userId, runOptions)
|
||||
accounts.push({
|
||||
cashAccountId: scope.cashAccountId,
|
||||
accountNumber: scope.accountNumber,
|
||||
currency: scope.currency,
|
||||
applied: result.applied,
|
||||
errors: result.errors,
|
||||
skippedBelowThreshold: result.skippedBelowThreshold,
|
||||
suggested: result.suggested,
|
||||
candidates: result.candidates,
|
||||
proposed: result.matches.length,
|
||||
})
|
||||
} catch (err) {
|
||||
log.warn('per-account sweep run failed; continuing with remaining accounts', {
|
||||
companyId,
|
||||
entityType: 'cash_account',
|
||||
details: {
|
||||
accountNumber: scope.accountNumber,
|
||||
cashAccountId: scope.cashAccountId,
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
})
|
||||
accounts.push({
|
||||
cashAccountId: scope.cashAccountId,
|
||||
accountNumber: scope.accountNumber,
|
||||
currency: scope.currency,
|
||||
applied: 0,
|
||||
errors: 1,
|
||||
skippedBelowThreshold: 0,
|
||||
suggested: 0,
|
||||
candidates: 0,
|
||||
proposed: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const applied = accounts.reduce((sum, a) => sum + a.applied, 0)
|
||||
const suggested = accounts.reduce((sum, a) => sum + a.suggested, 0)
|
||||
const candidates = accounts.reduce((sum, a) => sum + a.candidates, 0)
|
||||
|
||||
return {
|
||||
accounts,
|
||||
applied,
|
||||
errors: accounts.reduce((sum, a) => sum + a.errors, 0),
|
||||
skippedBelowThreshold: accounts.reduce((sum, a) => sum + a.skippedBelowThreshold, 0),
|
||||
suggested,
|
||||
unmatched: Math.max(0, candidates - applied - suggested),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user