feat: unified document inbox, full BAS 2026, and document-transaction matching
- Expand BAS reference from ~180 to ~1,276 accounts (full BAS Kontoplan 2026) with K2 exclusion flags, per-class data files, and computed SRU codes - Evolve invoice inbox into unified document inbox handling invoices, receipts, and government letters with AI-powered classification (Claude Haiku Vision) - Add multi-pass document-to-transaction matching engine with greedy assignment for both supplier invoices (reference/amount/date/name) and receipts (weighted amount/merchant/date scoring) - Add supplier invoice matching in transaction ingest pipeline - Inject booking template suggestions into AI extraction prompts - Surface matched documents in swipe categorization UI with one-tap booking - Auto-activate missing BAS accounts during SIE import against full reference - Add K2 filter toggle in Chart of Accounts manager - Add receipt confirmation route with BFNAR representation fields - Add database migrations for K2 support and document matching columns - Remove obsolete extension migration scripts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
6956a757f3
commit
39e407644d
@@ -0,0 +1,197 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { findSupplierInvoiceMatch } from '../supplier-invoice-matching'
|
||||
import { makeTransaction, makeSupplierInvoice, makeSupplier } from '@/tests/helpers'
|
||||
|
||||
describe('findSupplierInvoiceMatch', () => {
|
||||
const supplier = makeSupplier({
|
||||
name: 'Kontorsbolaget AB',
|
||||
bankgiro: '123-4567',
|
||||
plusgiro: '987654-3',
|
||||
})
|
||||
|
||||
it('returns null for empty invoice list', () => {
|
||||
const tx = makeTransaction({ amount: -1000 })
|
||||
expect(findSupplierInvoiceMatch(tx, [])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for zero-amount transactions', () => {
|
||||
const tx = makeTransaction({ amount: 0 })
|
||||
const inv = makeSupplierInvoice({ status: 'registered', remaining_amount: 1000 })
|
||||
expect(findSupplierInvoiceMatch(tx, [inv])).toBeNull()
|
||||
})
|
||||
|
||||
it('skips paid invoices (remaining_amount = 0)', () => {
|
||||
const tx = makeTransaction({ amount: -1000, reference: '12345' })
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 0,
|
||||
payment_reference: '12345',
|
||||
})
|
||||
expect(findSupplierInvoiceMatch(tx, [inv])).toBeNull()
|
||||
})
|
||||
|
||||
it('skips invoices with non-matching status', () => {
|
||||
const tx = makeTransaction({ amount: -1000, reference: '12345' })
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'paid',
|
||||
remaining_amount: 1000,
|
||||
payment_reference: '12345',
|
||||
})
|
||||
expect(findSupplierInvoiceMatch(tx, [inv])).toBeNull()
|
||||
})
|
||||
|
||||
// Pass 1: Payment reference
|
||||
it('matches by payment reference with confidence 0.98', () => {
|
||||
const tx = makeTransaction({ amount: -5000, reference: '73100 12345 67890' })
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 5000,
|
||||
payment_reference: '731001234567890',
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.98)
|
||||
expect(result!.matchMethod).toBe('payment_reference')
|
||||
})
|
||||
|
||||
// Pass 2: Amount + bankgiro
|
||||
it('matches by exact amount + bankgiro in description with confidence 0.92', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -10000,
|
||||
description: 'Betalning BG 1234567 Kontorsbolaget',
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'approved',
|
||||
remaining_amount: 10000,
|
||||
supplier: { ...supplier, bankgiro: '123-4567' },
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.92)
|
||||
expect(result!.matchMethod).toBe('amount_bankgiro')
|
||||
})
|
||||
|
||||
// Pass 3: Amount + date
|
||||
it('matches by exact amount + due date within 5 days with confidence 0.85', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -10000,
|
||||
date: '2024-07-03', // 2 days after due date
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 10000,
|
||||
due_date: '2024-07-01',
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.85)
|
||||
expect(result!.matchMethod).toBe('amount_date')
|
||||
})
|
||||
|
||||
it('does not match when date difference exceeds 5 days', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -10000,
|
||||
date: '2024-07-10', // 9 days after due date
|
||||
description: 'random payment',
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 10000,
|
||||
due_date: '2024-07-01',
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
// Pass 4: Fuzzy amount + name
|
||||
it('matches by fuzzy amount + supplier name in description with confidence 0.70', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -10000,
|
||||
description: 'Betalning Kontorsbolaget',
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 10000,
|
||||
due_date: '2024-01-01', // far away date — won't match pass 3
|
||||
supplier: { ...supplier, name: 'Kontorsbolaget AB' },
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.70)
|
||||
expect(result!.matchMethod).toBe('fuzzy_name')
|
||||
})
|
||||
|
||||
it('prefers higher-confidence matches', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -5000,
|
||||
date: '2024-07-02',
|
||||
reference: '999888777',
|
||||
})
|
||||
|
||||
const invoiceRef = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 5000,
|
||||
payment_reference: '999888777',
|
||||
due_date: '2024-07-01',
|
||||
})
|
||||
|
||||
const invoiceDate = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 5000,
|
||||
due_date: '2024-07-01',
|
||||
})
|
||||
|
||||
// Payment reference match should win (0.98 > 0.85)
|
||||
const result = findSupplierInvoiceMatch(tx, [invoiceDate, invoiceRef])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.98)
|
||||
expect(result!.matchMethod).toBe('payment_reference')
|
||||
})
|
||||
|
||||
it('handles öresavrundning (±0.01 fuzzy)', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -999.99,
|
||||
description: 'Betalning Kontorsbolaget faktura',
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 1000,
|
||||
due_date: '2024-01-01',
|
||||
supplier: { ...supplier, name: 'Kontorsbolaget AB' },
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.confidence).toBe(0.70)
|
||||
})
|
||||
|
||||
it('ignores short words when matching supplier name', () => {
|
||||
const tx = makeTransaction({
|
||||
amount: -5000,
|
||||
description: 'AB payment', // "AB" is only 2 chars, should be ignored
|
||||
})
|
||||
const inv = makeSupplierInvoice({
|
||||
status: 'registered',
|
||||
remaining_amount: 5000,
|
||||
due_date: '2024-01-01',
|
||||
supplier: { ...supplier, name: 'AB' },
|
||||
})
|
||||
|
||||
const result = findSupplierInvoiceMatch(tx, [inv])
|
||||
|
||||
// "AB" is filtered out (length < 3), so no name match
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Supplier Invoice Matching — auto-match expense transactions to unpaid supplier invoices.
|
||||
*
|
||||
* 4-pass matching algorithm (ordered by confidence):
|
||||
* 1. Payment reference/OCR exact match → 0.98
|
||||
* 2. Exact amount + bankgiro/plusgiro match → 0.92
|
||||
* 3. Exact amount + date ±5 days → 0.85
|
||||
* 4. Fuzzy amount (±0.01) + supplier name in description → 0.70
|
||||
*
|
||||
* Auto-match threshold: ≥0.85 → applied automatically
|
||||
* Suggestion threshold: 0.70–0.85 → stored as potential_supplier_invoice_id
|
||||
*/
|
||||
|
||||
import type { Transaction, SupplierInvoice } from '@/types'
|
||||
|
||||
export interface SupplierInvoiceMatch {
|
||||
supplierInvoice: SupplierInvoice
|
||||
confidence: number
|
||||
matchMethod: 'payment_reference' | 'amount_bankgiro' | 'amount_date' | 'fuzzy_name'
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize payment reference for comparison (strip whitespace and non-digits).
|
||||
*/
|
||||
function normalizeReference(ref: string): string {
|
||||
return ref.replace(/\D/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the best matching supplier invoice for an expense transaction.
|
||||
* Expects invoices to have the `supplier` relation populated (for name/bankgiro matching).
|
||||
* Only matches against invoices with status 'registered' or 'approved'
|
||||
* and with remaining_amount > 0.
|
||||
*/
|
||||
export function findSupplierInvoiceMatch(
|
||||
transaction: Transaction,
|
||||
unpaidInvoices: SupplierInvoice[]
|
||||
): SupplierInvoiceMatch | null {
|
||||
if (unpaidInvoices.length === 0) return null
|
||||
|
||||
// Only match expense transactions
|
||||
const txAmount = Math.abs(transaction.amount)
|
||||
if (txAmount === 0) return null
|
||||
|
||||
let bestMatch: SupplierInvoiceMatch | null = null
|
||||
|
||||
for (const invoice of unpaidInvoices) {
|
||||
// Only match against registered/approved invoices with remaining amount
|
||||
if (!['registered', 'approved'].includes(invoice.status)) continue
|
||||
const remaining = invoice.remaining_amount ?? invoice.total
|
||||
if (remaining <= 0) continue
|
||||
|
||||
// Pass 1: Payment reference/OCR exact match → 0.98
|
||||
if (transaction.reference && invoice.payment_reference) {
|
||||
const txRef = normalizeReference(transaction.reference)
|
||||
const invRef = normalizeReference(invoice.payment_reference)
|
||||
if (txRef && invRef && txRef === invRef) {
|
||||
return {
|
||||
supplierInvoice: invoice,
|
||||
confidence: 0.98,
|
||||
matchMethod: 'payment_reference',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: Exact amount + bankgiro/plusgiro match → 0.92
|
||||
const amountMatch = Math.abs(txAmount - remaining) < 0.005
|
||||
if (amountMatch) {
|
||||
const txDesc = (transaction.description || '').toLowerCase()
|
||||
const supplierBg = invoice.supplier?.bankgiro
|
||||
const supplierPg = invoice.supplier?.plusgiro
|
||||
const bgMatch = supplierBg && txDesc.includes(normalizeReference(supplierBg))
|
||||
const pgMatch = supplierPg && txDesc.includes(normalizeReference(supplierPg))
|
||||
|
||||
if (bgMatch || pgMatch) {
|
||||
return {
|
||||
supplierInvoice: invoice,
|
||||
confidence: 0.92,
|
||||
matchMethod: 'amount_bankgiro',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 3: Exact amount + date ±5 days → 0.85
|
||||
if (amountMatch && invoice.due_date) {
|
||||
const txDate = new Date(transaction.date)
|
||||
const dueDate = new Date(invoice.due_date)
|
||||
const diffDays = Math.abs((txDate.getTime() - dueDate.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
if (diffDays <= 5) {
|
||||
const confidence = 0.85
|
||||
if (!bestMatch || confidence > bestMatch.confidence) {
|
||||
bestMatch = {
|
||||
supplierInvoice: invoice,
|
||||
confidence,
|
||||
matchMethod: 'amount_date',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 4: Fuzzy amount (±0.01) + supplier name in description → 0.70
|
||||
const fuzzyAmountMatch = Math.abs(txAmount - remaining) <= 0.01
|
||||
const supplierName = invoice.supplier?.name
|
||||
if (fuzzyAmountMatch && supplierName) {
|
||||
const txDesc = (transaction.description || '').toLowerCase()
|
||||
const normalizedName = supplierName.toLowerCase()
|
||||
|
||||
// Check if any significant word from the supplier name appears in the description
|
||||
const nameWords = normalizedName
|
||||
.replace(/[^\w\såäöé]/g, '')
|
||||
.split(/\s+/)
|
||||
.filter((w) => w.length >= 3)
|
||||
|
||||
const nameInDesc = nameWords.some((word) => txDesc.includes(word))
|
||||
|
||||
if (nameInDesc) {
|
||||
const confidence = 0.70
|
||||
if (!bestMatch || confidence > bestMatch.confidence) {
|
||||
bestMatch = {
|
||||
supplierInvoice: invoice,
|
||||
confidence,
|
||||
matchMethod: 'fuzzy_name',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestMatch
|
||||
}
|
||||
Reference in New Issue
Block a user