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
+351
View File
@@ -0,0 +1,351 @@
import { describe, it, expect } from 'vitest'
import type { BASAccount } from '@/types'
import type { SIEAccount, SIEAccountMappingRecord } from '../types'
import {
suggestMappings,
validateMappings,
getMappingStats,
applyMappingOverride,
mappingsToMap,
} from '../account-mapper'
// --- Helpers ---
function makeBASAccount(number: string, name: string): BASAccount {
const classNum = parseInt(number.charAt(0), 10)
const accountType =
classNum <= 1
? 'asset'
: classNum === 2
? 'liability'
: classNum === 3
? 'revenue'
: 'expense'
return {
id: `bas-${number}`,
user_id: 'user-1',
account_number: number,
account_name: name,
account_class: classNum,
account_group: number.substring(0, 2),
account_type: accountType,
normal_balance: classNum <= 1 || classNum >= 4 ? 'debit' : 'credit',
plan_type: 'k1',
is_active: true,
is_system_account: false,
default_vat_code: null,
description: null,
sru_code: null,
sort_order: parseInt(number, 10),
created_at: '2024-01-01',
updated_at: '2024-01-01',
}
}
function makeSIEAccount(number: string, name: string): SIEAccount {
return { number, name }
}
// --- Fixtures ---
const basAccounts: BASAccount[] = [
makeBASAccount('1510', 'Kundfordringar'),
makeBASAccount('1930', 'Företagskonto'),
makeBASAccount('2440', 'Leverantörsskulder'),
makeBASAccount('3001', 'Försäljning varor 25%'),
makeBASAccount('3002', 'Försäljning varor 12%'),
makeBASAccount('5010', 'Lokalhyra'),
makeBASAccount('6211', 'Telekommunikation'),
]
// --- Tests ---
describe('suggestMappings', () => {
it('returns exact match with confidence 1.0', () => {
const source = [makeSIEAccount('1510', 'Kundfordringar')]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('1510')
expect(result[0].targetName).toBe('Kundfordringar')
expect(result[0].confidence).toBe(1.0)
expect(result[0].matchType).toBe('exact')
expect(result[0].isOverride).toBe(false)
})
it('returns unmapped entry when no match exists', () => {
const source = [makeSIEAccount('9999', 'Okänt konto')]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('')
expect(result[0].targetName).toBe('')
expect(result[0].confidence).toBe(0)
expect(result[0].matchType).toBe('manual')
})
it('does not fuzzy match accounts with similar names', () => {
// 3400 should NOT match 3001 or 3002 despite being in same class
const source = [makeSIEAccount('3400', 'Försäljning tjänster')]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('')
expect(result[0].confidence).toBe(0)
})
it('does not fuzzy match accounts with similar numbers', () => {
// 2510 should NOT match 2440 despite being in same class
const source = [makeSIEAccount('2510', 'Skatteskulder')]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('')
expect(result[0].confidence).toBe(0)
})
it('preserves user overrides from existing mappings', () => {
const source = [makeSIEAccount('3400', 'Försäljning tjänster')]
const existingMappings: SIEAccountMappingRecord[] = [
{
id: 'map-1',
user_id: 'user-1',
source_account: '3400',
source_name: 'Försäljning tjänster',
target_account: '3001',
confidence: 1.0,
match_type: 'manual',
created_at: '2024-01-01',
updated_at: '2024-01-01',
},
]
const result = suggestMappings(source, basAccounts, existingMappings)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('3001')
expect(result[0].isOverride).toBe(true)
expect(result[0].matchType).toBe('manual')
})
it('sorts unmapped accounts first (lowest confidence)', () => {
const source = [
makeSIEAccount('1510', 'Kundfordringar'),
makeSIEAccount('9999', 'Okänt konto'),
makeSIEAccount('1930', 'Företagskonto'),
]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(3)
// Unmapped (confidence 0) should come first
expect(result[0].sourceAccount).toBe('9999')
expect(result[0].confidence).toBe(0)
// Exact matches (confidence 1.0) come after
expect(result[1].confidence).toBe(1.0)
expect(result[2].confidence).toBe(1.0)
})
it('handles multiple accounts with mixed results', () => {
const source = [
makeSIEAccount('1510', 'Kundfordringar'),
makeSIEAccount('3400', 'Försäljning tjänster'),
makeSIEAccount('5010', 'Lokalhyra'),
]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(3)
const mapped = result.filter((m) => m.targetAccount)
const unmapped = result.filter((m) => !m.targetAccount)
expect(mapped).toHaveLength(2)
expect(unmapped).toHaveLength(1)
})
it('handles empty source accounts', () => {
const result = suggestMappings([], basAccounts)
expect(result).toHaveLength(0)
})
it('handles empty BAS accounts — everything unmapped', () => {
const source = [makeSIEAccount('1510', 'Kundfordringar')]
const result = suggestMappings(source, [])
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('')
expect(result[0].confidence).toBe(0)
})
})
describe('validateMappings', () => {
it('returns valid when all accounts are mapped', () => {
const mappings = suggestMappings(
[makeSIEAccount('1510', 'Kundfordringar'), makeSIEAccount('1930', 'Företagskonto')],
basAccounts
)
const validation = validateMappings(mappings)
expect(validation.valid).toBe(true)
expect(validation.unmappedAccounts).toHaveLength(0)
})
it('returns invalid when accounts are unmapped', () => {
const mappings = suggestMappings(
[makeSIEAccount('1510', 'Kundfordringar'), makeSIEAccount('9999', 'Okänt konto')],
basAccounts
)
const validation = validateMappings(mappings)
expect(validation.valid).toBe(false)
expect(validation.unmappedAccounts).toContain('9999')
expect(validation.unmappedAccounts).toHaveLength(1)
})
it('detects low confidence accounts', () => {
// With exact-match-only mapper, low confidence only comes from existing overrides
const mappings = [
{
sourceAccount: '3400',
sourceName: 'Försäljning tjänster',
targetAccount: '3001',
targetName: 'Försäljning varor 25%',
confidence: 0.3,
matchType: 'class' as const,
isOverride: false,
},
]
const validation = validateMappings(mappings)
expect(validation.lowConfidenceAccounts).toContain('3400')
})
})
describe('getMappingStats', () => {
it('counts total, mapped, unmapped correctly', () => {
const mappings = suggestMappings(
[
makeSIEAccount('1510', 'Kundfordringar'),
makeSIEAccount('9999', 'Okänt konto'),
makeSIEAccount('5010', 'Lokalhyra'),
],
basAccounts
)
const stats = getMappingStats(mappings)
expect(stats.total).toBe(3)
expect(stats.mapped).toBe(2)
expect(stats.unmapped).toBe(1)
})
it('counts match types correctly', () => {
const mappings = suggestMappings(
[
makeSIEAccount('1510', 'Kundfordringar'),
makeSIEAccount('9999', 'Okänt konto'),
],
basAccounts
)
const stats = getMappingStats(mappings)
expect(stats.exact).toBe(1)
expect(stats.manual).toBe(1) // unmapped gets matchType 'manual'
expect(stats.name).toBe(0)
expect(stats.class).toBe(0)
})
it('calculates average confidence for mapped accounts only', () => {
const mappings = suggestMappings(
[
makeSIEAccount('1510', 'Kundfordringar'), // exact, confidence 1.0
makeSIEAccount('1930', 'Företagskonto'), // exact, confidence 1.0
makeSIEAccount('9999', 'Okänt konto'), // unmapped, confidence 0
],
basAccounts
)
const stats = getMappingStats(mappings)
// Average of mapped only: (1.0 + 1.0) / 2 = 1.0
expect(stats.averageConfidence).toBe(1.0)
})
it('returns 0 average confidence when nothing is mapped', () => {
const mappings = suggestMappings(
[makeSIEAccount('9999', 'Okänt konto')],
basAccounts
)
const stats = getMappingStats(mappings)
expect(stats.averageConfidence).toBe(0)
})
})
describe('applyMappingOverride', () => {
it('sets target, confidence 1.0, matchType manual, and isOverride', () => {
const mappings = suggestMappings(
[makeSIEAccount('3400', 'Försäljning tjänster')],
basAccounts
)
const updated = applyMappingOverride(mappings, '3400', '3001', 'Försäljning varor 25%')
expect(updated).toHaveLength(1)
expect(updated[0].targetAccount).toBe('3001')
expect(updated[0].targetName).toBe('Försäljning varor 25%')
expect(updated[0].confidence).toBe(1.0)
expect(updated[0].matchType).toBe('manual')
expect(updated[0].isOverride).toBe(true)
})
it('does not mutate the original array', () => {
const mappings = suggestMappings(
[makeSIEAccount('3400', 'Försäljning tjänster')],
basAccounts
)
const original = [...mappings]
applyMappingOverride(mappings, '3400', '3001', 'Försäljning varor 25%')
expect(mappings[0].targetAccount).toBe(original[0].targetAccount)
expect(mappings[0].confidence).toBe(original[0].confidence)
})
it('only affects the specified source account', () => {
const mappings = suggestMappings(
[
makeSIEAccount('3400', 'Försäljning tjänster'),
makeSIEAccount('9998', 'Annat okänt konto'),
],
basAccounts
)
const updated = applyMappingOverride(mappings, '3400', '3001', 'Försäljning varor 25%')
const unchanged = updated.find((m) => m.sourceAccount === '9998')
expect(unchanged?.targetAccount).toBe('')
expect(unchanged?.confidence).toBe(0)
})
})
describe('mappingsToMap', () => {
it('creates a Map from source to target account', () => {
const mappings = suggestMappings(
[makeSIEAccount('1510', 'Kundfordringar'), makeSIEAccount('1930', 'Företagskonto')],
basAccounts
)
const map = mappingsToMap(mappings)
expect(map.get('1510')).toBe('1510')
expect(map.get('1930')).toBe('1930')
expect(map.size).toBe(2)
})
it('skips unmapped accounts', () => {
const mappings = suggestMappings(
[makeSIEAccount('1510', 'Kundfordringar'), makeSIEAccount('9999', 'Okänt konto')],
basAccounts
)
const map = mappingsToMap(mappings)
expect(map.get('1510')).toBe('1510')
expect(map.has('9999')).toBe(false)
expect(map.size).toBe(1)
})
})
+223
View File
@@ -0,0 +1,223 @@
import { describe, it, expect } from 'vitest'
import { generateImportPreview } from '../sie-import'
import type { ParsedSIEFile, AccountMapping } from '../types'
// --- Helpers ---
function makeParsedFile(overrides?: Partial<ParsedSIEFile>): ParsedSIEFile {
return {
header: {
sieType: 4,
program: 'TestProg',
programVersion: '1.0',
generatedDate: new Date(2024, 0, 1),
format: 'PC8',
companyName: 'Test AB',
orgNumber: '5566778899',
address: null,
fiscalYears: [{ yearIndex: 0, start: new Date(2024, 0, 1), end: new Date(2024, 11, 31) }],
currency: 'SEK',
},
accounts: [
{ number: '1510', name: 'Kundfordringar' },
{ number: '1930', name: 'Företagskonto' },
{ number: '2440', name: 'Leverantörsskulder' },
],
openingBalances: [
{ yearIndex: 0, account: '1510', amount: 50000 },
{ yearIndex: 0, account: '1930', amount: 100000 },
{ yearIndex: 0, account: '2440', amount: -150000 },
],
closingBalances: [],
resultBalances: [],
vouchers: [
{
series: 'A',
number: 1,
date: new Date(2024, 0, 15),
description: 'Faktura 1001',
lines: [
{ account: '1510', amount: 12500 },
{ account: '3001', amount: -10000 },
{ account: '2611', amount: -2500 },
],
},
],
issues: [],
stats: {
totalAccounts: 3,
totalVouchers: 1,
totalTransactionLines: 3,
fiscalYearStart: new Date(2024, 0, 1),
fiscalYearEnd: new Date(2024, 11, 31),
},
...overrides,
}
}
function makeMapping(source: string, target: string, confidence: number = 1.0): AccountMapping {
return {
sourceAccount: source,
sourceName: `Account ${source}`,
targetAccount: target,
targetName: `Target ${target}`,
confidence,
matchType: target ? 'exact' : 'manual',
isOverride: false,
}
}
// --- Tests ---
describe('generateImportPreview', () => {
describe('trial balance from IB', () => {
it('calculates debit totals from positive IB amounts', () => {
const parsed = makeParsedFile()
const mappings = [
makeMapping('1510', '1510'),
makeMapping('1930', '1930'),
makeMapping('2440', '2440'),
]
const preview = generateImportPreview(parsed, mappings)
// Positive amounts: 50000 + 100000 = 150000
expect(preview.trialBalance.totalDebit).toBe(150000)
})
it('calculates credit totals from negative IB amounts', () => {
const parsed = makeParsedFile()
const mappings = [
makeMapping('1510', '1510'),
makeMapping('1930', '1930'),
makeMapping('2440', '2440'),
]
const preview = generateImportPreview(parsed, mappings)
// Negative amounts: |-150000| = 150000
expect(preview.trialBalance.totalCredit).toBe(150000)
})
it('detects balanced trial balance', () => {
const parsed = makeParsedFile()
const mappings = [makeMapping('1510', '1510')]
const preview = generateImportPreview(parsed, mappings)
// 150000 debit = 150000 credit
expect(preview.trialBalance.isBalanced).toBe(true)
})
it('detects unbalanced trial balance', () => {
const parsed = makeParsedFile({
openingBalances: [
{ yearIndex: 0, account: '1510', amount: 50000 },
{ yearIndex: 0, account: '1930', amount: 100000 },
// Missing credit side — only 150000 debit, 0 credit
],
})
const mappings = [makeMapping('1510', '1510')]
const preview = generateImportPreview(parsed, mappings)
expect(preview.trialBalance.isBalanced).toBe(false)
})
it('handles zero opening balances', () => {
const parsed = makeParsedFile({ openingBalances: [] })
const mappings: AccountMapping[] = []
const preview = generateImportPreview(parsed, mappings)
expect(preview.trialBalance.totalDebit).toBe(0)
expect(preview.trialBalance.totalCredit).toBe(0)
expect(preview.trialBalance.isBalanced).toBe(true)
})
})
describe('company info passthrough', () => {
it('passes company name', () => {
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, [])
expect(preview.companyName).toBe('Test AB')
})
it('passes org number', () => {
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, [])
expect(preview.orgNumber).toBe('5566778899')
})
it('handles null company info', () => {
const parsed = makeParsedFile({
header: {
...makeParsedFile().header,
companyName: null,
orgNumber: null,
},
})
const preview = generateImportPreview(parsed, [])
expect(preview.companyName).toBeNull()
expect(preview.orgNumber).toBeNull()
})
})
describe('mapping status', () => {
it('reflects mapper output counts', () => {
const parsed = makeParsedFile()
const mappings = [
makeMapping('1510', '1510'), // mapped
makeMapping('1930', '1930'), // mapped
makeMapping('2440', '', 0), // unmapped
]
const preview = generateImportPreview(parsed, mappings)
expect(preview.mappingStatus.total).toBe(3)
expect(preview.mappingStatus.mapped).toBe(2)
expect(preview.mappingStatus.unmapped).toBe(1)
})
it('reports low confidence mappings', () => {
const mappings = [
makeMapping('1510', '1510', 1.0),
makeMapping('3400', '3001', 0.3), // low confidence
]
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, mappings)
expect(preview.mappingStatus.lowConfidence).toBe(1)
})
})
describe('statistics', () => {
it('passes account count', () => {
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, [])
expect(preview.accountCount).toBe(3)
})
it('passes voucher count', () => {
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, [])
expect(preview.voucherCount).toBe(1)
})
it('passes transaction line count', () => {
const parsed = makeParsedFile()
const preview = generateImportPreview(parsed, [])
expect(preview.transactionLineCount).toBe(3)
})
})
describe('issues passthrough', () => {
it('passes parse issues to preview', () => {
const parsed = makeParsedFile({
issues: [
{ severity: 'warning', line: 5, message: 'Unknown tag: #FOO', tag: 'FOO' },
{ severity: 'error', line: 10, message: 'Invalid voucher', tag: 'VER' },
],
})
const preview = generateImportPreview(parsed, [])
expect(preview.issues).toHaveLength(2)
expect(preview.issues[0].severity).toBe('warning')
expect(preview.issues[1].severity).toBe('error')
})
})
})
+345
View File
@@ -0,0 +1,345 @@
import { describe, it, expect } from 'vitest'
import { parseSIEFile, validateSIEFile } from '../sie-parser'
// --- SIE content fixtures ---
const MINIMAL_SIE = [
'#FLAGGA 0',
'#SIETYP 4',
'#PROGRAM "TestProg" "1.0"',
'#FORMAT PC8',
'#GEN 20240101',
'#FNAMN "Test AB"',
'#ORGNR 5566778899',
'#VALUTA SEK',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#KONTO 1930 "Företagskonto"',
'#KONTO 3001 "Försäljning varor 25%"',
].join('\n')
const SIE_WITH_BALANCES = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Balans AB"',
'#ORGNR 1234567890',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#KONTO 1930 "Företagskonto"',
'#KONTO 2440 "Leverantörsskulder"',
'#IB 0 1510 50000.00',
'#IB 0 1930 100000.00',
'#IB 0 2440 -150000.00',
'#UB 0 1510 75000.00',
'#UB 0 1930 125000.00',
'#UB 0 2440 -200000.00',
].join('\n')
const SIE_WITH_VOUCHERS = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Voucher AB"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#KONTO 1930 "Företagskonto"',
'#KONTO 3001 "Försäljning"',
'#KONTO 2611 "Utgående moms 25%"',
'#VER A 1 20240115 "Faktura 1001"',
'{',
'#TRANS 1510 {} 12500.00',
'#TRANS 3001 {} -10000.00',
'#TRANS 2611 {} -2500.00',
'}',
'#VER A 2 20240220 "Inbetalning faktura 1001"',
'{',
'#TRANS 1930 {} 12500.00',
'#TRANS 1510 {} -12500.00',
'}',
].join('\n')
const SIE_TYPE_1 = [
'#FLAGGA 0',
'#SIETYP 1',
'#FNAMN "SIE1 AB"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#IB 0 1510 50000.00',
'#UB 0 1510 75000.00',
].join('\n')
const SIE_WITH_SRU = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "SRU AB"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#SRU 1510 7251',
'#KONTO 3001 "Försäljning"',
'#SRU 3001 7410',
].join('\n')
const SIE_UNBALANCED_VOUCHER = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Obalanserad AB"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#KONTO 3001 "Försäljning"',
'#VER A 1 20240115 "Obalanserad verifikation"',
'{',
'#TRANS 1510 {} 10000.00',
'#TRANS 3001 {} -5000.00',
'}',
].join('\n')
const SIE_WITH_OBJECT_LIST = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Objects AB"',
'#RAR 0 20240101 20241231',
'#KONTO 5010 "Lokalhyra"',
'#KONTO 1930 "Företagskonto"',
'#VER A 1 20240115 "Hyra januari"',
'{',
'#TRANS 5010 {1 "Kontor"} 15000.00',
'#TRANS 1930 {} -15000.00',
'}',
].join('\n')
// --- parseSIEFile tests ---
describe('parseSIEFile', () => {
describe('header parsing', () => {
it('parses SIE type', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.sieType).toBe(4)
})
it('parses company name from #FNAMN', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.companyName).toBe('Test AB')
})
it('parses org number from #ORGNR', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.orgNumber).toBe('5566778899')
})
it('parses fiscal year from #RAR', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.fiscalYears).toHaveLength(1)
expect(result.header.fiscalYears[0].yearIndex).toBe(0)
expect(result.header.fiscalYears[0].start).toEqual(new Date(2024, 0, 1))
expect(result.header.fiscalYears[0].end).toEqual(new Date(2024, 11, 31))
})
it('parses currency from #VALUTA', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.currency).toBe('SEK')
})
it('defaults currency to SEK when not specified', () => {
const content = '#FLAGGA 0\n#SIETYP 4\n#FNAMN "Test"\n#RAR 0 20240101 20241231'
const result = parseSIEFile(content)
expect(result.header.currency).toBe('SEK')
})
it('parses program info', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.program).toBe('TestProg')
expect(result.header.programVersion).toBe('1.0')
})
it('parses generated date', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.header.generatedDate).toEqual(new Date(2024, 0, 1))
})
it('parses SIE type 1', () => {
const result = parseSIEFile(SIE_TYPE_1)
expect(result.header.sieType).toBe(1)
})
})
describe('account parsing', () => {
it('parses #KONTO with number and name', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.accounts).toHaveLength(3)
expect(result.accounts[0]).toEqual({ number: '1510', name: 'Kundfordringar' })
expect(result.accounts[1]).toEqual({ number: '1930', name: 'Företagskonto' })
})
it('parses #SRU codes onto accounts', () => {
const result = parseSIEFile(SIE_WITH_SRU)
const account1510 = result.accounts.find((a) => a.number === '1510')
expect(account1510?.sruCode).toBe('7251')
const account3001 = result.accounts.find((a) => a.number === '3001')
expect(account3001?.sruCode).toBe('7410')
})
})
describe('balance parsing', () => {
it('parses opening balances (#IB) with positive amounts', () => {
const result = parseSIEFile(SIE_WITH_BALANCES)
const ib1510 = result.openingBalances.find((b) => b.account === '1510')
expect(ib1510?.amount).toBe(50000)
expect(ib1510?.yearIndex).toBe(0)
})
it('parses opening balances (#IB) with negative amounts', () => {
const result = parseSIEFile(SIE_WITH_BALANCES)
const ib2440 = result.openingBalances.find((b) => b.account === '2440')
expect(ib2440?.amount).toBe(-150000)
})
it('parses closing balances (#UB)', () => {
const result = parseSIEFile(SIE_WITH_BALANCES)
expect(result.closingBalances).toHaveLength(3)
const ub1930 = result.closingBalances.find((b) => b.account === '1930')
expect(ub1930?.amount).toBe(125000)
})
})
describe('voucher parsing', () => {
it('parses #VER with series, number, date, description', () => {
const result = parseSIEFile(SIE_WITH_VOUCHERS)
expect(result.vouchers).toHaveLength(2)
const v1 = result.vouchers[0]
expect(v1.series).toBe('A')
expect(v1.number).toBe(1)
expect(v1.date).toEqual(new Date(2024, 0, 15))
expect(v1.description).toBe('Faktura 1001')
})
it('parses #TRANS lines within a voucher', () => {
const result = parseSIEFile(SIE_WITH_VOUCHERS)
const v1 = result.vouchers[0]
expect(v1.lines).toHaveLength(3)
expect(v1.lines[0]).toMatchObject({ account: '1510', amount: 12500 })
expect(v1.lines[1]).toMatchObject({ account: '3001', amount: -10000 })
expect(v1.lines[2]).toMatchObject({ account: '2611', amount: -2500 })
})
it('handles object lists in braces', () => {
const result = parseSIEFile(SIE_WITH_OBJECT_LIST)
expect(result.vouchers).toHaveLength(1)
const v = result.vouchers[0]
expect(v.lines).toHaveLength(2)
expect(v.lines[0]).toMatchObject({ account: '5010', amount: 15000 })
expect(v.lines[1]).toMatchObject({ account: '1930', amount: -15000 })
})
it('detects unbalanced vouchers as errors', () => {
const result = parseSIEFile(SIE_UNBALANCED_VOUCHER)
expect(result.vouchers).toHaveLength(1)
const errors = result.issues.filter((i) => i.severity === 'error')
expect(errors.length).toBeGreaterThanOrEqual(1)
expect(errors.some((e) => e.message.includes('not balanced'))).toBe(true)
})
})
describe('statistics', () => {
it('calculates account count', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.stats.totalAccounts).toBe(3)
})
it('calculates voucher count', () => {
const result = parseSIEFile(SIE_WITH_VOUCHERS)
expect(result.stats.totalVouchers).toBe(2)
})
it('calculates transaction line count', () => {
const result = parseSIEFile(SIE_WITH_VOUCHERS)
// Voucher 1: 3 lines, Voucher 2: 2 lines
expect(result.stats.totalTransactionLines).toBe(5)
})
it('sets fiscal year start/end from RAR 0', () => {
const result = parseSIEFile(MINIMAL_SIE)
expect(result.stats.fiscalYearStart).toEqual(new Date(2024, 0, 1))
expect(result.stats.fiscalYearEnd).toEqual(new Date(2024, 11, 31))
})
it('returns null fiscal year dates when no RAR', () => {
const content = '#FLAGGA 0\n#SIETYP 4\n#FNAMN "Test"'
const result = parseSIEFile(content)
expect(result.stats.fiscalYearStart).toBeNull()
expect(result.stats.fiscalYearEnd).toBeNull()
})
})
})
// --- validateSIEFile tests ---
describe('validateSIEFile', () => {
it('returns valid for a complete SIE file', () => {
const parsed = parseSIEFile(SIE_WITH_VOUCHERS)
const validation = validateSIEFile(parsed)
expect(validation.valid).toBe(true)
expect(validation.errors).toHaveLength(0)
})
it('adds error for unbalanced vouchers', () => {
const parsed = parseSIEFile(SIE_UNBALANCED_VOUCHER)
const validation = validateSIEFile(parsed)
expect(validation.valid).toBe(false)
expect(validation.errors.some((e) => e.includes('not balanced'))).toBe(true)
})
it('adds warning for undefined account references', () => {
const content = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Test"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#IB 0 9999 50000.00',
].join('\n')
const parsed = parseSIEFile(content)
const validation = validateSIEFile(parsed)
expect(validation.warnings.some((w) => w.includes('9999') && w.includes('not defined'))).toBe(true)
})
it('adds error for missing #RAR', () => {
const content = '#FLAGGA 0\n#SIETYP 4\n#FNAMN "Test"\n#KONTO 1510 "Kund"'
const parsed = parseSIEFile(content)
const validation = validateSIEFile(parsed)
expect(validation.valid).toBe(false)
expect(validation.errors.some((e) => e.includes('fiscal year') || e.includes('#RAR'))).toBe(true)
})
it('adds warning for unbalanced opening balances', () => {
const content = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Test"',
'#RAR 0 20240101 20241231',
'#KONTO 1510 "Kundfordringar"',
'#IB 0 1510 50000.00',
].join('\n')
const parsed = parseSIEFile(content)
const validation = validateSIEFile(parsed)
expect(validation.warnings.some((w) => w.includes('Opening balances not balanced'))).toBe(true)
})
it('passes with balanced opening balances', () => {
const parsed = parseSIEFile(SIE_WITH_BALANCES)
const validation = validateSIEFile(parsed)
// IB: 50000 + 100000 + (-150000) = 0 → balanced
const ibWarning = validation.warnings.find((w) => w.includes('Opening balances not balanced'))
expect(ibWarning).toBeUndefined()
})
})
+21 -181
View File
@@ -1,12 +1,10 @@
/**
* Account Mapping Engine
*
* Intelligently maps accounts from an imported SIE file to
* the user's BAS chart of accounts. Uses multiple strategies:
* 1. Exact account number match
* 2. Account name similarity (Levenshtein distance)
* 3. Account class consistency (5xxx → expense, etc.)
* 4. User-defined overrides
* Maps accounts from an imported SIE file to the user's BAS chart of accounts.
* Uses exact account number matching only — no fuzzy/heuristic matching.
* This aligns with Swedish industry standard (e.g. Fortnox): exact match,
* create new, or let the user map manually.
*/
import type { BASAccount } from '@/types'
@@ -18,113 +16,8 @@ import type {
} from './types'
/**
* Calculate Levenshtein distance between two strings
* Used for name similarity scoring
*/
function levenshteinDistance(str1: string, str2: string): number {
const s1 = str1.toLowerCase()
const s2 = str2.toLowerCase()
if (s1.length === 0) return s2.length
if (s2.length === 0) return s1.length
const matrix: number[][] = []
// Initialize first column
for (let i = 0; i <= s1.length; i++) {
matrix[i] = [i]
}
// Initialize first row
for (let j = 0; j <= s2.length; j++) {
matrix[0][j] = j
}
// Fill in the rest of the matrix
for (let i = 1; i <= s1.length; i++) {
for (let j = 1; j <= s2.length; j++) {
const cost = s1[i - 1] === s2[j - 1] ? 0 : 1
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1, // deletion
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j - 1] + cost // substitution
)
}
}
return matrix[s1.length][s2.length]
}
/**
* Calculate similarity score between two strings (0-1)
*/
function nameSimilarity(name1: string, name2: string): number {
if (!name1 || !name2) return 0
const distance = levenshteinDistance(name1, name2)
const maxLength = Math.max(name1.length, name2.length)
if (maxLength === 0) return 1
return 1 - distance / maxLength
}
/**
* Normalize Swedish account names for better matching
*/
function normalizeAccountName(name: string): string {
return name
.toLowerCase()
.replace(/[^\wåäö\s]/gi, '') // Remove special chars except Swedish
.replace(/\s+/g, ' ') // Normalize whitespace
.trim()
}
/**
* Get the account class (first digit) from an account number
*/
function getAccountClass(accountNumber: string): number {
const firstDigit = accountNumber.charAt(0)
return parseInt(firstDigit, 10) || 0
}
/**
* Get the account group (first two digits) from an account number
*/
function getAccountGroup(accountNumber: string): string {
return accountNumber.substring(0, 2)
}
/**
* Check if two accounts are in compatible classes
*/
function areClassesCompatible(sourceNumber: string, targetNumber: string): boolean {
const sourceClass = getAccountClass(sourceNumber)
const targetClass = getAccountClass(targetNumber)
// Same class is always compatible
if (sourceClass === targetClass) return true
// Allow some flexibility for related classes
// 1xxx (assets) can map to 1xxx
// 2xxx (equity/liabilities) can map to 2xxx
// 3xxx (revenue) can map to 3xxx
// 4xxx (cost of goods) can map to 4xxx or 5xxx
// 5xxx (external expenses) can map to 5xxx or 6xxx
// 6xxx (other external) can map to 6xxx or 5xxx
// 7xxx (personnel) can map to 7xxx
// 8xxx (financial) can map to 8xxx
if (sourceClass === 4 && targetClass === 5) return true
if (sourceClass === 5 && targetClass === 6) return true
if (sourceClass === 6 && targetClass === 5) return true
return false
}
/**
* Find the best matching BAS account for a source account
* Find the best matching BAS account for a source account.
* Only matches on exact account number — no fuzzy matching.
*/
function findBestMatch(
source: SIEAccount,
@@ -139,78 +32,25 @@ function findBestMatch(
}
}
let bestMatch: BASAccount | null = null
let bestScore = 0
let matchType: AccountMatchType = 'class'
// Exact account number match
const exactMatch = basAccounts.find(
(target) => source.number === target.account_number
)
for (const target of basAccounts) {
// Strategy 1: Exact account number match
if (source.number === target.account_number) {
return {
sourceAccount: source.number,
sourceName: source.name,
targetAccount: target.account_number,
targetName: target.account_name,
confidence: 1.0,
matchType: 'exact',
isOverride: false,
}
}
// Strategy 2: Name similarity
const nameSim = nameSimilarity(
normalizeAccountName(source.name),
normalizeAccountName(target.account_name)
)
// Strategy 3: Account class compatibility
const classCompatible = areClassesCompatible(source.number, target.account_number)
const sameGroup = getAccountGroup(source.number) === getAccountGroup(target.account_number)
// Calculate combined score
let score = 0
// Name similarity is most important
if (nameSim >= 0.9) {
score = 0.9 + (nameSim - 0.9) // 0.9 - 1.0
} else if (nameSim >= 0.7) {
score = 0.7 + (nameSim - 0.7) * 0.5 // 0.7 - 0.85
} else if (nameSim >= 0.5) {
score = 0.5 + (nameSim - 0.5) * 0.25 // 0.5 - 0.575
}
// Boost for same account group (first 2 digits)
if (sameGroup) {
score += 0.2
} else if (classCompatible) {
score += 0.1
}
// Penalize cross-class mappings
if (!classCompatible) {
score *= 0.5
}
if (score > bestScore) {
bestScore = score
bestMatch = target
matchType = nameSim >= 0.7 ? 'name' : 'class'
if (exactMatch) {
return {
sourceAccount: source.number,
sourceName: source.name,
targetAccount: exactMatch.account_number,
targetName: exactMatch.account_name,
confidence: 1.0,
matchType: 'exact',
isOverride: false,
}
}
if (!bestMatch || bestScore < 0.3) {
return null
}
return {
sourceAccount: source.number,
sourceName: source.name,
targetAccount: bestMatch.account_number,
targetName: bestMatch.account_name,
confidence: Math.min(bestScore, 1.0),
matchType,
isOverride: false,
}
// No match found
return null
}
/**
+71 -25
View File
@@ -2,20 +2,47 @@
* Swedbank CSV format parser
*
* Format: Comma-delimited, PERIOD decimal separator (exception among Swedish banks!)
* Columns: Clearingnummer, Kontonummer, Datum, Text, Belopp, Saldo, and more (12 columns)
* Columns (real export): Radnr, Clnr, Kontonr, Produkt, Valuta, Bokfdag, Transdag,
* Valutadag, Referens, Text, Belopp, Saldo
* Date format: YYYY-MM-DD
* Encoding: UTF-8 or Windows-1252
*
* Notes:
* - First line is metadata (account info), SKIP it
* - First line is metadata (e.g. "* Transaktionsrapport Period ..."), SKIP it
* - Second line is the actual header
* - Uses period as decimal separator (unlike Nordea/SEB/Handelsbanken)
* - Headers may be abbreviated (Clnr vs Clearingnummer, Bokfdag vs Bokföringsdatum)
* - Referens column contains counterparty/payee name
* - Text column contains transaction type (e.g. "Bg-bet. via internet")
*/
import type { BankFileFormat, BankFileParseResult, ParsedBankTransaction, BankFileParseIssue } from '../types'
import { prepareContent } from '../encoding'
import { parseCSVLine } from './nordea'
/**
* Check if a header value matches any of the given patterns (case-insensitive)
*/
function matchesHeader(header: string, patterns: string[]): boolean {
const h = header.toLowerCase()
return patterns.some((p) => h === p || h.includes(p))
}
/**
* Check if a line looks like a Swedbank header row
*/
function isSwedbankHeader(line: string): boolean {
const lower = line.toLowerCase()
return (
// Full names (legacy or alternative exports)
lower.includes('clearingnummer') || lower.includes('radnummer') ||
// Abbreviated names (current export format)
/\bradnr\b/.test(lower) || /\bclnr\b/.test(lower) ||
// Combination of typical Swedbank columns
(lower.includes('bokfdag') && lower.includes('belopp'))
)
}
export const swedbankFormat: BankFileFormat = {
id: 'swedbank',
name: 'Swedbank',
@@ -25,14 +52,10 @@ export const swedbankFormat: BankFileFormat = {
detect(content: string, _filename: string): boolean {
const prepared = prepareContent(content)
const lines = prepared.split('\n')
// Check first two lines — Swedbank has metadata line, then header
const line1 = lines[0]?.toLowerCase() || ''
const line2 = lines[1]?.toLowerCase() || ''
const line1 = lines[0] || ''
const line2 = lines[1] || ''
return (
(line1.includes('clearingnummer') || line2.includes('clearingnummer') ||
line1.includes('radnummer') || line2.includes('radnummer'))
)
return isSwedbankHeader(line1) || isSwedbankHeader(line2)
},
parse(content: string): BankFileParseResult {
@@ -43,16 +66,30 @@ export const swedbankFormat: BankFileFormat = {
const issues: BankFileParseIssue[] = []
let skippedRows = 0
// Determine where the header is
// Line 0 might be metadata, line 1 might be header
let headerLineIdx = 0
const line0Lower = lines[0]?.toLowerCase() || ''
const line1Lower = lines[1]?.toLowerCase() || ''
// Find the header row — may be line 0 or line 1 (if line 0 is metadata)
let headerLineIdx = -1
for (let i = 0; i < Math.min(lines.length, 3); i++) {
if (isSwedbankHeader(lines[i])) {
headerLineIdx = i
break
}
}
if (line1Lower.includes('clearingnummer') || line1Lower.includes('radnummer')) {
headerLineIdx = 1
} else if (line0Lower.includes('clearingnummer') || line0Lower.includes('radnummer')) {
headerLineIdx = 0
if (headerLineIdx === -1) {
issues.push({
row: 1,
message: 'Could not find Swedbank header row',
severity: 'error',
})
return {
format: 'swedbank',
format_name: 'Swedbank',
transactions: [],
date_from: null,
date_to: null,
issues,
stats: { total_rows: 0, parsed_rows: 0, skipped_rows: 0, total_income: 0, total_expenses: 0 },
}
}
const headerLine = lines[headerLineIdx] || ''
@@ -60,16 +97,19 @@ export const swedbankFormat: BankFileFormat = {
h.trim().toLowerCase().replace(/"/g, '')
)
// Find column indices
const dateIdx = headers.findIndex((h) => h === 'datum' || h.includes('bokföringsdatum'))
// Find column indices — support both abbreviated and full header names
const dateIdx = headers.findIndex((h) =>
matchesHeader(h, ['bokfdag', 'bokföringsdatum', 'datum'])
)
const descIdx = headers.findIndex((h) => h === 'text' || h.includes('beskrivning'))
const amountIdx = headers.findIndex((h) => h === 'belopp')
const balanceIdx = headers.findIndex((h) => h === 'saldo')
const referenceIdx = headers.findIndex((h) => h === 'referens')
if (dateIdx === -1 || amountIdx === -1) {
issues.push({
row: 1,
message: 'Could not identify required columns (datum, belopp)',
row: headerLineIdx + 1,
message: `Could not identify required columns (datum, belopp). Found headers: ${headers.join(', ')}`,
severity: 'error',
})
return {
@@ -91,7 +131,8 @@ export const swedbankFormat: BankFileFormat = {
const fields = parseCSVLine(line, ',').map((f) => f.trim().replace(/^"|"$/g, ''))
const date = fields[dateIdx]
const description = descIdx >= 0 ? fields[descIdx] : 'Unknown'
const reference = referenceIdx >= 0 ? fields[referenceIdx]?.trim() : null
const textDesc = descIdx >= 0 ? fields[descIdx]?.trim() : null
const amountStr = fields[amountIdx]
const balanceStr = balanceIdx >= 0 ? fields[balanceIdx] : undefined
@@ -116,14 +157,19 @@ export const swedbankFormat: BankFileFormat = {
const balance = balanceStr ? parseFloat(balanceStr.replace(/\s/g, '')) : null
// Build description: use reference (counterparty) as primary, text as secondary
const description = reference && textDesc
? `${reference} — ${textDesc}`
: reference || textDesc || 'Unknown'
transactions.push({
date,
description: (description || 'Unknown').trim(),
description,
amount,
currency: 'SEK',
balance: isNaN(balance as number) ? null : balance,
reference: null,
counterparty: null,
counterparty: reference || null,
raw_line: line,
})
}
+1
View File
@@ -357,6 +357,7 @@ async function importVouchers(
description: v.description,
source_type: 'import',
status: 'posted',
committed_at: new Date().toISOString(),
}))
// Insert headers