Merge remote-tracking branch 'origin/main' into code-quality-improvements

This commit is contained in:
Emil
2026-02-21 16:10:02 +01:00
121 changed files with 12004 additions and 1899 deletions
+126
View File
@@ -30,6 +30,13 @@ vi.mock('@/lib/invoices/invoice-matching', () => ({
getBestInvoiceMatch: (...args: unknown[]) => mockGetBestInvoiceMatch(...args),
}))
const mockTryReconcileTransaction = vi.fn()
const mockFetchUnlinkedGLLines = vi.fn()
vi.mock('@/lib/reconciliation/bank-reconciliation', () => ({
tryReconcileTransaction: (...args: unknown[]) => mockTryReconcileTransaction(...args),
fetchUnlinkedGLLines: (...args: unknown[]) => mockFetchUnlinkedGLLines(...args),
}))
// ---------------------------------------------------------------------------
// Queue-based Supabase mock
// ---------------------------------------------------------------------------
@@ -112,6 +119,9 @@ function makeMappingResult(overrides: Record<string, unknown> = {}) {
describe('ingestTransactions', () => {
beforeEach(() => {
vi.clearAllMocks()
// Default: no GL lines for reconciliation
mockFetchUnlinkedGLLines.mockResolvedValue([])
mockTryReconcileTransaction.mockReturnValue(null)
})
// -----------------------------------------------------------------------
@@ -426,6 +436,7 @@ describe('ingestTransactions', () => {
expect(result).toEqual({
imported: 0,
duplicates: 0,
reconciled: 0,
auto_categorized: 0,
auto_matched_invoices: 0,
errors: 0,
@@ -474,4 +485,119 @@ describe('ingestTransactions', () => {
expect(result.auto_categorized).toBe(0)
expect(result.errors).toBe(0)
})
// -----------------------------------------------------------------------
// Reconciliation: matched transactions skip auto-categorization
// -----------------------------------------------------------------------
it('reconciles transactions against GL lines and skips auto-categorization', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const raw = makeRaw({ amount: -500, external_id: 'ext-recon' })
const inserted = makeTransaction({
id: 'tx-recon',
amount: -500,
external_id: 'ext-recon',
currency: 'SEK',
})
const glLine = {
line_id: 'line-1',
journal_entry_id: 'je-1',
debit_amount: 0,
credit_amount: 500,
line_description: null,
entry_date: '2024-06-15',
voucher_number: 1,
voucher_series: 'A',
entry_description: 'Test entry',
source_type: 'import',
}
// Pre-fetch returns GL lines
mockFetchUnlinkedGLLines.mockResolvedValue([glLine])
// tryReconcileTransaction returns a match
mockTryReconcileTransaction.mockReturnValue({
transaction: inserted,
glLine,
method: 'auto_exact',
confidence: 0.95,
})
// Dedup: no duplicate
enqueue({ data: null, error: null })
// Insert
enqueue({ data: inserted, error: null })
// Reconciliation update
enqueue({ data: null, error: null })
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
expect(result.imported).toBe(1)
expect(result.reconciled).toBe(1)
// Should NOT have attempted auto-categorization
expect(mockEvaluateMappingRules).not.toHaveBeenCalled()
expect(mockGetBestInvoiceMatch).not.toHaveBeenCalled()
})
// -----------------------------------------------------------------------
// Reconciliation: falls through when no GL matches
// -----------------------------------------------------------------------
it('falls through to auto-categorization when reconciliation finds no match', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const raw = makeRaw({ amount: -200 })
const inserted = makeTransaction({ id: 'tx-no-recon', amount: -200 })
mockFetchUnlinkedGLLines.mockResolvedValue([
{
line_id: 'line-other',
journal_entry_id: 'je-other',
debit_amount: 999,
credit_amount: 0,
entry_date: '2024-01-01',
voucher_number: 1,
voucher_series: 'A',
entry_description: 'Unrelated',
source_type: 'import',
line_description: null,
},
])
mockTryReconcileTransaction.mockReturnValue(null)
// Dedup: no duplicate
enqueue({ data: null, error: null })
// Insert
enqueue({ data: inserted, error: null })
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
expect(result.imported).toBe(1)
expect(result.reconciled).toBe(0)
// Should have fallen through to auto-categorization
expect(mockEvaluateMappingRules).toHaveBeenCalled()
})
// -----------------------------------------------------------------------
// Reconciliation: error is non-critical
// -----------------------------------------------------------------------
it('continues when reconciliation throws an error', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const raw = makeRaw({ amount: -300 })
const inserted = makeTransaction({ id: 'tx-recon-err', amount: -300 })
mockFetchUnlinkedGLLines.mockRejectedValue(new Error('RPC error'))
// Dedup: no duplicate
enqueue({ data: null, error: null })
// Insert
enqueue({ data: inserted, error: null })
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
expect(result.imported).toBe(1)
expect(result.reconciled).toBe(0)
expect(result.errors).toBe(0)
})
})
+36
View File
@@ -2,6 +2,8 @@ import type { SupabaseClient } from '@supabase/supabase-js'
import { evaluateMappingRules } from '@/lib/bookkeeping/mapping-engine'
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
import { getBestInvoiceMatch } from '@/lib/invoices/invoice-matching'
import { tryReconcileTransaction, fetchUnlinkedGLLines } from '@/lib/reconciliation/bank-reconciliation'
import type { UnlinkedGLLine } from '@/lib/reconciliation/bank-reconciliation'
import type { Transaction } from '@/types'
/**
@@ -24,6 +26,7 @@ export interface RawTransaction {
export interface IngestResult {
imported: number
duplicates: number
reconciled: number
auto_categorized: number
auto_matched_invoices: number
errors: number
@@ -51,12 +54,21 @@ export async function ingestTransactions(
const result: IngestResult = {
imported: 0,
duplicates: 0,
reconciled: 0,
auto_categorized: 0,
auto_matched_invoices: 0,
errors: 0,
transaction_ids: [],
}
// Pre-fetch unlinked GL lines for reconciliation (non-critical)
let glLinePool: UnlinkedGLLine[] = []
try {
glLinePool = await fetchUnlinkedGLLines(supabase, userId)
} catch {
// Non-critical — reconciliation will be skipped
}
for (const raw of rawTransactions) {
// 1. Check for duplicates via external_id
const { data: existing } = await supabase
@@ -100,6 +112,30 @@ export async function ingestTransactions(
result.imported++
result.transaction_ids.push(newTransaction.id)
// 2.5. Try reconciliation against pre-fetched unlinked GL lines
if (glLinePool.length > 0) {
try {
const match = tryReconcileTransaction(newTransaction as Transaction, glLinePool)
if (match) {
await supabase
.from('transactions')
.update({
journal_entry_id: match.glLine.journal_entry_id,
reconciliation_method: match.method,
is_business: true,
})
.eq('id', newTransaction.id)
// Remove matched GL line from pool to prevent double-matching
glLinePool = glLinePool.filter((l) => l.line_id !== match.glLine.line_id)
result.reconciled++
continue // Skip invoice matching and auto-categorization
}
} catch {
// Non-critical — fall through to normal flow
}
}
// 3. For income transactions, try invoice matching
if (newTransaction.amount > 0) {
try {