Per-line VAT rates: - Add generatePerRateLines() to group invoice items by vat_rate with separate revenue + VAT lines per rate group (invoice-entries.ts) - Add getAvailableVatRates() and getVatTreatmentForRate() (vat-rules.ts) - PDF template shows per-line VAT column and per-rate totals for mixed-rate invoices - Invoice create/review UI supports per-line rate selection - Types: add vat_rate/vat_amount to InvoiceItem, vat_rate to CreateInvoiceItemInput Invoice document types (proforma, delivery note): - Add InvoiceDocumentType, document_type and converted_from_id to Invoice type - PDF hides prices for delivery notes, adds proforma notice - Email templates support all document types - mark-paid skips journal entries for non-invoice document types - Migration 031: invoice_document_type Accounting method support: - Add AccountingMethod type (accrual/cash) - Migration 032: add_accounting_method column to company_settings VAT declaration rewrite: - Rewrite to read directly from general ledger (26xx/3xxx account lines) instead of aggregating invoices/transactions/receipts - ACCOUNT_RUTA mapping drives momsdeklaration boxes from GL balances Bank reconciliation: - Transaction ingest now pre-fetches unlinked GL lines and attempts auto-reconciliation during import - Add transaction.reconciled event type - Add ReconciliationMethod type and reconciliation_method on Transaction - Migration 030: bank_reconciliation - New reconciliation engine, API routes, and BankReconciliationView component Pagination (fetchAllRows): - New lib/supabase/fetch-all.ts overcomes PostgREST 1000-row limit - Adopted in all report generators, SIE/SRU export, account list APIs Fiscal period validation: - New validate-period-duration.ts enforces max 18 months per BFL 3 kap. - Applied in period-service.ts and fiscal-periods API Account mapper simplification: - Remove Levenshtein/fuzzy matching, use exact account number match only Swedbank parser improvements: - Support abbreviated headers (Clnr, Bokfdag, Radnr) - Use Referens column as counterparty Chart of accounts management: - Add DELETE endpoint with system account and usage protection - PUT uses partial updates - New AccountCombobox, AddAccountDialog, EditAccountDialog, ChartOfAccountsManager Tax deadline corrections: - Rewrite inkomstdeklaration_ab using Skatteverket lookup table - Rewrite arsredovisning deadline to 7 months after FY end per ÅRL 8:3 Onboarding first fiscal year: - Add first fiscal year toggle with date pickers and 18-month validation UI terminology: - Change "okategoriserad/kategorisera" to "obokförd/bokföra" throughout Report column fix: - Fix start_date/end_date to period_start/period_end in report queries Supplier invoice input: - CreateSupplierInvoiceItemInput uses amount field (legacy quantity/unit_price kept) Misc: - SIE import uses upsert for idempotent account creation - account-descriptions.ts falls back to BAS reference data - Add invoice_default_notes to CompanySettings - Update CLAUDE.md to reflect current project state Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
196 lines
5.7 KiB
TypeScript
196 lines
5.7 KiB
TypeScript
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/invoice/invoice-matching'
|
|
import { tryReconcileTransaction, fetchUnlinkedGLLines } from '@/lib/reconciliation/bank-reconciliation'
|
|
import type { UnlinkedGLLine } from '@/lib/reconciliation/bank-reconciliation'
|
|
import type { Transaction } from '@/types'
|
|
|
|
/**
|
|
* Normalized transaction input for the generic ingestion pipeline.
|
|
* Both file import and PSD2 sync convert to this format before ingesting.
|
|
*/
|
|
export interface RawTransaction {
|
|
date: string
|
|
description: string
|
|
amount: number
|
|
currency: string
|
|
external_id: string // dedup key
|
|
mcc_code?: number | null
|
|
merchant_name?: string | null
|
|
reference?: string | null // OCR number, Bankgiro ref, etc.
|
|
bank_connection_id?: string | null
|
|
import_source?: string // 'csv_nordea', 'camt053', 'enable_banking', etc.
|
|
}
|
|
|
|
export interface IngestResult {
|
|
imported: number
|
|
duplicates: number
|
|
reconciled: number
|
|
auto_categorized: number
|
|
auto_matched_invoices: number
|
|
errors: number
|
|
transaction_ids: string[]
|
|
}
|
|
|
|
/**
|
|
* Generic transaction ingestion pipeline.
|
|
*
|
|
* Handles:
|
|
* 1. Deduplication via external_id
|
|
* 2. Insert into transactions table
|
|
* 3. OCR/reference-based invoice matching (highest confidence)
|
|
* 4. Amount+customer fallback invoice matching
|
|
* 5. Mapping rule evaluation for auto-categorization
|
|
* 6. Auto-journal-entry creation for high-confidence matches
|
|
*
|
|
* Used by both bank file import and Enable Banking PSD2 sync.
|
|
*/
|
|
export async function ingestTransactions(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
rawTransactions: RawTransaction[]
|
|
): Promise<IngestResult> {
|
|
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
|
|
.from('transactions')
|
|
.select('id')
|
|
.eq('user_id', userId)
|
|
.eq('external_id', raw.external_id)
|
|
.single()
|
|
|
|
if (existing) {
|
|
result.duplicates++
|
|
continue
|
|
}
|
|
|
|
// 2. Insert new transaction
|
|
const { data: newTransaction, error: insertError } = await supabase
|
|
.from('transactions')
|
|
.insert({
|
|
user_id: userId,
|
|
bank_connection_id: raw.bank_connection_id || null,
|
|
external_id: raw.external_id,
|
|
date: raw.date,
|
|
description: raw.description,
|
|
amount: raw.amount,
|
|
currency: raw.currency,
|
|
category: 'uncategorized',
|
|
is_business: null,
|
|
mcc_code: raw.mcc_code || null,
|
|
merchant_name: raw.merchant_name || null,
|
|
reference: raw.reference || null,
|
|
import_source: raw.import_source || null,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (insertError || !newTransaction) {
|
|
result.errors++
|
|
continue
|
|
}
|
|
|
|
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 {
|
|
// OCR/reference matching is handled inside getBestInvoiceMatch
|
|
// (which calls findMatchingInvoices, which now checks references)
|
|
const bestMatch = await getBestInvoiceMatch(
|
|
userId,
|
|
newTransaction as Transaction,
|
|
0.50
|
|
)
|
|
|
|
if (bestMatch) {
|
|
await supabase
|
|
.from('transactions')
|
|
.update({ potential_invoice_id: bestMatch.invoice.id })
|
|
.eq('id', newTransaction.id)
|
|
|
|
result.auto_matched_invoices++
|
|
}
|
|
} catch {
|
|
// Non-critical — continue processing
|
|
}
|
|
}
|
|
|
|
// 4. Evaluate mapping rules for auto-categorization
|
|
try {
|
|
const mappingResult = await evaluateMappingRules(
|
|
userId,
|
|
newTransaction as Transaction
|
|
)
|
|
|
|
if (mappingResult.confidence >= 0.8 && !mappingResult.requires_review) {
|
|
const journalEntry = await createTransactionJournalEntry(
|
|
userId,
|
|
newTransaction as Transaction,
|
|
mappingResult
|
|
)
|
|
|
|
if (journalEntry) {
|
|
await supabase
|
|
.from('transactions')
|
|
.update({
|
|
journal_entry_id: journalEntry.id,
|
|
is_business: !mappingResult.default_private,
|
|
})
|
|
.eq('id', newTransaction.id)
|
|
|
|
result.auto_categorized++
|
|
}
|
|
}
|
|
} catch {
|
|
// Non-critical — continue processing
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|