fix(import): show "created on import" as the mapping target for source accounts the chart lacks (#2342)

The guided Fortnox import self-mapped a source account that exists in
neither the company chart nor BAS (4599) and then rendered its Malkonto
select blank, because the dropdown only knew chart + BAS accounts. The
row looked unmapped and unmappable while the import created the account
correctly. A nameless account (referenced by #TRANS without #KONTO) was
worse: the mapper refused the self-map, so it stayed unmapped with no
self-target to pick.

- account-mapper: the bas_range self-map no longer requires a #KONTO
  name; unmapped now means exactly "outside 1000-8999". isValidBASRange
  exported as the auto-create boundary.
- AccountMappingStep (shared by both wizards): a target the list cannot
  name is an explicit "<nr> <name> (skapas vid importen)" option, a
  "nya konton skapas" badge/filter lists them, out-of-range accounts
  that block Continue are named, nameless sources say so.
- sie-import: skippedVouchers.unmappedAccounts (per account, voucher
  count) via summarizeUnmappedSkips; warning names the accounts.
- Migration result step: names created accounts and the accounts behind
  "med ej kopplade konton".

Closes #2212


Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-09-06 18:39:36 +02:00
committed by GitHub
co-authored by Jakob Wennberg Claude Fable 5.1
parent ea4da0eb07
commit 162de2128a
10 changed files with 318 additions and 14 deletions
@@ -108,6 +108,20 @@ describe('suggestMappings', () => {
expect(result[0].matchType).toBe('bas_range')
})
// Issue #2212: an account referenced only by #TRANS/#IB arrives without a
// #KONTO name. Refusing the self-map left it unmapped with no self-target to
// pick, while the parser had already promised it would be created.
it('self-maps a nameless in-range account (referenced without #KONTO)', () => {
const source = [makeSIEAccount('4599', '')]
const result = suggestMappings(source, basAccounts)
expect(result).toHaveLength(1)
expect(result[0].targetAccount).toBe('4599')
expect(result[0].targetName).toBe('')
expect(result[0].matchType).toBe('bas_range')
expect(result[0].confidence).toBe(0.7)
})
it('does not self-map accounts outside BAS range (9000+)', () => {
const source = [makeSIEAccount('9100', 'Internt konto')]
const result = suggestMappings(source, basAccounts)
+23
View File
@@ -6,6 +6,7 @@ import {
ensureFiscalPeriod,
precheckFiscalPeriod,
importVouchers,
summarizeUnmappedSkips,
computeVoucherNumberRanges,
linkOpeningBalanceEntryToPeriod,
companyHasPriorActivity,
@@ -1845,3 +1846,25 @@ describe('precheckFiscalPeriod', () => {
).rejects.toThrow(precheck.verdict === 'conflict' ? precheck.message : 'unreachable')
})
})
describe('summarizeUnmappedSkips', () => {
// Issue #2212: the result step must name WHICH accounts excluded vouchers,
// not just how many vouchers were excluded.
it('counts vouchers per unmapped account, most excluded first', () => {
const summary = summarizeUnmappedSkips([
{ reason: 'unmapped', unmappedAccounts: ['0099'] },
{ reason: 'unmapped', unmappedAccounts: ['0099', '9100'] },
{ reason: 'unmapped', unmappedAccounts: ['9100', '9100'] },
{ reason: 'unbalanced' },
{ reason: 'single_line', unmappedAccounts: ['0099'] },
])
expect(summary).toEqual([
{ account: '0099', vouchers: 2 },
{ account: '9100', vouchers: 2 },
])
})
it('is empty when nothing was skipped for a missing mapping', () => {
expect(summarizeUnmappedSkips([{ reason: 'empty' }])).toEqual([])
})
})
+16 -3
View File
@@ -47,8 +47,13 @@ export function isSystemAccount(accountNumber: string): boolean {
/**
* Check if an account number is in the valid BAS range (1000-8999).
* Standard Swedish BAS accounts are 4-digit numbers in classes 1-8.
*
* This is the auto-create boundary: a source account in this range can
* always be carried into the chart under its own number (the importer derives
* class and type from the number), so it never needs a manual target. Outside
* it (class 9, 5-digit numbers) the user must pick a target.
*/
function isValidBASRange(accountNumber: string): boolean {
export function isValidBASRange(accountNumber: string): boolean {
if (!/^\d{4}$/.test(accountNumber)) return false
const num = parseInt(accountNumber, 10)
return num >= 1000 && num <= 8999
@@ -109,8 +114,16 @@ function findBestMatch(
// Fallback: if the account is a valid BAS-range number (1000-8999),
// self-map it using the name from the SIE file. These are standard
// BAS sub-accounts not in our reference (e.g. 1241 Personbilar).
if (isValidBASRange(source.number) && source.name) {
// BAS sub-accounts not in our reference (e.g. 1241 Personbilar), or
// accounts a source system kept outside BAS (e.g. a Fortnox chart's 4599).
//
// A missing name is not a reason to refuse: an account referenced only by
// #TRANS/#IB (no #KONTO row) arrives nameless, and the parser has already
// told the user it will be created. The number alone determines class and
// type; the importer names it "Konto <nr>" when the file has no name.
// Leaving it unmapped offered no way forward except merging it into a
// different account, which is wrong for a ledger migration (issue #2212).
if (isValidBASRange(source.number)) {
return {
sourceAccount: source.number,
sourceName: source.name,
+31 -1
View File
@@ -1214,6 +1214,29 @@ export async function resyncNextPeriodOpeningBalance(
}
}
/**
* Roll the per-voucher unmapped skips up per source account: which accounts
* had no mapping and how many vouchers each one excluded. Sorted by voucher
* count (most excluded first), then by account number, so the result step
* names the account that matters most first. Pure: exported for tests and
* for the result surface (ImportResultDetails.skippedVouchers.unmappedAccounts).
*/
export function summarizeUnmappedSkips(
skippedDetails: ReadonlyArray<{ reason: string; unmappedAccounts?: string[] }>,
): Array<{ account: string; vouchers: number }> {
const perAccount = new Map<string, number>()
for (const detail of skippedDetails) {
if (detail.reason !== 'unmapped') continue
for (const account of new Set(detail.unmappedAccounts ?? [])) {
perAccount.set(account, (perAccount.get(account) ?? 0) + 1)
}
}
return [...perAccount]
.map(([account, vouchers]) => ({ account, vouchers }))
.sort((a, b) => b.vouchers - a.vouchers || a.account.localeCompare(b.account))
}
/**
* Create journal entries from vouchers using batch insert for performance.
*
@@ -2512,6 +2535,7 @@ export async function executeSIEImport(
let voucherNumberMapping: Array<{ sourceId: string; series: string; targetNumber: number }> = []
let voucherSeriesUsed: string[] = []
let voucherRetryStats = { retriedBatches: 0, failedBatches: 0 }
let unmappedSkipSummary: Array<{ account: string; vouchers: number }> = []
let voucherStats = {
total: parsed.vouchers.length,
imported: 0,
@@ -2904,12 +2928,17 @@ export async function executeSIEImport(
}
// Report skipped vouchers as warnings
unmappedSkipSummary = summarizeUnmappedSkips(voucherResults.skippedDetails)
const totalSkipped = voucherResults.skippedEmpty + voucherResults.skippedSingleLine + voucherResults.skippedUnbalanced + voucherResults.skippedUnmapped
if (totalSkipped > 0) {
const parts: string[] = []
if (voucherResults.skippedEmpty > 0) parts.push(`${voucherResults.skippedEmpty} ${voucherResults.skippedEmpty === 1 ? 'tom' : 'tomma'}`)
if (voucherResults.skippedUnbalanced > 0) parts.push(`${voucherResults.skippedUnbalanced} obalanserade`)
if (voucherResults.skippedUnmapped > 0) parts.push(`${voucherResults.skippedUnmapped} med ej mappade konton`)
if (voucherResults.skippedUnmapped > 0) {
parts.push(
`${voucherResults.skippedUnmapped} med ej mappade konton (${unmappedSkipSummary.map((a) => a.account).join(', ')})`
)
}
result.warnings.push(
`${totalSkipped} ${totalSkipped === 1 ? 'verifikation' : 'verifikationer'} hoppades över (${totalSkipped === 1 ? 'ofullständig' : 'ofullständiga'} i källsystemet): ${parts.join(', ')}`
)
@@ -3083,6 +3112,7 @@ export async function executeSIEImport(
singleLine: voucherStats.skippedSingleLine,
empty: voucherStats.skippedEmpty,
total: totalSkippedForDetails,
...(unmappedSkipSummary.length > 0 ? { unmappedAccounts: unmappedSkipSummary } : {}),
} : undefined,
openingBalance: ibRoundingAdjustment !== 0 ? {
imbalance: ibRoundingAdjustment,
+8
View File
@@ -253,6 +253,14 @@ export interface ImportResultDetails {
singleLine: number
empty: number
total: number
/**
* The source accounts behind `unmapped`, with how many vouchers each one
* excluded. Lets the result step name the accounts instead of leaving
* the user to diff the general ledger against the source system
* (issue #2212). Absent when `unmapped` is 0 and on results recorded
* before this field existed.
*/
unmappedAccounts?: Array<{ account: string; vouchers: number }>
}
/** Opening balance imbalance info */