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:
co-authored by
Claude Opus 4.6
parent
f1d187c005
commit
91e2c1705a
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user