feat: per-line VAT, invoice document types, ledger-based VAT declaration, bank reconciliation, and pagination

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>
This commit is contained in:
Jakob Wennberg
2026-02-21 14:57:15 +01:00
co-authored by Claude Opus 4.6
parent f1d187c005
commit 91e2c1705a
106 changed files with 9950 additions and 1641 deletions
+126
View File
@@ -30,6 +30,13 @@ vi.mock('@/lib/invoice/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/invoice/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 {