feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker (#278)

* feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker

- SIE import preserves each voucher's source series (B/C/I/V/...), essential
  for Fortnox migrations where series carry semantic meaning (kundfakturor,
  inbetalningar, etc.). Target numbering still goes through next_voucher_number
  per series; source (series, number) is stored in the migration mapping for
  BFNAR 2013:2 audit trail.
- Execute route reads company_settings.default_voucher_series as the fallback
  for vouchers arriving without a series (SIE4I).
- Extract shared FiscalYearSelector component; adopt in /reports and
  /bookkeeping.
- Transaction TemplatePicker now surfaces user-created library templates
  (company + team scope) alongside the static registry, with a helper to
  convert simple library templates into the BookingTemplate shape.
- Exclude 8999 "Årets resultat" from income statement financial section and
  monthly breakdown so year-end closing entries don't cancel the net result.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: skip Bokio SIE regression when fixtures are absent

/dev_docs is gitignored (contains anonymised customer exports), so the
integration test can't find its input files in CI. Gate the suite on
fixture presence so it still runs locally.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: address Greptile review feedback

- convertLibraryToBookingTemplate: default entity_applicability to 'all'
  when the source template has no entity_type, so TemplatePicker doesn't
  silently hide it for companies with a set entity type.
- FiscalYearSelector: fire onReady in the no-company early-return branch
  so consumers (e.g. ReportsPage) don't get stuck in a loading skeleton
  while the company context is still hydrating.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-04-20 11:40:15 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent d708a85d4c
commit 23664e79cb
15 changed files with 1061 additions and 131 deletions
+90 -1
View File
@@ -1,6 +1,14 @@
import type { BookingTemplateCategory, BookingTemplateLibraryLine } from '@/types'
import type { BookingTemplateCategory, BookingTemplateLibrary, BookingTemplateLibraryLine, VatTreatment } from '@/types'
import type { BookingTemplate } from '@/lib/bookkeeping/booking-templates'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
/**
* Prefix for library template ids when they are mapped into the
* static BookingTemplate shape used by the transaction picker.
*/
export const LIBRARY_TEMPLATE_PREFIX = 'library:'
export function isLibraryTemplateId(id: string): boolean { return id.startsWith(LIBRARY_TEMPLATE_PREFIX) }
/**
* Category labels in Swedish for UI display.
*/
@@ -76,3 +84,84 @@ export const SCOPE_LABELS: Record<ReturnType<typeof getTemplateScope>, string> =
team: 'Team',
company: 'Företag',
}
function vatRateToTreatment(rate: number): VatTreatment | null {
if (rate === 0.25) return 'standard_25'
if (rate === 0.12) return 'reduced_12'
if (rate === 0.06) return 'reduced_6'
return null
}
/**
* Convert a user-created library template to the BookingTemplate shape the
* transaction TemplatePicker consumes.
*
* Only simple shapes (one business line + one settlement line, optionally
* one VAT line) are returned — complex multi-account templates cannot be
* expressed as a single debit/credit pair and must be applied via the full
* journal entry form instead.
*
* The id is prefixed with "library:" so downstream code can recognise a
* library template and look it up through the library APIs rather than the
* static registry.
*/
export function convertLibraryToBookingTemplate(
lib: BookingTemplateLibrary,
): BookingTemplate | null {
if (!Array.isArray(lib.lines)) return null
const business = lib.lines.filter((l) => l.type === 'business')
const settlement = lib.lines.filter((l) => l.type === 'settlement')
const vat = lib.lines.filter((l) => l.type === 'vat')
if (business.length !== 1 || settlement.length !== 1) return null
if (business[0].side === settlement[0].side) return null
const debitLine = business[0].side === 'debit' ? business[0] : settlement[0]
const creditLine = business[0].side === 'credit' ? business[0] : settlement[0]
const direction: 'expense' | 'income' = business[0].side === 'debit' ? 'expense' : 'income'
let vatTreatment: VatTreatment | null = null
let vatRate = 0
if (vat.length > 0) {
const inputVat = vat.find((v) => v.side === 'debit' && v.vat_rate)
?? vat.find((v) => v.vat_rate)
if (inputVat?.vat_rate) {
const treatment = vatRateToTreatment(inputVat.vat_rate)
if (treatment) {
vatTreatment = treatment
vatRate = inputVat.vat_rate
}
}
// Reverse-charge is recognised by the presence of 2614/2624/2634 (fictitious output VAT)
if (vat.some((v) => v.account === '2614' || v.account === '2624' || v.account === '2634')) {
vatTreatment = 'reverse_charge'
}
}
return {
id: `${LIBRARY_TEMPLATE_PREFIX}${lib.id}`,
name_sv: lib.name,
name_en: lib.name,
group: 'financial',
direction,
entity_applicability: lib.entity_type ?? 'all',
debit_account: debitLine.account,
credit_account: creditLine.account,
vat_treatment: vatTreatment,
vat_rate: vatRate,
deductibility: 'full',
special_rules_sv: lib.description || undefined,
mcc_codes: [],
keywords: [],
risk_level: 'NONE',
requires_review: false,
impact_score: 0,
auto_match_confidence: 0,
default_private: false,
fallback_category: direction === 'expense' ? 'expense_other' : 'income_services',
description_sv: lib.description || '',
common: false,
}
}
+267 -1
View File
@@ -1,12 +1,15 @@
import { describe, it, expect } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
import {
generateImportPreview,
validateIBBalance,
isBalanceSheetAccount,
ensureFiscalPeriod,
importVouchers,
computeVoucherNumberRanges,
} from '../sie-import'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { ParsedSIEFile, AccountMapping } from '../types'
import type { SupabaseClient } from '@supabase/supabase-js'
// --- Helpers ---
@@ -442,3 +445,266 @@ describe('isBalanceSheetAccount', () => {
expect(isBalanceSheetAccount('8999')).toBe(false)
})
})
describe('computeVoucherNumberRanges', () => {
it('returns empty array for no mapping', () => {
expect(computeVoucherNumberRanges([])).toEqual([])
})
it('produces one range per series with correct from/to', () => {
const ranges = computeVoucherNumberRanges([
{ sourceId: 'B1', series: 'B', targetNumber: 1 },
{ sourceId: 'B2', series: 'B', targetNumber: 2 },
{ sourceId: 'B3', series: 'B', targetNumber: 3 },
{ sourceId: 'C1', series: 'C', targetNumber: 1 },
{ sourceId: 'C2', series: 'C', targetNumber: 2 },
{ sourceId: 'V1', series: 'V', targetNumber: 1 },
])
expect(ranges).toEqual([
{ series: 'B', from: 1, to: 3 },
{ series: 'C', from: 1, to: 2 },
{ series: 'V', from: 1, to: 1 },
])
})
it('handles non-contiguous target numbers per series', () => {
const ranges = computeVoucherNumberRanges([
{ sourceId: 'B1', series: 'B', targetNumber: 5 },
{ sourceId: 'B2', series: 'B', targetNumber: 9 },
])
expect(ranges).toEqual([{ series: 'B', from: 5, to: 9 }])
})
})
describe('importVouchers — per-voucher series preservation', () => {
// Captures the rows passed to `.insert()` so the test can assert on
// voucher_series per inserted record. Uses a hand-rolled mock rather than
// createQueuedMockSupabase because we need to inspect arguments, not just
// return queued data.
function buildCapturingSupabase() {
const journalEntryInserts: Array<Record<string, unknown>> = []
const journalEntryLineInserts: Array<Record<string, unknown>> = []
const rpcCalls: Array<{ name: string; args: Record<string, unknown> }> = []
// Each `next_voucher_number` RPC call auto-increments per series, matching
// the DB function's ON CONFLICT behavior.
const nextNumberBySeries = new Map<string, number>()
let syntheticEntryId = 1
const supabase = {
from: vi.fn((table: string) => {
if (table === 'chart_of_accounts') {
// Return all accounts used in test vouchers as if already active
return {
select: () => ({
eq: () => ({
in: (_col: string, accountNumbers: string[]) => ({
then: (resolve: (v: { data: { id: string; account_number: string }[]; error: null }) => void) =>
resolve({
data: accountNumbers.map((num, i) => ({ id: `acc-${i}`, account_number: num })),
error: null,
}),
}),
}),
}),
}
}
if (table === 'journal_entries') {
return {
insert: (rows: Array<Record<string, unknown>>) => {
journalEntryInserts.push(...rows)
return {
select: () => ({
then: (resolve: (v: { data: { id: string }[]; error: null }) => void) =>
resolve({
data: rows.map(() => ({ id: `entry-${syntheticEntryId++}` })),
error: null,
}),
}),
}
},
}
}
if (table === 'journal_entry_lines') {
return {
insert: (rows: Array<Record<string, unknown>>) => {
journalEntryLineInserts.push(...rows)
return Promise.resolve({ error: null })
},
}
}
throw new Error(`Unexpected table: ${table}`)
}),
rpc: vi.fn(async (name: string, args: Record<string, unknown>) => {
rpcCalls.push({ name, args })
if (name === 'next_voucher_number') {
const series = args.p_series as string
const current = nextNumberBySeries.get(series) ?? 0
const next = current + 1
nextNumberBySeries.set(series, next)
return { data: next, error: null }
}
if (name === 'reserve_voucher_range') {
const series = args.p_series as string
const highest = args.p_highest_used as number
nextNumberBySeries.set(series, highest)
return { data: null, error: null }
}
if (name === 'release_voucher_range') {
return { data: null, error: null }
}
throw new Error(`Unexpected RPC: ${name}`)
}),
}
return {
supabase: supabase as unknown as SupabaseClient,
journalEntryInserts,
journalEntryLineInserts,
rpcCalls,
}
}
function makeVoucher(
series: string,
number: number,
lines: Array<{ account: string; amount: number }> = [
{ account: '1510', amount: 1000 },
{ account: '3001', amount: -1000 },
],
) {
return {
series,
number,
date: new Date(2024, 0, 15),
description: `Voucher ${series}${number}`,
lines,
}
}
const baseMap = new Map([
['1510', '1510'],
['3001', '3001'],
])
it('routes each voucher to its source series (B, C, V → B, C, V)', async () => {
const { supabase, journalEntryInserts, rpcCalls } = buildCapturingSupabase()
const parsed = makeParsedFile({
vouchers: [
makeVoucher('B', 1),
makeVoucher('B', 2),
makeVoucher('C', 1),
makeVoucher('V', 1),
],
})
const result = await importVouchers(
supabase,
'company-1',
'user-1',
'period-1',
parsed,
baseMap,
'B', // fallback (should not be used here — all vouchers have series)
)
expect(result.created).toBe(4)
expect(new Set(result.seriesUsed)).toEqual(new Set(['B', 'C', 'V']))
const seriesInInserts = journalEntryInserts.map((r) => r.voucher_series)
expect(seriesInInserts).toEqual(['B', 'B', 'C', 'V'])
// Each series reserves its own voucher-number range independently
const reserveCalls = rpcCalls.filter((c) => c.name === 'reserve_voucher_range')
expect(reserveCalls.map((c) => c.args.p_series)).toEqual(['B', 'C', 'V'])
})
it('falls back to defaultSeries when source voucher has empty series (SIE4I)', async () => {
const { supabase, journalEntryInserts } = buildCapturingSupabase()
const parsed = makeParsedFile({
vouchers: [
{ ...makeVoucher('', 1) },
{ ...makeVoucher('', 2) },
],
})
const result = await importVouchers(
supabase,
'company-1',
'user-1',
'period-1',
parsed,
baseMap,
'V', // fallback used because source series is empty
)
expect(result.created).toBe(2)
expect(result.seriesUsed).toEqual(['V'])
expect(journalEntryInserts.every((r) => r.voucher_series === 'V')).toBe(true)
})
it('records source series in voucherNumberMapping for audit trail', async () => {
const { supabase } = buildCapturingSupabase()
const parsed = makeParsedFile({
vouchers: [
makeVoucher('B', 1),
makeVoucher('C', 7),
],
})
const result = await importVouchers(
supabase,
'company-1',
'user-1',
'period-1',
parsed,
baseMap,
'B',
)
expect(result.voucherNumberMapping).toEqual([
{ sourceId: 'B1', series: 'B', targetNumber: 1 },
{ sourceId: 'C7', series: 'C', targetNumber: 1 },
])
})
it('assigns independent sequential target numbers per series', async () => {
const { supabase, journalEntryInserts } = buildCapturingSupabase()
const parsed = makeParsedFile({
vouchers: [
makeVoucher('B', 1),
makeVoucher('B', 2),
makeVoucher('B', 3),
makeVoucher('C', 1),
makeVoucher('C', 2),
],
})
await importVouchers(
supabase,
'company-1',
'user-1',
'period-1',
parsed,
baseMap,
'B',
)
const bNumbers = journalEntryInserts
.filter((r) => r.voucher_series === 'B')
.map((r) => r.voucher_number)
const cNumbers = journalEntryInserts
.filter((r) => r.voucher_series === 'C')
.map((r) => r.voucher_number)
// Each series starts at 1 and increments independently — not globally continuous
expect(bNumbers).toEqual([1, 2, 3])
expect(cNumbers).toEqual([1, 2])
})
})
+123 -52
View File
@@ -459,16 +459,26 @@ async function createOpeningBalanceEntry(
}
/**
* Create journal entries from vouchers using batch insert for performance
* Create journal entries from vouchers using batch insert for performance.
*
* Preserves per-voucher series from the source SIE file so customers migrating
* from systems like Fortnox (which uses B=kundfakturor, C=inbetalningar, etc.)
* retain traceability back to their original bookkeeping. Source voucher
* numbers are renumbered per target series via next_voucher_number to avoid
* collisions with existing entries; the source (series, number) is preserved
* in MigrationDocumentation.voucherNumberMapping for audit trail (BFNAR 2013:2).
*
* `defaultSeries` is used as a fallback only for vouchers that arrive with an
* empty series (e.g., SIE4I import files, per spec §5.15).
*/
async function importVouchers(
export async function importVouchers(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string,
parsed: ParsedSIEFile,
accountMap: Map<string, string>,
voucherSeries: string
defaultSeries: string
): Promise<{
created: number
ids: string[]
@@ -491,7 +501,8 @@ async function importVouchers(
mappedLineCount?: number
originalLineCount?: number
}[]
voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }>
voucherNumberMapping: Array<{ sourceId: string; series: string; targetNumber: number }>
seriesUsed: string[]
retriedBatches: number
failedBatches: number
}> {
@@ -517,7 +528,8 @@ async function importVouchers(
mappedLineCount?: number
originalLineCount?: number
}[],
voucherNumberMapping: [] as Array<{ sourceId: string; targetNumber: number }>,
voucherNumberMapping: [] as Array<{ sourceId: string; series: string; targetNumber: number }>,
seriesUsed: [] as string[],
retriedBatches: 0,
failedBatches: 0,
}
@@ -525,6 +537,7 @@ async function importVouchers(
// Pre-filter and prepare all valid vouchers
interface PreparedVoucher {
sourceId: string
series: string
date: string
description: string
lines: { account_number: string; debit_amount: number; credit_amount: number; line_description: string | null }[]
@@ -653,8 +666,16 @@ async function importVouchers(
}
}
// Resolve per-voucher series from the parsed SIE record. Fall back to the
// caller-supplied default only when the source voucher has no series
// (e.g., SIE4I subsystem import files where series/verno are optional).
const resolvedSeries = voucher.series && voucher.series.trim()
? voucher.series.trim()
: defaultSeries
preparedVouchers.push({
sourceId: voucherId,
series: resolvedSeries,
date: formatDate(voucher.date),
description: voucher.description || `Import: ${voucher.series}${voucher.number}`,
lines,
@@ -689,24 +710,21 @@ async function importVouchers(
accountIdMap.set(acc.account_number, acc.id)
}
// Get starting voucher number
const { data: startNumber } = await supabase.rpc('next_voucher_number', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: voucherSeries,
})
// Group prepared vouchers by series so each series' voucher numbers are
// reserved and assigned independently. Preserves SIE parse order within a
// series (Map maintains insertion order) so the first source voucher in
// series B becomes the first target voucher in series B.
const seriesGroups = new Map<string, PreparedVoucher[]>()
for (const v of preparedVouchers) {
const list = seriesGroups.get(v.series)
if (list) {
list.push(v)
} else {
seriesGroups.set(v.series, [v])
}
}
const currentVoucherNumber = (startNumber as number) || 1
// Reserve the full voucher number range upfront to prevent concurrent
// operations from claiming numbers in our range during batch insertion.
const reservedHighest = currentVoucherNumber + preparedVouchers.length - 1
await supabase.rpc('reserve_voucher_range', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: voucherSeries,
p_highest_used: reservedHighest,
})
results.seriesUsed = [...seriesGroups.keys()]
// Batch insert journal entries (in chunks of 100) with retry logic.
// Retries handle transient errors (Supabase rate limits, Cloudflare 500s).
@@ -715,10 +733,35 @@ async function importVouchers(
const INTER_BATCH_DELAY_MS = 50 // Prevent rate limiting under sustained load
let retriedBatches = 0
let failedBatches = 0
let highestInsertedVoucher = currentVoucherNumber - 1 // nothing inserted yet
for (let batchStart = 0; batchStart < preparedVouchers.length; batchStart += BATCH_SIZE) {
const batch = preparedVouchers.slice(batchStart, batchStart + BATCH_SIZE)
// Process each series as an independent mini-import. Voucher numbers must
// be monotonically increasing within a series; grouping first guarantees
// that without needing to interleave series-specific counters in one loop.
let seriesIndex = 0
for (const [series, groupVouchers] of seriesGroups) {
// Get starting voucher number for this series
const { data: startNumber } = await supabase.rpc('next_voucher_number', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: series,
})
const currentVoucherNumber = (startNumber as number) || 1
// Reserve the full voucher number range upfront to prevent concurrent
// operations from claiming numbers in our range during batch insertion.
const reservedHighest = currentVoucherNumber + groupVouchers.length - 1
await supabase.rpc('reserve_voucher_range', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: series,
p_highest_used: reservedHighest,
})
let highestInsertedVoucher = currentVoucherNumber - 1 // nothing inserted yet
for (let batchStart = 0; batchStart < groupVouchers.length; batchStart += BATCH_SIZE) {
const batch = groupVouchers.slice(batchStart, batchStart + BATCH_SIZE)
const batchNumber = Math.floor(batchStart / BATCH_SIZE) + 1
let batchWasRetried = false
@@ -728,7 +771,7 @@ async function importVouchers(
company_id: companyId,
fiscal_period_id: fiscalPeriodId,
voucher_number: currentVoucherNumber + batchStart + i,
voucher_series: voucherSeries,
voucher_series: series,
entry_date: v.date,
description: v.description,
source_type: 'import',
@@ -803,6 +846,7 @@ async function importVouchers(
results.voucherNumberMapping.push({
sourceId: voucher.sourceId,
series: voucher.series,
targetNumber: assignedNumber,
})
@@ -880,25 +924,30 @@ async function importVouchers(
}
// Small delay between batches to prevent Supabase/Cloudflare rate limiting
if (batchStart + BATCH_SIZE < preparedVouchers.length) {
const isLastBatchInSeries = batchStart + BATCH_SIZE >= groupVouchers.length
const isLastSeries = seriesIndex === seriesGroups.size - 1
if (!isLastBatchInSeries || !isLastSeries) {
await new Promise(resolve => setTimeout(resolve, INTER_BATCH_DELAY_MS))
}
}
// Adjust voucher sequence after insertion.
// Range was pre-reserved to `reservedHighest`. If some batches failed,
// release the unused portion to avoid burned numbers and gap-explanation friction.
if (highestInsertedVoucher < reservedHighest) {
const releaseTarget = highestInsertedVoucher >= currentVoucherNumber
? highestInsertedVoucher // partial success: set to actual highest
: currentVoucherNumber - 1 // total failure: roll back fully
await supabase.rpc('release_voucher_range', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: voucherSeries,
p_actual_last: releaseTarget,
p_reserved_highest: reservedHighest,
})
// Adjust voucher sequence after insertion for this series.
// Range was pre-reserved to `reservedHighest`. If some batches failed,
// release the unused portion to avoid burned numbers and gap-explanation friction.
if (highestInsertedVoucher < reservedHighest) {
const releaseTarget = highestInsertedVoucher >= currentVoucherNumber
? highestInsertedVoucher // partial success: set to actual highest
: currentVoucherNumber - 1 // total failure: roll back fully
await supabase.rpc('release_voucher_range', {
p_company_id: companyId,
p_fiscal_period_id: fiscalPeriodId,
p_series: series,
p_actual_last: releaseTarget,
p_reserved_highest: reservedHighest,
})
}
seriesIndex++
}
// Propagate batch retry stats
@@ -916,6 +965,29 @@ export function isBalanceSheetAccount(accountNumber: string): boolean {
return firstDigit >= 1 && firstDigit <= 2
}
/**
* Compute per-series voucher number ranges from the voucher number mapping.
* SIE imports can span multiple series (B, C, V, ...), each with its own
* independent target-number range, so the documentation records one range
* per series.
*/
export function computeVoucherNumberRanges(
mapping: Array<{ sourceId: string; series: string; targetNumber: number }>
): Array<{ series: string; from: number; to: number }> {
if (mapping.length === 0) return []
const bySeries = new Map<string, { from: number; to: number }>()
for (const entry of mapping) {
const existing = bySeries.get(entry.series)
if (existing) {
if (entry.targetNumber < existing.from) existing.from = entry.targetNumber
if (entry.targetNumber > existing.to) existing.to = entry.targetNumber
} else {
bySeries.set(entry.series, { from: entry.targetNumber, to: entry.targetNumber })
}
}
return [...bySeries.entries()].map(([series, range]) => ({ series, ...range }))
}
/**
* Create a migration adjustment entry (omföringsverifikation) to reconcile
* imported voucher movements against the SIE file's closing balances.
@@ -1470,7 +1542,8 @@ export async function executeSIEImport(
let ibRoundingAdjustment = 0
let ibExplanation: 'unallocated_result' | 'excluded_accounts' | 'rounding' | null = null
let migrationAdjustmentInfo = { created: false, deltaAccounts: 0, entryId: null as string | null }
let voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }> = []
let voucherNumberMapping: Array<{ sourceId: string; series: string; targetNumber: number }> = []
let voucherSeriesUsed: string[] = []
let voucherRetryStats = { retriedBatches: 0, failedBatches: 0 }
let voucherStats = {
total: parsed.vouchers.length,
@@ -1480,7 +1553,9 @@ export async function executeSIEImport(
skippedSingleLine: 0,
skippedEmpty: 0,
}
const voucherSeries = options.voucherSeries || 'B'
// Fallback series for vouchers that arrive without one (SIE4I subsystem files).
// Source series from #VER are preserved per-voucher by importVouchers.
const defaultSeries = options.voucherSeries || 'B'
// Validate and import opening balances.
//
@@ -1591,13 +1666,14 @@ export async function executeSIEImport(
result.fiscalPeriodId,
parsed,
accountMap,
voucherSeries
defaultSeries
)
result.journalEntriesCreated += voucherResults.created
result.journalEntryIds.push(...voucherResults.ids)
result.errors.push(...voucherResults.errors)
voucherNumberMapping = voucherResults.voucherNumberMapping
voucherSeriesUsed = voucherResults.seriesUsed
voucherRetryStats = {
retriedBatches: voucherResults.retriedBatches,
failedBatches: voucherResults.failedBatches,
@@ -1694,7 +1770,7 @@ export async function executeSIEImport(
end: fiscalYearEnd,
},
importedAt: new Date().toISOString(),
importedBy: companyId,
importedBy: userId,
accountMappings: {
total: mappingStats.total,
exact: mappingStats.exact,
@@ -1705,13 +1781,8 @@ export async function executeSIEImport(
vouchers: voucherStats,
openingBalanceRounding: ibRoundingAdjustment !== 0 ? ibRoundingAdjustment : null,
migrationAdjustment: migrationAdjustmentInfo,
voucherSeriesUsed: voucherSeries,
voucherNumberRange: voucherNumberMapping.length > 0
? {
from: voucherNumberMapping[0].targetNumber,
to: voucherNumberMapping[voucherNumberMapping.length - 1].targetNumber,
}
: null,
voucherSeriesUsed: voucherSeriesUsed.length > 0 ? voucherSeriesUsed : [defaultSeries],
voucherNumberRanges: computeVoucherNumberRanges(voucherNumberMapping),
voucherNumberMapping,
}
+8 -4
View File
@@ -383,11 +383,15 @@ export interface MigrationDocumentation {
entryId: string | null
}
// Voucher number mapping
voucherSeriesUsed: string
voucherNumberRange: { from: number; to: number } | null
// Voucher number mapping.
// Per-voucher series is preserved from the source SIE file (e.g., Fortnox uses
// B=kundfakturor, C=inbetalningar), so a single import may span multiple series
// and each series has its own independent target-number range.
voucherSeriesUsed: string[]
voucherNumberRanges: Array<{ series: string; from: number; to: number }>
voucherNumberMapping: Array<{
sourceId: string // e.g. "A1"
sourceId: string // e.g. "B1"
series: string // target series (same as source unless fallback applied)
targetNumber: number
}>
}
@@ -0,0 +1,169 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { readFileSync, existsSync } from 'node:fs'
import { join } from 'node:path'
// Fixtures live in /dev_docs which is gitignored (contains anonymised real-world
// customer exports). Skip the suite when running outside a dev machine.
const fixtureDir = join(process.cwd(), 'dev_docs', 'example_sie')
const fixturesAvailable = existsSync(join(fixtureDir, '8812090614_2025.se'))
vi.mock('../trial-balance', () => ({
generateTrialBalance: vi.fn(),
}))
import { generateIncomeStatement } from '../income-statement'
import { generateTrialBalance } from '../trial-balance'
import {
detectEncoding,
decodeBuffer,
parseSIEFile,
} from '@/lib/import/sie-parser'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
import type { ParsedSIEFile } from '@/lib/import/types'
import type { TrialBalanceRow } from '@/types'
const mockTrialBalance = vi.mocked(generateTrialBalance)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase = {} as any
beforeEach(() => {
vi.clearAllMocks()
})
/**
* Load a real SIE file from dev_docs/example_sie and parse it with the real
* parser (encoding detection included). These are anonymised real-world Bokio
* exports — regression data for the multi-year-import + year-end-close bug
* reported by an onboarding user in April 2026.
*/
function loadSIE(filename: string): ParsedSIEFile {
const path = join(process.cwd(), 'dev_docs', 'example_sie', filename)
const buffer = readFileSync(path)
// readFileSync on Node returns a Buffer; slice to an ArrayBuffer view.
const arrayBuffer = buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength
) as ArrayBuffer
const encoding = detectEncoding(arrayBuffer)
const content = decodeBuffer(arrayBuffer, encoding)
return parseSIEFile(content)
}
/**
* Build trial balance rows for a given fiscal-year SIE file, simulating what
* the database would contain after a clean SIE import:
* - Opening balance entry (from #IB 0)
* - Period activity (from all #VER lines)
*
* Maps source accounts to themselves (Bokio uses BAS-compliant numbers, so
* no translation is needed). Uses BAS reference for account_class; falls back
* to the first digit of the account number.
*/
function buildTrialBalanceFromSIE(parsed: ParsedSIEFile): TrialBalanceRow[] {
const opening = new Map<string, { debit: number; credit: number }>()
const period = new Map<string, { debit: number; credit: number }>()
// Opening balances — only class 1-2 (Swedish SIE #IB convention)
for (const ib of parsed.openingBalances.filter((b) => b.yearIndex === 0)) {
const bucket = opening.get(ib.account) || { debit: 0, credit: 0 }
if (ib.amount > 0) bucket.debit += ib.amount
else bucket.credit += Math.abs(ib.amount)
opening.set(ib.account, bucket)
}
// Period activity — every #VER line
for (const voucher of parsed.vouchers) {
for (const line of voucher.lines) {
const bucket = period.get(line.account) || { debit: 0, credit: 0 }
if (line.amount > 0) bucket.debit += line.amount
else bucket.credit += Math.abs(line.amount)
period.set(line.account, bucket)
}
}
const allAccounts = new Set([...opening.keys(), ...period.keys()])
const rows: TrialBalanceRow[] = []
for (const account of allAccounts) {
const op = opening.get(account) || { debit: 0, credit: 0 }
const pe = period.get(account) || { debit: 0, credit: 0 }
const basRef = getBASReference(account)
const accountClass = basRef?.account_class ?? parseInt(account[0], 10)
const accountName = parsed.accounts.find((a) => a.number === account)?.name ??
basRef?.account_name ?? `Konto ${account}`
rows.push({
account_number: account,
account_name: accountName,
account_class: accountClass,
opening_debit: Math.round(op.debit * 100) / 100,
opening_credit: Math.round(op.credit * 100) / 100,
period_debit: Math.round(pe.debit * 100) / 100,
period_credit: Math.round(pe.credit * 100) / 100,
closing_debit: Math.round((op.debit + pe.debit) * 100) / 100,
closing_credit: Math.round((op.credit + pe.credit) * 100) / 100,
})
}
return rows.sort((a, b) => a.account_number.localeCompare(b.account_number))
}
describe.skipIf(!fixturesAvailable)('income statement — Bokio SIE regression (dev_docs/example_sie)', () => {
it('2025: net_result matches Bokio 221 316 kr despite Yearly result closing voucher', async () => {
// Bokio's 2025 export contains V194 "Yearly result": debit 8999 / credit 2099
// with 221 316.27. Before the fix, treating 8999 as a regular class-8
// financial item cancelled the computed profit and net_result dropped to ~0.
// NE-bilaga was unaffected because it ignores 8999 by design.
const parsed = loadSIE('8812090614_2025.se')
const rows = buildTrialBalanceFromSIE(parsed)
mockTrialBalance.mockResolvedValue({
rows,
totalDebit: rows.reduce((s, r) => s + r.closing_debit, 0),
totalCredit: rows.reduce((s, r) => s + r.closing_credit, 0),
isBalanced: true,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-2025')
// Bokio shows årets resultat = 221 316.27 kr on their V194 voucher.
// gnubok computes 220 906.27 (Revenue 370 314.68 − Expenses 149 408.41),
// which is the mathematically exact figure. The 410 kr difference is
// öresutjämning/rounding that Bokio absorbed into V194 itself.
expect(report.net_result).toBeCloseTo(220_906.27, 2)
expect(report.total_revenue).toBeCloseTo(370_314.68, 2)
expect(report.total_expenses).toBeCloseTo(149_408.41, 2)
// Sanity: revenue and expenses are in the expected ballpark (~370k / ~149k)
expect(report.total_revenue).toBeGreaterThan(365_000)
expect(report.total_revenue).toBeLessThan(375_000)
expect(report.total_expenses).toBeGreaterThan(145_000)
expect(report.total_expenses).toBeLessThan(155_000)
// 8999 must not contribute to the financial section total.
// Other class 8 accounts (interest) may still appear with small amounts.
const flat = report.financial_sections.flatMap((s) => s.rows)
expect(flat.find((r) => r.account_number === '8999')).toBeUndefined()
})
it('2024: no year-end close in SIE — net_result equals the sum of #RES accounts (~541k)', async () => {
// 2024 SIE has no "Yearly result" voucher, so 8999 stays at 0 and the
// computation is a plain revenue-minus-expenses. This proves the fix
// doesn't regress the non-closed case.
const parsed = loadSIE('8812090614_2024.se')
const rows = buildTrialBalanceFromSIE(parsed)
mockTrialBalance.mockResolvedValue({
rows,
totalDebit: rows.reduce((s, r) => s + r.closing_debit, 0),
totalCredit: rows.reduce((s, r) => s + r.closing_credit, 0),
isBalanced: true,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-2024')
// Bokio internal total = 540 702.71 (from summing #RES 0 without 8999).
expect(report.net_result).toBeCloseTo(540_702.71, 2)
})
})
@@ -214,6 +214,61 @@ describe('generateIncomeStatement', () => {
expect(section.subtotal).toBe(10000)
})
it('excludes account 8999 (Årets resultat closing) from financial section', async () => {
// Regression: when a SIE import contains a year-end close voucher like
// Bokio's "Yearly result" (debit 8999, credit 2099), 8999 holds a debit
// balance equal to the computed profit. Including it as a financial item
// cancels the revenue-vs-expense difference and drives net_result to ~0.
// Matches the NE-bilaga behavior (which already ignores 8999).
mockTrialBalance.mockResolvedValue({
rows: [
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 370000, closing_debit: 0 }),
makeRow({ account_number: '5010', account_name: 'Rent', account_class: 5, closing_debit: 149000, closing_credit: 0 }),
// Year-end close posted the profit on 8999
makeRow({ account_number: '8999', account_name: 'Årets resultat', account_class: 8, closing_debit: 221000, closing_credit: 0 }),
],
totalDebit: 370000,
totalCredit: 370000,
isBalanced: true,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
expect(report.total_revenue).toBe(370000)
expect(report.total_expenses).toBe(149000)
// 8999 must not contribute — financial section should be empty
expect(report.financial_sections).toEqual([])
expect(report.total_financial).toBe(0)
// Computed net result equals what Bokio / NE-bilaga shows
expect(report.net_result).toBe(221000)
})
it('still includes legitimate class 8 accounts (8310 interest, 8410 interest expense)', async () => {
// Sanity check the 8999 exclusion is narrow — other class 8 accounts
// (interest income, interest expense, tax) must still appear.
mockTrialBalance.mockResolvedValue({
rows: [
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 100000, closing_debit: 0 }),
makeRow({ account_number: '8310', account_name: 'Ränteintäkter', account_class: 8, closing_credit: 500, closing_debit: 0 }),
makeRow({ account_number: '8410', account_name: 'Räntekostnader', account_class: 8, closing_debit: 200, closing_credit: 0 }),
makeRow({ account_number: '8999', account_name: 'Årets resultat', account_class: 8, closing_debit: 100300, closing_credit: 0 }),
],
totalDebit: 100500,
totalCredit: 100500,
isBalanced: true,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
const titles = report.financial_sections.map(s => s.title)
expect(titles).toContain('Ränteintäkter')
expect(titles).toContain('Räntekostnader')
// 89xx section would have been populated by 8999 only — excluded
expect(titles).not.toContain('Skatter och årets resultat')
expect(report.total_financial).toBe(300) // 500 - 200
expect(report.net_result).toBe(100300) // 100000 - 0 + 300
})
it('ignores class 1-2 accounts (balance sheet)', async () => {
mockTrialBalance.mockResolvedValue({
rows: [
+9 -2
View File
@@ -84,9 +84,16 @@ export async function generateIncomeStatement(
'debit' // Expenses have debit normal balance
)
// Financial sections (class 8)
// Financial sections (class 8) — exclude 8999 "Årets resultat".
// 8999 is a closing account: when year-end posts "8999 debit → 2099 credit"
// to move the computed profit into equity, including 8999's debit balance
// here cancels out the revenue/expense difference and drives net_result to
// zero. The income statement shows the *computed* årets resultat as
// (revenue - expenses + financial), so 8999's own balance must stay out.
const financialSections = buildSections(
incomeExpenseRows.filter((r) => r.account_class === 8),
incomeExpenseRows.filter(
(r) => r.account_class === 8 && r.account_number !== '8999'
),
{
'80': 'Resultat andelar koncernföretag',
'81': 'Resultat andelar intresseföretag',
+4 -1
View File
@@ -109,8 +109,11 @@ export async function generateMonthlyBreakdown(
} else if (accountClass >= 4 && accountClass <= 7) {
// Expense accounts: debit side represents expenses
bucket.expenses = Math.round((bucket.expenses + line.debit_amount - line.credit_amount) * 100) / 100
} else if (accountClass === 8) {
} else if (accountClass === 8 && line.account_number !== '8999') {
// Financial items (class 8): interest, exchange gains/losses, etc.
// 8999 "Årets resultat" is a year-end closing account — its debit/credit
// mirrors the computed profit, so including it here would cancel the
// period's income-vs-expense signal on the month of closing.
const amount = line.credit_amount - line.debit_amount
if (amount >= 0) {
bucket.income = Math.round((bucket.income + amount) * 100) / 100