fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,208 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyVatTreatmentReview,
|
||||
enrichChangedAccountMappingWithVat,
|
||||
enrichAccountMappingsWithVat,
|
||||
applyVatTreatmentReviewAll,
|
||||
} from '../account-vat-treatment'
|
||||
import type { AccountMapping } from '../types'
|
||||
|
||||
function mapping(account: string, name: string): AccountMapping {
|
||||
return {
|
||||
sourceAccount: account,
|
||||
sourceName: name,
|
||||
targetAccount: account,
|
||||
targetName: name,
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
|
||||
describe('enrichAccountMappingsWithVat', () => {
|
||||
it('marks label suggestions for user review', () => {
|
||||
const [result] = enrichAccountMappingsWithVat(
|
||||
[mapping('4056', 'Inköp varor 25% EU')],
|
||||
[],
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
defaultVatTreatment: 'reverse_charge_eu_goods',
|
||||
defaultVatRate: 0.25,
|
||||
vatTreatmentSuggested: true,
|
||||
vatTreatmentReviewed: false,
|
||||
requiresVatTreatmentReview: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('suggests oss from an OSS label and leaves the BAS 3106 label for review', () => {
|
||||
const [oss, b2c] = enrichAccountMappingsWithVat(
|
||||
[
|
||||
mapping('3111', 'Försäljning enl. OSS (Spanien 21%)'),
|
||||
mapping('3106', 'Försäljning varor till annat EU-land, momspliktig'),
|
||||
],
|
||||
[],
|
||||
)
|
||||
expect(oss).toMatchObject({
|
||||
defaultVatTreatment: 'oss',
|
||||
defaultVatRate: null,
|
||||
vatTreatmentSuggested: true,
|
||||
vatTreatmentReviewed: false,
|
||||
requiresVatTreatmentReview: true,
|
||||
})
|
||||
expect(b2c).toMatchObject({
|
||||
defaultVatTreatment: null,
|
||||
vatTreatmentSuggested: false,
|
||||
vatTreatmentReviewed: false,
|
||||
requiresVatTreatmentReview: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an existing account treatment without asking again', () => {
|
||||
const [result] = enrichAccountMappingsWithVat(
|
||||
[mapping('3041', 'Försäljning tjänst 25% sv')],
|
||||
[{
|
||||
account_number: '3041',
|
||||
default_vat_treatment: 'standard_25',
|
||||
default_vat_rate: 0.25,
|
||||
} as never],
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
defaultVatTreatment: 'standard_25',
|
||||
vatTreatmentSuggested: false,
|
||||
vatTreatmentReviewed: true,
|
||||
requiresVatTreatmentReview: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves an existing booking rate when suggesting a missing treatment', () => {
|
||||
const [result] = enrichAccountMappingsWithVat(
|
||||
[mapping('3041', 'Försäljning tjänst 25% sv')],
|
||||
[{
|
||||
account_number: '3041',
|
||||
default_vat_treatment: null,
|
||||
default_vat_rate: 0.12,
|
||||
} as never],
|
||||
)
|
||||
expect(result.defaultVatTreatment).toBe('standard_25')
|
||||
expect(result.defaultVatRate).toBe(0.12)
|
||||
})
|
||||
|
||||
it('requires review for a suggested class 6 service treatment', () => {
|
||||
const [result] = enrichAccountMappingsWithVat(
|
||||
[mapping('6545', 'Inköp tjänster utanför EU 25%')],
|
||||
[],
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
defaultVatTreatment: 'reverse_charge_non_eu_services',
|
||||
requiresVatTreatmentReview: true,
|
||||
vatTreatmentReviewed: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyVatTreatmentReview', () => {
|
||||
it('persists a suggestion only after an explicit row confirmation', () => {
|
||||
const mappings = enrichAccountMappingsWithVat([
|
||||
mapping('4056', 'Inköp varor 25% EU'),
|
||||
], [])
|
||||
|
||||
expect(mappings[0].vatTreatmentReviewed).toBe(false)
|
||||
const reviewed = applyVatTreatmentReview(
|
||||
mappings,
|
||||
'4056',
|
||||
mappings[0].defaultVatTreatment ?? null,
|
||||
mappings[0].defaultVatRate ?? null,
|
||||
)
|
||||
expect(reviewed[0]).toMatchObject({
|
||||
defaultVatTreatment: 'reverse_charge_eu_goods',
|
||||
vatTreatmentReviewed: true,
|
||||
vatTreatmentSuggested: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('clears hidden review state on remap and restores it on identity mapping', () => {
|
||||
const [suggested] = enrichAccountMappingsWithVat([
|
||||
mapping('4056', 'Inköp varor 25% EU'),
|
||||
], [])
|
||||
|
||||
const [remapped] = enrichAccountMappingsWithVat([{
|
||||
...suggested,
|
||||
targetAccount: '4010',
|
||||
targetName: 'Inköp material',
|
||||
}], [])
|
||||
expect(remapped).toMatchObject({
|
||||
defaultVatTreatment: null,
|
||||
requiresVatTreatmentReview: false,
|
||||
vatTreatmentReviewed: true,
|
||||
})
|
||||
|
||||
const [identity] = enrichAccountMappingsWithVat([{
|
||||
...remapped,
|
||||
targetAccount: '4056',
|
||||
targetName: 'Inköp varor 25% EU',
|
||||
}], [])
|
||||
expect(identity).toMatchObject({
|
||||
defaultVatTreatment: 'reverse_charge_eu_goods',
|
||||
requiresVatTreatmentReview: true,
|
||||
vatTreatmentReviewed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves another row review when one mapping changes', () => {
|
||||
const initial = enrichAccountMappingsWithVat([
|
||||
mapping('3041', 'Försäljning tjänst 25% sv'),
|
||||
mapping('4056', 'Inköp varor 25% EU'),
|
||||
], [])
|
||||
const reviewed = applyVatTreatmentReview(initial, '3041', 'exempt', 0)
|
||||
const remapped = enrichChangedAccountMappingWithVat(
|
||||
reviewed.map((item) => item.sourceAccount === '4056'
|
||||
? { ...item, targetAccount: '4010', targetName: 'Inköp material' }
|
||||
: item),
|
||||
'4056',
|
||||
[],
|
||||
)
|
||||
|
||||
expect(remapped[0]).toMatchObject({
|
||||
defaultVatTreatment: 'exempt',
|
||||
defaultVatRate: 0,
|
||||
vatTreatmentReviewed: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyVatTreatmentReviewAll', () => {
|
||||
it('marks every unreviewed row reviewed and keeps its suggested default', () => {
|
||||
const mappings = [
|
||||
{
|
||||
sourceAccount: '3001', sourceName: 'Försäljning', targetAccount: '3001', targetName: 'Försäljning',
|
||||
confidence: 1, matchType: 'exact', isOverride: false,
|
||||
defaultVatTreatment: 'sales_25', defaultVatRate: 25,
|
||||
vatTreatmentSuggested: true, vatTreatmentReviewed: false, requiresVatTreatmentReview: true,
|
||||
},
|
||||
{
|
||||
sourceAccount: '4010', sourceName: 'Inköp', targetAccount: '4010', targetName: 'Inköp',
|
||||
confidence: 1, matchType: 'exact', isOverride: false,
|
||||
defaultVatTreatment: null, defaultVatRate: null,
|
||||
vatTreatmentSuggested: false, vatTreatmentReviewed: false, requiresVatTreatmentReview: true,
|
||||
},
|
||||
{
|
||||
sourceAccount: '1930', sourceName: 'Bank', targetAccount: '1930', targetName: 'Bank',
|
||||
confidence: 1, matchType: 'exact', isOverride: false,
|
||||
defaultVatTreatment: null, defaultVatRate: null,
|
||||
vatTreatmentSuggested: false, vatTreatmentReviewed: true, requiresVatTreatmentReview: false,
|
||||
},
|
||||
] as never[]
|
||||
|
||||
const result = applyVatTreatmentReviewAll(mappings)
|
||||
|
||||
// Both review rows confirmed in one action, defaults untouched.
|
||||
expect(result[0]).toMatchObject({ vatTreatmentReviewed: true, defaultVatTreatment: 'sales_25', defaultVatRate: 25 })
|
||||
expect(result[1]).toMatchObject({ vatTreatmentReviewed: true, defaultVatTreatment: null })
|
||||
// Already-reviewed rows pass through by reference.
|
||||
expect(result[2]).toBe(mappings[2])
|
||||
// No row is left gating the wizard's Continue button.
|
||||
expect(result.filter((m: { requiresVatTreatmentReview?: boolean; vatTreatmentReviewed?: boolean }) =>
|
||||
m.requiresVatTreatmentReview && !m.vatTreatmentReviewed
|
||||
)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { planChartChanges } from '../chart-plan'
|
||||
import type { AccountMapping } from '../types'
|
||||
|
||||
function mapping(
|
||||
partial: Partial<AccountMapping> & { sourceAccount: string; targetAccount: string }
|
||||
): AccountMapping {
|
||||
return {
|
||||
sourceName: '',
|
||||
targetName: '',
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
...partial,
|
||||
}
|
||||
}
|
||||
|
||||
describe('planChartChanges', () => {
|
||||
it('splits distinct target accounts into new and existing for this company', () => {
|
||||
const plan = planChartChanges(
|
||||
[
|
||||
mapping({ sourceAccount: '1930', targetAccount: '1930', sourceName: 'Företagskonto' }),
|
||||
mapping({ sourceAccount: '3010', targetAccount: '3010', sourceName: 'Konsultarvoden' }),
|
||||
mapping({ sourceAccount: '6110', targetAccount: '6110', targetName: 'Kontorsmateriel' }),
|
||||
],
|
||||
new Set(['1930']),
|
||||
)
|
||||
|
||||
expect(plan.toCreate).toBe(2)
|
||||
expect(plan.existing).toBe(1)
|
||||
expect(plan.sample).toEqual([
|
||||
{ number: '3010', name: 'Konsultarvoden' },
|
||||
{ number: '6110', name: 'Kontorsmateriel' },
|
||||
])
|
||||
})
|
||||
|
||||
it('names a new identity-mapped account after the file, not the BAS reference', () => {
|
||||
// Matches syncMappedAccounts with "Använd kontonamn från filen" on (the
|
||||
// default): the file's #KONTO name wins for sourceAccount === targetAccount.
|
||||
const plan = planChartChanges(
|
||||
[
|
||||
mapping({
|
||||
sourceAccount: '1930',
|
||||
targetAccount: '1930',
|
||||
sourceName: 'Företagskonto Swedbank',
|
||||
targetName: 'Företagskonto/checkkonto',
|
||||
}),
|
||||
],
|
||||
new Set(),
|
||||
)
|
||||
|
||||
expect(plan.sample).toEqual([{ number: '1930', name: 'Företagskonto Swedbank' }])
|
||||
})
|
||||
|
||||
it('names a remapped account after its target', () => {
|
||||
const plan = planChartChanges(
|
||||
[
|
||||
mapping({
|
||||
sourceAccount: '1910',
|
||||
targetAccount: '1930',
|
||||
sourceName: 'Kassa',
|
||||
targetName: 'Företagskonto/checkkonto',
|
||||
}),
|
||||
],
|
||||
new Set(),
|
||||
)
|
||||
|
||||
expect(plan.sample).toEqual([{ number: '1930', name: 'Företagskonto/checkkonto' }])
|
||||
})
|
||||
|
||||
it('counts two sources remapped onto one target once', () => {
|
||||
const plan = planChartChanges(
|
||||
[
|
||||
mapping({ sourceAccount: '1910', targetAccount: '1930' }),
|
||||
mapping({ sourceAccount: '1920', targetAccount: '1930' }),
|
||||
],
|
||||
new Set(),
|
||||
)
|
||||
|
||||
expect(plan.toCreate).toBe(1)
|
||||
expect(plan.existing).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves an unmapped source out of both counts', () => {
|
||||
// The import refuses while anything is unmapped; the account is neither
|
||||
// added nor present until the user creates or maps it.
|
||||
const plan = planChartChanges(
|
||||
[
|
||||
mapping({ sourceAccount: '9030', targetAccount: '', sourceName: 'Obokat resultat' }),
|
||||
mapping({ sourceAccount: '1930', targetAccount: '1930' }),
|
||||
],
|
||||
new Set(['1930']),
|
||||
)
|
||||
|
||||
expect(plan.toCreate).toBe(0)
|
||||
expect(plan.existing).toBe(1)
|
||||
expect(plan.sample).toEqual([])
|
||||
})
|
||||
|
||||
it('caps the sample but not the count', () => {
|
||||
const mappings = Array.from({ length: 12 }, (_, i) =>
|
||||
mapping({ sourceAccount: `40${10 + i}`, targetAccount: `40${10 + i}` }),
|
||||
)
|
||||
|
||||
const plan = planChartChanges(mappings, new Set())
|
||||
|
||||
expect(plan.toCreate).toBe(12)
|
||||
expect(plan.sample).toHaveLength(8)
|
||||
expect(plan.sample[0].number).toBe('4010')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
// Covers enforce_first_of_month_for_subsequent_periods (migration
|
||||
// 20260418120000). The trigger only blocks mid-month period_start when a
|
||||
// strictly earlier period exists: so importing a company's chronologically
|
||||
// first fiscal year (förlängt första räkenskapsår) via SIE must succeed even
|
||||
// after a later period was created during onboarding.
|
||||
//
|
||||
// seedCompany() creates a default 2026-01-01..2026-12-31 fiscal period; the
|
||||
// no_overlapping_fiscal_periods exclusion constraint (per-company since
|
||||
// migration 20260506140100) means every period inserted here must avoid
|
||||
// overlapping that year. The years below are chosen accordingly.
|
||||
describe('fiscal_periods: subsequent-period start-day trigger', () => {
|
||||
async function insertPeriod(
|
||||
companyId: string,
|
||||
name: string,
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
) {
|
||||
return getPool().query(
|
||||
`INSERT INTO public.fiscal_periods
|
||||
(company_id, name, period_start, period_end, is_closed, opening_balances_set)
|
||||
VALUES ($1, $2, $3, $4, false, false)
|
||||
RETURNING id`,
|
||||
[companyId, name, periodStart, periodEnd],
|
||||
)
|
||||
}
|
||||
|
||||
it('allows a mid-month start when no earlier period exists', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
// The seeded 2026 period is later than this one, so this insert is the
|
||||
// chronologically earliest period for the company → trigger must permit
|
||||
// a mid-month start (förlängt första räkenskapsår path).
|
||||
const { rows } = await insertPeriod(
|
||||
companyId,
|
||||
'Räkenskapsår 2024/2025',
|
||||
'2024-06-15',
|
||||
'2025-12-31',
|
||||
)
|
||||
expect(rows[0]!.id).toBeTruthy()
|
||||
})
|
||||
|
||||
it('allows importing an earlier mid-month period after a later day-1 period exists', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
// Onboarding-created period (day 1, year N): sits before the seeded 2026.
|
||||
await insertPeriod(companyId, 'Räkenskapsår 2025', '2025-01-01', '2025-12-31')
|
||||
|
||||
// SIE import of förlängt första räkenskapsår: earlier in time,
|
||||
// mid-month start. This used to fail with the old trigger.
|
||||
const { rows } = await insertPeriod(
|
||||
companyId,
|
||||
'Räkenskapsår 2023/2024',
|
||||
'2023-06-15',
|
||||
'2024-12-31',
|
||||
)
|
||||
expect(rows[0]!.id).toBeTruthy()
|
||||
})
|
||||
|
||||
it('still rejects mid-month start when a strictly earlier period already exists', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
await insertPeriod(companyId, 'Räkenskapsår 2024', '2024-01-01', '2024-12-31')
|
||||
|
||||
// Mid-month start in 2025: strictly later than 2024 and not overlapping
|
||||
// with the seeded 2026 period → only the start-day trigger should fire.
|
||||
await expect(
|
||||
insertPeriod(companyId, 'Räkenskapsår 2025 (bad)', '2025-06-15', '2025-12-31'),
|
||||
).rejects.toThrow(/Non-first fiscal period must start on the 1st of a month/)
|
||||
})
|
||||
|
||||
it('still rejects changing a subsequent period to a mid-month start', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
|
||||
await insertPeriod(companyId, 'Räkenskapsår 2024', '2024-01-01', '2024-12-31')
|
||||
const { rows } = await insertPeriod(
|
||||
companyId,
|
||||
'Räkenskapsår 2025',
|
||||
'2025-01-01',
|
||||
'2025-12-31',
|
||||
)
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.fiscal_periods
|
||||
SET period_start = '2025-06-15'
|
||||
WHERE id = $1`,
|
||||
[rows[0]!.id],
|
||||
),
|
||||
).rejects.toThrow(/Non-first fiscal period must start on the 1st of a month/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Tests for the CP1252-artifact tripwire (lib/import/sie-artifact-scan.ts).
|
||||
*
|
||||
* The corruption under test is CP437 SIE bytes decoded as windows-1252 by an
|
||||
* upstream system BEFORE the string reached this repo (the retired Arcim Sync
|
||||
* gateway, 2026-03-17): o-umlaut 0x94 -> U+201D, a-umlaut 0x84 -> U+201E,
|
||||
* A-umlaut 0x8E -> U+017D. The mojibake literals below are the subject being
|
||||
* tested and must stay byte-exact.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
scanSieForCp1252Artifacts,
|
||||
formatSieArtifactWarning,
|
||||
SIE_ARTIFACT_THRESHOLD,
|
||||
} from '../sie-artifact-scan'
|
||||
import { parseSIEFile } from '../sie-parser'
|
||||
import type { SIEAccount, SIEVoucher } from '../types'
|
||||
|
||||
function account(number: string, name: string): SIEAccount {
|
||||
return { number, name }
|
||||
}
|
||||
|
||||
function voucher(
|
||||
description: string,
|
||||
lineDescriptions: (string | undefined)[] = [],
|
||||
): SIEVoucher {
|
||||
return {
|
||||
series: 'A',
|
||||
number: 1,
|
||||
date: new Date('2024-01-15'),
|
||||
description,
|
||||
lines: lineDescriptions.map((d, i) => ({
|
||||
account: '1930',
|
||||
amount: i % 2 === 0 ? 100 : -100,
|
||||
description: d,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
describe('scanSieForCp1252Artifacts', () => {
|
||||
it('flags a file with artifacts in account names and voucher descriptions', () => {
|
||||
const result = scanSieForCp1252Artifacts({
|
||||
accounts: [
|
||||
account('1930', 'F”retagskonto'), // ö -> U+201D
|
||||
account('4056', 'Ink”p tj„nster inom EU'), // ö/ä -> U+201D/U+201E
|
||||
],
|
||||
vouchers: [voucher('L”neutbetalning')],
|
||||
})
|
||||
|
||||
expect(result.flagged).toBe(true)
|
||||
expect(result.artifactCount).toBe(3)
|
||||
expect(result.samples).toContain('Ink”p tj„nster inom EU')
|
||||
expect(result.samples).toContain('L”neutbetalning')
|
||||
})
|
||||
|
||||
it('counts transaction line descriptions (BANKTJŽNSTER/UTLŽGG signature)', () => {
|
||||
const result = scanSieForCp1252Artifacts({
|
||||
accounts: [account('1930', 'Bank')],
|
||||
vouchers: [voucher('Banktransaktion', ['BANKTJŽNSTER', 'UTLŽGG'])],
|
||||
})
|
||||
|
||||
expect(result.flagged).toBe(true)
|
||||
expect(result.artifactCount).toBe(2)
|
||||
expect(result.samples).toEqual(['BANKTJŽNSTER', 'UTLŽGG'])
|
||||
})
|
||||
|
||||
it('does not flag clean Swedish text, including legitimate space-padded typography', () => {
|
||||
const result = scanSieForCp1252Artifacts({
|
||||
accounts: [
|
||||
account('1930', 'Företagskonto'),
|
||||
account('1513', 'Kundfordringar – delad faktura'), // legit space-padded en dash
|
||||
],
|
||||
vouchers: [voucher('Löneutbetalning', ['Inköp tjänster inom EU', 'Avvaktar underlag …'])],
|
||||
})
|
||||
|
||||
expect(result.flagged).toBe(false)
|
||||
expect(result.artifactCount).toBe(0)
|
||||
expect(result.samples).toEqual([])
|
||||
})
|
||||
|
||||
it('stays below the threshold on a single artifact (no false alarm on one odd string)', () => {
|
||||
const result = scanSieForCp1252Artifacts({
|
||||
accounts: [account('1930', 'Företagskonto')],
|
||||
// One typographic apostrophe adjacent to letters is indistinguishable
|
||||
// from mojibake at the single-string level; the >= 2 threshold is what
|
||||
// keeps a lone occurrence from flagging the whole file.
|
||||
vouchers: [voucher('Betalning McDonald’s')],
|
||||
})
|
||||
|
||||
expect(result.flagged).toBe(false)
|
||||
expect(result.artifactCount).toBe(1)
|
||||
expect(SIE_ARTIFACT_THRESHOLD).toBe(2)
|
||||
})
|
||||
|
||||
it('caps samples at three distinct strings while counting every hit', () => {
|
||||
const result = scanSieForCp1252Artifacts({
|
||||
accounts: [
|
||||
account('4010', 'Ink”p material'),
|
||||
account('4056', 'Ink”p tj„nster inom EU'),
|
||||
account('7210', 'L”ner tj„nstem„n'),
|
||||
account('7510', 'Arbetsgivaravgifter l”n'),
|
||||
],
|
||||
vouchers: [voucher('L”neutbetalning'), voucher('L”neutbetalning')],
|
||||
})
|
||||
|
||||
expect(result.flagged).toBe(true)
|
||||
expect(result.artifactCount).toBe(6)
|
||||
expect(result.samples).toHaveLength(3)
|
||||
// Distinct: the duplicated voucher description appears once at most.
|
||||
expect(new Set(result.samples).size).toBe(3)
|
||||
})
|
||||
|
||||
it('flags real parseSIEFile output for a gateway-mojibaked SIE string', () => {
|
||||
const mojibakeSie = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Migrerad AB"',
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#KONTO 1930 "F”retagskonto"',
|
||||
'#KONTO 4056 "Ink”p tj„nster inom EU"',
|
||||
'#VER A 1 20240115 "L”neutbetalning"',
|
||||
'{',
|
||||
'#TRANS 1930 {} -100.00',
|
||||
'#TRANS 4056 {} 100.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
|
||||
const flagged = scanSieForCp1252Artifacts(parseSIEFile(mojibakeSie))
|
||||
expect(flagged.flagged).toBe(true)
|
||||
expect(flagged.artifactCount).toBe(3)
|
||||
|
||||
const cleanSie = mojibakeSie
|
||||
.replace('F”retagskonto', 'Företagskonto')
|
||||
.replace('Ink”p tj„nster inom EU', 'Inköp tjänster inom EU')
|
||||
.replace('L”neutbetalning', 'Löneutbetalning')
|
||||
const clean = scanSieForCp1252Artifacts(parseSIEFile(cleanSie))
|
||||
expect(clean.flagged).toBe(false)
|
||||
expect(clean.artifactCount).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSieArtifactWarning', () => {
|
||||
it('includes the count and the first sample in Swedish', () => {
|
||||
const message = formatSieArtifactWarning({
|
||||
flagged: true,
|
||||
artifactCount: 3,
|
||||
samples: ['Ink”p tj„nster inom EU', 'L”neutbetalning'],
|
||||
})
|
||||
|
||||
expect(message).toContain('felaktigt teckenkodad')
|
||||
expect(message).toContain('3 textfält')
|
||||
expect(message).toContain('"Ink”p tj„nster inom EU"')
|
||||
expect(message).toContain('blockeras inte')
|
||||
})
|
||||
|
||||
it('omits the example clause when no sample is available', () => {
|
||||
const message = formatSieArtifactWarning({ flagged: true, artifactCount: 2, samples: [] })
|
||||
expect(message).not.toContain('till exempel')
|
||||
expect(message).toContain('2 textfält')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { parseSIEFile } from '../sie-parser'
|
||||
import { collectSIEDimensionUsage } from '../sie-dimensions'
|
||||
import { normalizeLineDimensions } from '@/lib/bookkeeping/dimension-resolver'
|
||||
import { generateSIEExport } from '@/lib/reports/sie-export'
|
||||
|
||||
// ============================================================
|
||||
// Dimensions plan PR5: the lossless round-trip guarantee.
|
||||
//
|
||||
// parse(source) → what import writes (registry rows + line dimension maps)
|
||||
// → generateSIEExport over exactly that state → parse(exported) must carry
|
||||
// the same dimension surface: #DIM/#UNDERDIM declarations, #OBJEKT values,
|
||||
// and per-line object lists. The comparison is structural (both files run
|
||||
// through the same parser), so formatting/order differences don't matter.
|
||||
// ============================================================
|
||||
|
||||
// Sequential-queue supabase mock: same consumption order as
|
||||
// sie-export.test.ts documents:
|
||||
// 0 fiscal_periods.single, 1 prev period, 2 accounts, 3 journal_entries,
|
||||
// 4 journal_entry_lines, 5 dimensions, 6 dimension_values, 7 OB fallback
|
||||
let resultIdx: number
|
||||
let results: Array<{ data?: unknown; error?: unknown }>
|
||||
|
||||
function makeBuilder() {
|
||||
const b: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'in', 'order', 'range', 'lt', 'lte', 'gte', 'gt', 'limit', 'neq', 'eq']) {
|
||||
b[m] = vi.fn().mockReturnValue(b)
|
||||
}
|
||||
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||||
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
|
||||
return b
|
||||
}
|
||||
|
||||
function makeClient() {
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => makeBuilder()),
|
||||
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resultIdx = 0
|
||||
results = []
|
||||
})
|
||||
|
||||
const SOURCE_SIE = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Roundtrip AB"',
|
||||
'#RAR 0 20260101 20261231',
|
||||
'#KONTO 5010 "Lokalhyra"',
|
||||
'#KONTO 1930 "Företagskonto"',
|
||||
'#DIM 1 "Kostnadsställe"',
|
||||
'#DIM 6 "Projekt"',
|
||||
'#UNDERDIM 2 "Kostnadsbärare" 1',
|
||||
// Custom dimension + custom child — exactly what PR10's "Ny dimension"
|
||||
// (SIE 20+, optional parent) produces. Proves the round-trip covers
|
||||
// user-created dims, not just the reserved 1/2/6 set.
|
||||
'#DIM 20 "Avdelning"',
|
||||
'#UNDERDIM 25 "Team" 20',
|
||||
'#OBJEKT 1 "KS01" "Butiken"',
|
||||
'#OBJEKT 2 "KB1" "Bärare ett"',
|
||||
'#OBJEKT 6 "P001" "Villa Almgren"',
|
||||
'#OBJEKT 20 "SYD" "Avdelning Syd"',
|
||||
'#OBJEKT 25 "T1" "Team ett"',
|
||||
'#VER A 1 20260115 "Hyra januari"',
|
||||
'{',
|
||||
'#TRANS 5010 {1 "KS01" 2 "KB1" 6 "P001"} 15000.00',
|
||||
'#TRANS 1930 {} -15000.00',
|
||||
'}',
|
||||
'#VER A 2 20260116 "Odeklarerat projekt"',
|
||||
'{',
|
||||
// P002 is referenced but never declared via #OBJEKT: import synthesizes
|
||||
// it (name = code) and export must re-declare it.
|
||||
'#TRANS 5010 {6 "P002"} 500.00',
|
||||
'#TRANS 1930 {} -500.00',
|
||||
'}',
|
||||
'#VER A 3 20260117 "Avdelningskostnad"',
|
||||
'{',
|
||||
'#TRANS 5010 {20 "SYD" 25 "T1"} 800.00',
|
||||
'#TRANS 1930 {} -800.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
|
||||
describe('SIE dimensions round-trip', () => {
|
||||
it('parse → import state → export → parse preserves the dimension surface', async () => {
|
||||
const parsedSource = parseSIEFile(SOURCE_SIE)
|
||||
expect(parsedSource.issues.filter((i) => i.severity === 'error')).toEqual([])
|
||||
|
||||
// ── What the importer writes ─────────────────────────────────
|
||||
const usage = collectSIEDimensionUsage(parsedSource)
|
||||
|
||||
// Registry rows exactly as importDimensionRegistry inserts them.
|
||||
const dimensionRows = [...usage.dims.entries()].map(([sieDimNo, info], i) => ({
|
||||
id: `dim-${sieDimNo}`,
|
||||
sie_dim_no: sieDimNo,
|
||||
parent_sie_dim_no: info.parent ?? null,
|
||||
name: info.name,
|
||||
sort_order: i,
|
||||
}))
|
||||
const valueRows = [...usage.values.values()].map((v) => ({
|
||||
dimension_id: `dim-${v.sieDimNo}`,
|
||||
code: v.code,
|
||||
name: v.name,
|
||||
}))
|
||||
|
||||
// Journal lines exactly as importVouchers inserts them (dimensions jsonb
|
||||
// via normalizeLineDimensions; SIE amount sign → debit/credit).
|
||||
const journalEntries = parsedSource.vouchers.map((v, i) => ({
|
||||
id: `e${i + 1}`,
|
||||
entry_date: '2026-01-15',
|
||||
voucher_number: v.number,
|
||||
voucher_series: v.series,
|
||||
description: v.description,
|
||||
status: 'posted',
|
||||
}))
|
||||
const journalLines = parsedSource.vouchers.flatMap((v, i) =>
|
||||
v.lines.map((line) => ({
|
||||
journal_entry_id: `e${i + 1}`,
|
||||
account_number: line.account,
|
||||
debit_amount: line.amount > 0 ? line.amount : 0,
|
||||
credit_amount: line.amount < 0 ? Math.abs(line.amount) : 0,
|
||||
line_description: line.description ?? null,
|
||||
dimensions: normalizeLineDimensions({ dimensions: line.dimensions ?? null }),
|
||||
}))
|
||||
)
|
||||
|
||||
// ── Export over exactly that state ───────────────────────────
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2026-01-01', period_end: '2026-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prev period
|
||||
{
|
||||
data: [
|
||||
{ account_number: '5010', account_name: 'Lokalhyra', sru_code: null, is_active: true },
|
||||
{ account_number: '1930', account_name: 'Företagskonto', sru_code: null, is_active: true },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: journalEntries, error: null },
|
||||
{ data: journalLines, error: null },
|
||||
{ data: dimensionRows, error: null },
|
||||
{ data: valueRows, error: null },
|
||||
{ data: [], error: null }, // OB fallback
|
||||
]
|
||||
|
||||
const exported = await generateSIEExport(makeClient(), 'company-1', {
|
||||
fiscal_period_id: 'period-1',
|
||||
company_name: 'Roundtrip AB',
|
||||
org_number: null,
|
||||
program_name: 'ERPBase',
|
||||
})
|
||||
|
||||
// ── Compare the two dimension surfaces structurally ──────────
|
||||
const parsedExport = parseSIEFile(exported)
|
||||
expect(parsedExport.issues.filter((i) => i.severity === 'error')).toEqual([])
|
||||
|
||||
const dimSet = (dims: typeof parsedSource.dimensions) =>
|
||||
new Set(dims.map((d) => `${d.sieDimNo}|${d.name}|${d.parentSieDimNo ?? ''}`))
|
||||
// Every declaration that carries data survives: including the
|
||||
// #UNDERDIM child with its parent link. (A declared dimension with no
|
||||
// values and no tagged lines is metadata without data; export
|
||||
// deliberately omits it, so the fixture gives every dim a value.)
|
||||
for (const entry of dimSet(parsedSource.dimensions)) {
|
||||
expect(dimSet(parsedExport.dimensions)).toContain(entry)
|
||||
}
|
||||
|
||||
const valueSet = (values: typeof parsedSource.dimensionValues) =>
|
||||
new Set(values.map((v) => `${v.sieDimNo}|${v.code}|${v.name}`))
|
||||
for (const entry of valueSet(parsedSource.dimensionValues)) {
|
||||
expect(valueSet(parsedExport.dimensionValues)).toContain(entry)
|
||||
}
|
||||
// The undeclared-but-referenced P002 got synthesized (name = code).
|
||||
expect(valueSet(parsedExport.dimensionValues)).toContain('6|P002|P002')
|
||||
|
||||
// Per-line object lists survive verbatim.
|
||||
const lineDims = (parsed: typeof parsedSource) =>
|
||||
parsed.vouchers.flatMap((v) => v.lines.map((l) => l.dimensions ?? null))
|
||||
expect(lineDims(parsedExport)).toEqual(lineDims(parsedSource))
|
||||
})
|
||||
|
||||
it('collectSIEDimensionUsage synthesizes reserved names and prefers declared ones', () => {
|
||||
const parsed = parseSIEFile(
|
||||
[
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#RAR 0 20260101 20261231',
|
||||
// Dim 7 (reserved: Anställd) referenced without declaration; dim 6
|
||||
// declared with a custom name that must win over "Projekt".
|
||||
'#DIM 6 "Mina projekt"',
|
||||
'#VER A 1 20260115 "Löner"',
|
||||
'{',
|
||||
'#TRANS 7010 {7 "ANNA" 6 "P001" 42 "X"} 1000.00',
|
||||
'#TRANS 1930 {} -1000.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
const usage = collectSIEDimensionUsage(parsed)
|
||||
expect(usage.dims.get(7)?.name).toBe('Anställd')
|
||||
expect(usage.dims.get(6)?.name).toBe('Mina projekt')
|
||||
// Unknown custom number falls back to a generic label.
|
||||
expect(usage.dims.get(42)?.name).toBe('Dimension 42')
|
||||
expect(usage.taggedLines).toBe(1)
|
||||
expect([...usage.values.keys()].sort()).toEqual(['42 X', '6 P001', '7 ANNA'])
|
||||
})
|
||||
|
||||
it('rejects registry codes that violate the DB CHECK but keeps them on lines', () => {
|
||||
const longCode = 'X'.repeat(41)
|
||||
const parsed = parseSIEFile(
|
||||
[
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#RAR 0 20260101 20261231',
|
||||
'#VER A 1 20260115 "För lång kod"',
|
||||
'{',
|
||||
`#TRANS 5010 {6 "${longCode}"} 100.00`,
|
||||
'#TRANS 1930 {} -100.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
// The line keeps the tag (legacy free-text survives on lines)…
|
||||
expect(parsed.vouchers[0].lines[0].dimensions).toEqual({ '6': longCode })
|
||||
// …but the registry collection skips it and reports why.
|
||||
const usage = collectSIEDimensionUsage(parsed)
|
||||
expect(usage.values.size).toBe(0)
|
||||
expect(usage.invalidCodes.size).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,374 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
// A completed sie_imports row the correction history can point at.
|
||||
async function insertSieImport(companyId: string, userId: string): Promise<string> {
|
||||
const { rows } = await getPool().query<{ id: string }>(
|
||||
`INSERT INTO public.sie_imports (company_id, user_id, filename, file_hash, sie_type, status)
|
||||
VALUES ($1, $2, 'fixture.se', md5(gen_random_uuid()::text), 4, 'completed')
|
||||
RETURNING id`,
|
||||
[companyId, userId],
|
||||
)
|
||||
return rows[0]!.id
|
||||
}
|
||||
|
||||
describe('import_sie_journal_entries RPC', () => {
|
||||
it('rolls back the journal entry header when a line insert fails', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A1',
|
||||
series: 'A',
|
||||
date: '2026-01-15',
|
||||
description: 'Bad imported voucher',
|
||||
sourceSeries: 'A',
|
||||
sourceNumber: 1,
|
||||
sourceType: 'import',
|
||||
lines: [
|
||||
{
|
||||
account_number: '1930',
|
||||
debit_amount: 100,
|
||||
credit_amount: 0,
|
||||
currency: 'SEK',
|
||||
line_description: 'Bank',
|
||||
sort_order: 0,
|
||||
},
|
||||
{
|
||||
account_number: null,
|
||||
debit_amount: 0,
|
||||
credit_amount: 100,
|
||||
currency: 'SEK',
|
||||
line_description: 'Invalid line',
|
||||
sort_order: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[companyId, userId, fiscalPeriodId, JSON.stringify(payload)],
|
||||
),
|
||||
).rejects.toThrow(/null value in column "account_number"|violates not-null constraint/i)
|
||||
|
||||
const headers = await getPool().query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count
|
||||
FROM public.journal_entries
|
||||
WHERE company_id = $1
|
||||
AND fiscal_period_id = $2
|
||||
AND description = 'Bad imported voucher'`,
|
||||
[companyId, fiscalPeriodId],
|
||||
)
|
||||
expect(headers.rows[0]!.count).toBe('0')
|
||||
|
||||
const sequence = await getPool().query<{ last_number: number }>(
|
||||
`SELECT last_number
|
||||
FROM public.voucher_sequences
|
||||
WHERE company_id = $1
|
||||
AND fiscal_period_id = $2
|
||||
AND voucher_series = 'A'`,
|
||||
[companyId, fiscalPeriodId],
|
||||
)
|
||||
expect(sequence.rowCount).toBe(0)
|
||||
})
|
||||
|
||||
it('posts a balanced voucher and carries the dimensions jsonb through to the generated mirrors', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A1',
|
||||
series: 'A',
|
||||
date: '2026-02-01',
|
||||
description: 'Dimensioned import',
|
||||
sourceSeries: 'A',
|
||||
sourceNumber: 1,
|
||||
sourceType: 'import',
|
||||
lines: [
|
||||
{
|
||||
account_number: '5010',
|
||||
debit_amount: 100,
|
||||
credit_amount: 0,
|
||||
currency: 'SEK',
|
||||
line_description: 'Lokalhyra',
|
||||
sort_order: 0,
|
||||
// SIE object-list codes: 1 = kostnadsställe, 6 = projekt.
|
||||
dimensions: { '1': 'CC-10', '6': 'PROJ-X' },
|
||||
},
|
||||
{
|
||||
account_number: '1930',
|
||||
debit_amount: 0,
|
||||
credit_amount: 100,
|
||||
currency: 'SEK',
|
||||
line_description: 'Bank',
|
||||
sort_order: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const res = await getPool().query<{ import_sie_journal_entries: { inserted_entries: unknown[] } }>(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[companyId, userId, fiscalPeriodId, JSON.stringify(payload)],
|
||||
)
|
||||
expect(res.rows[0]!.import_sie_journal_entries.inserted_entries).toHaveLength(1)
|
||||
|
||||
const posted = await getPool().query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count
|
||||
FROM public.journal_entries
|
||||
WHERE company_id = $1 AND status = 'posted' AND description = 'Dimensioned import'`,
|
||||
[companyId],
|
||||
)
|
||||
expect(posted.rows[0]!.count).toBe('1')
|
||||
|
||||
const dimLine = await getPool().query<{
|
||||
dimensions: Record<string, string>
|
||||
cost_center: string | null
|
||||
project: string | null
|
||||
}>(
|
||||
`SELECT l.dimensions, l.cost_center, l.project
|
||||
FROM public.journal_entry_lines l
|
||||
JOIN public.journal_entries je ON je.id = l.journal_entry_id
|
||||
WHERE je.company_id = $1 AND l.account_number = '5010'`,
|
||||
[companyId],
|
||||
)
|
||||
expect(dimLine.rows[0]!.dimensions).toEqual({ '1': 'CC-10', '6': 'PROJ-X' })
|
||||
// GENERATED mirrors derive from the jsonb: both must be populated.
|
||||
expect(dimLine.rows[0]!.cost_center).not.toBeNull()
|
||||
expect(dimLine.rows[0]!.project).not.toBeNull()
|
||||
})
|
||||
|
||||
it('rejects an unbalanced voucher and rolls the whole import back', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A1',
|
||||
series: 'A',
|
||||
date: '2026-02-01',
|
||||
description: 'Unbalanced import',
|
||||
sourceType: 'import',
|
||||
lines: [
|
||||
{ account_number: '5010', debit_amount: 100, credit_amount: 0, currency: 'SEK', sort_order: 0 },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 90, currency: 'SEK', sort_order: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[companyId, userId, fiscalPeriodId, JSON.stringify(payload)],
|
||||
),
|
||||
).rejects.toThrow(/unbalanced/i)
|
||||
|
||||
const headers = await getPool().query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count FROM public.journal_entries
|
||||
WHERE company_id = $1 AND description = 'Unbalanced import'`,
|
||||
[companyId],
|
||||
)
|
||||
expect(headers.rows[0]!.count).toBe('0')
|
||||
})
|
||||
|
||||
it('rejects a fiscal period that belongs to another company', async () => {
|
||||
const a = await seedCompany()
|
||||
const b = await seedCompany()
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A1',
|
||||
series: 'A',
|
||||
date: '2026-02-01',
|
||||
description: 'Foreign fiscal period',
|
||||
sourceType: 'import',
|
||||
lines: [
|
||||
{ account_number: '5010', debit_amount: 100, credit_amount: 0, currency: 'SEK', sort_order: 0 },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 100, currency: 'SEK', sort_order: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
// company A's id + user, but company B's fiscal period.
|
||||
await expect(
|
||||
getPool().query(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[a.companyId, a.userId, b.fiscalPeriodId, JSON.stringify(payload)],
|
||||
),
|
||||
).rejects.toThrow(/does not belong to company/i)
|
||||
})
|
||||
// Migration 20260909132618 (#2427): #BTRANS/#RTRANS history rides on the
|
||||
// payload as `corrections` and lands as ONE rättelselogg row per voucher,
|
||||
// source='sie_import'. The ledger insert is unchanged.
|
||||
it('writes source-system correction history to the rättelselogg without touching the lines', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const sieImportId = await insertSieImport(companyId, userId)
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A7',
|
||||
series: 'A',
|
||||
date: '2026-03-01',
|
||||
description: 'Corrected in source',
|
||||
sourceSeries: 'A',
|
||||
sourceNumber: 7,
|
||||
sourceType: 'import',
|
||||
sieImportId,
|
||||
corrections: {
|
||||
struck: [
|
||||
{ account_number: '5010', debit_amount: 1200, credit_amount: 0, line_description: 'Lokalhyra', sort_order: 0, signature: 'EL' },
|
||||
],
|
||||
added: [
|
||||
{ account_number: '6540', debit_amount: 1200, credit_amount: 0, line_description: 'IT', sort_order: 0, signature: 'AB' },
|
||||
],
|
||||
signature: 'EL',
|
||||
},
|
||||
lines: [
|
||||
{ account_number: '6540', debit_amount: 1200, credit_amount: 0, currency: 'SEK', line_description: 'IT', sort_order: 0 },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 1200, currency: 'SEK', line_description: 'Bank', sort_order: 1 },
|
||||
],
|
||||
},
|
||||
{
|
||||
sourceId: 'A8',
|
||||
series: 'A',
|
||||
date: '2026-03-02',
|
||||
description: 'Plain voucher',
|
||||
sourceSeries: 'A',
|
||||
sourceNumber: 8,
|
||||
sourceType: 'import',
|
||||
lines: [
|
||||
{ account_number: '5010', debit_amount: 100, credit_amount: 0, currency: 'SEK', line_description: null, sort_order: 0 },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 100, currency: 'SEK', line_description: null, sort_order: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const res = await getPool().query<{ import_sie_journal_entries: { inserted_entries: Array<{ id: string; sourceId: string }> } }>(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[companyId, userId, fiscalPeriodId, JSON.stringify(payload)],
|
||||
)
|
||||
const inserted = res.rows[0]!.import_sie_journal_entries.inserted_entries
|
||||
expect(inserted).toHaveLength(2)
|
||||
const correctedId = inserted.find((e) => e.sourceId === 'A7')!.id
|
||||
|
||||
// Ledger: exactly the #TRANS rows, posted and balanced. History never
|
||||
// becomes a line.
|
||||
const lines = await getPool().query<{ account_number: string; debit_amount: string; credit_amount: string }>(
|
||||
`SELECT account_number, debit_amount::text, credit_amount::text
|
||||
FROM public.journal_entry_lines
|
||||
WHERE journal_entry_id = $1
|
||||
ORDER BY sort_order`,
|
||||
[correctedId],
|
||||
)
|
||||
expect(lines.rows.map((r) => r.account_number)).toEqual(['6540', '1930'])
|
||||
|
||||
// One log row for the corrected voucher, none for the plain one.
|
||||
const logs = await getPool().query<{
|
||||
journal_entry_id: string
|
||||
rattelse_type: string
|
||||
source: string
|
||||
sie_import_id: string | null
|
||||
external_signature: string | null
|
||||
actor: string | null
|
||||
struck_lines: Array<Record<string, unknown>>
|
||||
added_lines: Array<Record<string, unknown>>
|
||||
}>(
|
||||
`SELECT journal_entry_id, rattelse_type, source, sie_import_id, external_signature, actor, struck_lines, added_lines
|
||||
FROM public.journal_entry_rattelse_log
|
||||
WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(logs.rows).toHaveLength(1)
|
||||
const log = logs.rows[0]!
|
||||
expect(log).toMatchObject({
|
||||
journal_entry_id: correctedId,
|
||||
rattelse_type: 'lines',
|
||||
source: 'sie_import',
|
||||
sie_import_id: sieImportId,
|
||||
external_signature: 'EL',
|
||||
actor: null,
|
||||
})
|
||||
// Snapshot shape matches what correct_entry_lines_inline stores, so the
|
||||
// verifikat page renders both the same way.
|
||||
expect(log.struck_lines).toHaveLength(1)
|
||||
expect(log.struck_lines[0]).toMatchObject({
|
||||
journal_entry_id: correctedId,
|
||||
account_number: '5010',
|
||||
debit_amount: 1200,
|
||||
credit_amount: 0,
|
||||
line_description: 'Lokalhyra',
|
||||
sort_order: 0,
|
||||
currency: 'SEK',
|
||||
signature: 'EL',
|
||||
})
|
||||
expect(typeof log.struck_lines[0]!.id).toBe('string')
|
||||
// Per-line signatures survive: the added row names a different corrector.
|
||||
expect(log.added_lines[0]).toMatchObject({ account_number: '6540', debit_amount: 1200, signature: 'AB' })
|
||||
|
||||
// The log stays WORM for imported rows too.
|
||||
await expect(
|
||||
getPool().query(`DELETE FROM public.journal_entry_rattelse_log WHERE company_id = $1`, [companyId]),
|
||||
).rejects.toThrow(/oföränderlig/)
|
||||
})
|
||||
|
||||
it('rejects correction history whose sie_import_id belongs to another company', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const other = await seedCompany()
|
||||
const foreignImportId = await insertSieImport(other.companyId, other.userId)
|
||||
|
||||
const payload = [
|
||||
{
|
||||
sourceId: 'A1',
|
||||
series: 'A',
|
||||
date: '2026-03-01',
|
||||
description: 'Foreign provenance',
|
||||
sourceSeries: 'A',
|
||||
sourceNumber: 1,
|
||||
sourceType: 'import',
|
||||
sieImportId: foreignImportId,
|
||||
corrections: {
|
||||
struck: [{ account_number: '5010', debit_amount: 100, credit_amount: 0, line_description: null, sort_order: 0 }],
|
||||
added: [],
|
||||
signature: null,
|
||||
},
|
||||
lines: [
|
||||
{ account_number: '6540', debit_amount: 100, credit_amount: 0, currency: 'SEK', line_description: null, sort_order: 0 },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 100, currency: 'SEK', line_description: null, sort_order: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`SELECT public.import_sie_journal_entries($1::uuid, $2::uuid, $3::uuid, $4::jsonb)`,
|
||||
[companyId, userId, fiscalPeriodId, JSON.stringify(payload)],
|
||||
),
|
||||
).rejects.toThrow(/does not belong to company/)
|
||||
|
||||
// Fail closed: the whole import rolled back, nothing posted, no log row.
|
||||
const posted = await getPool().query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count FROM public.journal_entries WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(posted.rows[0]!.count).toBe('0')
|
||||
const logs = await getPool().query<{ count: string }>(
|
||||
`SELECT count(*)::text AS count FROM public.journal_entry_rattelse_log WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(logs.rows[0]!.count).toBe('0')
|
||||
})
|
||||
|
||||
it('rejects an imported history row that claims an actor (provenance check)', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.journal_entry_rattelse_log
|
||||
(company_id, journal_entry_id, rattelse_type, struck_lines, added_lines, actor, source)
|
||||
VALUES ($1, gen_random_uuid(), 'lines', '[]', '[]', gen_random_uuid(), 'sie_import')`,
|
||||
[companyId],
|
||||
),
|
||||
).rejects.toThrow(/journal_entry_rattelse_log_import_provenance_check/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,459 @@
|
||||
/**
|
||||
* Regression suite for the Lookma AB support case (2026-05-28).
|
||||
*
|
||||
* The bug: gnubok_import_sie + executeSIEImport accepted mappings that
|
||||
* couldn't cover a single account in the file. The per-voucher loop then
|
||||
* silently skipped every verifikation, finalizeImportRecord marked the
|
||||
* sie_imports row 'completed' with transactions_count=0, and the partial
|
||||
* unique index on (company_id, file_hash) held the slot: blocking retry.
|
||||
*
|
||||
* The fix layers three guards:
|
||||
* 1. Stage-time refusal in gnubok_import_sie (covered in
|
||||
* extensions/general/mcp-server/__tests__/import-sie-stage.test.ts).
|
||||
* 2. Defense-in-depth refusal in executeSIEImport (this file).
|
||||
* 3. Finalizer downgrade of any 0-entry success to 'failed' (this file).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { executeSIEImport, finalizeImportRecord } from '../sie-import'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { ParsedSIEFile, AccountMapping, ImportResult, MigrationDocumentation } from '../types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
function makeParsedFile(overrides?: Partial<ParsedSIEFile>): ParsedSIEFile {
|
||||
return {
|
||||
header: {
|
||||
sieType: 4,
|
||||
flagga: 0,
|
||||
program: 'TestProg',
|
||||
programVersion: '1.0',
|
||||
generatedDate: '2024-01-01',
|
||||
format: 'PC8',
|
||||
companyName: 'Lookma Mock AB',
|
||||
orgNumber: '5567201701',
|
||||
address: null,
|
||||
fiscalYears: [{ yearIndex: 0, start: '2024-01-01', end: '2024-12-31' }],
|
||||
currency: 'SEK',
|
||||
kontoPlanType: null,
|
||||
},
|
||||
accounts: [
|
||||
{ number: '1930', name: 'Företagskonto' },
|
||||
{ number: '6110', name: 'Kontorsmaterial' },
|
||||
],
|
||||
openingBalances: [{ yearIndex: 0, account: '1930', amount: 50000 }],
|
||||
closingBalances: [],
|
||||
resultBalances: [],
|
||||
dimensions: [],
|
||||
dimensionValues: [],
|
||||
vouchers: [
|
||||
{
|
||||
series: 'A',
|
||||
number: 1,
|
||||
date: new Date(2024, 0, 15),
|
||||
description: 'Inköp',
|
||||
lines: [
|
||||
{ account: '6110', amount: 1000 },
|
||||
{ account: '1930', amount: -1000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
issues: [],
|
||||
stats: {
|
||||
totalAccounts: 2,
|
||||
totalVouchers: 1,
|
||||
totalTransactionLines: 2,
|
||||
fiscalYearStart: '2024-01-01',
|
||||
fiscalYearEnd: '2024-12-31',
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMapping(source: string, target: string | null): AccountMapping {
|
||||
return {
|
||||
sourceAccount: source,
|
||||
sourceName: `Account ${source}`,
|
||||
targetAccount: target as string,
|
||||
targetName: target ? `Target ${target}` : '',
|
||||
confidence: target ? 1 : 0,
|
||||
matchType: target ? 'exact' : 'manual',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
|
||||
describe('executeSIEImport: defense-in-depth coverage check', () => {
|
||||
it('refuses to insert a sie_imports row when mappings is empty', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const parsed = makeParsedFile()
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
parsed,
|
||||
[],
|
||||
{
|
||||
filename: 'lookma.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.importId).toBeNull()
|
||||
expect(result.errors.join(' ')).toMatch(/täcker inga konton/i)
|
||||
})
|
||||
|
||||
it('refuses when mappings exist but cover none of the file\'s accounts', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const parsed = makeParsedFile()
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
parsed,
|
||||
[makeMapping('9999', '9999')],
|
||||
{
|
||||
filename: 'wrong.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.importId).toBeNull()
|
||||
expect(result.errors.join(' ')).toMatch(/täcker inga konton/i)
|
||||
})
|
||||
|
||||
it('still rejects mappings with targetAccount=null (existing guard)', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const parsed = makeParsedFile()
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
parsed,
|
||||
[makeMapping('6110', null), makeMapping('1930', null)],
|
||||
{
|
||||
filename: 'half.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/not mapped/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('finalizeImportRecord: 0-entry downgrade', () => {
|
||||
it('flips a 0-entry success to status=failed and records the reason', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-1',
|
||||
fiscalPeriodId: 'fp-1',
|
||||
openingBalanceEntryId: null,
|
||||
journalEntriesCreated: 0,
|
||||
journalEntryIds: [],
|
||||
errors: [],
|
||||
warnings: ['100 verifikationer hoppades över med ej mappade konton'],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-1',
|
||||
'company-1',
|
||||
result,
|
||||
'#dummy',
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/0 verifikationer/i)
|
||||
})
|
||||
|
||||
it('leaves a successful run with entries alone', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-2',
|
||||
fiscalPeriodId: 'fp-2',
|
||||
openingBalanceEntryId: null,
|
||||
journalEntriesCreated: 42,
|
||||
journalEntryIds: Array(42).fill('je'),
|
||||
errors: [],
|
||||
warnings: [],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-2',
|
||||
'company-1',
|
||||
result,
|
||||
'#dummy',
|
||||
)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.errors).toEqual([])
|
||||
})
|
||||
|
||||
// The CashLeads Fortnox migration case (2026-08-06): Fortnox exports an
|
||||
// empty SIE file for a fiscal year with nothing booked yet. The parsed
|
||||
// voucher count travels in documentation.vouchers.total; when it is 0 the
|
||||
// run is a legitimate no-op, not a failure, and flipping it to 'failed'
|
||||
// aborted the whole migration wizard.
|
||||
function makeDocumentation(voucherTotal: number): MigrationDocumentation {
|
||||
return {
|
||||
sourceSystem: 'Fortnox',
|
||||
sourceVersion: '3.61.17',
|
||||
sieType: 4,
|
||||
generatedDate: '2026-08-06',
|
||||
fiscalYear: { start: '2026-01-01', end: '2026-12-31' },
|
||||
importedAt: '2026-08-06T19:40:46.781Z',
|
||||
importedBy: 'user-1',
|
||||
accountMappings: { total: 739, exact: 613, basRange: 126, manual: 0, unmapped: 0 },
|
||||
vouchers: {
|
||||
total: voucherTotal,
|
||||
imported: 0,
|
||||
skippedUnbalanced: 0,
|
||||
skippedUnmapped: voucherTotal,
|
||||
skippedSingleLine: 0,
|
||||
skippedEmpty: 0,
|
||||
},
|
||||
openingBalanceRounding: null,
|
||||
migrationAdjustment: { created: false, deltaAccounts: 0, entryId: null },
|
||||
voucherSeriesUsed: ['B'],
|
||||
voucherNumberRanges: [],
|
||||
voucherNumberMapping: [],
|
||||
}
|
||||
}
|
||||
|
||||
it('keeps a 0-entry run completed when the file itself contained no vouchers', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-empty',
|
||||
fiscalPeriodId: 'fp-2026',
|
||||
openingBalanceEntryId: null,
|
||||
journalEntriesCreated: 0,
|
||||
journalEntryIds: [],
|
||||
errors: [],
|
||||
warnings: [],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-empty',
|
||||
'company-1',
|
||||
result,
|
||||
'#dummy',
|
||||
makeDocumentation(0),
|
||||
)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.errors).toEqual([])
|
||||
expect(result.warnings.join(' ')).toMatch(/inga verifikationer/i)
|
||||
})
|
||||
|
||||
it('still flips to failed when raw content declares #VER but parsing yielded 0 vouchers', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-swallowed',
|
||||
fiscalPeriodId: 'fp-2026',
|
||||
openingBalanceEntryId: null,
|
||||
journalEntriesCreated: 0,
|
||||
journalEntryIds: [],
|
||||
errors: [],
|
||||
warnings: ['3 #VER-rader hittades men inga verifikationer kunde tolkas: kontrollera fältavskiljare och teckenkodning'],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
// A truncated or mis-decoded file: the parser saw no vouchers
|
||||
// (documentation says total 0) but the raw content declares #VER.
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-swallowed',
|
||||
'company-1',
|
||||
result,
|
||||
'#FLAGGA 0\n#VER "A" "1" 20260115 "Inköp"\n{\n}\n',
|
||||
makeDocumentation(0),
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/0 verifikationer/i)
|
||||
})
|
||||
|
||||
it('still flips to failed when the file had vouchers but none were imported', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-skipped',
|
||||
fiscalPeriodId: 'fp-1',
|
||||
openingBalanceEntryId: null,
|
||||
journalEntriesCreated: 0,
|
||||
journalEntryIds: [],
|
||||
errors: [],
|
||||
warnings: ['100 verifikationer hoppades över med ej mappade konton'],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-skipped',
|
||||
'company-1',
|
||||
result,
|
||||
'#dummy',
|
||||
makeDocumentation(100),
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/0 verifikationer/i)
|
||||
})
|
||||
|
||||
it('leaves a 0-voucher run alone when an OB entry was created', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result: ImportResult = {
|
||||
success: true,
|
||||
importId: 'imp-3',
|
||||
fiscalPeriodId: 'fp-3',
|
||||
openingBalanceEntryId: 'ob-1',
|
||||
journalEntriesCreated: 1,
|
||||
journalEntryIds: ['ob-1'],
|
||||
errors: [],
|
||||
warnings: [],
|
||||
replacedPriorImport: null,
|
||||
}
|
||||
|
||||
await finalizeImportRecord(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'imp-3',
|
||||
'company-1',
|
||||
result,
|
||||
'#dummy',
|
||||
)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeSIEImport: coverage check with derived IB (issue #675)', () => {
|
||||
// SIE type 1/2-style file: no vouchers, no #IB 0: only #UB -1. The
|
||||
// current-year IB must be derived from #UB -1, and the derived accounts
|
||||
// must feed the coverage guard (before the fix this set was empty, so the
|
||||
// guard never inspected UB-1-only files at all).
|
||||
function makeUb1OnlyFile(): ParsedSIEFile {
|
||||
return makeParsedFile({
|
||||
openingBalances: [],
|
||||
closingBalances: [
|
||||
{ yearIndex: -1, account: '1930', amount: 37400.78 },
|
||||
{ yearIndex: -1, account: '2010', amount: -37400.78 },
|
||||
],
|
||||
vouchers: [],
|
||||
stats: {
|
||||
totalAccounts: 2,
|
||||
totalVouchers: 0,
|
||||
totalTransactionLines: 0,
|
||||
fiscalYearStart: '2024-01-01',
|
||||
fiscalYearEnd: '2024-12-31',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('refuses when mappings cover none of the derived IB accounts', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeUb1OnlyFile(),
|
||||
[makeMapping('9999', '9999')],
|
||||
{
|
||||
filename: 'ub1-only.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: true,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.importId).toBeNull()
|
||||
expect(result.errors.join(' ')).toMatch(/täcker inga konton/i)
|
||||
})
|
||||
|
||||
it('passes the coverage guard when mappings cover the derived IB accounts', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
// Past the guard the flow proceeds: dup check → stale cleanup → pending
|
||||
// record insert → chart fetch → period-dup check → find fiscal period
|
||||
// (null → clean stop with a NON-coverage error, which is all this test
|
||||
// needs to prove).
|
||||
enqueueMany([
|
||||
{ data: null }, // checkDuplicateImport
|
||||
{ data: null }, // cleanupStaleImportRecords delete
|
||||
{ data: { id: 'imp-1' } }, // createPendingImportRecord insert
|
||||
{ data: [] }, // syncMappedAccounts chart fetch
|
||||
{ data: null }, // chart insert (missing accounts)
|
||||
{ data: null }, // checkDuplicatePeriodImport
|
||||
{ data: null }, // find existing fiscal period → stops here
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeUb1OnlyFile(),
|
||||
[makeMapping('1930', '1930'), makeMapping('2010', '2010')],
|
||||
{
|
||||
filename: 'ub1-only.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: true,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
expect(result.errors.join(' ')).not.toMatch(/täcker inga konton/i)
|
||||
expect(result.errors.join(' ')).toMatch(/No matching fiscal period found/i)
|
||||
})
|
||||
|
||||
it('skips the IB accounts in the guard when importOpeningBalances is false', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeUb1OnlyFile(),
|
||||
[makeMapping('9999', '9999')],
|
||||
{
|
||||
filename: 'ub1-only.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
},
|
||||
)
|
||||
|
||||
// No vouchers + IB import disabled → sourceAccountsInFile is empty and
|
||||
// the guard does not fire (existing semantics preserved).
|
||||
expect(result.errors.join(' ')).not.toMatch(/täcker inga konton/i)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,486 @@
|
||||
/**
|
||||
* Regression suite for issue #1667 (Boltonshield AB support case, 2026-08-17).
|
||||
*
|
||||
* The bug: after partially deleting imported data, a provider re-sync could
|
||||
* not re-import an earlier fiscal year. Three defects compounded:
|
||||
*
|
||||
* 1. The sie_imports 'completed' watermark survives data deletion, and the
|
||||
* replace path aborted the WHOLE year when replaceSIEImport could not
|
||||
* resolve the prior row (its data already gone).
|
||||
* 2. Prior-import detection used `.limit(1).maybeSingle()` with no
|
||||
* ordering: with multiple overlapping completed rows for the same year
|
||||
* it picked an arbitrary one and left the rest standing.
|
||||
* 3. The wizard error did not say which fiscal year failed (covered in the
|
||||
* component, not testable here).
|
||||
*
|
||||
* The fix: findOverlappingPeriodImports returns ALL overlapping completed
|
||||
* rows newest-first (failing closed on query errors); replace mode resolves
|
||||
* every row and treats an unresolvable row (not_found / not_completed) as a
|
||||
* stale watermark: warn and continue as a fresh import — but only after
|
||||
* positively confirming no posted import entries survive in the year, since
|
||||
* replace_sie_import deletes by fiscal period and entries can outlive their
|
||||
* sie_imports row. Genuine refusals (locked period, RPC errors) still abort.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
executeSIEImport,
|
||||
replaceSIEImport,
|
||||
checkDuplicatePeriodImport,
|
||||
findOverlappingPeriodImports,
|
||||
} from '../sie-import'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { ParsedSIEFile, AccountMapping } from '../types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
function makeParsedFile(overrides?: Partial<ParsedSIEFile>): ParsedSIEFile {
|
||||
return {
|
||||
header: {
|
||||
sieType: 4,
|
||||
flagga: 0,
|
||||
program: 'TestProg',
|
||||
programVersion: '1.0',
|
||||
generatedDate: '2026-08-17',
|
||||
format: 'PC8',
|
||||
companyName: 'Boltonshield Mock AB',
|
||||
orgNumber: '5567201701',
|
||||
address: null,
|
||||
fiscalYears: [{ yearIndex: 0, start: '2025-01-01', end: '2025-12-31' }],
|
||||
currency: 'SEK',
|
||||
kontoPlanType: null,
|
||||
},
|
||||
accounts: [
|
||||
{ number: '1930', name: 'Företagskonto' },
|
||||
{ number: '6110', name: 'Kontorsmaterial' },
|
||||
],
|
||||
openingBalances: [],
|
||||
closingBalances: [],
|
||||
resultBalances: [],
|
||||
dimensions: [],
|
||||
dimensionValues: [],
|
||||
vouchers: [
|
||||
{
|
||||
series: 'A',
|
||||
number: 1,
|
||||
date: new Date(2025, 0, 15),
|
||||
description: 'Inköp',
|
||||
lines: [
|
||||
{ account: '6110', amount: 1000 },
|
||||
{ account: '1930', amount: -1000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
issues: [],
|
||||
stats: {
|
||||
totalAccounts: 2,
|
||||
totalVouchers: 1,
|
||||
totalTransactionLines: 2,
|
||||
fiscalYearStart: '2025-01-01',
|
||||
fiscalYearEnd: '2025-12-31',
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMapping(source: string, target: string): AccountMapping {
|
||||
return {
|
||||
sourceAccount: source,
|
||||
sourceName: `Account ${source}`,
|
||||
targetAccount: target,
|
||||
targetName: `Target ${target}`,
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
|
||||
const mappings = [makeMapping('1930', '1930'), makeMapping('6110', '6110')]
|
||||
|
||||
const importOptions = {
|
||||
filename: 'migration-sie-2025.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
onExistingPeriod: 'replace' as const,
|
||||
}
|
||||
|
||||
function makePriorImportRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'imp-prior',
|
||||
user_id: 'user-1',
|
||||
filename: 'old.se',
|
||||
file_hash: 'hash-old',
|
||||
fiscal_year_start: '2025-01-01',
|
||||
fiscal_year_end: '2025-12-31',
|
||||
transactions_count: 10,
|
||||
status: 'completed',
|
||||
fiscal_period_id: 'fp-2025',
|
||||
opening_balance_entry_id: null,
|
||||
imported_at: '2026-06-01T00:00:00Z',
|
||||
created_at: '2026-06-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('findOverlappingPeriodImports', () => {
|
||||
it('returns every overlapping completed row, and [] when there are none', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const rows = [makePriorImportRow({ id: 'a' }), makePriorImportRow({ id: 'b' })]
|
||||
enqueue({ data: rows })
|
||||
|
||||
const result = await findOverlappingPeriodImports(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
expect(result.map((r) => r.id)).toEqual(['a', 'b'])
|
||||
|
||||
const empty = await findOverlappingPeriodImports(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
expect(empty).toEqual([])
|
||||
})
|
||||
|
||||
it('orders newest first so the pick is deterministic', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
|
||||
await findOverlappingPeriodImports(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
|
||||
const orderCalls = findCalls('sie_imports', 'order')
|
||||
expect(orderCalls).toEqual([
|
||||
['imported_at', { ascending: false, nullsFirst: false }],
|
||||
['created_at', { ascending: false }],
|
||||
['id', { ascending: false }],
|
||||
])
|
||||
})
|
||||
|
||||
it('throws on a query error instead of returning [] (fail closed)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'connection reset' } })
|
||||
|
||||
await expect(
|
||||
findOverlappingPeriodImports(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
).rejects.toThrow(/connection reset/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkDuplicatePeriodImport', () => {
|
||||
it('returns the newest row when several overlap the period', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: [
|
||||
makePriorImportRow({ id: 'newest', imported_at: '2026-08-01T00:00:00Z' }),
|
||||
makePriorImportRow({ id: 'older', imported_at: '2026-05-01T00:00:00Z' }),
|
||||
],
|
||||
})
|
||||
|
||||
const result = await checkDuplicatePeriodImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
expect(result?.id).toBe('newest')
|
||||
})
|
||||
|
||||
it('returns null when nothing overlaps', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await checkDuplicatePeriodImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', '2025-01-01', '2025-12-31'
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('replaceSIEImport: failure classification', () => {
|
||||
it('classifies a vanished sie_imports row as not_found', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null }) // sie_imports fetch: row gone
|
||||
|
||||
const result = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.code).toBe('not_found')
|
||||
})
|
||||
|
||||
it('classifies PGRST116 (zero rows) on the pre-check as not_found', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { code: 'PGRST116', message: 'JSON object requested, multiple (or no) rows returned' },
|
||||
}) // sie_imports fetch: .single() zero-rows error
|
||||
|
||||
const result = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.code).toBe('not_found')
|
||||
})
|
||||
|
||||
it('classifies a non-PGRST116 pre-check query failure as rpc_error, never not_found (fail closed)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { code: '57014', message: 'canceling statement due to statement timeout' },
|
||||
}) // sie_imports fetch: transient query failure, row state UNKNOWN
|
||||
|
||||
const result = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.code).toBe('rpc_error')
|
||||
expect(result.error).toMatch(/statement timeout/i)
|
||||
|
||||
// Failed before the delete RPC: nothing was touched.
|
||||
const rpcCalls = (supabase.rpc.mock.calls as [string][])
|
||||
.filter(([fn]) => fn === 'replace_sie_import')
|
||||
expect(rpcCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('classifies a row that already left completed as not_completed', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { status: 'replaced', fiscal_period_id: null } })
|
||||
|
||||
const result = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.code).toBe('not_completed')
|
||||
})
|
||||
|
||||
it('classifies a locked fiscal period as period_locked', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: { status: 'completed', fiscal_period_id: 'fp-1' } },
|
||||
{ data: { is_closed: false, locked_at: '2026-01-31T00:00:00Z' } },
|
||||
])
|
||||
|
||||
const result = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.code).toBe('period_locked')
|
||||
})
|
||||
|
||||
it('classifies the RPC status-race raise as not_completed and other RPC errors as rpc_error', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: { status: 'completed', fiscal_period_id: null } },
|
||||
{ data: null, error: { message: 'Import imp-x not found or not in completed status' } },
|
||||
])
|
||||
|
||||
const raced = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(raced.success).toBe(false)
|
||||
expect(raced.code).toBe('not_completed')
|
||||
|
||||
enqueueMany([
|
||||
{ data: { status: 'completed', fiscal_period_id: null } },
|
||||
{ data: null, error: { message: 'canceling statement due to statement timeout' } },
|
||||
])
|
||||
|
||||
const failed = await replaceSIEImport(
|
||||
supabase as unknown as SupabaseClient, 'company-1', 'imp-x', 'user-1'
|
||||
)
|
||||
expect(failed.success).toBe(false)
|
||||
expect(failed.code).toBe('rpc_error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeSIEImport replace mode: re-sync after deletion (issue #1667)', () => {
|
||||
it('replaces EVERY overlapping completed import, not just the newest', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
const rowNew = makePriorImportRow({
|
||||
id: 'imp-new',
|
||||
opening_balance_entry_id: 'ob-1',
|
||||
imported_at: '2026-08-01T00:00:00Z',
|
||||
})
|
||||
const rowOld = makePriorImportRow({
|
||||
id: 'imp-old',
|
||||
imported_at: '2026-05-01T00:00:00Z',
|
||||
})
|
||||
enqueueMany([
|
||||
{ data: [rowNew, rowOld] }, // findOverlappingPeriodImports
|
||||
{ data: { status: 'completed', fiscal_period_id: 'fp-2025' } }, // replace imp-new: fetch
|
||||
{ data: { is_closed: false, locked_at: null } }, // replace imp-new: period check
|
||||
{ data: 5 }, // rpc replace_sie_import → 5 deleted
|
||||
{ data: null }, // OB safety-net update (imp-new had an OB entry)
|
||||
{ data: { status: 'completed', fiscal_period_id: 'fp-2025' } }, // replace imp-old: fetch
|
||||
{ data: { is_closed: false, locked_at: null } }, // replace imp-old: period check
|
||||
{ data: 3 }, // rpc → 3 deleted
|
||||
{ data: null }, // cleanupStaleImportRecords delete
|
||||
{ data: { id: 'imp-created' } }, // pending sie_imports insert
|
||||
{ data: [] }, // syncMappedAccounts chart fetch
|
||||
{ data: null }, // chart insert (missing accounts)
|
||||
{ data: null }, // find existing fiscal period → clean stop
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
// Both prior rows were pushed through the replace RPC.
|
||||
const rpcCalls = (supabase.rpc.mock.calls as [string, Record<string, unknown>][])
|
||||
.filter(([fn]) => fn === 'replace_sie_import')
|
||||
expect(rpcCalls.map(([, params]) => params.p_import_id)).toEqual(['imp-new', 'imp-old'])
|
||||
|
||||
// The reported shape stays a single object: newest id, total deleted.
|
||||
expect(result.replacedPriorImport).toEqual({ importId: 'imp-new', deletedEntries: 8 })
|
||||
|
||||
// The run then proceeds past the replace block (stops at the benign
|
||||
// fiscal-period stop this queue sets up, NOT a replace failure).
|
||||
expect(result.errors.join(' ')).toMatch(/No matching fiscal period found/i)
|
||||
expect(result.errors.join(' ')).not.toMatch(/ersätta/i)
|
||||
})
|
||||
|
||||
it('treats a stale watermark (prior row unresolvable) as a fresh import instead of aborting the year', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [makePriorImportRow({ id: 'imp-stale' })] }, // findOverlappingPeriodImports
|
||||
{ data: null }, // replaceSIEImport fetch: row gone (deleted between the two queries)
|
||||
{ data: null, count: 0 }, // survivor guard: no posted import entries remain
|
||||
{ data: null }, // cleanupStaleImportRecords delete
|
||||
{ data: { id: 'imp-created' } }, // pending sie_imports insert
|
||||
{ data: [] }, // chart fetch
|
||||
{ data: null }, // chart insert
|
||||
{ data: null }, // find existing fiscal period → clean stop
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
// Not stranded: the import continued past the replace block.
|
||||
expect(result.errors.join(' ')).not.toMatch(/ersätta/i)
|
||||
expect(result.errors.join(' ')).toMatch(/No matching fiscal period found/i)
|
||||
expect(result.warnings.join(' ')).toMatch(/fortsätter som ny import/i)
|
||||
expect(result.replacedPriorImport).toBeNull()
|
||||
|
||||
const rpcCalls = (supabase.rpc.mock.calls as [string][])
|
||||
.filter(([fn]) => fn === 'replace_sie_import')
|
||||
expect(rpcCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('aborts when posted import entries survive a stale watermark, instead of duplicating them', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [makePriorImportRow({ id: 'imp-stale' })] }, // findOverlappingPeriodImports
|
||||
{ data: null }, // replaceSIEImport fetch: metadata row gone
|
||||
{ data: null, count: 42 }, // survivor guard: 42 posted import entries REMAIN in the year
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
// The metadata row is gone but its verifikationer are not: importing
|
||||
// fresh would duplicate them (BFL 4:1), so the year aborts.
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/42 kvarvarande verifikationer/)
|
||||
expect(result.importId).toBeNull()
|
||||
})
|
||||
|
||||
it('aborts when the survivor check itself fails, instead of assuming zero survivors', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [makePriorImportRow({ id: 'imp-stale' })] }, // findOverlappingPeriodImports
|
||||
{ data: null }, // replaceSIEImport fetch: metadata row gone
|
||||
{
|
||||
data: null,
|
||||
count: null,
|
||||
error: { message: 'canceling statement due to statement timeout' },
|
||||
}, // survivor guard query fails: survivor state UNKNOWN
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/Kunde inte verifiera att tidigare importdata är borttagen/)
|
||||
expect(result.importId).toBeNull()
|
||||
})
|
||||
|
||||
it('aborts the year when the replace pre-check query fails, instead of importing fresh', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [makePriorImportRow({ id: 'imp-prior' })] }, // findOverlappingPeriodImports
|
||||
{
|
||||
data: null,
|
||||
error: { code: '57014', message: 'canceling statement due to statement timeout' },
|
||||
}, // replaceSIEImport fetch: transient failure, prior entries may still exist
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
// NOT treated as a stale watermark: the year aborts fail-closed.
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/statement timeout/i)
|
||||
expect(result.warnings.join(' ')).not.toMatch(/fortsätter som ny import/i)
|
||||
// Aborted before any sie_imports row was created: nothing imported fresh.
|
||||
expect(result.importId).toBeNull()
|
||||
const rpcCalls = (supabase.rpc.mock.calls as [string][])
|
||||
.filter(([fn]) => fn === 'replace_sie_import')
|
||||
expect(rpcCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('still aborts the year when the prior import sits in a locked period', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [makePriorImportRow({ id: 'imp-locked' })] }, // findOverlappingPeriodImports
|
||||
{ data: { status: 'completed', fiscal_period_id: 'fp-2025' } }, // replace fetch
|
||||
{ data: { is_closed: false, locked_at: '2026-01-31T00:00:00Z' } }, // period check: LOCKED
|
||||
])
|
||||
|
||||
const result = await executeSIEImport(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
mappings,
|
||||
importOptions,
|
||||
)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors.join(' ')).toMatch(/låst eller stängt/i)
|
||||
// Aborted before any sie_imports row was created.
|
||||
expect(result.importId).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,351 @@
|
||||
/**
|
||||
* executeSIEImport ↔ syncMappedAccounts wiring (F: customized #KONTO names
|
||||
* from Fortnox were lost on import).
|
||||
*
|
||||
* The name-resolution behavior itself is covered by account-sync.test.ts:
|
||||
* these tests assert that executeSIEImport threads the updateAccountNames
|
||||
* option through (default ON), surfaces rename counts as Swedish warnings,
|
||||
* and aborts on a fatal create error.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { executeSIEImport } from '../sie-import'
|
||||
import { syncMappedAccounts } from '../account-sync'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { ParsedSIEFile, AccountMapping } from '../types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
vi.mock('../account-sync', () => ({
|
||||
syncMappedAccounts: vi.fn(),
|
||||
}))
|
||||
|
||||
const mockSync = vi.mocked(syncMappedAccounts)
|
||||
|
||||
// Stops right after the account sync: stats carry no fiscal year, so
|
||||
// executeSIEImport returns "No fiscal year defined" without needing the
|
||||
// fiscal-period / voucher mocks.
|
||||
function makeParsedFile(): ParsedSIEFile {
|
||||
return {
|
||||
header: {
|
||||
sieType: 4,
|
||||
flagga: 0,
|
||||
program: 'TestProg',
|
||||
programVersion: '1.0',
|
||||
generatedDate: '2024-01-01',
|
||||
format: 'PC8',
|
||||
companyName: 'Test AB',
|
||||
orgNumber: '5566778899',
|
||||
address: null,
|
||||
fiscalYears: [],
|
||||
currency: 'SEK',
|
||||
kontoPlanType: null,
|
||||
},
|
||||
accounts: [
|
||||
{ number: '1930', name: 'Företagskonto Swedbank' },
|
||||
{ number: '6110', name: 'Kontorsmaterial' },
|
||||
],
|
||||
openingBalances: [],
|
||||
closingBalances: [],
|
||||
resultBalances: [],
|
||||
dimensions: [],
|
||||
dimensionValues: [],
|
||||
vouchers: [
|
||||
{
|
||||
series: 'A',
|
||||
number: 1,
|
||||
date: new Date(2024, 0, 15),
|
||||
description: 'Inköp',
|
||||
lines: [
|
||||
{ account: '6110', amount: 1000 },
|
||||
{ account: '1930', amount: -1000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
issues: [],
|
||||
stats: {
|
||||
totalAccounts: 2,
|
||||
totalVouchers: 1,
|
||||
totalTransactionLines: 2,
|
||||
fiscalYearStart: null,
|
||||
fiscalYearEnd: null,
|
||||
},
|
||||
} as unknown as ParsedSIEFile
|
||||
}
|
||||
|
||||
function makeMappings(): AccountMapping[] {
|
||||
return [
|
||||
{
|
||||
sourceAccount: '1930',
|
||||
sourceName: 'Företagskonto Swedbank',
|
||||
targetAccount: '1930',
|
||||
targetName: 'Företagskonto/checkkonto',
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
},
|
||||
{
|
||||
sourceAccount: '6110',
|
||||
sourceName: 'Kontorsmaterial',
|
||||
targetAccount: '6110',
|
||||
targetName: 'Kontorsmaterial',
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildSupabase() {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: null }, // checkDuplicateImport: no prior import
|
||||
{ data: null }, // cleanupStaleImportRecords
|
||||
{ data: { id: 'imp-1' } }, // createPendingImportRecord insert
|
||||
])
|
||||
return supabase as unknown as SupabaseClient
|
||||
}
|
||||
|
||||
function runImport(opts?: { updateAccountNames?: boolean }) {
|
||||
return executeSIEImport(
|
||||
buildSupabase(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
makeMappings(),
|
||||
{
|
||||
filename: 'fortnox.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
...opts,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockSync.mockReset()
|
||||
mockSync.mockResolvedValue({
|
||||
created: 0,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 0,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeSIEImport: account name sync wiring', () => {
|
||||
it('defaults updateAccountNames to true', async () => {
|
||||
await runImport()
|
||||
|
||||
expect(mockSync).toHaveBeenCalledTimes(1)
|
||||
const [, companyId, userId, mappings, updateNames] = mockSync.mock.calls[0]
|
||||
expect(companyId).toBe('company-1')
|
||||
expect(userId).toBe('user-1')
|
||||
expect(mappings).toHaveLength(2)
|
||||
expect(updateNames).toBe(true)
|
||||
})
|
||||
|
||||
it('passes updateAccountNames: false through', async () => {
|
||||
await runImport({ updateAccountNames: false })
|
||||
|
||||
expect(mockSync.mock.calls[0][4]).toBe(false)
|
||||
})
|
||||
|
||||
it('surfaces rename counts as a Swedish warning (plural)', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 1,
|
||||
renamed: 2,
|
||||
renamedAccounts: [
|
||||
{ accountNumber: '1930', from: 'Företagskonto/checkkonto', to: 'Företagskonto Swedbank' },
|
||||
{ accountNumber: '1510', from: 'Kundfordringar', to: 'Kundfordringar SEK' },
|
||||
],
|
||||
renameFailed: 0,
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.warnings).toContain('2 konton bytte namn till namnen från SIE-filen')
|
||||
})
|
||||
|
||||
it('uses singular wording for one rename', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 0,
|
||||
renamed: 1,
|
||||
renamedAccounts: [
|
||||
{ accountNumber: '1930', from: 'Företagskonto/checkkonto', to: 'Företagskonto Swedbank' },
|
||||
],
|
||||
renameFailed: 0,
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.warnings).toContain('1 konto bytte namn till namnet från SIE-filen')
|
||||
})
|
||||
|
||||
it('warns about failed renames without failing the import step', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 0,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 1,
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.warnings).toContain('1 kontonamn kunde inte uppdateras från SIE-filen')
|
||||
expect(result.errors.join(' ')).not.toMatch(/Failed to create accounts/)
|
||||
})
|
||||
|
||||
it('aborts with an error when the create pass fails', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 0,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 0,
|
||||
error: 'permission denied',
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.errors).toContain('Failed to create accounts: permission denied')
|
||||
})
|
||||
|
||||
it('adds no rename warning when nothing was renamed', async () => {
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.warnings.join(' ')).not.toMatch(/bytte namn/)
|
||||
})
|
||||
|
||||
it('reports the number of accounts the sync inserted', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 109,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 0,
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.accountsCreated).toBe(109)
|
||||
})
|
||||
|
||||
it('leaves accountsCreated unset when the create pass fails', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 3,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 0,
|
||||
error: 'permission denied',
|
||||
})
|
||||
|
||||
const result = await runImport()
|
||||
|
||||
expect(result.accountsCreated).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// Regression for 2026-09-09: the account insert timed out, executeSIEImport
|
||||
// returned through the early `return result` after syncMappedAccounts, and
|
||||
// the sie_imports row it had just created stayed 'pending'. That row holds
|
||||
// the (company_id, file_hash) slot in the partial unique index, so the user's
|
||||
// retry 40 s later failed on the index with a message that named the retired
|
||||
// brand and a button that does not exist.
|
||||
describe('executeSIEImport: pending import record on early exit', () => {
|
||||
function importWith(mock: ReturnType<typeof createQueuedMockSupabase>) {
|
||||
return executeSIEImport(
|
||||
mock.supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
makeParsedFile(),
|
||||
makeMappings(),
|
||||
{
|
||||
filename: 'bokio.se',
|
||||
fileContent: '#dummy',
|
||||
createFiscalPeriod: false,
|
||||
importOpeningBalances: false,
|
||||
importTransactions: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
it('closes the pending record as failed when the create pass aborts', async () => {
|
||||
mockSync.mockResolvedValue({
|
||||
created: 0,
|
||||
renamed: 0,
|
||||
renamedAccounts: [],
|
||||
renameFailed: 0,
|
||||
error: 'canceling statement due to statement timeout',
|
||||
})
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueueMany([
|
||||
{ data: null }, // checkDuplicateImport: no prior import
|
||||
{ data: null }, // cleanupStaleImportRecords
|
||||
{ data: { id: 'imp-1' } }, // createPendingImportRecord insert
|
||||
{ data: null }, // finalizeImportRecord update
|
||||
])
|
||||
|
||||
const result = await importWith(mock)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.importId).toBe('imp-1')
|
||||
const updates = mock.findCalls('sie_imports', 'update')
|
||||
expect(updates).toHaveLength(1)
|
||||
expect(updates[0][0]).toMatchObject({
|
||||
status: 'failed',
|
||||
imported_at: null,
|
||||
transactions_count: 0,
|
||||
error_message: expect.stringContaining('statement timeout'),
|
||||
})
|
||||
})
|
||||
|
||||
it('closes the pending record as failed when the file has no fiscal year', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueueMany([
|
||||
{ data: null },
|
||||
{ data: null },
|
||||
{ data: { id: 'imp-2' } },
|
||||
{ data: null },
|
||||
])
|
||||
|
||||
const result = await importWith(mock)
|
||||
|
||||
expect(result.errors).toContain('No fiscal year defined in the SIE file')
|
||||
const updates = mock.findCalls('sie_imports', 'update')
|
||||
expect(updates).toHaveLength(1)
|
||||
expect(updates[0][0]).toMatchObject({ status: 'failed' })
|
||||
})
|
||||
|
||||
it('explains a held file-hash slot in Swedish, without the retired brand or a missing button', async () => {
|
||||
const mock = createQueuedMockSupabase()
|
||||
mock.enqueueMany([
|
||||
{ data: null }, // checkDuplicateImport
|
||||
{ data: null }, // cleanupStaleImportRecords
|
||||
{
|
||||
data: null,
|
||||
error: {
|
||||
code: '23505',
|
||||
message:
|
||||
'duplicate key value violates unique constraint "sie_imports_company_id_file_hash_active_idx"',
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const result = await importWith(mock)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.importId).toBeNull()
|
||||
expect(result.errors).toHaveLength(1)
|
||||
expect(result.errors[0]).toMatch(
|
||||
/^Importen misslyckades: Samma SIE-fil håller redan på att importeras/
|
||||
)
|
||||
expect(result.errors[0]).toMatch(/Vänta några minuter och försök igen/)
|
||||
expect(result.errors[0]).not.toMatch(/gnubok|Ersätt import|Fortnox/)
|
||||
// No row was created, so there is nothing to close.
|
||||
expect(mock.findCalls('sie_imports', 'update')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Regression suite for saveMappings (P0, 2026-07-26).
|
||||
*
|
||||
* The bug: after the 2026-03-30 multi-tenant refactor added company_id to
|
||||
* sie_account_mappings, saveMappings() built its upsert payload WITHOUT
|
||||
* user_id. That column is NOT NULL with no default and no BEFORE INSERT
|
||||
* trigger, and PostgREST sends an upsert as INSERT ... ON CONFLICT DO UPDATE
|
||||
* (NOT NULL is checked on the proposed tuple before conflict resolution), so
|
||||
* every row was rejected with 23502 on both the insert and the update path.
|
||||
* The function then discarded the result instead of destructuring { error },
|
||||
* and supabase-js does not throw on Postgres errors, so 834 imports between
|
||||
* 2026-03-30 and 2026-07-26 reported success while persisting zero mappings.
|
||||
*
|
||||
* These tests therefore assert on the ACTUAL upsert payload. The shared queued
|
||||
* mock is a Proxy that discards call arguments, so it cannot see a missing
|
||||
* column: that blindness is exactly what let the bug survive four months.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { saveMappings } from '../sie-import'
|
||||
import type { AccountMapping } from '../types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
type UpsertCall = {
|
||||
table: string
|
||||
rows: Record<string, unknown>[]
|
||||
options: { onConflict?: string } | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Supabase double that records every upserted row verbatim.
|
||||
*
|
||||
* `sessionUserId` mirrors a cookie-session client (auth.getUser() resolves a
|
||||
* user); pass null for the cookieless service-role clients the API-key/MCP
|
||||
* paths use, where auth.uid() is NULL and there is no session to read.
|
||||
* `upsertError` mirrors a Postgres rejection: supabase-js returns it in the
|
||||
* result envelope and never throws.
|
||||
*/
|
||||
function createRecordingSupabase(options?: {
|
||||
sessionUserId?: string | null
|
||||
upsertError?: { code: string; message: string }
|
||||
failOnCall?: number
|
||||
}) {
|
||||
const upserts: UpsertCall[] = []
|
||||
const sessionUserId = options?.sessionUserId ?? null
|
||||
const failOnCall = options?.failOnCall ?? 1
|
||||
|
||||
const supabase = {
|
||||
auth: {
|
||||
getUser: async () => ({
|
||||
data: { user: sessionUserId ? { id: sessionUserId } : null },
|
||||
error: null,
|
||||
}),
|
||||
},
|
||||
from: (table: string) => ({
|
||||
upsert: async (
|
||||
rows: Record<string, unknown>[],
|
||||
upsertOptions?: { onConflict?: string },
|
||||
) => {
|
||||
upserts.push({ table, rows, options: upsertOptions })
|
||||
const shouldFail = options?.upsertError && upserts.length === failOnCall
|
||||
return { data: null, error: shouldFail ? options.upsertError : null }
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
return { supabase: supabase as unknown as SupabaseClient, upserts }
|
||||
}
|
||||
|
||||
function makeMapping(
|
||||
source: string,
|
||||
target: string,
|
||||
overrides?: Partial<AccountMapping>,
|
||||
): AccountMapping {
|
||||
return {
|
||||
sourceAccount: source,
|
||||
sourceName: `Konto ${source}`,
|
||||
targetAccount: target,
|
||||
targetName: `BAS ${target}`,
|
||||
confidence: 1,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('saveMappings: the row that actually reaches Postgres', () => {
|
||||
it('writes both company_id and user_id into every mapping row', async () => {
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
|
||||
await saveMappings(
|
||||
supabase,
|
||||
'company-1',
|
||||
[makeMapping('1910', '1930')],
|
||||
'user-1',
|
||||
)
|
||||
|
||||
expect(upserts).toHaveLength(1)
|
||||
expect(upserts[0].table).toBe('sie_account_mappings')
|
||||
// Full column set, not toMatchObject: a missing NOT NULL column is the bug
|
||||
// being pinned, and toMatchObject cannot see an absent key. id, created_at
|
||||
// and updated_at are deliberately absent (DB default / trigger).
|
||||
expect(upserts[0].rows).toEqual([
|
||||
{
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
source_account: '1910',
|
||||
source_name: 'Konto 1910',
|
||||
target_account: '1930',
|
||||
confidence: 1,
|
||||
match_type: 'exact',
|
||||
},
|
||||
])
|
||||
expect(upserts[0].options?.onConflict).toBe('company_id,source_account')
|
||||
})
|
||||
|
||||
it('keeps user_id distinct from company_id', async () => {
|
||||
// Both are UUID strings, so the compiler cannot tell them apart: this is
|
||||
// the same class of mistake that once put a user id in company_id.
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
|
||||
await saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')], 'user-1')
|
||||
|
||||
expect(upserts[0].rows[0].company_id).toBe('company-1')
|
||||
expect(upserts[0].rows[0].user_id).toBe('user-1')
|
||||
expect(upserts[0].rows[0].user_id).not.toBe(upserts[0].rows[0].company_id)
|
||||
})
|
||||
|
||||
it('stamps user_id on every row of every batch past the 100-row chunk', async () => {
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
const mappings = Array.from({ length: 250 }, (_, i) =>
|
||||
makeMapping(String(4000 + i), String(4000 + i)),
|
||||
)
|
||||
|
||||
await saveMappings(supabase, 'company-1', mappings, 'user-1')
|
||||
|
||||
expect(upserts).toHaveLength(3)
|
||||
expect(upserts.map((u) => u.rows.length)).toEqual([100, 100, 50])
|
||||
for (const call of upserts) {
|
||||
for (const row of call.rows) {
|
||||
expect(row.user_id).toBe('user-1')
|
||||
expect(row.company_id).toBe('company-1')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('skips unmapped accounts but still stamps the ones it keeps', async () => {
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
|
||||
await saveMappings(
|
||||
supabase,
|
||||
'company-1',
|
||||
[
|
||||
makeMapping('1910', '1930'),
|
||||
makeMapping('9999', '', { targetName: '', confidence: 0, matchType: 'manual' }),
|
||||
],
|
||||
'user-1',
|
||||
)
|
||||
|
||||
expect(upserts[0].rows).toHaveLength(1)
|
||||
expect(upserts[0].rows[0].source_account).toBe('1910')
|
||||
expect(upserts[0].rows[0].user_id).toBe('user-1')
|
||||
})
|
||||
|
||||
it('does not touch the table when nothing is mapped', async () => {
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
|
||||
await saveMappings(
|
||||
supabase,
|
||||
'company-1',
|
||||
[makeMapping('9999', '', { confidence: 0, matchType: 'manual' })],
|
||||
'user-1',
|
||||
)
|
||||
|
||||
expect(upserts).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveMappings: failures are surfaced, never swallowed', () => {
|
||||
it('throws when the upsert is rejected by Postgres', async () => {
|
||||
// supabase-js resolves with { error } instead of throwing. The old code
|
||||
// never destructured it, so this exact rejection was invisible.
|
||||
const { supabase } = createRecordingSupabase({
|
||||
upsertError: { code: '23502', message: 'null value in column "user_id"' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')], 'user-1'),
|
||||
).rejects.toThrow(/kunde inte spara kontomappningar/i)
|
||||
})
|
||||
|
||||
it('reports how many rows landed before the failing batch', async () => {
|
||||
const { supabase } = createRecordingSupabase({
|
||||
upsertError: { code: '23503', message: 'violates foreign key constraint' },
|
||||
failOnCall: 2,
|
||||
})
|
||||
const mappings = Array.from({ length: 150 }, (_, i) =>
|
||||
makeMapping(String(4000 + i), String(4000 + i)),
|
||||
)
|
||||
|
||||
await expect(
|
||||
saveMappings(supabase, 'company-1', mappings, 'user-1'),
|
||||
).rejects.toThrow(/100 av 150/)
|
||||
})
|
||||
|
||||
it('resolves quietly when every batch succeeds', async () => {
|
||||
const { supabase, upserts } = createRecordingSupabase()
|
||||
|
||||
await expect(
|
||||
saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')], 'user-1'),
|
||||
).resolves.toBeUndefined()
|
||||
expect(upserts).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveMappings: where user_id comes from', () => {
|
||||
it('prefers the explicitly passed userId over the session', async () => {
|
||||
// executeSIEImport and the MCP/API-key paths must win: their client is
|
||||
// often a cookieless service client whose session would resolve to nobody.
|
||||
const { supabase, upserts } = createRecordingSupabase({ sessionUserId: 'session-user' })
|
||||
|
||||
await saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')], 'explicit-user')
|
||||
|
||||
expect(upserts[0].rows[0].user_id).toBe('explicit-user')
|
||||
})
|
||||
|
||||
it('falls back to the session user when the caller omits userId', async () => {
|
||||
// The POST /api/import/sie/mappings handler still calls with three
|
||||
// arguments; its client is the cookie-session server client, so the
|
||||
// fallback resolves a real user there.
|
||||
const { supabase, upserts } = createRecordingSupabase({ sessionUserId: 'session-user' })
|
||||
|
||||
await saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')])
|
||||
|
||||
expect(upserts[0].rows[0].user_id).toBe('session-user')
|
||||
})
|
||||
|
||||
it('refuses to upsert at all when no user id can be resolved', async () => {
|
||||
// Better a loud failure than a 23502 the caller cannot see: user_id is
|
||||
// NOT NULL, so there is no row to write here.
|
||||
const { supabase, upserts } = createRecordingSupabase({ sessionUserId: null })
|
||||
|
||||
await expect(
|
||||
saveMappings(supabase, 'company-1', [makeMapping('1910', '1930')]),
|
||||
).rejects.toThrow(/user_id saknas/i)
|
||||
expect(upserts).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,111 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
// Migration 20260529120000_sie_imports_undone_release_slot.sql extends
|
||||
// the partial unique index sie_imports_company_id_file_hash_active_idx
|
||||
// to also exclude 'undone'. Without this, undo_sie_import marks a row
|
||||
// 'undone' but the slot stays held: the caller cannot re-import the
|
||||
// same file.
|
||||
|
||||
async function insertSIEImport(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
fileHash: string
|
||||
status: 'pending' | 'mapped' | 'completed' | 'failed' | 'replaced' | 'undone'
|
||||
fiscalPeriodId?: string
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.sie_imports
|
||||
(id, user_id, company_id, filename, file_hash, sie_type,
|
||||
fiscal_year_start, fiscal_year_end, accounts_count, transactions_count,
|
||||
status, fiscal_period_id, imported_at)
|
||||
VALUES ($1, $2, $3, 'undone-test.se', $4, 4,
|
||||
'2026-01-01', '2026-12-31', 0, 0,
|
||||
$5, $6, $7)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fileHash,
|
||||
params.status,
|
||||
params.fiscalPeriodId ?? null,
|
||||
params.status === 'completed' ? new Date().toISOString() : null,
|
||||
],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
describe('sie_imports partial unique index: undone status releases the slot', () => {
|
||||
it('still blocks a duplicate active row (regression guard)', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const hash = `hash-${randomUUID()}`
|
||||
|
||||
await insertSIEImport({ companyId, userId, fileHash: hash, status: 'completed', fiscalPeriodId })
|
||||
|
||||
await expect(
|
||||
insertSIEImport({ companyId, userId, fileHash: hash, status: 'pending', fiscalPeriodId }),
|
||||
).rejects.toThrow(/sie_imports_company_id_file_hash_active_idx/)
|
||||
})
|
||||
|
||||
it('allows a new pending row once the prior is undone', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const hash = `hash-${randomUUID()}`
|
||||
|
||||
const priorId = await insertSIEImport({
|
||||
companyId,
|
||||
userId,
|
||||
fileHash: hash,
|
||||
status: 'completed',
|
||||
fiscalPeriodId,
|
||||
})
|
||||
|
||||
// Mimic undo_sie_import's terminal write (we don't run the RPC here:
|
||||
// the RPC also detaches docs + deletes JEs which need richer setup).
|
||||
await getPool().query(
|
||||
`UPDATE public.sie_imports SET status = 'undone', replaced_at = now() WHERE id = $1`,
|
||||
[priorId],
|
||||
)
|
||||
|
||||
const newId = await insertSIEImport({
|
||||
companyId,
|
||||
userId,
|
||||
fileHash: hash,
|
||||
status: 'pending',
|
||||
fiscalPeriodId,
|
||||
})
|
||||
expect(newId).toBeTruthy()
|
||||
})
|
||||
|
||||
it('allows a re-import after a 0-entry vacuous import is backfilled to failed', async () => {
|
||||
// Mirrors the Lookma AB recovery path: 0-entry 'completed' rows are
|
||||
// backfilled to 'failed' by the same migration; the partial index
|
||||
// already excludes 'failed', so a fresh re-import succeeds.
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const hash = `hash-${randomUUID()}`
|
||||
|
||||
const stuckId = await insertSIEImport({
|
||||
companyId,
|
||||
userId,
|
||||
fileHash: hash,
|
||||
status: 'completed',
|
||||
fiscalPeriodId,
|
||||
})
|
||||
|
||||
await getPool().query(
|
||||
`UPDATE public.sie_imports SET status = 'failed' WHERE id = $1`,
|
||||
[stuckId],
|
||||
)
|
||||
|
||||
const newId = await insertSIEImport({
|
||||
companyId,
|
||||
userId,
|
||||
fileHash: hash,
|
||||
status: 'pending',
|
||||
fiscalPeriodId,
|
||||
})
|
||||
expect(newId).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseSIEFile } from '../sie-parser'
|
||||
import { mergeParsedSIEFiles } from '../sie-merge'
|
||||
import { generateImportPreview } from '../sie-import'
|
||||
import { buildTheaterModel } from '../theater-model'
|
||||
import type { AccountMapping } from '../types'
|
||||
|
||||
/**
|
||||
* One provider-style SIE 4 export per fiscal year, like the files
|
||||
* fetchProviderSieFiles returns (oldest first).
|
||||
*/
|
||||
function sieYear(opts: {
|
||||
year: number
|
||||
companyName?: string
|
||||
konto?: string[]
|
||||
vouchers?: string[][]
|
||||
extra?: string[]
|
||||
}): string {
|
||||
const { year, companyName = 'One Punkt Com AB', konto = [], vouchers = [], extra = [] } = opts
|
||||
return [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
`#FNAMN "${companyName}"`,
|
||||
'#ORGNR 5566778899',
|
||||
`#RAR 0 ${year}0101 ${year}1231`,
|
||||
`#RAR -1 ${year - 1}0101 ${year - 1}1231`,
|
||||
'#KONTO 1930 "Företagskonto"',
|
||||
'#KONTO 2641 "Ingående moms"',
|
||||
...konto,
|
||||
...extra,
|
||||
...vouchers.flat(),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function voucher(num: number, date: string, description: string, account: string, amount = 100): string[] {
|
||||
return [
|
||||
`#VER A ${num} ${date} "${description}"`,
|
||||
'{',
|
||||
`#TRANS ${account} {} ${amount}.00`,
|
||||
`#TRANS 1930 {} -${amount}.00`,
|
||||
'}',
|
||||
]
|
||||
}
|
||||
|
||||
describe('mergeParsedSIEFiles', () => {
|
||||
it('throws on an empty list and passes a single file through unchanged', () => {
|
||||
expect(() => mergeParsedSIEFiles([])).toThrow()
|
||||
const parsed = parseSIEFile(sieYear({ year: 2026 }))
|
||||
expect(mergeParsedSIEFiles([parsed])).toBe(parsed)
|
||||
})
|
||||
|
||||
it('merges distinct years: vouchers concatenated, fiscal years union oldest first', () => {
|
||||
const y2024 = parseSIEFile(
|
||||
sieYear({
|
||||
year: 2024,
|
||||
konto: ['#KONTO 4010 "Material"'],
|
||||
vouchers: [voucher(1, '20240315', 'Bolagsverket', '4010'), voucher(2, '20240601', 'Loopia', '4010')],
|
||||
}),
|
||||
)
|
||||
const y2025 = parseSIEFile(
|
||||
sieYear({
|
||||
year: 2025,
|
||||
konto: ['#KONTO 3041 "Försäljning tjänster"'],
|
||||
vouchers: [voucher(1, '20250210', 'Kund AB', '3041', 250)],
|
||||
}),
|
||||
)
|
||||
const y2026 = parseSIEFile(sieYear({ year: 2026 }))
|
||||
|
||||
const merged = mergeParsedSIEFiles([y2024, y2025, y2026])
|
||||
|
||||
expect(merged.vouchers).toHaveLength(3)
|
||||
expect(merged.stats.totalVouchers).toBe(3)
|
||||
expect(merged.stats.totalTransactionLines).toBe(6)
|
||||
// Union of #RAR periods: 2023 (from y2024's #RAR -1) through 2026,
|
||||
// oldest first, newest re-indexed to yearIndex 0.
|
||||
expect(merged.header.fiscalYears.map((fy) => fy.start)).toEqual([
|
||||
'2023-01-01',
|
||||
'2024-01-01',
|
||||
'2025-01-01',
|
||||
'2026-01-01',
|
||||
])
|
||||
expect(merged.header.fiscalYears.map((fy) => fy.yearIndex)).toEqual([-3, -2, -1, 0])
|
||||
expect(merged.stats.fiscalYearStart).toBe('2026-01-01')
|
||||
expect(merged.stats.fiscalYearEnd).toBe('2026-12-31')
|
||||
// Accounts are a union across files.
|
||||
expect(merged.accounts.map((a) => a.number).sort()).toEqual(['1930', '2641', '3041', '4010'])
|
||||
expect(merged.stats.totalAccounts).toBe(4)
|
||||
expect(merged.header.companyName).toBe('One Punkt Com AB')
|
||||
expect(merged.header.orgNumber).toBe('5566778899')
|
||||
})
|
||||
|
||||
it('dedupes duplicate account numbers: first name wins, later files fill missing metadata', () => {
|
||||
const older = parseSIEFile(
|
||||
sieYear({ year: 2024, konto: ['#KONTO 4010 "Material och varor"'] }),
|
||||
)
|
||||
const newer = parseSIEFile(
|
||||
sieYear({
|
||||
year: 2025,
|
||||
konto: ['#KONTO 4010 "Inköp material"'],
|
||||
extra: ['#SRU 4010 7512'],
|
||||
}),
|
||||
)
|
||||
|
||||
const merged = mergeParsedSIEFiles([older, newer])
|
||||
|
||||
const acc = merged.accounts.filter((a) => a.number === '4010')
|
||||
expect(acc).toHaveLength(1)
|
||||
expect(acc[0].name).toBe('Material och varor')
|
||||
// The older file had no #SRU for 4010: the newer file's code fills it in.
|
||||
expect(acc[0].sruCode).toBe('7512')
|
||||
})
|
||||
|
||||
it('an empty newest file plus a rich older file yields a rich merge', () => {
|
||||
const rich = parseSIEFile(
|
||||
sieYear({
|
||||
year: 2025,
|
||||
konto: ['#KONTO 4010 "Material"', '#KONTO 3041 "Försäljning tjänster"'],
|
||||
vouchers: [
|
||||
voucher(1, '20250110', 'Loopia', '4010'),
|
||||
voucher(2, '20250211', 'Loopia', '4010'),
|
||||
voucher(3, '20250320', 'Kund AB', '3041', 900),
|
||||
],
|
||||
extra: ['#IB 0 1930 5000.00', '#IB 0 2081 -5000.00'],
|
||||
}),
|
||||
)
|
||||
// Mid-year export: the newest fiscal year has accounts but zero vouchers.
|
||||
const empty = parseSIEFile(sieYear({ year: 2026 }))
|
||||
|
||||
const merged = mergeParsedSIEFiles([rich, empty])
|
||||
|
||||
expect(merged.stats.totalVouchers).toBe(3)
|
||||
expect(merged.openingBalances).toHaveLength(2)
|
||||
|
||||
// The preview built from the merge reports the whole dataset, not the
|
||||
// empty newest file (the "Hittade 740 konton och 0 verifikationer" bug).
|
||||
const mappings: AccountMapping[] = []
|
||||
const preview = generateImportPreview(merged, mappings)
|
||||
expect(preview.voucherCount).toBe(3)
|
||||
// 1930, 2641, 4010, 3041 from #KONTO plus 2081 auto-registered from #IB.
|
||||
expect(preview.accountCount).toBe(5)
|
||||
|
||||
// The theater model gets the full history: both years, real accounts,
|
||||
// a counterparty seen twice.
|
||||
const model = buildTheaterModel(merged)
|
||||
expect(model.totalVouchers).toBe(3)
|
||||
expect(model.years.length).toBeGreaterThanOrEqual(2)
|
||||
expect(model.accounts.length).toBeGreaterThan(0)
|
||||
expect(model.counterparties.map((c) => c.name)).toContain('Loopia')
|
||||
})
|
||||
|
||||
it('keeps the most common non-empty company name and concatenates issues', () => {
|
||||
const a = parseSIEFile(sieYear({ year: 2024, companyName: 'Gamla Namnet AB' }))
|
||||
const b = parseSIEFile(sieYear({ year: 2025, companyName: 'One Punkt Com AB' }))
|
||||
const c = parseSIEFile(sieYear({ year: 2026, companyName: 'One Punkt Com AB' }))
|
||||
|
||||
const merged = mergeParsedSIEFiles([a, b, c])
|
||||
expect(merged.header.companyName).toBe('One Punkt Com AB')
|
||||
expect(merged.issues).toEqual([...a.issues, ...b.issues, ...c.issues])
|
||||
})
|
||||
|
||||
it('dedupes dimension registrations by number and (number, code)', () => {
|
||||
const dims = [
|
||||
'#DIM 6 "Projekt"',
|
||||
'#OBJEKT 6 "P1" "Bryggan"',
|
||||
]
|
||||
const a = parseSIEFile(sieYear({ year: 2024, extra: dims }))
|
||||
const b = parseSIEFile(
|
||||
sieYear({ year: 2025, extra: [...dims, '#OBJEKT 6 "P2" "Kajen"'] }),
|
||||
)
|
||||
|
||||
const merged = mergeParsedSIEFiles([a, b])
|
||||
expect(merged.dimensions).toHaveLength(1)
|
||||
expect(merged.dimensionValues.map((v) => v.code).sort()).toEqual(['P1', 'P2'])
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseSIEFile } from '../sie-parser'
|
||||
import { bucketOfAccount, buildTheaterModel } from '../theater-model'
|
||||
|
||||
function sie(lines: string[]): string {
|
||||
return [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Nordvik Bygg AB"',
|
||||
'#ORGNR 5566778899',
|
||||
'#RAR 0 20260101 20261231',
|
||||
'#RAR -1 20250101 20251231',
|
||||
'#KONTO 1930 "Företagskonto"',
|
||||
'#KONTO 3041 "Försäljning tjänster"',
|
||||
'#KONTO 4010 "Material"',
|
||||
'#KONTO 2641 "Ingående moms"',
|
||||
...lines,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function voucher(num: number, description: string, account = '4010', amount = 100): string[] {
|
||||
return [
|
||||
`#VER A ${num} 20260115 "${description}"`,
|
||||
'{',
|
||||
`#TRANS ${account} {} ${amount}.00`,
|
||||
`#TRANS 2641 {} ${(amount * 0.25).toFixed(2)}`,
|
||||
`#TRANS 1930 {} -${(amount * 1.25).toFixed(2)}`,
|
||||
'}',
|
||||
]
|
||||
}
|
||||
|
||||
describe('bucketOfAccount', () => {
|
||||
it('maps class digits to the four display buckets', () => {
|
||||
expect(bucketOfAccount('1930')).toBe('tillgangar')
|
||||
expect(bucketOfAccount('2641')).toBe('skulder')
|
||||
expect(bucketOfAccount('3041')).toBe('intakter')
|
||||
expect(bucketOfAccount('4010')).toBe('kostnader')
|
||||
expect(bucketOfAccount('7010')).toBe('kostnader')
|
||||
expect(bucketOfAccount('8310')).toBe('kostnader')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildTheaterModel', () => {
|
||||
it('aggregates accounts by posting count and years oldest first', () => {
|
||||
const parsed = parseSIEFile(
|
||||
sie([...voucher(1, 'Byggmax'), ...voucher(2, 'Byggmax'), ...voucher(3, 'Ahlsell')])
|
||||
)
|
||||
const model = buildTheaterModel(parsed)
|
||||
expect(model.companyName).toBe('Nordvik Bygg AB')
|
||||
expect(model.years.map((y) => y.start)).toEqual(['2025-01-01', '2026-01-01'])
|
||||
expect(model.totalVouchers).toBe(3)
|
||||
// 4010, 2641, 1930 each appear 3 times; heaviest-first with names.
|
||||
const acc4010 = model.accounts.find((a) => a.number === '4010')
|
||||
expect(acc4010).toMatchObject({ name: 'Material', bucket: 'kostnader', weight: 3 })
|
||||
expect(model.buckets.map((b) => b.id)).toEqual(['tillgangar', 'skulder', 'kostnader'])
|
||||
})
|
||||
|
||||
it('groups counterparties by normalized name and needs at least two sightings', () => {
|
||||
const parsed = parseSIEFile(
|
||||
sie([
|
||||
...voucher(1, 'BYGGMAX AB'),
|
||||
...voucher(2, 'Byggmax'),
|
||||
...voucher(3, 'Engångsleverantören'),
|
||||
])
|
||||
)
|
||||
const model = buildTheaterModel(parsed)
|
||||
expect(model.counterparties).toHaveLength(1)
|
||||
expect(model.counterparties[0]).toMatchObject({ name: 'Byggmax', weight: 2, account: '4010' })
|
||||
expect(model.totalCounterparties).toBe(1)
|
||||
})
|
||||
|
||||
it('attaches the counterparty to the counter account, not the bank leg', () => {
|
||||
const parsed = parseSIEFile(
|
||||
sie([...voucher(1, 'Vasakronan', '5010', 18500), ...voucher(2, 'Vasakronan', '5010', 18500)])
|
||||
)
|
||||
const model = buildTheaterModel(parsed)
|
||||
expect(model.counterparties[0]).toMatchObject({ name: 'Vasakronan', account: '5010' })
|
||||
})
|
||||
|
||||
it('skips internal accounting voucher texts', () => {
|
||||
const parsed = parseSIEFile(
|
||||
sie([
|
||||
...voucher(1, 'Lön juli'),
|
||||
...voucher(2, 'Lön augusti'),
|
||||
...voucher(3, 'Momsredovisning Q2'),
|
||||
...voucher(4, 'Avskrivning inventarier'),
|
||||
...voucher(5, 'Årets resultat'),
|
||||
])
|
||||
)
|
||||
expect(buildTheaterModel(parsed).counterparties).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('caps accounts and counterparties to readable sizes', () => {
|
||||
const accounts: string[] = []
|
||||
const vouchers: string[] = []
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const num = String(5000 + i)
|
||||
accounts.push(`#KONTO ${num} "Konto ${num}"`)
|
||||
for (let j = 0; j < 3; j++) {
|
||||
vouchers.push(...voucher(i * 3 + j + 1, `Leverantör ${i} AB`, num))
|
||||
}
|
||||
}
|
||||
const model = buildTheaterModel(parseSIEFile(sie([...accounts, ...vouchers])))
|
||||
expect(model.accounts.length).toBeLessThanOrEqual(14)
|
||||
expect(model.counterparties.length).toBeLessThanOrEqual(12)
|
||||
expect(model.totalCounterparties).toBe(30)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool, runAsServiceRole, withUserContext } from '@/tests/pg/setup'
|
||||
import {
|
||||
seedCompany,
|
||||
insertAuthUser,
|
||||
insertCompanyMember,
|
||||
insertPostedJournalEntry,
|
||||
insertTransaction,
|
||||
} from '@/tests/pg/fixtures'
|
||||
|
||||
// Migration 20260820071500_undo_bank_file_import.sql (issue #1672):
|
||||
// transactions.bank_file_import_id links every bank-file-imported row to its
|
||||
// batch, and undo_bank_file_import bulk-deletes the batch's unbooked rows
|
||||
// (ignored INCLUDED) while skipping booked rows and rows with
|
||||
// payment_match_log history. The actor gate mirrors undo_sie_import
|
||||
// (20260727121000): p_user_id honored only for service_role callers, every
|
||||
// other caller pinned to its own auth.uid(), 42501 otherwise.
|
||||
|
||||
async function insertCompletedBankImport(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
status?: string
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.bank_file_imports
|
||||
(id, user_id, company_id, filename, file_hash, file_format,
|
||||
transaction_count, imported_count, status, date_from, date_to)
|
||||
VALUES ($1, $2, $3, 'lunar-2026.csv', $4, 'lunar',
|
||||
3, 3, $5, '2026-01-01', '2026-06-30')`,
|
||||
[id, params.userId, params.companyId, `hash-${id}`, params.status ?? 'completed'],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
type UndoReport = {
|
||||
deleted: number
|
||||
skipped_booked: number
|
||||
skipped_match_history: number
|
||||
}
|
||||
|
||||
async function callUndo(
|
||||
companyId: string,
|
||||
importId: string,
|
||||
actor: string | null,
|
||||
): Promise<UndoReport> {
|
||||
const res = await runAsServiceRole((client) =>
|
||||
client.query<{ report: UndoReport }>(
|
||||
`SELECT public.undo_bank_file_import($1::uuid, $2::uuid, $3::uuid) AS report`,
|
||||
[companyId, importId, actor],
|
||||
),
|
||||
)
|
||||
return res.rows[0].report
|
||||
}
|
||||
|
||||
describe('undo_bank_file_import', () => {
|
||||
it('deletes the batch unbooked rows (ignored included), skips booked and match-history rows, and reports', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedBankImport({ companyId, userId })
|
||||
|
||||
// Two plain unbooked rows, one of them ignored: both must go.
|
||||
const plainTx = await insertTransaction({
|
||||
companyId,
|
||||
userId,
|
||||
bankFileImportId: importId,
|
||||
})
|
||||
const ignoredTx = await insertTransaction({
|
||||
companyId,
|
||||
userId,
|
||||
isIgnored: true,
|
||||
bankFileImportId: importId,
|
||||
})
|
||||
|
||||
// A booked row from the same batch: must stay.
|
||||
const jeId = await insertPostedJournalEntry({ userId, companyId, fiscalPeriodId })
|
||||
const bookedTx = await insertTransaction({
|
||||
companyId,
|
||||
userId,
|
||||
journalEntryId: jeId,
|
||||
bankFileImportId: importId,
|
||||
})
|
||||
|
||||
// An unbooked row carrying append-only match history: must stay (its
|
||||
// payment_match_log rows cascade on delete, which audit_log_immutable
|
||||
// blocks; same rule as the single-row DELETE route).
|
||||
const historyTx = await insertTransaction({
|
||||
companyId,
|
||||
userId,
|
||||
bankFileImportId: importId,
|
||||
})
|
||||
await getPool().query(
|
||||
`INSERT INTO public.payment_match_log (user_id, transaction_id, action)
|
||||
VALUES ($1, $2, 'auto_suggested')`,
|
||||
[userId, historyTx],
|
||||
)
|
||||
|
||||
// Rows OUTSIDE the batch: another import's row and an unlinked (PSD2-ish)
|
||||
// row. Strict scoping means neither is touched.
|
||||
const otherImportId = await insertCompletedBankImport({ companyId, userId })
|
||||
const otherBatchTx = await insertTransaction({
|
||||
companyId,
|
||||
userId,
|
||||
bankFileImportId: otherImportId,
|
||||
})
|
||||
const unlinkedTx = await insertTransaction({ companyId, userId })
|
||||
|
||||
const report = await callUndo(companyId, importId, userId)
|
||||
|
||||
expect(report.deleted).toBe(2)
|
||||
expect(report.skipped_booked).toBe(1)
|
||||
expect(report.skipped_match_history).toBe(1)
|
||||
|
||||
const { rows: remaining } = await getPool().query<{ id: string }>(
|
||||
`SELECT id FROM public.transactions WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
const remainingIds = new Set(remaining.map((r) => r.id))
|
||||
expect(remainingIds.has(plainTx)).toBe(false)
|
||||
expect(remainingIds.has(ignoredTx)).toBe(false)
|
||||
expect(remainingIds.has(bookedTx)).toBe(true)
|
||||
expect(remainingIds.has(historyTx)).toBe(true)
|
||||
expect(remainingIds.has(otherBatchTx)).toBe(true)
|
||||
expect(remainingIds.has(unlinkedTx)).toBe(true)
|
||||
|
||||
const { rows: impRows } = await getPool().query<{ status: string }>(
|
||||
`SELECT status FROM public.bank_file_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(impRows[0].status).toBe('undone')
|
||||
|
||||
// Behandlingshistorik: the bulk delete leaves one audit_log summary row.
|
||||
const { rows: auditRows } = await getPool().query<{
|
||||
new_state: { deleted_transactions: number }
|
||||
}>(
|
||||
`SELECT new_state FROM public.audit_log
|
||||
WHERE table_name = 'transactions' AND record_id = $1 AND action = 'DELETE'`,
|
||||
[importId],
|
||||
)
|
||||
expect(auditRows).toHaveLength(1)
|
||||
expect(auditRows[0].new_state.deleted_transactions).toBe(2)
|
||||
})
|
||||
|
||||
it('raises when the import is not in completed status', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const importId = await insertCompletedBankImport({
|
||||
companyId,
|
||||
userId,
|
||||
status: 'processing',
|
||||
})
|
||||
const txId = await insertTransaction({ companyId, userId, bankFileImportId: importId })
|
||||
|
||||
await expect(callUndo(companyId, importId, userId)).rejects.toThrow(
|
||||
/not in completed status/i,
|
||||
)
|
||||
|
||||
const { rows } = await getPool().query(
|
||||
`SELECT 1 FROM public.transactions WHERE id = $1`,
|
||||
[txId],
|
||||
)
|
||||
expect(rows).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('raises 42501 for a plain member and for a stranger', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const importId = await insertCompletedBankImport({ companyId, userId })
|
||||
|
||||
const memberId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
|
||||
await expect(callUndo(companyId, importId, memberId)).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
await expect(callUndo(companyId, importId, randomUUID())).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
await expect(callUndo(companyId, importId, null)).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores a spoofed p_user_id from an authenticated (non-service) caller', async () => {
|
||||
const { companyId, userId: ownerId } = await seedCompany()
|
||||
const memberId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
|
||||
const importId = await insertCompletedBankImport({ companyId, userId: ownerId })
|
||||
const txId = await insertTransaction({
|
||||
companyId,
|
||||
userId: ownerId,
|
||||
bankFileImportId: importId,
|
||||
})
|
||||
|
||||
await withUserContext(memberId, async (client) => {
|
||||
let raised: (Error & { code?: string }) | null = null
|
||||
try {
|
||||
await client.query(
|
||||
`SELECT public.undo_bank_file_import($1::uuid, $2::uuid, $3::uuid)`,
|
||||
[companyId, importId, ownerId],
|
||||
)
|
||||
} catch (err) {
|
||||
raised = err as Error & { code?: string }
|
||||
}
|
||||
expect(raised, 'spoofed p_user_id must not authorize').not.toBeNull()
|
||||
expect(raised!.message).toMatch(/owners and admins/i)
|
||||
expect(raised!.code).toBe('42501')
|
||||
})
|
||||
|
||||
// The gate fired before any mutation.
|
||||
const { rows: impRows } = await getPool().query<{ status: string }>(
|
||||
`SELECT status FROM public.bank_file_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(impRows[0].status).toBe('completed')
|
||||
const { rows: txRows } = await getPool().query(
|
||||
`SELECT 1 FROM public.transactions WHERE id = $1`,
|
||||
[txId],
|
||||
)
|
||||
expect(txRows).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('resolves the actor from auth.uid() for an authenticated owner (session-client fallback)', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const importId = await insertCompletedBankImport({ companyId, userId })
|
||||
await insertTransaction({ companyId, userId, bankFileImportId: importId })
|
||||
|
||||
const report = await withUserContext(userId, async (client) => {
|
||||
const res = await client.query<{ report: UndoReport }>(
|
||||
`SELECT public.undo_bank_file_import($1::uuid, $2::uuid) AS report`,
|
||||
[companyId, importId],
|
||||
)
|
||||
const imp = await client.query<{ status: string }>(
|
||||
`SELECT status FROM public.bank_file_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(imp.rows[0].status).toBe('undone')
|
||||
return res.rows[0].report
|
||||
})
|
||||
expect(report.deleted).toBe(1)
|
||||
})
|
||||
|
||||
it('does not grant EXECUTE to anon or PUBLIC (least privilege)', async () => {
|
||||
const { rows } = await getPool().query<{
|
||||
anon_can: boolean
|
||||
public_can: boolean
|
||||
authenticated_can: boolean
|
||||
service_role_can: boolean
|
||||
}>(
|
||||
`SELECT has_function_privilege('anon', 'public.undo_bank_file_import(uuid,uuid,uuid)', 'EXECUTE') AS anon_can,
|
||||
has_function_privilege('public', 'public.undo_bank_file_import(uuid,uuid,uuid)', 'EXECUTE') AS public_can,
|
||||
has_function_privilege('authenticated', 'public.undo_bank_file_import(uuid,uuid,uuid)', 'EXECUTE') AS authenticated_can,
|
||||
has_function_privilege('service_role', 'public.undo_bank_file_import(uuid,uuid,uuid)', 'EXECUTE') AS service_role_can`,
|
||||
)
|
||||
expect(rows[0].anon_can, 'anon must not be able to call undo_bank_file_import').toBe(false)
|
||||
expect(rows[0].public_can, 'PUBLIC must not hold EXECUTE').toBe(false)
|
||||
expect(rows[0].authenticated_can).toBe(true)
|
||||
expect(rows[0].service_role_can).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool, runAsServiceRole, withUserContext } from '@/tests/pg/setup'
|
||||
import {
|
||||
seedCompany,
|
||||
insertAuthUser,
|
||||
insertCompanyMember,
|
||||
insertDraftJournalEntry,
|
||||
insertBalancedLines,
|
||||
} from '@/tests/pg/fixtures'
|
||||
|
||||
// Migration 20260624120000_undo_sie_import_explicit_actor.sql makes
|
||||
// undo_sie_import accept the authorising user as p_user_id.
|
||||
//
|
||||
// Why: the RPC runs on the service-role client (to escape the 8s
|
||||
// statement_timeout on large imports). That client is cookie-less, so inside
|
||||
// the RPC auth.uid() is NULL: before that fix the role lookup matched nothing
|
||||
// and the function ALWAYS raised "Only company owners and admins can undo SIE
|
||||
// imports", breaking undo entirely on hosted.
|
||||
//
|
||||
// Migration 20260727121000_undo_sie_import_caller_guard.sql then closes the
|
||||
// hole the COALESCE(p_user_id, auth.uid()) shape opened: EXECUTE is granted
|
||||
// to `authenticated`, so any signed-in PostgREST caller could pass an owner's
|
||||
// UUID as p_user_id and impersonate them into the gate. p_user_id is now
|
||||
// honored ONLY when auth.role() = 'service_role'; every other caller is
|
||||
// pinned to its own auth.uid().
|
||||
//
|
||||
// These tests call the function under a simulated service-role context
|
||||
// (runAsServiceRole), which is how the app's service client presents:
|
||||
// auth.uid() NULL, auth.role() = 'service_role'.
|
||||
|
||||
async function insertCompletedImport(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
fiscalPeriodId: string
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.sie_imports
|
||||
(id, user_id, company_id, filename, file_hash, sie_type,
|
||||
fiscal_year_start, fiscal_year_end, accounts_count, transactions_count,
|
||||
status, fiscal_period_id, imported_at)
|
||||
VALUES ($1, $2, $3, 'undo-actor-test.se', $4, 4,
|
||||
'2026-01-01', '2026-12-31', 0, 1,
|
||||
'completed', $5, now())`,
|
||||
[id, params.userId, params.companyId, `hash-${id}`, params.fiscalPeriodId],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
// Seed one posted source_type='import' verifikat so undo has something to
|
||||
// delete. Insert as draft + balanced lines, then commit the draft→posted
|
||||
// transition (the balance trigger requires balanced lines on that step).
|
||||
async function insertPostedImportEntry(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
fiscalPeriodId: string
|
||||
}): Promise<string> {
|
||||
const jeId = await insertDraftJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
sourceType: 'import',
|
||||
status: 'draft',
|
||||
voucherNumber: 1,
|
||||
})
|
||||
await insertBalancedLines(jeId, 1000)
|
||||
await getPool().query(
|
||||
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`,
|
||||
[jeId],
|
||||
)
|
||||
return jeId
|
||||
}
|
||||
|
||||
async function callUndo(companyId: string, importId: string, actor: string | null) {
|
||||
return runAsServiceRole((client) =>
|
||||
client.query<{ deleted: number }>(
|
||||
`SELECT public.undo_sie_import($1::uuid, $2::uuid, $3::uuid) AS deleted`,
|
||||
[companyId, importId, actor],
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
describe('undo_sie_import: explicit actor (service-client path)', () => {
|
||||
it('succeeds with an owner p_user_id even when auth.uid() is NULL', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
const jeId = await insertPostedImportEntry({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const res = await callUndo(companyId, importId, userId)
|
||||
expect(res.rows[0].deleted).toBe(1)
|
||||
|
||||
const { rows: jeRows } = await getPool().query(
|
||||
`SELECT 1 FROM public.journal_entries WHERE id = $1`,
|
||||
[jeId],
|
||||
)
|
||||
expect(jeRows).toHaveLength(0)
|
||||
|
||||
const { rows: impRows } = await getPool().query<{ status: string }>(
|
||||
`SELECT status FROM public.sie_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(impRows[0].status).toBe('undone')
|
||||
})
|
||||
|
||||
it('raises when no authorising identity is supplied (auth.uid() NULL, p_user_id NULL)', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
await expect(callUndo(companyId, importId, null)).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
|
||||
// The gate fired before any mutation: the import is untouched.
|
||||
const { rows } = await getPool().query<{ status: string }>(
|
||||
`SELECT status FROM public.sie_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(rows[0].status).toBe('completed')
|
||||
})
|
||||
|
||||
it('raises when p_user_id is not an owner/admin of the company', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
// A 'member' of the same company is still not allowed to undo.
|
||||
const memberId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
|
||||
await expect(callUndo(companyId, importId, memberId)).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
|
||||
// And a complete stranger (no membership) is rejected too.
|
||||
await expect(callUndo(companyId, importId, randomUUID())).rejects.toThrow(
|
||||
/owners and admins/i,
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores a spoofed p_user_id from an authenticated (non-service) caller', async () => {
|
||||
// 20260727121000: a member passing the OWNER's UUID as p_user_id over an
|
||||
// authenticated PostgREST session must stay pinned to their own
|
||||
// auth.uid(), be rejected with 42501, and delete nothing. Same guard as
|
||||
// replace_sie_import (20260727120000).
|
||||
const { companyId, userId: ownerId, fiscalPeriodId } = await seedCompany()
|
||||
const memberId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
|
||||
|
||||
const importId = await insertCompletedImport({ companyId, userId: ownerId, fiscalPeriodId })
|
||||
const jeId = await insertPostedImportEntry({ companyId, userId: ownerId, fiscalPeriodId })
|
||||
|
||||
await withUserContext(memberId, async (client) => {
|
||||
let raised: (Error & { code?: string }) | null = null
|
||||
try {
|
||||
await client.query(
|
||||
`SELECT public.undo_sie_import($1::uuid, $2::uuid, $3::uuid)`,
|
||||
[companyId, importId, ownerId],
|
||||
)
|
||||
} catch (err) {
|
||||
raised = err as Error & { code?: string }
|
||||
}
|
||||
expect(raised, 'spoofed p_user_id must not authorize').not.toBeNull()
|
||||
expect(raised!.message).toMatch(/owners and admins/i)
|
||||
expect(raised!.code).toBe('42501')
|
||||
})
|
||||
|
||||
// The gate fired before any mutation.
|
||||
const { rows: impRows } = await getPool().query<{ status: string }>(
|
||||
`SELECT status FROM public.sie_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(impRows[0].status).toBe('completed')
|
||||
const { rows: jeRows } = await getPool().query(
|
||||
`SELECT 1 FROM public.journal_entries WHERE id = $1`,
|
||||
[jeId],
|
||||
)
|
||||
expect(jeRows).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not grant EXECUTE to anon or PUBLIC (20260727121000 least privilege)', async () => {
|
||||
const { rows } = await getPool().query<{
|
||||
anon_can: boolean
|
||||
public_can: boolean
|
||||
authenticated_can: boolean
|
||||
service_role_can: boolean
|
||||
}>(
|
||||
`SELECT has_function_privilege('anon', 'public.undo_sie_import(uuid,uuid,uuid)', 'EXECUTE') AS anon_can,
|
||||
has_function_privilege('public', 'public.undo_sie_import(uuid,uuid,uuid)', 'EXECUTE') AS public_can,
|
||||
has_function_privilege('authenticated', 'public.undo_sie_import(uuid,uuid,uuid)', 'EXECUTE') AS authenticated_can,
|
||||
has_function_privilege('service_role', 'public.undo_sie_import(uuid,uuid,uuid)', 'EXECUTE') AS service_role_can`,
|
||||
)
|
||||
expect(rows[0].anon_can, 'anon must not be able to call undo_sie_import').toBe(false)
|
||||
expect(rows[0].public_can, 'PUBLIC must not hold EXECUTE').toBe(false)
|
||||
expect(rows[0].authenticated_can).toBe(true)
|
||||
expect(rows[0].service_role_can).toBe(true)
|
||||
})
|
||||
|
||||
it('still resolves the actor from auth.uid() when p_user_id is omitted (backward compat)', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
// Seed a posted import verifikat so undo has something to delete. Without it
|
||||
// the returned count is 0 regardless of behaviour, so the assertion would
|
||||
// pass even if the function deleted nothing: making the count meaningless.
|
||||
await insertPostedImportEntry({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
// 2-arg shape: p_user_id defaults to NULL, so the gate falls back to
|
||||
// auth.uid(). withUserContext sets the JWT sub to the owner and runs in a
|
||||
// transaction; assert inside it (the helper rolls back on return).
|
||||
const deleted = await withUserContext(userId, async (client) => {
|
||||
const res = await client.query<{ deleted: number }>(
|
||||
`SELECT public.undo_sie_import($1::uuid, $2::uuid) AS deleted`,
|
||||
[companyId, importId],
|
||||
)
|
||||
const imp = await client.query<{ status: string }>(
|
||||
`SELECT status FROM public.sie_imports WHERE id = $1`,
|
||||
[importId],
|
||||
)
|
||||
expect(imp.rows[0].status).toBe('undone')
|
||||
return res.rows[0].deleted
|
||||
})
|
||||
expect(deleted).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,237 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool, runAsServiceRole } from '@/tests/pg/setup'
|
||||
import { seedCompany, insertDraftJournalEntry } from '@/tests/pg/fixtures'
|
||||
|
||||
// Migration 20260702154500_dimension_import_provenance_undo_lockstep.sql:
|
||||
// SIE import creates dimensions/dimension_values rows carrying
|
||||
// created_by_import_id; undo_sie_import deletes the rows the undone import
|
||||
// introduced, but ONLY when no remaining posted/reversed line references
|
||||
// them, and NEVER user-created rows (created_by_import_id IS NULL).
|
||||
//
|
||||
// The registry guard triggers (enforce_dimension_registry_guards /
|
||||
// enforce_dimension_value_retention) fire on these deletes as a backstop, so
|
||||
// these tests also prove the lockstep deletes are trigger-compatible.
|
||||
|
||||
async function insertCompletedImport(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
fiscalPeriodId: string
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.sie_imports
|
||||
(id, user_id, company_id, filename, file_hash, sie_type,
|
||||
fiscal_year_start, fiscal_year_end, accounts_count, transactions_count,
|
||||
status, fiscal_period_id, imported_at)
|
||||
VALUES ($1, $2, $3, 'undo-dims-test.se', $4, 4,
|
||||
'2026-01-01', '2026-12-31', 0, 1,
|
||||
'completed', $5, now())`,
|
||||
[id, params.userId, params.companyId, `hash-${id}`, params.fiscalPeriodId],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
/** Posted entry with dimension-tagged balanced lines. */
|
||||
async function insertPostedTaggedEntry(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
fiscalPeriodId: string
|
||||
sourceType: string
|
||||
voucherNumber: number
|
||||
dimensions: Record<string, string>
|
||||
}): Promise<string> {
|
||||
const jeId = await insertDraftJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
sourceType: params.sourceType,
|
||||
status: 'draft',
|
||||
voucherNumber: params.voucherNumber,
|
||||
})
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions)
|
||||
VALUES ($1, '5010', 1000, 0, $2::jsonb),
|
||||
($1, '1930', 0, 1000, '{}'::jsonb)`,
|
||||
[jeId, JSON.stringify(params.dimensions)],
|
||||
)
|
||||
await getPool().query(
|
||||
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`,
|
||||
[jeId],
|
||||
)
|
||||
return jeId
|
||||
}
|
||||
|
||||
async function insertDimension(params: {
|
||||
companyId: string
|
||||
sieDimNo: number
|
||||
name: string
|
||||
importId?: string | null
|
||||
isSystem?: boolean
|
||||
}): Promise<string> {
|
||||
const { rows } = await getPool().query<{ id: string }>(
|
||||
`INSERT INTO public.dimensions
|
||||
(company_id, sie_dim_no, name, resets_annually, is_system, created_by_import_id)
|
||||
VALUES ($1, $2, $3, true, $4, $5)
|
||||
RETURNING id`,
|
||||
[params.companyId, params.sieDimNo, params.name, params.isSystem ?? false, params.importId ?? null],
|
||||
)
|
||||
return rows[0].id
|
||||
}
|
||||
|
||||
async function insertDimensionValue(params: {
|
||||
companyId: string
|
||||
dimensionId: string
|
||||
code: string
|
||||
importId?: string | null
|
||||
}): Promise<string> {
|
||||
const { rows } = await getPool().query<{ id: string }>(
|
||||
`INSERT INTO public.dimension_values
|
||||
(company_id, dimension_id, code, name, created_by_import_id)
|
||||
VALUES ($1, $2, $3, $3, $4)
|
||||
RETURNING id`,
|
||||
[params.companyId, params.dimensionId, params.code, params.importId ?? null],
|
||||
)
|
||||
return rows[0].id
|
||||
}
|
||||
|
||||
// undo_sie_import honors p_user_id only for service_role callers
|
||||
// (20260727121000), and these cases assert persisted state over the plain
|
||||
// pool afterwards, so the call runs under a committing service-role context.
|
||||
async function callUndo(companyId: string, importId: string, actor: string) {
|
||||
return runAsServiceRole((client) =>
|
||||
client.query<{ deleted: number }>(
|
||||
`SELECT public.undo_sie_import($1::uuid, $2::uuid, $3::uuid) AS deleted`,
|
||||
[companyId, importId, actor],
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async function countRows(table: string, id: string): Promise<number> {
|
||||
const { rows } = await getPool().query(
|
||||
`SELECT 1 FROM public.${table} WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
return rows.length
|
||||
}
|
||||
|
||||
describe('undo_sie_import: dimension registry lockstep', () => {
|
||||
it('deletes import-created values whose references vanish with the import', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 6, name: 'Projekt' })
|
||||
const valueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'P001', importId })
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'import', voucherNumber: 1,
|
||||
dimensions: { '6': 'P001' },
|
||||
})
|
||||
|
||||
const res = await callUndo(companyId, importId, userId)
|
||||
expect(res.rows[0].deleted).toBe(1)
|
||||
|
||||
// The import's value is gone; the dimension itself (not import-created)
|
||||
// survives.
|
||||
expect(await countRows('dimension_values', valueId)).toBe(0)
|
||||
expect(await countRows('dimensions', dimId)).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps import-created values that other posted bookkeeping still references', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 6, name: 'Projekt' })
|
||||
const valueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'P002', importId })
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'import', voucherNumber: 1,
|
||||
dimensions: { '6': 'P002' },
|
||||
})
|
||||
// A MANUAL posted entry tagged with the same code: survives the undo and
|
||||
// must keep its registry row (retention trigger would block the delete;
|
||||
// the lockstep's own WHERE avoids even attempting it).
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'manual', voucherNumber: 2,
|
||||
dimensions: { '6': 'P002' },
|
||||
})
|
||||
|
||||
const res = await callUndo(companyId, importId, userId)
|
||||
expect(res.rows[0].deleted).toBe(1) // only the import entry
|
||||
|
||||
expect(await countRows('dimension_values', valueId)).toBe(1)
|
||||
})
|
||||
|
||||
it('never touches user-created values (no provenance)', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 6, name: 'Projekt' })
|
||||
const userValueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'EGEN', importId: null })
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'import', voucherNumber: 1,
|
||||
dimensions: { '6': 'EGEN' },
|
||||
})
|
||||
|
||||
await callUndo(companyId, importId, userId)
|
||||
|
||||
// Unreferenced now, but user-created → stays.
|
||||
expect(await countRows('dimension_values', userValueId)).toBe(1)
|
||||
})
|
||||
|
||||
it('deletes an import-created custom dimension once empty and unreferenced', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 7, name: 'Anställd', importId })
|
||||
const valueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'ANNA', importId })
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'import', voucherNumber: 1,
|
||||
dimensions: { '7': 'ANNA' },
|
||||
})
|
||||
|
||||
await callUndo(companyId, importId, userId)
|
||||
|
||||
expect(await countRows('dimension_values', valueId)).toBe(0)
|
||||
expect(await countRows('dimensions', dimId)).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps an import-created dimension that still has user-created values', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 8, name: 'Kund', importId })
|
||||
const userValueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'KUND1', importId: null })
|
||||
await insertPostedTaggedEntry({
|
||||
companyId, userId, fiscalPeriodId,
|
||||
sourceType: 'import', voucherNumber: 1,
|
||||
dimensions: { '8': 'KUND1' },
|
||||
})
|
||||
|
||||
await callUndo(companyId, importId, userId)
|
||||
|
||||
// The user's value anchors the dimension.
|
||||
expect(await countRows('dimension_values', userValueId)).toBe(1)
|
||||
expect(await countRows('dimensions', dimId)).toBe(1)
|
||||
})
|
||||
|
||||
it('deleting an old sie_imports row nulls provenance instead of cascading', async () => {
|
||||
const { companyId, userId, fiscalPeriodId } = await seedCompany()
|
||||
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
|
||||
const dimId = await insertDimension({ companyId, sieDimNo: 6, name: 'Projekt' })
|
||||
const valueId = await insertDimensionValue({ companyId, dimensionId: dimId, code: 'P009', importId })
|
||||
|
||||
await getPool().query(`DELETE FROM public.sie_imports WHERE id = $1`, [importId])
|
||||
|
||||
const { rows } = await getPool().query<{ created_by_import_id: string | null }>(
|
||||
`SELECT created_by_import_id FROM public.dimension_values WHERE id = $1`,
|
||||
[valueId],
|
||||
)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].created_by_import_id).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Account Mapping Engine
|
||||
*
|
||||
* Maps accounts from an imported SIE file to the user's BAS chart of accounts.
|
||||
* Uses exact account number matching against the BAS reference, with a fallback
|
||||
* for valid BAS-range sub-accounts (1000-8999) not in the reference.
|
||||
* This aligns with Swedish industry standard (e.g. Fortnox): exact match,
|
||||
* create new, or let the user map manually.
|
||||
*/
|
||||
|
||||
import type {
|
||||
SIEAccount,
|
||||
AccountMapping,
|
||||
AccountMatchType,
|
||||
SIEAccountMappingRecord,
|
||||
} from './types'
|
||||
|
||||
/**
|
||||
* Minimal account shape needed for mapping.
|
||||
* Both BASAccount (from user chart) and BASReferenceAccount (from reference data)
|
||||
* satisfy this interface.
|
||||
*/
|
||||
export type MappableAccount = {
|
||||
account_number: string
|
||||
account_name: string
|
||||
}
|
||||
|
||||
// Group header accounts that should redirect to their posting sub-account.
|
||||
// These are BAS group headers not meant for direct posting.
|
||||
const GROUP_HEADER_REDIRECTS: Record<string, string> = {
|
||||
'2640': '2641', // Ingående moms → Debiterad ingående moms
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an account is a source-system internal account that should be
|
||||
* excluded from import. BAS accounts use classes 1-8 (1000-8999). Account
|
||||
* numbers starting with 0 (e.g. Fortnox 0099) are internal system accounts
|
||||
* with no BAS equivalent: they should be silently filtered out rather than
|
||||
* forcing the user to map them.
|
||||
*/
|
||||
export function isSystemAccount(accountNumber: string): boolean {
|
||||
if (!/^\d{4}$/.test(accountNumber)) return false
|
||||
const num = parseInt(accountNumber, 10)
|
||||
return num < 1000
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function isValidBASRange(accountNumber: string): boolean {
|
||||
if (!/^\d{4}$/.test(accountNumber)) return false
|
||||
const num = parseInt(accountNumber, 10)
|
||||
return num >= 1000 && num <= 8999
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the best matching BAS account for a source account.
|
||||
* First tries exact match against the reference, then falls back to
|
||||
* self-mapping for valid BAS-range accounts not in the reference
|
||||
* (common for sub-accounts like 1241 Personbilar under 1240).
|
||||
*/
|
||||
function findBestMatch(
|
||||
source: SIEAccount,
|
||||
basAccounts: MappableAccount[],
|
||||
existingOverride?: AccountMapping
|
||||
): AccountMapping | null {
|
||||
// If there's a user override, use it
|
||||
if (existingOverride) {
|
||||
return {
|
||||
...existingOverride,
|
||||
isOverride: true,
|
||||
}
|
||||
}
|
||||
|
||||
// Exact account number match against reference
|
||||
const exactMatch = basAccounts.find(
|
||||
(target) => source.number === target.account_number
|
||||
)
|
||||
|
||||
if (exactMatch) {
|
||||
// Redirect group header accounts to their posting sub-account
|
||||
const redirect = GROUP_HEADER_REDIRECTS[exactMatch.account_number]
|
||||
if (redirect) {
|
||||
const redirectTarget = basAccounts.find((a) => a.account_number === redirect)
|
||||
if (redirectTarget) {
|
||||
return {
|
||||
sourceAccount: source.number,
|
||||
sourceName: source.name,
|
||||
targetAccount: redirectTarget.account_number,
|
||||
targetName: redirectTarget.account_name,
|
||||
confidence: 1.0,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sourceAccount: source.number,
|
||||
sourceName: source.name,
|
||||
targetAccount: exactMatch.account_number,
|
||||
targetName: exactMatch.account_name,
|
||||
confidence: 1.0,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
|
||||
// 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), 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,
|
||||
targetAccount: source.number,
|
||||
targetName: source.name,
|
||||
confidence: 0.7,
|
||||
matchType: 'bas_range',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
|
||||
// No match found
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest mappings for all source accounts
|
||||
*/
|
||||
export function suggestMappings(
|
||||
sourceAccounts: SIEAccount[],
|
||||
basAccounts: MappableAccount[],
|
||||
existingMappings?: SIEAccountMappingRecord[]
|
||||
): AccountMapping[] {
|
||||
// Convert existing mappings to a lookup map
|
||||
const overrideMap = new Map<string, AccountMapping>()
|
||||
if (existingMappings) {
|
||||
for (const mapping of existingMappings) {
|
||||
const basAccount = basAccounts.find((a) => a.account_number === mapping.target_account)
|
||||
overrideMap.set(mapping.source_account, {
|
||||
sourceAccount: mapping.source_account,
|
||||
sourceName: mapping.source_name || '',
|
||||
targetAccount: mapping.target_account,
|
||||
targetName: basAccount?.account_name || mapping.target_account,
|
||||
confidence: mapping.confidence,
|
||||
matchType: mapping.match_type,
|
||||
isOverride: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const mappings: AccountMapping[] = []
|
||||
|
||||
for (const source of sourceAccounts) {
|
||||
const existingOverride = overrideMap.get(source.number)
|
||||
const mapping = findBestMatch(source, basAccounts, existingOverride)
|
||||
|
||||
if (mapping) {
|
||||
mappings.push(mapping)
|
||||
} else {
|
||||
// No match found - add with null target
|
||||
mappings.push({
|
||||
sourceAccount: source.number,
|
||||
sourceName: source.name,
|
||||
targetAccount: '',
|
||||
targetName: '',
|
||||
confidence: 0,
|
||||
matchType: 'manual',
|
||||
isOverride: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by confidence (low to high) so users see problematic mappings first
|
||||
mappings.sort((a, b) => a.confidence - b.confidence)
|
||||
|
||||
return mappings
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that all accounts are mapped
|
||||
*/
|
||||
export function validateMappings(mappings: AccountMapping[]): {
|
||||
valid: boolean
|
||||
unmappedAccounts: string[]
|
||||
lowConfidenceAccounts: string[]
|
||||
} {
|
||||
const unmapped = mappings.filter((m) => !m.targetAccount)
|
||||
const lowConfidence = mappings.filter((m) => m.targetAccount && m.confidence < 0.5)
|
||||
|
||||
return {
|
||||
valid: unmapped.length === 0,
|
||||
unmappedAccounts: unmapped.map((m) => m.sourceAccount),
|
||||
lowConfidenceAccounts: lowConfidence.map((m) => m.sourceAccount),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get mapping statistics
|
||||
*/
|
||||
export function getMappingStats(mappings: AccountMapping[]): {
|
||||
total: number
|
||||
mapped: number
|
||||
unmapped: number
|
||||
exact: number
|
||||
basRange: number
|
||||
name: number
|
||||
class: number
|
||||
manual: number
|
||||
lowConfidence: number
|
||||
averageConfidence: number
|
||||
} {
|
||||
const total = mappings.length
|
||||
const mapped = mappings.filter((m) => m.targetAccount).length
|
||||
const unmapped = total - mapped
|
||||
|
||||
const exact = mappings.filter((m) => m.matchType === 'exact').length
|
||||
const basRange = mappings.filter((m) => m.matchType === 'bas_range').length
|
||||
const name = mappings.filter((m) => m.matchType === 'name').length
|
||||
const classMatch = mappings.filter((m) => m.matchType === 'class').length
|
||||
const manual = mappings.filter((m) => m.matchType === 'manual').length
|
||||
|
||||
const lowConfidence = mappings.filter((m) => m.targetAccount && m.confidence < 0.5).length
|
||||
|
||||
const confidenceSum = mappings
|
||||
.filter((m) => m.targetAccount)
|
||||
.reduce((sum, m) => sum + m.confidence, 0)
|
||||
const averageConfidence = mapped > 0 ? confidenceSum / mapped : 0
|
||||
|
||||
return {
|
||||
total,
|
||||
mapped,
|
||||
unmapped,
|
||||
exact,
|
||||
basRange,
|
||||
name,
|
||||
class: classMatch,
|
||||
manual,
|
||||
lowConfidence,
|
||||
averageConfidence,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a user override to the mappings
|
||||
*/
|
||||
export function applyMappingOverride(
|
||||
mappings: AccountMapping[],
|
||||
sourceAccount: string,
|
||||
targetAccount: string,
|
||||
targetName: string
|
||||
): AccountMapping[] {
|
||||
return mappings.map((m) => {
|
||||
if (m.sourceAccount === sourceAccount) {
|
||||
return {
|
||||
...m,
|
||||
targetAccount,
|
||||
targetName,
|
||||
confidence: 1.0,
|
||||
matchType: 'manual' as AccountMatchType,
|
||||
isOverride: true,
|
||||
}
|
||||
}
|
||||
return m
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert mappings to a lookup map for quick access during import
|
||||
*/
|
||||
export function mappingsToMap(mappings: AccountMapping[]): Map<string, string> {
|
||||
const map = new Map<string, string>()
|
||||
for (const mapping of mappings) {
|
||||
if (mapping.targetAccount) {
|
||||
map.set(mapping.sourceAccount, mapping.targetAccount)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* Chart-of-accounts synchronization for SIE imports.
|
||||
*
|
||||
* Single home for the "ensure every mapped target account exists" logic that
|
||||
* previously lived in three near-identical copies (executeSIEImport, the
|
||||
* /api/import/sie/execute route, and the arcim-migration extension), plus the
|
||||
* rename pass that carries customized #KONTO names from the SIE file into
|
||||
* accounts that already exist (e.g. the K1-seeded defaults).
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { getBASReference, type BASReferenceAccount } from '@/lib/bookkeeping/bas-reference'
|
||||
import { classifyAccount } from '@/lib/bookkeeping/account-classifier'
|
||||
import { computeSRUCode } from '@/lib/bookkeeping/bas-data/sru-mapping'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import type { AccountMapping } from './types'
|
||||
import {
|
||||
defaultRateForVatTreatment,
|
||||
isAccountVatTreatment,
|
||||
isVatTreatmentAllowedForAccountClass,
|
||||
type AccountVatTreatment,
|
||||
} from '@/lib/vat/account-vat-treatment'
|
||||
|
||||
export interface AccountSyncResult {
|
||||
/** Accounts inserted into chart_of_accounts */
|
||||
created: number
|
||||
/** Existing accounts whose name was updated from the SIE file */
|
||||
renamed: number
|
||||
/** Detail of each rename, for warnings/logging */
|
||||
renamedAccounts: Array<{ accountNumber: string; from: string; to: string }>
|
||||
/** Renames that failed (non-fatal: the import proceeds with old names) */
|
||||
renameFailed: number
|
||||
/** Fatal error from the create pass; null on success */
|
||||
error: string | null
|
||||
}
|
||||
|
||||
function emptyResult(): AccountSyncResult {
|
||||
return { created: 0, renamed: 0, renamedAccounts: [], renameFailed: 0, error: null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows per INSERT statement in the create pass.
|
||||
*
|
||||
* PostgREST runs every request under the authenticated role's 8 s
|
||||
* statement_timeout, and each chart_of_accounts row fires four row-level
|
||||
* triggers (audit log, writer-role guard, updated_at, known VAT rate) plus the
|
||||
* RLS WITH CHECK. A full-BAS SIE import creates 1 200+ accounts in one go; on
|
||||
* prod (2026-09-09) that single statement took 6.5 s for one company and was
|
||||
* cancelled at 8.2 s for the next, so whether an import went through was a
|
||||
* coin flip. 100 rows keeps every statement an order of magnitude inside the
|
||||
* limit. Exported for the chunking test.
|
||||
*/
|
||||
export const INSERT_CHUNK_SIZE = 100
|
||||
|
||||
/**
|
||||
* Build a chart_of_accounts insert row with the richest metadata available:
|
||||
* BAS reference when the number is in BAS_REFERENCE (incl. description and
|
||||
* k2_excluded), otherwise derived from the account number.
|
||||
*/
|
||||
function buildInsertRow(
|
||||
accountNumber: string,
|
||||
accountName: string,
|
||||
basRef: BASReferenceAccount | undefined,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
vatDefaults?: { treatment: AccountVatTreatment | null; rate: number | null },
|
||||
) {
|
||||
const sortOrder = /^\d+$/.test(accountNumber) ? parseInt(accountNumber, 10) : null
|
||||
|
||||
if (basRef) {
|
||||
return {
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
account_number: accountNumber,
|
||||
account_name: accountName,
|
||||
account_class: basRef.account_class,
|
||||
account_group: basRef.account_group,
|
||||
account_type: basRef.account_type,
|
||||
normal_balance: basRef.normal_balance,
|
||||
sru_code: basRef.sru_code ?? computeSRUCode(accountNumber),
|
||||
k2_excluded: basRef.k2_excluded,
|
||||
plan_type: 'full_bas' as const,
|
||||
is_active: true,
|
||||
is_system_account: false,
|
||||
description: basRef.description,
|
||||
sort_order: sortOrder,
|
||||
default_vat_treatment: vatDefaults?.treatment ?? null,
|
||||
default_vat_rate: vatDefaults?.rate ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
// Sub-account not in the BAS reference (e.g. 1932 Sparkonto). Derive
|
||||
// metadata from the account number.
|
||||
const classified = classifyAccount(accountNumber)
|
||||
return {
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
account_number: accountNumber,
|
||||
account_name: accountName,
|
||||
account_class: parseInt(accountNumber.charAt(0), 10),
|
||||
account_group: accountNumber.substring(0, 2),
|
||||
account_type: classified.account_type,
|
||||
normal_balance: classified.normal_balance,
|
||||
sru_code: computeSRUCode(accountNumber),
|
||||
plan_type: 'full_bas' as const,
|
||||
is_active: true,
|
||||
is_system_account: false,
|
||||
description: accountName,
|
||||
sort_order: sortOrder,
|
||||
default_vat_treatment: vatDefaults?.treatment ?? null,
|
||||
default_vat_rate: vatDefaults?.rate ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure every mapped target account exists in chart_of_accounts and,
|
||||
* when `updateAccountNames` is true, carry the SIE file's #KONTO names into
|
||||
* the chart.
|
||||
*
|
||||
* Name resolution: the file's name applies only to IDENTITY mappings
|
||||
* (sourceAccount === targetAccount with a non-empty sourceName): when the
|
||||
* user remaps a source to a different target, the file name describes the
|
||||
* source account, not the target, so the target keeps its BAS/current name.
|
||||
*
|
||||
* - Create: account_name = file name (identity, flag on)
|
||||
* ?? BAS reference name
|
||||
* ?? targetName/sourceName fallback (non-BAS numbers)
|
||||
* ?? `Konto ${number}`.
|
||||
* - Rename (flag on only): existing accounts that are identity targets and
|
||||
* whose stored name differs from the file name get a scoped UPDATE of
|
||||
* account_name, and nothing else. Applies to is_system_account rows too
|
||||
* (K1-seeded defaults); the flag itself is never touched. Equal names are
|
||||
* a no-op, so replace-mode re-imports (Fortnox re-sync) are idempotent.
|
||||
*
|
||||
* When `updateAccountNames` is false the behavior matches the legacy code
|
||||
* exactly: BAS defaults on create, existing accounts untouched.
|
||||
*/
|
||||
export async function syncMappedAccounts(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
mappings: AccountMapping[],
|
||||
updateAccountNames: boolean,
|
||||
): Promise<AccountSyncResult> {
|
||||
const result = emptyResult()
|
||||
|
||||
const targetAccounts = [...new Set(
|
||||
mappings.filter((m) => m.targetAccount).map((m) => m.targetAccount)
|
||||
)]
|
||||
if (targetAccounts.length === 0) return result
|
||||
|
||||
// The SIE file's name for each identity-mapped account. Last write wins on
|
||||
// duplicate #KONTO records (rare, benign).
|
||||
const desiredNames = new Map<string, string>()
|
||||
if (updateAccountNames) {
|
||||
for (const m of mappings) {
|
||||
const name = m.sourceName?.trim()
|
||||
if (name && m.targetAccount && m.sourceAccount === m.targetAccount) {
|
||||
desiredNames.set(m.targetAccount, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy create-time fallback for numbers outside the BAS reference.
|
||||
const fallbackNames = new Map<string, string>()
|
||||
for (const m of mappings) {
|
||||
const fallback = m.targetName || m.sourceName
|
||||
if (m.targetAccount && fallback) fallbackNames.set(m.targetAccount, fallback)
|
||||
}
|
||||
|
||||
const vatDefaults = new Map<string, { treatment: AccountVatTreatment | null; rate: number | null }>()
|
||||
for (const mapping of mappings) {
|
||||
if (
|
||||
!mapping.vatTreatmentReviewed ||
|
||||
!mapping.targetAccount ||
|
||||
mapping.sourceAccount !== mapping.targetAccount
|
||||
) continue
|
||||
if (
|
||||
mapping.defaultVatTreatment !== null &&
|
||||
mapping.defaultVatTreatment !== undefined &&
|
||||
!isAccountVatTreatment(mapping.defaultVatTreatment)
|
||||
) {
|
||||
result.error = `Invalid VAT treatment for account ${mapping.sourceAccount}`
|
||||
return result
|
||||
}
|
||||
const accountClass = Number(mapping.targetAccount.charAt(0))
|
||||
if (
|
||||
mapping.defaultVatTreatment &&
|
||||
!isVatTreatmentAllowedForAccountClass(mapping.defaultVatTreatment, accountClass)
|
||||
) {
|
||||
result.error = `VAT treatment is not valid for account ${mapping.sourceAccount}`
|
||||
return result
|
||||
}
|
||||
vatDefaults.set(mapping.targetAccount, {
|
||||
treatment: mapping.defaultVatTreatment ?? null,
|
||||
rate: mapping.defaultVatTreatment && mapping.defaultVatRate == null
|
||||
? defaultRateForVatTreatment(mapping.defaultVatTreatment, accountClass)
|
||||
: mapping.defaultVatRate ?? null,
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch the company's chart once (paged) and filter in JS: avoids a huge
|
||||
// .in() URL for full-chart imports and the silent 1000-row PostgREST cap.
|
||||
let existingByNumber: Map<string, string>
|
||||
try {
|
||||
const targetSet = new Set(targetAccounts)
|
||||
const allAccounts = await fetchAllRows<{ account_number: string; account_name: string }>(
|
||||
({ from, to }) =>
|
||||
supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number, account_name')
|
||||
.eq('company_id', companyId)
|
||||
// Stable total order on the unique account_number: paging is only
|
||||
// correct with a deterministic order, else rows duplicate/skip across
|
||||
// pages (see fetch-all.ts ordering invariant). The result is read into
|
||||
// a Map below, so this order is invisible to callers.
|
||||
.order('account_number', { ascending: true })
|
||||
.range(from, to)
|
||||
)
|
||||
existingByNumber = new Map(
|
||||
allAccounts
|
||||
.filter((a) => targetSet.has(a.account_number))
|
||||
.map((a) => [a.account_number, a.account_name])
|
||||
)
|
||||
} catch (err) {
|
||||
result.error = err instanceof Error ? err.message : 'Failed to load chart of accounts'
|
||||
return result
|
||||
}
|
||||
|
||||
// Create pass: insert missing target accounts.
|
||||
const missing = targetAccounts.filter((num) => !existingByNumber.has(num))
|
||||
if (missing.length > 0) {
|
||||
const inserts = missing.map((num) => {
|
||||
const basRef = getBASReference(num)
|
||||
const name =
|
||||
desiredNames.get(num) ??
|
||||
basRef?.account_name ??
|
||||
fallbackNames.get(num) ??
|
||||
`Konto ${num}`
|
||||
return buildInsertRow(num, name, basRef, companyId, userId, vatDefaults.get(num))
|
||||
})
|
||||
|
||||
// One statement per chunk (see INSERT_CHUNK_SIZE). A chunk that fails
|
||||
// leaves the earlier ones committed, which is safe: the next attempt reads
|
||||
// the chart again and only inserts what is still missing.
|
||||
//
|
||||
// ON CONFLICT (company_id, account_number) DO NOTHING: a concurrent import
|
||||
// (or the replace flow) can create an account between our read and this
|
||||
// write. With a plain INSERT that duplicate rolled back the whole
|
||||
// statement while the caller treated "duplicate" as success, silently
|
||||
// dropping every other account in it. Rows the conflict skipped are not
|
||||
// returned, so `created` counts exactly what landed, chunk by chunk (the
|
||||
// audit_log trigger on chart_of_accounts stays the per-row source of
|
||||
// truth for behandlingshistoriken).
|
||||
for (let i = 0; i < inserts.length; i += INSERT_CHUNK_SIZE) {
|
||||
const chunk = inserts.slice(i, i + INSERT_CHUNK_SIZE)
|
||||
const { data: insertedRows, error: insertError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.upsert(chunk, { onConflict: 'company_id,account_number', ignoreDuplicates: true })
|
||||
.select('account_number')
|
||||
if (insertError) {
|
||||
result.error = insertError.message
|
||||
return result
|
||||
}
|
||||
result.created += insertedRows?.length ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
const existingVatUpdates = [...vatDefaults]
|
||||
.filter(([account]) => existingByNumber.has(account))
|
||||
for (const [account, defaults] of existingVatUpdates) {
|
||||
const { error: vatUpdateError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.update({
|
||||
default_vat_treatment: defaults.treatment,
|
||||
default_vat_rate: defaults.rate,
|
||||
})
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_number', account)
|
||||
if (vatUpdateError) {
|
||||
result.error = vatUpdateError.message
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// Rename pass: carry the file's names into existing accounts. The diff set
|
||||
// is small (only names that actually changed), so the UPDATEs run
|
||||
// concurrently in bounded batches: a full-chart re-sync must not serialize
|
||||
// N round trips, but also must not stampede the API with 1000+ in flight.
|
||||
if (updateAccountNames) {
|
||||
const renames: Array<{ num: string; from: string; to: string }> = []
|
||||
for (const [num, currentName] of existingByNumber) {
|
||||
const desired = desiredNames.get(num)
|
||||
if (desired && desired !== currentName) {
|
||||
renames.push({ num, from: currentName, to: desired })
|
||||
}
|
||||
}
|
||||
|
||||
const RENAME_BATCH_SIZE = 25
|
||||
for (let i = 0; i < renames.length; i += RENAME_BATCH_SIZE) {
|
||||
const batch = renames.slice(i, i + RENAME_BATCH_SIZE)
|
||||
const outcomes = await Promise.allSettled(
|
||||
batch.map(async ({ num, to }) => {
|
||||
const { error: updateError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.update({ account_name: to })
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_number', num)
|
||||
if (updateError) throw new Error(updateError.message)
|
||||
})
|
||||
)
|
||||
|
||||
outcomes.forEach((outcome, idx) => {
|
||||
if (outcome.status === 'rejected') {
|
||||
// Non-fatal: the import is still correct with the old name.
|
||||
result.renameFailed++
|
||||
return
|
||||
}
|
||||
result.renamed++
|
||||
const { num, from, to } = batch[idx]
|
||||
result.renamedAccounts.push({ accountNumber: num, from, to })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { BASAccount } from '@/types'
|
||||
import {
|
||||
suggestVatTreatment,
|
||||
type AccountVatTreatment,
|
||||
} from '@/lib/vat/account-vat-treatment'
|
||||
import type { AccountMapping } from './types'
|
||||
|
||||
/**
|
||||
* Add reviewable VAT suggestions to identity mappings. SIE itself has no VAT
|
||||
* treatment record, so suggestions come only from the account label and are
|
||||
* never considered reviewed until the user continues from the mapping step.
|
||||
*/
|
||||
export function enrichAccountMappingsWithVat(
|
||||
mappings: AccountMapping[],
|
||||
existingAccounts: BASAccount[],
|
||||
): AccountMapping[] {
|
||||
const existingByNumber = new Map(
|
||||
existingAccounts.map((account) => [account.account_number, account]),
|
||||
)
|
||||
|
||||
return mappings.map((mapping) => {
|
||||
if (!mapping.targetAccount || mapping.sourceAccount !== mapping.targetAccount) {
|
||||
return {
|
||||
...mapping,
|
||||
defaultVatTreatment: null,
|
||||
defaultVatRate: null,
|
||||
vatTreatmentSuggested: false,
|
||||
vatTreatmentReviewed: true,
|
||||
requiresVatTreatmentReview: false,
|
||||
}
|
||||
}
|
||||
const accountClass = Number(mapping.sourceAccount.charAt(0))
|
||||
if (accountClass < 3 || accountClass > 6) return mapping
|
||||
|
||||
const existing = existingByNumber.get(mapping.targetAccount)
|
||||
if (existing?.default_vat_treatment) {
|
||||
return {
|
||||
...mapping,
|
||||
defaultVatTreatment: existing.default_vat_treatment,
|
||||
defaultVatRate: existing.default_vat_rate,
|
||||
vatTreatmentReviewed: true,
|
||||
vatTreatmentSuggested: false,
|
||||
requiresVatTreatmentReview: false,
|
||||
}
|
||||
}
|
||||
|
||||
const suggestion = suggestVatTreatment(mapping.sourceAccount, mapping.sourceName)
|
||||
return {
|
||||
...mapping,
|
||||
defaultVatTreatment: suggestion?.treatment ?? null,
|
||||
defaultVatRate: existing?.default_vat_rate ?? suggestion?.rate ?? null,
|
||||
vatTreatmentSuggested: Boolean(suggestion),
|
||||
vatTreatmentReviewed: false,
|
||||
requiresVatTreatmentReview: accountClass === 3 || accountClass === 4 || Boolean(suggestion),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function applyVatTreatmentReview(
|
||||
mappings: AccountMapping[],
|
||||
sourceAccount: string,
|
||||
treatment: AccountVatTreatment | null,
|
||||
rate: number | null,
|
||||
): AccountMapping[] {
|
||||
return mappings.map((mapping) =>
|
||||
mapping.sourceAccount === sourceAccount
|
||||
? {
|
||||
...mapping,
|
||||
defaultVatTreatment: treatment,
|
||||
defaultVatRate: rate,
|
||||
vatTreatmentSuggested: false,
|
||||
vatTreatmentReviewed: true,
|
||||
}
|
||||
: mapping
|
||||
)
|
||||
}
|
||||
|
||||
export function enrichChangedAccountMappingWithVat(
|
||||
mappings: AccountMapping[],
|
||||
sourceAccount: string,
|
||||
existingAccounts: BASAccount[],
|
||||
): AccountMapping[] {
|
||||
return mappings.map((mapping) =>
|
||||
mapping.sourceAccount === sourceAccount
|
||||
? enrichAccountMappingsWithVat([mapping], existingAccounts)[0]
|
||||
: mapping
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept the suggested VAT treatment for every mapping still awaiting review,
|
||||
* in one action. Exactly the per-row "Bekräfta" semantics batched: each row
|
||||
* keeps its current suggested default (or null when there is none) and is
|
||||
* marked reviewed. Added because a Fortnox chart routinely puts 70+ class 3/4
|
||||
* accounts behind the review gate, and clicking them one by one across
|
||||
* paginated pages was an observed migration dead end (2026-08-18).
|
||||
*/
|
||||
export function applyVatTreatmentReviewAll(mappings: AccountMapping[]): AccountMapping[] {
|
||||
return mappings.map((mapping) =>
|
||||
mapping.requiresVatTreatmentReview && !mapping.vatTreatmentReviewed
|
||||
? {
|
||||
...mapping,
|
||||
vatTreatmentSuggested: false,
|
||||
vatTreatmentReviewed: true,
|
||||
}
|
||||
: mapping
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectArticleColumns } from '../column-detector'
|
||||
|
||||
describe('detectArticleColumns', () => {
|
||||
it('detects a rich Swedish header at high confidence', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Artikelnummer', 'Benämning', 'Typ', 'Enhet', 'Pris', 'Moms', 'Försäljningskonto',
|
||||
])
|
||||
expect(cols.name_col).toBe(1)
|
||||
expect(cols.article_number_col).toBe(0)
|
||||
expect(cols.type_col).toBe(2)
|
||||
expect(cols.unit_col).toBe(3)
|
||||
expect(cols.price_col).toBe(4)
|
||||
expect(cols.vat_rate_col).toBe(5)
|
||||
expect(cols.revenue_account_col).toBe(6)
|
||||
expect(cols.confidence).toBeGreaterThanOrEqual(0.8)
|
||||
})
|
||||
|
||||
it('keeps price, VAT and account in distinct columns (no keyword collision)', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Benämning', 'Pris exkl moms', 'Moms %', 'Försäljningskonto',
|
||||
])
|
||||
expect(cols.price_col).toBe(1) // "Pris exkl moms" → price, not VAT
|
||||
expect(cols.vat_rate_col).toBe(2)
|
||||
expect(cols.revenue_account_col).toBe(3)
|
||||
expect(cols.price_col).not.toBe(cols.vat_rate_col)
|
||||
})
|
||||
|
||||
it('does not read Fortnox "Momskod" as the article number', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'Momskod'])
|
||||
expect(cols.vat_rate_col).toBe(1)
|
||||
expect(cols.article_number_col).toBeNull()
|
||||
})
|
||||
|
||||
it('claims EAN before the generic article number', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'EAN-nummer', 'Artikelnummer'])
|
||||
expect(cols.ean_col).toBe(1)
|
||||
expect(cols.article_number_col).toBe(2)
|
||||
})
|
||||
|
||||
it('detects the English name column separately from the main name', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'Benämning engelska'])
|
||||
expect(cols.name_col).toBe(0)
|
||||
expect(cols.name_en_col).toBe(1)
|
||||
})
|
||||
|
||||
it('detects Fortnox-style headers', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Artikelnr', 'Benämning', 'Försäljningspris', 'Inköpspris', 'Momskod', 'Enhet',
|
||||
])
|
||||
expect(cols.article_number_col).toBe(0)
|
||||
expect(cols.price_col).toBe(2)
|
||||
expect(cols.cost_price_col).toBe(3)
|
||||
expect(cols.vat_rate_col).toBe(4)
|
||||
})
|
||||
|
||||
it('reports low confidence when only a name column is present', () => {
|
||||
const cols = detectArticleColumns(['Benämning'])
|
||||
expect(cols.name_col).toBe(0)
|
||||
expect(cols.confidence).toBeLessThan(0.8)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,266 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { parseArticlesFile } from '../parser'
|
||||
|
||||
function buildXlsx(rows: (string | number)[][]): ArrayBuffer {
|
||||
const ws = XLSX.utils.aoa_to_sheet(rows)
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Artiklar')
|
||||
return XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer
|
||||
}
|
||||
|
||||
describe('parseArticlesFile', () => {
|
||||
it('parses a basic Swedish article register', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Artikelnummer', 'Pris', 'Moms', 'Enhet', 'Typ'],
|
||||
['Konsulttimme', 'A-100', '950', '25', 'tim', 'tjänst'],
|
||||
['Skruv', 'A-200', '2,50', '25', 'st', 'vara'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'artiklar.xlsx')
|
||||
|
||||
expect(result.total_rows).toBe(2)
|
||||
expect(result.rows[0].name).toBe('Konsulttimme')
|
||||
expect(result.rows[0].article_number).toBe('A-100')
|
||||
expect(result.rows[0].price_excl_vat).toBe(950)
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[0].unit).toBe('tim')
|
||||
expect(result.rows[0].type).toBe('tjanst')
|
||||
expect(result.rows[1].type).toBe('vara')
|
||||
expect(result.rows[1].price_excl_vat).toBe(2.5)
|
||||
expect(result.rows[0].is_valid).toBe(true)
|
||||
// A clean, valid VAT rate is not flagged as adjusted.
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(false)
|
||||
})
|
||||
|
||||
it('detects Fortnox-style export headers', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Artikelnummer', 'Benämning', 'Försäljningspris', 'Momskod', 'Försäljningskonto', 'Enhet'],
|
||||
['100', 'Webdesign', '1 200', '25', '3001', 'st'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'fortnox.xlsx')
|
||||
const r = result.rows[0]
|
||||
expect(r.article_number).toBe('100')
|
||||
expect(r.name).toBe('Webdesign')
|
||||
expect(r.price_excl_vat).toBe(1200) // "1 200" → 1200
|
||||
expect(r.vat_rate).toBe(25)
|
||||
expect(r.revenue_account).toBe('3001')
|
||||
})
|
||||
|
||||
it('parses Swedish decimal prices', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris'],
|
||||
['A', '1 234,56'],
|
||||
['B', '1.234,50'],
|
||||
['C', '500'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'priser.xlsx')
|
||||
expect(result.rows[0].price_excl_vat).toBe(1234.56)
|
||||
expect(result.rows[1].price_excl_vat).toBe(1234.5)
|
||||
expect(result.rows[2].price_excl_vat).toBe(500)
|
||||
})
|
||||
|
||||
it('snaps VAT to the nearest statutory rate and warns', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Moms'],
|
||||
['A', '25%'],
|
||||
['B', '7'], // → 6
|
||||
['C', ''], // → 25 default
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'moms.xlsx')
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[1].vat_rate).toBe(6)
|
||||
expect(result.rows[2].vat_rate).toBe(25)
|
||||
// The "7" → 6 snap should surface a file-level warning.
|
||||
expect(result.warnings.some((w) => w.includes('momssats'))).toBe(true)
|
||||
// Per-row flag: only the snapped row (7 → 6) is marked adjusted.
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(false) // "25%" is already valid
|
||||
expect(result.rows[1].vat_rate_adjusted).toBe(true) // 7 → 6
|
||||
expect(result.rows[2].vat_rate_adjusted).toBe(false) // empty → default 25
|
||||
})
|
||||
|
||||
it('defaults an unparseable momskod to 25 with a warning', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Momskod'],
|
||||
['A', 'MP1'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'momskod.xlsx')
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(true)
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('moms'))).toBe(true)
|
||||
})
|
||||
|
||||
it('normalizes article type and falls back to tjanst', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Typ'],
|
||||
['A', 'Produkt'],
|
||||
['B', 'service'],
|
||||
['C', ''],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'typ.xlsx')
|
||||
expect(result.rows[0].type).toBe('vara')
|
||||
expect(result.rows[1].type).toBe('tjanst')
|
||||
expect(result.rows[2].type).toBe('tjanst')
|
||||
})
|
||||
|
||||
it('falls back to "st" when no unit is given', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning'],
|
||||
['A'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'unit.xlsx')
|
||||
expect(result.rows[0].unit).toBe('st')
|
||||
})
|
||||
|
||||
it('keeps class 1-3 posting accounts and drops a class-4 account', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Försäljningskonto'],
|
||||
['A', '3001'],
|
||||
['B', '1930'],
|
||||
['C', '4000'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'konto.xlsx')
|
||||
expect(result.rows[0].revenue_account).toBe('3001')
|
||||
expect(result.rows[1].revenue_account).toBe('1930')
|
||||
expect(result.rows[2].revenue_account).toBeNull()
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('bokföringskonto'))).toBe(true)
|
||||
})
|
||||
|
||||
it('treats a blank cost price as null (not 0)', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Inköpspris'],
|
||||
['A', ''],
|
||||
['B', '100'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'cost.xlsx')
|
||||
expect(result.rows[0].cost_price).toBeNull()
|
||||
expect(result.rows[1].cost_price).toBe(100)
|
||||
})
|
||||
|
||||
it('warns when the price column looks incl-VAT', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris inkl moms'],
|
||||
['A', '125'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'brutto.xlsx')
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('inkl'))).toBe(true)
|
||||
})
|
||||
|
||||
it('skips rows with empty name and preserves row_index', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning'],
|
||||
['A'],
|
||||
[''],
|
||||
['C'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'sparse.xlsx')
|
||||
expect(result.total_rows).toBe(2)
|
||||
expect(result.rows.map((r) => r.name)).toEqual(['A', 'C'])
|
||||
expect(result.rows[0].row_index).toBe(2)
|
||||
expect(result.rows[1].row_index).toBe(4)
|
||||
})
|
||||
|
||||
it('flags a negative price as invalid', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris'],
|
||||
['A', '-50'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'neg.xlsx')
|
||||
expect(result.rows[0].is_valid).toBe(false)
|
||||
expect(result.rows[0].validation_errors).toContain('Priset kan inte vara negativt')
|
||||
})
|
||||
|
||||
it('returns a warning when zero rows match', () => {
|
||||
const buffer = buildXlsx([['Benämning']])
|
||||
const result = parseArticlesFile(buffer, 'empty.xlsx')
|
||||
expect(result.total_rows).toBe(0)
|
||||
expect(result.warnings.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('preserves Swedish characters when reading a UTF-8 CSV', () => {
|
||||
const csv = new TextEncoder().encode(
|
||||
'Benämning,Enhet\nMöbel,st\nKärra,st\n',
|
||||
).buffer
|
||||
const result = parseArticlesFile(csv, 'artiklar.csv')
|
||||
expect(result.rows[0].name).toBe('Möbel')
|
||||
expect(result.rows[1].name).toBe('Kärra')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseArticlesFile currency (Valuta) column', () => {
|
||||
it('parses and normalizes a Valuta column', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Försäljningspris', 'Valuta'],
|
||||
['EU-konsulting', '950', 'eur'],
|
||||
['Svensk tjänst', '500', 'SEK'],
|
||||
['Utan valuta', '100', ''],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'valuta.xlsx')
|
||||
|
||||
expect(result.detected_columns.currency_col).toBe(2)
|
||||
expect(result.rows[0].currency).toBe('EUR')
|
||||
expect(result.rows[1].currency).toBe('SEK')
|
||||
// Blank cell = not specified: the execute route imports it as SEK.
|
||||
expect(result.rows[2].currency).toBeNull()
|
||||
expect(result.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it('drops malformed currency codes with a warning', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris', 'Valuta'],
|
||||
['A', '100', 'EURO'],
|
||||
['B', '200', 'EUR'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'valuta.xlsx')
|
||||
|
||||
expect(result.rows[0].currency).toBeNull()
|
||||
expect(result.rows[1].currency).toBe('EUR')
|
||||
expect(result.warnings.some((w) => w.includes('valutakod'))).toBe(true)
|
||||
})
|
||||
|
||||
it('does not let Valuta steal the price or VAT columns', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Valuta', 'Försäljningspris', 'Moms %'],
|
||||
['A', 'EUR', '100', '25'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'valuta.xlsx')
|
||||
|
||||
expect(result.detected_columns.currency_col).toBe(1)
|
||||
expect(result.rows[0].price_excl_vat).toBe(100)
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseArticlesFile ROT/RUT (housework) column', () => {
|
||||
it('normalizes work-type codes and bare kinds, and drops boolean-style values', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris', 'Husarbete'],
|
||||
['Städning', '450', 'stad'],
|
||||
['Fönsterputs', '500', 'RUT'],
|
||||
// A boolean "Rot"/"Husarbete" column exported by other systems: '1'/'0'
|
||||
// are not values the invoice editor can interpret, so they must not be
|
||||
// stored (this is what produced 178 junk rows on prod).
|
||||
['Bygg', '600', '1'],
|
||||
['Skruv', '2', '0'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'husarbete.xlsx')
|
||||
|
||||
expect(result.detected_columns.housework_type_col).toBe(2)
|
||||
expect(result.rows[0].housework_type).toBe('STAD')
|
||||
expect(result.rows[1].housework_type).toBe('RUT')
|
||||
expect(result.rows[2].housework_type).toBeNull()
|
||||
expect(result.rows[3].housework_type).toBeNull()
|
||||
// Dropping a non-empty value is surfaced, never silent.
|
||||
expect(result.warnings.some((w) => w.includes('2 rader hade ett ROT/RUT-värde'))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { findColumn } from '../shared/column-utils'
|
||||
import type { DetectedArticleColumns } from './types'
|
||||
|
||||
// Keyword lists cover the export headers of Fortnox, Visma and Bokio so files
|
||||
// from those systems auto-map. Header-only matching (register imports always
|
||||
// have a header row).
|
||||
|
||||
const NAME_KEYWORDS = [
|
||||
'benämning', 'benamning', 'artikelnamn', 'artikel namn', 'namn', 'name',
|
||||
'produktnamn', 'produkt namn', 'product name', 'article name', 'beskrivning',
|
||||
'description', 'title',
|
||||
]
|
||||
|
||||
const NAME_EN_KEYWORDS = [
|
||||
'engelska', 'english', 'name en', 'name english', 'name_english',
|
||||
'engelskt namn', 'benämning engelska',
|
||||
]
|
||||
|
||||
// Note: bare 'kod'/'code' are deliberately excluded: they collide with
|
||||
// Fortnox's "Momskod" (a VAT column). EAN is detected first so "EAN-nummer"
|
||||
// is claimed before the generic 'nummer'/'number' here.
|
||||
const ARTICLE_NUMBER_KEYWORDS = [
|
||||
'artikelnummer', 'artikelnr', 'artnr', 'art nr', 'art no', 'artikelkod',
|
||||
'article code', 'sku', 'nummer', 'number',
|
||||
]
|
||||
|
||||
const TYPE_KEYWORDS = ['typ', 'type', 'artikeltyp', 'article type', 'varutyp']
|
||||
|
||||
const UNIT_KEYWORDS = ['enhet', 'unit', 'enh', 'uom', 'måttenhet', 'mattenhet']
|
||||
|
||||
const VAT_RATE_KEYWORDS = [
|
||||
'momssats', 'momskod', 'moms %', 'moms', 'momsprocent', 'vat rate', 'vat code',
|
||||
'vat %', 'vat', 'tax rate',
|
||||
]
|
||||
|
||||
const REVENUE_ACCOUNT_KEYWORDS = [
|
||||
'försäljningskonto', 'forsaljningskonto', 'intäktskonto', 'intaktskonto',
|
||||
'bokföringskonto', 'bokforingskonto', 'sales account', 'revenue account',
|
||||
'kontering', 'coding', 'konto', 'account',
|
||||
]
|
||||
|
||||
const COST_PRICE_KEYWORDS = [
|
||||
'inköpspris', 'inkopspris', 'självkostnad', 'sjalvkostnad', 'kostpris',
|
||||
'kostnadspris', 'purchase price', 'cost price', 'cost',
|
||||
]
|
||||
|
||||
const PRICE_KEYWORDS = [
|
||||
'försäljningspris', 'forsaljningspris', 'pris exkl moms', 'pris exkl. moms',
|
||||
'à-pris', 'a-pris', 'apris', 'styckpris', 'nettopris', 'net price',
|
||||
'unit price', 'pris', 'price', 'belopp', 'sales price',
|
||||
]
|
||||
|
||||
const EAN_KEYWORDS = ['ean', 'ean-kod', 'streckkod', 'gtin', 'barcode']
|
||||
|
||||
const HOUSEWORK_KEYWORDS = [
|
||||
'rot/rut', 'rot rut', 'arbetstyp', 'husarbete', 'housework', 'rot', 'rut',
|
||||
]
|
||||
|
||||
const NOTES_KEYWORDS = [
|
||||
'anteckning', 'anteckningar', 'kommentar', 'kommentarer', 'comment', 'notes',
|
||||
'note', 'övrigt', 'ovrigt',
|
||||
]
|
||||
|
||||
// Matches our own register export header ("Valuta", #1166) plus common
|
||||
// English variants. Deliberately NO bare 'kod'/'code': collides with Momskod.
|
||||
const CURRENCY_KEYWORDS = ['valuta', 'valutakod', 'currency', 'currency code']
|
||||
|
||||
/**
|
||||
* Detect article-register columns from headers.
|
||||
*
|
||||
* Detection order matters: more specific columns are claimed first (via the
|
||||
* shared `taken` set) so a generic keyword can't swallow them: e.g. EAN before
|
||||
* the article number ("EAN-nummer" must not be read as the article number), and
|
||||
* the English name before the generic name column.
|
||||
*/
|
||||
export function detectArticleColumns(headers: string[]): DetectedArticleColumns {
|
||||
const taken = new Set<number>()
|
||||
|
||||
// Order matters (shared `taken` set): claim specific columns before generic
|
||||
// ones. EAN before the article number ("EAN-nummer"), the price columns
|
||||
// before VAT (so "Pris exkl moms" isn't read as the VAT column), and the
|
||||
// generic name column dead last.
|
||||
const name_en_col = findColumn(headers, NAME_EN_KEYWORDS, taken)
|
||||
const ean_col = findColumn(headers, EAN_KEYWORDS, taken)
|
||||
const currency_col = findColumn(headers, CURRENCY_KEYWORDS, taken)
|
||||
const article_number_col = findColumn(headers, ARTICLE_NUMBER_KEYWORDS, taken)
|
||||
const revenue_account_col = findColumn(headers, REVENUE_ACCOUNT_KEYWORDS, taken)
|
||||
const cost_price_col = findColumn(headers, COST_PRICE_KEYWORDS, taken)
|
||||
const price_col = findColumn(headers, PRICE_KEYWORDS, taken)
|
||||
const vat_rate_col = findColumn(headers, VAT_RATE_KEYWORDS, taken)
|
||||
const type_col = findColumn(headers, TYPE_KEYWORDS, taken)
|
||||
const unit_col = findColumn(headers, UNIT_KEYWORDS, taken)
|
||||
const housework_type_col = findColumn(headers, HOUSEWORK_KEYWORDS, taken)
|
||||
const notes_col = findColumn(headers, NOTES_KEYWORDS, taken)
|
||||
const name_col = findColumn(headers, NAME_KEYWORDS, taken) ?? -1
|
||||
|
||||
// Confidence: name is required; bonus from how many other columns matched.
|
||||
let confidence = 0
|
||||
if (name_col >= 0) {
|
||||
const matched = [
|
||||
article_number_col, price_col, vat_rate_col, unit_col,
|
||||
revenue_account_col, type_col,
|
||||
].filter((c) => c !== null).length
|
||||
confidence = 0.55 + Math.min(matched, 6) * 0.075
|
||||
}
|
||||
|
||||
return {
|
||||
name_col: name_col >= 0 ? name_col : 0,
|
||||
article_number_col,
|
||||
name_en_col,
|
||||
type_col,
|
||||
unit_col,
|
||||
price_col,
|
||||
currency_col,
|
||||
vat_rate_col,
|
||||
revenue_account_col,
|
||||
cost_price_col,
|
||||
ean_col,
|
||||
housework_type_col,
|
||||
notes_col,
|
||||
// Confidence is a 0-1 heuristic score (not money), only compared against the
|
||||
// 0.8 skip-mapping threshold: no öre rounding needed.
|
||||
confidence: Math.min(confidence, 1),
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user