Feat/verification attachments (#371)
* feat(attachments): enhance document preview functionality for images and PDFs * feat(reconciliation): enhance transaction matching logic and clarify reconciliation process
This commit is contained in:
@@ -28,13 +28,6 @@ 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
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -125,9 +118,6 @@ function makeMappingResult(overrides: Record<string, unknown> = {}) {
|
||||
describe('ingestTransactions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// Default: no GL lines for reconciliation
|
||||
mockFetchUnlinkedGLLines.mockResolvedValue([])
|
||||
mockTryReconcileTransaction.mockReturnValue(null)
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -571,9 +561,12 @@ describe('ingestTransactions', () => {
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Reconciliation: matched transactions skip auto-categorization
|
||||
// Imports never auto-link to existing journal entries.
|
||||
// Reconciliation must be an explicit user action (manualLink / runReconciliation).
|
||||
// Regression: viktor@frnzn.com — bank txns from 2026 were silently linked
|
||||
// to SIE-imported vouchers, surfacing them as "bokförda" without action.
|
||||
// -----------------------------------------------------------------------
|
||||
it('reconciles transactions against GL lines and skips auto-categorization', async () => {
|
||||
it('never auto-reconciles imported transactions to existing GL lines', async () => {
|
||||
const { supabase, enqueue } = createQueueMockSupabase()
|
||||
const raw = makeRaw({ amount: -500, external_id: 'ext-recon' })
|
||||
const inserted = makeTransaction({
|
||||
@@ -583,75 +576,6 @@ describe('ingestTransactions', () => {
|
||||
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,
|
||||
})
|
||||
|
||||
// Booked transaction map query
|
||||
enqueue({ data: [], error: null })
|
||||
// Unbooked bank-synced transaction map query
|
||||
enqueue({ data: [], error: null })
|
||||
// Supplier invoices fetch
|
||||
enqueue({ data: [], error: null })
|
||||
// Batch external_id dedup query (no matches)
|
||||
enqueue({ data: [], error: null })
|
||||
// Insert
|
||||
enqueue({ data: inserted, error: null })
|
||||
// Reconciliation update
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, 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)
|
||||
|
||||
// Booked transaction map query
|
||||
enqueue({ data: [], error: null })
|
||||
// Unbooked bank-synced transaction map query
|
||||
@@ -669,38 +593,6 @@ describe('ingestTransactions', () => {
|
||||
|
||||
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'))
|
||||
|
||||
// Booked transaction map query
|
||||
enqueue({ data: [], error: null })
|
||||
// Unbooked bank-synced transaction map query
|
||||
enqueue({ data: [], error: null })
|
||||
// Supplier invoices fetch
|
||||
enqueue({ data: [], error: null })
|
||||
// Batch external_id dedup query (no matches)
|
||||
enqueue({ data: [], error: null })
|
||||
// Insert
|
||||
enqueue({ data: inserted, error: null })
|
||||
|
||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||
|
||||
const result = await ingestTransactions(supabase as never, COMPANY_ID, USER_ID, [raw])
|
||||
|
||||
expect(result.imported).toBe(1)
|
||||
expect(result.reconciled).toBe(0)
|
||||
expect(result.errors).toBe(0)
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -735,8 +627,6 @@ describe('ingestTransactions', () => {
|
||||
expect(result.auto_categorized).toBe(0)
|
||||
expect(result.auto_matched_invoices).toBe(0)
|
||||
// Should NOT have attempted any post-insert operations
|
||||
expect(mockFetchUnlinkedGLLines).not.toHaveBeenCalled()
|
||||
expect(mockTryReconcileTransaction).not.toHaveBeenCalled()
|
||||
expect(mockGetBestInvoiceMatch).not.toHaveBeenCalled()
|
||||
expect(mockEvaluateMappingRules).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
+14
-42
@@ -1,14 +1,13 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { evaluateMappingRules } from '@/lib/bookkeeping/mapping-engine'
|
||||
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { isAutoBookEnabled } from '@/lib/ai/feature-flag'
|
||||
import { upsertCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { getBestInvoiceMatch } from '@/lib/invoices/invoice-matching'
|
||||
import { findSupplierInvoiceMatch } from '@/lib/invoices/supplier-invoice-matching'
|
||||
import { tryReconcileTransaction, fetchUnlinkedGLLines } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { fetchMultipleRates } from '@/lib/currency/riksbanken'
|
||||
import { logMatchEvent } from '@/lib/invoices/match-log'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import type { UnlinkedGLLine } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import type { Transaction, RawTransaction, IngestResult, IngestOptions, SupplierInvoice, Currency, ExchangeRate } from '@/types'
|
||||
|
||||
// Re-export types for backward compatibility
|
||||
@@ -142,20 +141,12 @@ export async function ingestTransactions(
|
||||
return aiFlowEnabledCache
|
||||
}
|
||||
|
||||
// When rawInsertOnly is set (viewer imports), skip pre-fetching GL lines,
|
||||
// supplier invoices, and exchange rates — they are not used.
|
||||
let glLinePool: UnlinkedGLLine[] = []
|
||||
// When rawInsertOnly is set (viewer imports), skip pre-fetching supplier
|
||||
// invoices and exchange rates — they are not used.
|
||||
let unpaidSupplierInvoices: SupplierInvoice[] = []
|
||||
let exchangeRates = new Map<Currency, ExchangeRate>()
|
||||
|
||||
if (!options?.rawInsertOnly) {
|
||||
// Pre-fetch unlinked GL lines for reconciliation (non-critical)
|
||||
try {
|
||||
glLinePool = await fetchUnlinkedGLLines(supabase, companyId, undefined, undefined, options?.settlementAccount)
|
||||
} catch {
|
||||
// Non-critical — reconciliation will be skipped
|
||||
}
|
||||
|
||||
// Pre-fetch unpaid supplier invoices for expense matching (non-critical)
|
||||
try {
|
||||
unpaidSupplierInvoices = await fetchAllRows<SupplierInvoice>(({ from, to }) =>
|
||||
@@ -275,32 +266,13 @@ export async function ingestTransactions(
|
||||
result.imported++
|
||||
result.transaction_ids.push(newTransaction.id)
|
||||
|
||||
// rawInsertOnly: skip reconciliation, invoice matching, and auto-categorization
|
||||
// rawInsertOnly: skip invoice matching, and auto-categorization
|
||||
if (options?.rawInsertOnly) continue
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
// Reconciliation against existing GL lines is intentionally NOT run on
|
||||
// import — auto-linking made imported transactions appear "bokförda" to
|
||||
// the user without any explicit action. Reconciliation is now a manual
|
||||
// operation (BankReconciliationView / runReconciliation / manualLink).
|
||||
|
||||
// 3. For income transactions, try invoice matching
|
||||
if (newTransaction.amount > 0) {
|
||||
@@ -391,12 +363,12 @@ export async function ingestTransactions(
|
||||
}
|
||||
|
||||
// 4. Evaluate mapping rules for auto-categorization
|
||||
// Skipped when SIE-imported entries overlap the sync range — prevents
|
||||
// double-booking. Reconciliation (step 2.5) still links transactions to
|
||||
// existing GL lines; only the "create new journal entry" path is suppressed.
|
||||
// Also skipped when the company has opted into the AI agent flow — every
|
||||
// uncategorized transaction must become a proposal, not a silent post.
|
||||
if (!options?.skipAutoCategorization && !(await isAiFlowEnabled())) {
|
||||
// Production-disabled: auto-booking only runs in local dev (isAutoBookEnabled).
|
||||
// Users must explicitly book each transaction on the deployed app.
|
||||
// Also skipped when the company has opted into the AI agent flow (proposals)
|
||||
// and when SIE-imported entries overlap the sync range (prevents double-book).
|
||||
// Reconciliation (step 2.5) still links transactions to existing GL lines.
|
||||
if (isAutoBookEnabled() && !options?.skipAutoCategorization && !(await isAiFlowEnabled())) {
|
||||
try {
|
||||
const mappingResult = await evaluateMappingRules(
|
||||
supabase,
|
||||
|
||||
Reference in New Issue
Block a user