docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,107 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { classifyCustomer, classifySupplier } from '../classify'
|
||||
|
||||
describe('classifyCustomer', () => {
|
||||
it('classifies 12-digit personnummer as individual', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: '198001011234',
|
||||
vat_number: null,
|
||||
})).toBe('individual')
|
||||
})
|
||||
|
||||
it('classifies 10-digit Swedish org as swedish_business', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: '5560217780',
|
||||
vat_number: null,
|
||||
})).toBe('swedish_business')
|
||||
})
|
||||
|
||||
it('classifies non-SE EU VAT prefix as eu_business', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: null,
|
||||
vat_number: 'DE123456789',
|
||||
})).toBe('eu_business')
|
||||
})
|
||||
|
||||
it('classifies non-EU VAT prefix as non_eu_business', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: null,
|
||||
vat_number: 'NO12345678',
|
||||
})).toBe('non_eu_business')
|
||||
})
|
||||
|
||||
it('keeps SE VAT prefix as swedish_business', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: '5560217780',
|
||||
vat_number: 'SE556021778001',
|
||||
})).toBe('swedish_business')
|
||||
})
|
||||
|
||||
it('classifies 10-digit personnummer-month-pattern as individual', () => {
|
||||
// Third digit is 0 (month 01), classic personnummer pattern
|
||||
expect(classifyCustomer({
|
||||
org_number: '8001011234',
|
||||
vat_number: null,
|
||||
})).toBe('individual')
|
||||
})
|
||||
|
||||
it('falls back to swedish_business when no signals', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
})).toBe('swedish_business')
|
||||
})
|
||||
|
||||
it('uses country code when VAT missing', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
country: 'DE',
|
||||
})).toBe('eu_business')
|
||||
})
|
||||
|
||||
it('detects Norway as non-EU', () => {
|
||||
expect(classifyCustomer({
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
country: 'Norge',
|
||||
})).toBe('non_eu_business')
|
||||
})
|
||||
})
|
||||
|
||||
describe('classifySupplier', () => {
|
||||
it('never returns individual', () => {
|
||||
expect(classifySupplier({
|
||||
org_number: '198001011234',
|
||||
vat_number: null,
|
||||
})).toBe('swedish_business')
|
||||
})
|
||||
|
||||
it('classifies non-SE EU VAT prefix as eu_business', () => {
|
||||
expect(classifySupplier({
|
||||
org_number: null,
|
||||
vat_number: 'FR12345678901',
|
||||
})).toBe('eu_business')
|
||||
})
|
||||
|
||||
it('classifies post-Brexit GB VAT as non_eu_business', () => {
|
||||
expect(classifySupplier({
|
||||
org_number: null,
|
||||
vat_number: 'GB123456789',
|
||||
})).toBe('non_eu_business')
|
||||
})
|
||||
|
||||
it('classifies XI (Northern Ireland) VAT as eu_business', () => {
|
||||
expect(classifySupplier({
|
||||
org_number: null,
|
||||
vat_number: 'XI123456789',
|
||||
})).toBe('eu_business')
|
||||
})
|
||||
|
||||
it('falls back to swedish_business by default', () => {
|
||||
expect(classifySupplier({
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
})).toBe('swedish_business')
|
||||
})
|
||||
})
|
||||
@@ -1,197 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
decodeFileContent,
|
||||
decodeStringContent,
|
||||
hasEncodingIssues,
|
||||
recoverStringWithFFFD,
|
||||
recoverWordWithFFFD,
|
||||
stripBOM,
|
||||
} from '../encoding'
|
||||
|
||||
describe('decodeStringContent', () => {
|
||||
it('recovers UTF-8-as-Latin-1 mojibake for lowercase Swedish chars', () => {
|
||||
expect(decodeStringContent('Malmö')).toBe('Malmö')
|
||||
expect(decodeStringContent('Ã¥re')).toBe('Åre'.toLowerCase())
|
||||
expect(decodeStringContent('Linköping')).toBe('Linköping')
|
||||
})
|
||||
|
||||
it('recovers UTF-8-as-Latin-1 mojibake for uppercase Swedish chars', () => {
|
||||
// The middle char is U+0096 (control), invisible in most renderings → "GÃTEBORG"
|
||||
expect(decodeStringContent('GÃ\u0096TEBORG')).toBe('GÖTEBORG')
|
||||
expect(decodeStringContent('HISINGS KÃ\u0084RRA')).toBe('HISINGS KÄRRA')
|
||||
expect(decodeStringContent('Ã\u0085NGE')).toBe('ÅNGE')
|
||||
})
|
||||
|
||||
it('is a no-op on already-correct Swedish strings', () => {
|
||||
expect(decodeStringContent('GÖTEBORG')).toBe('GÖTEBORG')
|
||||
expect(decodeStringContent('Malmö')).toBe('Malmö')
|
||||
expect(decodeStringContent('STOCKHOLM')).toBe('STOCKHOLM')
|
||||
expect(decodeStringContent('')).toBe('')
|
||||
})
|
||||
|
||||
it('is idempotent (running twice equals running once)', () => {
|
||||
const once = decodeStringContent('Malmö')
|
||||
const twice = decodeStringContent(once)
|
||||
expect(twice).toBe(once)
|
||||
expect(twice).toBe('Malmö')
|
||||
})
|
||||
|
||||
it('preserves non-Swedish strings unchanged', () => {
|
||||
expect(decodeStringContent('Café')).toBe('Café')
|
||||
expect(decodeStringContent('München')).toBe('München')
|
||||
expect(decodeStringContent('123 Main St')).toBe('123 Main St')
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasEncodingIssues', () => {
|
||||
it('detects U+FFFD replacement characters', () => {
|
||||
expect(hasEncodingIssues('Foo\uFFFDbar')).toBe(true)
|
||||
})
|
||||
|
||||
it('detects all six Swedish mojibake patterns', () => {
|
||||
expect(hasEncodingIssues('Malmö')).toBe(true) // ö
|
||||
expect(hasEncodingIssues('Ã¥re')).toBe(true) // å
|
||||
expect(hasEncodingIssues('älg')).toBe(true) // ä
|
||||
expect(hasEncodingIssues('GÃ\u0096TEBORG')).toBe(true) // Ö
|
||||
expect(hasEncodingIssues('Ã\u0085NGE')).toBe(true) // Å
|
||||
expect(hasEncodingIssues('Ã\u0084RRA')).toBe(true) // Ä
|
||||
})
|
||||
|
||||
it('returns false for clean strings', () => {
|
||||
expect(hasEncodingIssues('Stockholm')).toBe(false)
|
||||
expect(hasEncodingIssues('Malmö')).toBe(false)
|
||||
expect(hasEncodingIssues('Café')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('decodeFileContent', () => {
|
||||
function buf(bytes: number[]): ArrayBuffer {
|
||||
return new Uint8Array(bytes).buffer
|
||||
}
|
||||
|
||||
it('decodes UTF-8 bytes correctly', () => {
|
||||
const utf8 = new TextEncoder().encode('GÖTEBORG').buffer
|
||||
expect(decodeFileContent(utf8)).toBe('GÖTEBORG')
|
||||
})
|
||||
|
||||
it('falls back to Windows-1252 when UTF-8 decode is invalid', () => {
|
||||
// 0xD6 = Ö in Windows-1252; lone 0xD6 is not valid UTF-8 start byte
|
||||
const cp1252 = buf([0x47, 0xd6, 0x54, 0x45, 0x42, 0x4f, 0x52, 0x47])
|
||||
expect(decodeFileContent(cp1252)).toBe('GÖTEBORG')
|
||||
})
|
||||
|
||||
it('strips a UTF-8 BOM (EF BB BF) and decodes the remainder as UTF-8', () => {
|
||||
const payload = Array.from(new TextEncoder().encode('Bokföringsdag;Belopp'))
|
||||
const text = decodeFileContent(buf([0xef, 0xbb, 0xbf, ...payload]))
|
||||
expect(text).toBe('Bokföringsdag;Belopp')
|
||||
expect(text.charCodeAt(0)).not.toBe(0xfeff)
|
||||
})
|
||||
|
||||
it('never produces a mojibake BOM prefix when a BOM-ed file needs the Windows-1252 fallback', () => {
|
||||
// 'Datum;' + 0xD6 (Ö in Windows-1252, invalid as a lone UTF-8 byte),
|
||||
// behind a UTF-8 BOM. The BOM bytes must never re-enter the fallback
|
||||
// decode, so the result starts with 'Datum', not the literal mojibake.
|
||||
const bytes = buf([0xef, 0xbb, 0xbf, 0x44, 0x61, 0x74, 0x75, 0x6d, 0x3b, 0xd6])
|
||||
const text = decodeFileContent(bytes)
|
||||
expect(text.startsWith('')).toBe(false)
|
||||
expect(text).toBe('Datum;Ö')
|
||||
})
|
||||
|
||||
it('decodes UTF-16LE content behind a FF FE BOM', () => {
|
||||
// 'Öre' in UTF-16LE: d6 00, 72 00, 65 00
|
||||
const bytes = buf([0xff, 0xfe, 0xd6, 0x00, 0x72, 0x00, 0x65, 0x00])
|
||||
expect(decodeFileContent(bytes)).toBe('Öre')
|
||||
})
|
||||
|
||||
it('decodes UTF-16BE content behind a FE FF BOM', () => {
|
||||
const bytes = buf([0xfe, 0xff, 0x00, 0xd6, 0x00, 0x72, 0x00, 0x65])
|
||||
expect(decodeFileContent(bytes)).toBe('Öre')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stripBOM', () => {
|
||||
it('strips a leading U+FEFF', () => {
|
||||
expect(stripBOM('\uFEFF' + 'Datum;Belopp')).toBe('Datum;Belopp')
|
||||
})
|
||||
|
||||
it('strips a leading literal mojibake BOM ()', () => {
|
||||
expect(stripBOM('Datum;Belopp')).toBe('Datum;Belopp')
|
||||
})
|
||||
|
||||
it('is a no-op on clean content and never strips mid-string', () => {
|
||||
expect(stripBOM('Datum;Belopp')).toBe('Datum;Belopp')
|
||||
expect(stripBOM('Datum;Belopp')).toBe('Datum;Belopp')
|
||||
})
|
||||
})
|
||||
|
||||
// --- U+FFFD heuristic recovery ---
|
||||
|
||||
describe('recoverWordWithFFFD', () => {
|
||||
it('recovers uppercase Ö in common Swedish stems', () => {
|
||||
expect(recoverWordWithFFFD('F\uFFFDRENING')).toBe('FÖRENING')
|
||||
expect(recoverWordWithFFFD('F\uFFFDRETAG')).toBe('FÖRETAG')
|
||||
expect(recoverWordWithFFFD('G\uFFFDTEBORG')).toBe('GÖTEBORG')
|
||||
expect(recoverWordWithFFFD('LINK\uFFFDPING')).toBe('LINKÖPING')
|
||||
})
|
||||
|
||||
it('recovers lowercase ö in common Swedish stems', () => {
|
||||
expect(recoverWordWithFFFD('f\uFFFDrening')).toBe('förening')
|
||||
expect(recoverWordWithFFFD('malm\uFFFD')).toBe('malmö')
|
||||
expect(recoverWordWithFFFD('k\uFFFDp')).toBe('köp')
|
||||
})
|
||||
|
||||
it('recovers compound words via substring match', () => {
|
||||
expect(recoverWordWithFFFD('BOSTADSR\uFFFDTTSF\uFFFDRENING')).toBe(
|
||||
'BOSTADSRÄTTSFÖRENING'
|
||||
)
|
||||
expect(recoverWordWithFFFD('Idrottsf\uFFFDrening')).toBe('Idrottsförening')
|
||||
})
|
||||
|
||||
it('is a no-op when the input has no U+FFFD', () => {
|
||||
expect(recoverWordWithFFFD('FÖRENING')).toBe('FÖRENING')
|
||||
expect(recoverWordWithFFFD('hello')).toBe('hello')
|
||||
})
|
||||
|
||||
it('returns null for ambiguous words not in the dictionary', () => {
|
||||
// Random 4-letter word with U+FFFD; no Swedish stem hits.
|
||||
expect(recoverWordWithFFFD('Z\uFFFDXQ')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for words with too many U+FFFDs to disambiguate', () => {
|
||||
expect(
|
||||
recoverWordWithFFFD('\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD')
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('recoverStringWithFFFD', () => {
|
||||
it('repairs the canonical "Levbet FÖRENING" case', () => {
|
||||
expect(recoverStringWithFFFD('Levbet F\uFFFDRENING')).toBe('Levbet FÖRENING')
|
||||
})
|
||||
|
||||
it('repairs city + business-name combos', () => {
|
||||
expect(recoverStringWithFFFD('Sjöberg AB, Malm\uFFFD')).toBe('Sjöberg AB, Malmö')
|
||||
expect(recoverStringWithFFFD('Faktura fr\uFFFDn G\uFFFDTEBORG AB')).toBe(
|
||||
'Faktura från GÖTEBORG AB'
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves punctuation, whitespace, and digits', () => {
|
||||
expect(recoverStringWithFFFD('K\uFFFDp 1 234,56 SEK')).toBe('Köp 1 234,56 SEK')
|
||||
})
|
||||
|
||||
it('is a no-op on clean strings', () => {
|
||||
expect(recoverStringWithFFFD('Hello World')).toBe('Hello World')
|
||||
expect(recoverStringWithFFFD('FÖRENING')).toBe('FÖRENING')
|
||||
})
|
||||
|
||||
it('returns null when any word in the string is ambiguous', () => {
|
||||
expect(recoverStringWithFFFD('FÖRENING Z\uFFFDXQ')).toBeNull()
|
||||
})
|
||||
|
||||
it('is idempotent on recovered output', () => {
|
||||
const once = recoverStringWithFFFD('F\uFFFDRENING')
|
||||
expect(once).toBe('FÖRENING')
|
||||
expect(recoverStringWithFFFD(once!)).toBe('FÖRENING')
|
||||
})
|
||||
})
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { readWorkbookFromBuffer } from '../workbook-reader'
|
||||
|
||||
function bufFromBytes(bytes: number[]): ArrayBuffer {
|
||||
return new Uint8Array(bytes).buffer
|
||||
}
|
||||
|
||||
function rowsOf(workbook: XLSX.WorkBook): string[][] {
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]]
|
||||
return XLSX.utils.sheet_to_json(sheet, { header: 1, defval: '', raw: false }) as string[][]
|
||||
}
|
||||
|
||||
describe('readWorkbookFromBuffer', () => {
|
||||
it('decodes UTF-8 CSV with Swedish characters correctly', () => {
|
||||
const csv = new TextEncoder().encode('Namn,Ort\nAcme,GÖTEBORG\nBeta,KÄRRA\n').buffer
|
||||
const wb = readWorkbookFromBuffer(csv, 'lev.csv')
|
||||
expect(rowsOf(wb)).toEqual([
|
||||
['Namn', 'Ort'],
|
||||
['Acme', 'GÖTEBORG'],
|
||||
['Beta', 'KÄRRA'],
|
||||
])
|
||||
})
|
||||
|
||||
it('decodes UTF-8 CSV with BOM', () => {
|
||||
const bom = [0xef, 0xbb, 0xbf]
|
||||
const body = Array.from(new TextEncoder().encode('Namn,Ort\nAcme,GÖTEBORG\n'))
|
||||
const wb = readWorkbookFromBuffer(bufFromBytes([...bom, ...body]), 'lev.csv')
|
||||
expect(rowsOf(wb)).toEqual([
|
||||
['Namn', 'Ort'],
|
||||
['Acme', 'GÖTEBORG'],
|
||||
])
|
||||
})
|
||||
|
||||
it('decodes Windows-1252 CSV with Swedish characters', () => {
|
||||
// "Namn,Ort\nAcme,GÖTEBORG\nBeta,KÄRRA\n" in Windows-1252:
|
||||
// Ö = 0xD6, Ä = 0xC4
|
||||
const bytes = [
|
||||
0x4e, 0x61, 0x6d, 0x6e, 0x2c, 0x4f, 0x72, 0x74, 0x0a,
|
||||
0x41, 0x63, 0x6d, 0x65, 0x2c, 0x47, 0xd6, 0x54, 0x45, 0x42, 0x4f, 0x52, 0x47, 0x0a,
|
||||
0x42, 0x65, 0x74, 0x61, 0x2c, 0x4b, 0xc4, 0x52, 0x52, 0x41, 0x0a,
|
||||
]
|
||||
const wb = readWorkbookFromBuffer(bufFromBytes(bytes), 'lev.csv')
|
||||
expect(rowsOf(wb)).toEqual([
|
||||
['Namn', 'Ort'],
|
||||
['Acme', 'GÖTEBORG'],
|
||||
['Beta', 'KÄRRA'],
|
||||
])
|
||||
})
|
||||
|
||||
it('reads xlsx files via the binary path', () => {
|
||||
const ws = XLSX.utils.aoa_to_sheet([
|
||||
['Namn', 'Ort'],
|
||||
['Acme', 'GÖTEBORG'],
|
||||
])
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
|
||||
const buffer = XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer
|
||||
|
||||
const result = readWorkbookFromBuffer(buffer, 'data.xlsx')
|
||||
expect(rowsOf(result)).toEqual([
|
||||
['Namn', 'Ort'],
|
||||
['Acme', 'GÖTEBORG'],
|
||||
])
|
||||
})
|
||||
|
||||
it('treats non-csv extensions as binary spreadsheets', () => {
|
||||
// .xls and .ods both go through the binary path; xlsx handles encoding internally
|
||||
const ws = XLSX.utils.aoa_to_sheet([['A'], ['Ö']])
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
|
||||
const buffer = XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer
|
||||
|
||||
const result = readWorkbookFromBuffer(buffer, 'data.xls')
|
||||
expect(rowsOf(result)).toEqual([['A'], ['Ö']])
|
||||
})
|
||||
})
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { CustomerType, SupplierType } from '@/types'
|
||||
|
||||
/**
|
||||
* EU VAT number prefixes (excluding SE).
|
||||
* Source: https://taxation-ec.europa.eu/online-services/check-vat-number-vies_en
|
||||
*/
|
||||
export const EU_VAT_PREFIXES = new Set([
|
||||
'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES',
|
||||
'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV',
|
||||
'MT', 'NL', 'PL', 'PT', 'RO', 'SI', 'SK', 'XI', // XI = Northern Ireland
|
||||
])
|
||||
|
||||
/**
|
||||
* Strip whitespace, dashes, and dots from an org/personnummer for length checks.
|
||||
*/
|
||||
function digits(value: string | null): string {
|
||||
if (!value) return ''
|
||||
return value.replace(/\D/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the third digit of a Swedish org/personnummer.
|
||||
*
|
||||
* Personnummer: month digit (00-12): third digit ≤ 1.
|
||||
* Företag: third digit ≥ 2 (per Skatteverket's allocation rules).
|
||||
*/
|
||||
function looksLikePersonnummer(orgNumber: string | null): boolean {
|
||||
const d = digits(orgNumber)
|
||||
// 12 digits = full personnummer (YYYYMMDDXXXX)
|
||||
if (d.length === 12) return true
|
||||
// 10 digits: disambiguate by month (positions 3-4 are month, 01-12)
|
||||
if (d.length === 10) {
|
||||
const month = parseInt(d.substring(2, 4), 10)
|
||||
if (month >= 1 && month <= 12 && d[2] <= '1') return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function vatPrefix(vatNumber: string | null): string | null {
|
||||
if (!vatNumber) return null
|
||||
const cleaned = vatNumber.trim().toUpperCase()
|
||||
const match = cleaned.match(/^([A-Z]{2})/)
|
||||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-classify a customer based on org_number + vat_number heuristics.
|
||||
*
|
||||
* Precedence:
|
||||
* 1. Non-SE EU VAT prefix → 'eu_business'
|
||||
* 2. Non-EU letter prefix → 'non_eu_business'
|
||||
* 3. Personnummer-shaped org → 'individual'
|
||||
* 4. Default → 'swedish_business'
|
||||
*/
|
||||
export function classifyCustomer(args: {
|
||||
org_number: string | null
|
||||
vat_number: string | null
|
||||
country?: string | null
|
||||
}): CustomerType {
|
||||
const prefix = vatPrefix(args.vat_number)
|
||||
if (prefix && prefix !== 'SE') {
|
||||
if (EU_VAT_PREFIXES.has(prefix)) return 'eu_business'
|
||||
return 'non_eu_business'
|
||||
}
|
||||
|
||||
const country = args.country?.trim().toUpperCase()
|
||||
if (country && country !== 'SE' && country !== 'SVERIGE' && country !== 'SWEDEN') {
|
||||
// Country-based fallback when VAT is missing.
|
||||
if (country.length === 2 && EU_VAT_PREFIXES.has(country)) return 'eu_business'
|
||||
if (country.length >= 3) {
|
||||
// Common Swedish names for non-EU jurisdictions; heuristic is best-effort
|
||||
if (/norge|norway|usa|kanada|canada|storbritannien|uk|united kingdom/i.test(country)) {
|
||||
return 'non_eu_business'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (looksLikePersonnummer(args.org_number)) return 'individual'
|
||||
return 'swedish_business'
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-classify a supplier. Suppliers cannot be 'individual': Swedish business
|
||||
* with personnummer is still 'swedish_business' (a sole trader supplier).
|
||||
*/
|
||||
export function classifySupplier(args: {
|
||||
org_number: string | null
|
||||
vat_number: string | null
|
||||
country?: string | null
|
||||
}): SupplierType {
|
||||
const prefix = vatPrefix(args.vat_number)
|
||||
if (prefix && prefix !== 'SE') {
|
||||
if (EU_VAT_PREFIXES.has(prefix)) return 'eu_business'
|
||||
return 'non_eu_business'
|
||||
}
|
||||
|
||||
const country = args.country?.trim().toUpperCase()
|
||||
if (country && country !== 'SE' && country !== 'SVERIGE' && country !== 'SWEDEN') {
|
||||
if (country.length === 2 && EU_VAT_PREFIXES.has(country)) return 'eu_business'
|
||||
if (/norge|norway|usa|kanada|canada|storbritannien|uk|united kingdom/i.test(country)) {
|
||||
return 'non_eu_business'
|
||||
}
|
||||
}
|
||||
|
||||
return 'swedish_business'
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/**
|
||||
* Shared column-detection helpers for register imports
|
||||
* (customers, suppliers, articles).
|
||||
*/
|
||||
|
||||
export function normalize(header: string): string {
|
||||
return header.toLowerCase().trim().replace(/[_\-./]/g, ' ')
|
||||
}
|
||||
|
||||
export function matchesKeywords(header: string, keywords: string[]): boolean {
|
||||
const normalized = normalize(header)
|
||||
return keywords.some((kw) => normalized === kw || normalized.includes(kw))
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first column index whose header matches one of `keywords`,
|
||||
* skipping any indices already taken by other columns.
|
||||
*/
|
||||
export function findColumn(
|
||||
headers: string[],
|
||||
keywords: string[],
|
||||
taken: Set<number>,
|
||||
): number | null {
|
||||
for (let i = 0; i < headers.length; i++) {
|
||||
if (taken.has(i)) continue
|
||||
if (matchesKeywords(headers[i], keywords)) {
|
||||
taken.add(i)
|
||||
return i
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Trim a string-or-blank cell, returning null when empty. */
|
||||
export function cellOrNull(value: unknown): string | null {
|
||||
if (value === null || value === undefined) return null
|
||||
const str = String(value).trim()
|
||||
return str === '' ? null : str
|
||||
}
|
||||
|
||||
/** Parse an integer payment term ("30 dagar" → 30) with a default fallback. */
|
||||
export function parsePaymentTerms(value: unknown, fallback: number): number {
|
||||
const str = cellOrNull(value)
|
||||
if (!str) return fallback
|
||||
const match = str.match(/-?\d+/)
|
||||
if (!match) return fallback
|
||||
const n = parseInt(match[0], 10)
|
||||
if (isNaN(n) || n < 0 || n > 365) return fallback
|
||||
return n
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an org/personal number to its dedup key (digits only).
|
||||
* Returns null for empty input or strings that contain no digits.
|
||||
*/
|
||||
export function normalizeOrgNumber(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.replace(/\D/g, '') || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize an email to its dedup key (trimmed + lowercased).
|
||||
* Returns null for empty/whitespace-only input.
|
||||
*/
|
||||
export function normalizeEmail(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Lowercased dedup key for matching a row by name (articles, and any other
|
||||
* importer that dedupes on a free-text name). Same rule as normalizeEmail.
|
||||
*/
|
||||
export function normalizeNameKey(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
/**
|
||||
* Encoding detection and conversion for Swedish import files.
|
||||
*
|
||||
* Used by bank file, supplier, customer, and opening-balance parsers.
|
||||
* Swedish data exports use either UTF-8 or Windows-1252 (ISO-8859-1).
|
||||
* We detect encoding by checking for valid Swedish characters.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Decode file content, handling BOMs plus UTF-8 and Windows-1252 encodings.
|
||||
*
|
||||
* Strategy: inspect the leading BYTES first.
|
||||
* - FF FE / FE FF: UTF-16LE/BE (e.g. Excel "Unicode text" re-saves). Decode
|
||||
* as such; TextDecoder consumes the BOM itself.
|
||||
* - EF BB BF (UTF-8 BOM): strip the three bytes and decode the REMAINDER.
|
||||
* If the remainder still contains U+FFFD (invalid UTF-8 somewhere in the
|
||||
* file), decode the remainder as Windows-1252. The BOM bytes are never
|
||||
* re-included, so the fallback can no longer produce a literal mojibake
|
||||
* "" prefix that breaks exact-match header detection.
|
||||
* - No BOM: try UTF-8; fall back to Windows-1252 on replacement characters
|
||||
* or garbled Swedish chars (unchanged behavior).
|
||||
*/
|
||||
export function decodeFileContent(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer)
|
||||
|
||||
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
|
||||
return new TextDecoder('utf-16le', { fatal: false }).decode(buffer)
|
||||
}
|
||||
if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
|
||||
return new TextDecoder('utf-16be', { fatal: false }).decode(buffer)
|
||||
}
|
||||
|
||||
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
||||
const rest = bytes.subarray(3)
|
||||
const utf8Rest = new TextDecoder('utf-8', { fatal: false }).decode(rest)
|
||||
if (!utf8Rest.includes('�')) {
|
||||
return utf8Rest
|
||||
}
|
||||
return new TextDecoder('windows-1252', { fatal: false }).decode(rest)
|
||||
}
|
||||
|
||||
const utf8Decoder = new TextDecoder('utf-8', { fatal: false })
|
||||
const utf8Result = utf8Decoder.decode(buffer)
|
||||
|
||||
if (!hasEncodingIssues(utf8Result)) {
|
||||
return utf8Result
|
||||
}
|
||||
|
||||
const latin1Decoder = new TextDecoder('windows-1252', { fatal: false })
|
||||
return latin1Decoder.decode(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-decode a string that suffered the canonical "UTF-8 bytes read as Latin-1"
|
||||
* mojibake (e.g. "Malmö" → "Malmö", "GÖTEBORG" → "GÖTEBORG").
|
||||
*
|
||||
* Mechanism: each char in the input is a codepoint that was originally a UTF-8
|
||||
* byte misinterpreted as a Latin-1/Windows-1252 character. We pack those chars
|
||||
* back into a byte sequence and decode the bytes as UTF-8 to recover the
|
||||
* original text.
|
||||
*
|
||||
* No-op when the string is already clean (no garbled patterns).
|
||||
*/
|
||||
export function decodeStringContent(content: string): string {
|
||||
if (!hasEncodingIssues(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
try {
|
||||
const bytes = new Uint8Array(content.length)
|
||||
for (let i = 0; i < content.length; i++) {
|
||||
bytes[i] = content.charCodeAt(i) & 0xff
|
||||
}
|
||||
const decoder = new TextDecoder('utf-8', { fatal: false })
|
||||
return decoder.decode(bytes)
|
||||
} catch {
|
||||
return content
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a string has encoding issues (garbled Swedish characters).
|
||||
*/
|
||||
export function hasEncodingIssues(text: string): boolean {
|
||||
if (text.includes('\uFFFD')) return true
|
||||
|
||||
// Common garbled patterns when Windows-1252 is read as UTF-8:
|
||||
// Ã¥ = å, ä = ä, ö = ö, Ã… = Å, Ä = Ä, Ö = Ö
|
||||
const garbledPatterns = ['Ã¥', 'ä', 'ö', 'Ã\u0085', 'Ã\u0084', 'Ã\u0096']
|
||||
return garbledPatterns.some((pattern) => text.includes(pattern))
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize line endings to \n
|
||||
*/
|
||||
export function normalizeLineEndings(content: string): string {
|
||||
return content.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip BOM (Byte Order Mark) from start of content.
|
||||
*
|
||||
* Also strips the literal mojibake form "" (U+00EF U+00BB U+00BF): a
|
||||
* UTF-8 BOM whose bytes were decoded as Windows-1252/Latin-1 upstream.
|
||||
* Covers string-entry paths that were pre-decoded outside decodeFileContent.
|
||||
*/
|
||||
export function stripBOM(content: string): string {
|
||||
if (content.charCodeAt(0) === 0xfeff) {
|
||||
return content.slice(1)
|
||||
}
|
||||
if (content.startsWith('')) {
|
||||
return content.slice(3)
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare file content for parsing: strip BOM, normalize line endings, handle encoding
|
||||
*/
|
||||
export function prepareContent(content: string): string {
|
||||
return normalizeLineEndings(stripBOM(decodeStringContent(content)))
|
||||
}
|
||||
|
||||
/**
|
||||
* --- U+FFFD heuristic recovery ---
|
||||
*
|
||||
* When Windows-1252 / Latin-1 bytes are decoded as UTF-8 with `fatal: false`,
|
||||
* invalid sequences silently become U+FFFD. The original byte is lost, but
|
||||
* for Swedish text we can guess from context: the missing letter is almost
|
||||
* always one of Å/Ä/Ö (uppercase context) or å/ä/ö (lowercase context).
|
||||
*
|
||||
* This recovery tries each Swedish vowel substitution and scores the resulting
|
||||
* word against a small dictionary of Swedish stems. If exactly one candidate
|
||||
* scores above the threshold, it's applied. Ambiguous cases return null and
|
||||
* must be reviewed manually.
|
||||
*/
|
||||
|
||||
const REPLACEMENT = '\uFFFD'
|
||||
const SWEDISH_VOWELS_UPPER = ['Å', 'Ä', 'Ö'] as const
|
||||
const SWEDISH_VOWELS_LOWER = ['å', 'ä', 'ö'] as const
|
||||
|
||||
/**
|
||||
* Stems of common Swedish words containing åäö that appear in business names,
|
||||
* place names, addresses, and accounting descriptions.
|
||||
*/
|
||||
const SWEDISH_STEMS = new Set<string>([
|
||||
// -för- prefix (extremely common)
|
||||
'för', 'före', 'förening', 'företag', 'försäkring', 'försäljning',
|
||||
'försäljnings', 'förskola', 'församling', 'förvaltning', 'förbund',
|
||||
'förlag', 'föräldra', 'försök', 'förbrukning', 'förbättring', 'förskott',
|
||||
'försening', 'förhandling', 'förbättrings',
|
||||
// för-* derivatives that often appear in account names
|
||||
'förmån', 'förmåner', 'förmedlad', 'förmedlade', 'förmedling', 'förmedlings',
|
||||
'förvaltar', 'förmedla',
|
||||
// -mark- / marknadsföring
|
||||
'marknadsföring', 'marknadsförings', 'marknad',
|
||||
// common Swedish words/prefixes
|
||||
'bostadsrätt', 'rätt', 'samfällighet', 'idrott', 'fastighet', 'utbildning',
|
||||
'näring', 'växel', 'värme', 'köp', 'köpa', 'inköp', 'sälja', 'säljs',
|
||||
'tjänst', 'tjänster',
|
||||
// accounting terms
|
||||
'kostnad', 'kostnader', 'intäkt', 'intäkter', 'avskrivning', 'avsättning',
|
||||
'lön', 'löner', 'lönekostnad', 'pension', 'utgående', 'ingående',
|
||||
'momspliktig', 'redovisning', 'företagskonto', 'bankkonto',
|
||||
'överavskrivning', 'överskott', 'underskott', 'överföring', 'överlåtelse',
|
||||
'återbetalning', 'utlägg', 'utgift', 'avdrag',
|
||||
// omvänd moms etc.
|
||||
'omvänd', 'omvänt', 'omvända',
|
||||
// 3+ letter prepositions/adverbs (skip 2-letter ones: too ambiguous)
|
||||
'från', 'över', 'när', 'där', 'även', 'någon', 'något', 'många',
|
||||
'själv', 'små', 'väg', 'gång', 'räkning', 'räntor', 'är',
|
||||
// 'på': short but extremely common; include explicitly
|
||||
'på',
|
||||
// cities
|
||||
'göteborg', 'malmö', 'örebro', 'östersund', 'jönköping', 'linköping',
|
||||
'norrköping', 'lidköping', 'köping', 'helsingborg', 'umeå', 'skellefteå',
|
||||
'piteå', 'luleå', 'borås', 'växjö', 'östhammar', 'södertälje', 'västerås',
|
||||
'härnösand', 'värnamo', 'mölndal', 'mörrum', 'mönsterås', 'färjestaden',
|
||||
'eskilstuna',
|
||||
// directions / geo
|
||||
'östra', 'västra', 'södra', 'norra', 'öster', 'väster', 'söder',
|
||||
// legal forms
|
||||
'aktiebolag', 'handelsbolag', 'ekonomisk', 'allmännyttig',
|
||||
// misc
|
||||
'företagsledare', 'koncernbidrag', 'utländsk', 'utländska', 'främmande',
|
||||
'vägen', 'gatan', 'allén', 'gränden', 'torget',
|
||||
// surnames containing åäö
|
||||
'lindström', 'sjöberg', 'söderberg', 'öberg', 'åström', 'åkerlund',
|
||||
'östlund', 'lindgren', 'sjögren', 'hägglund', 'bäckström',
|
||||
])
|
||||
|
||||
/**
|
||||
* Score a candidate word by *length-weighted* stem matching.
|
||||
*
|
||||
* - Exact word match: 1_000_000 (still beats any substring sum).
|
||||
* - Otherwise: sum the lengths of every stem that is a substring of the
|
||||
* candidate. Length-weighting is the critical fix vs. simple counting:
|
||||
* "fårmedlad" hits "år" (2 chars), "förmedlad" hits "för" (3 chars).
|
||||
* Counting would tie them at 1; length-weighting gives 2 vs 3, so the
|
||||
* correct candidate wins.
|
||||
*/
|
||||
function scoreCandidate(word: string): number {
|
||||
const lower = word.toLowerCase()
|
||||
if (SWEDISH_STEMS.has(lower)) return 1_000_000
|
||||
let score = 0
|
||||
for (const stem of SWEDISH_STEMS) {
|
||||
if (lower.includes(stem)) score += stem.length
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
function chooseCase(word: string): 'upper' | 'lower' {
|
||||
let upper = 0
|
||||
let lower = 0
|
||||
for (const ch of word) {
|
||||
if (ch === REPLACEMENT) continue
|
||||
if (ch >= 'A' && ch <= 'Z') upper++
|
||||
else if (ch >= 'a' && ch <= 'z') lower++
|
||||
}
|
||||
return upper > lower ? 'upper' : 'lower'
|
||||
}
|
||||
|
||||
/**
|
||||
* Try every Swedish-vowel substitution for the U+FFFDs in `word`, then return
|
||||
* the highest-scoring candidate. Returns null if no candidate matches a
|
||||
* dictionary stem (i.e. ambiguous: operator must review).
|
||||
*/
|
||||
export function recoverWordWithFFFD(word: string): string | null {
|
||||
if (!word.includes(REPLACEMENT)) return word
|
||||
|
||||
const vowels = chooseCase(word) === 'upper' ? SWEDISH_VOWELS_UPPER : SWEDISH_VOWELS_LOWER
|
||||
const positions: number[] = []
|
||||
for (let i = 0; i < word.length; i++) {
|
||||
if (word[i] === REPLACEMENT) positions.push(i)
|
||||
}
|
||||
|
||||
// Words with more than ~6 lost bytes blow up the combinatorial space: // bail out rather than spend cycles on something that's likely garbage anyway.
|
||||
const totalCombos = Math.pow(vowels.length, positions.length)
|
||||
if (totalCombos > 729) return null
|
||||
|
||||
let best: { word: string; score: number } | null = null
|
||||
for (let combo = 0; combo < totalCombos; combo++) {
|
||||
const chars = word.split('')
|
||||
let c = combo
|
||||
for (const pos of positions) {
|
||||
chars[pos] = vowels[c % vowels.length]
|
||||
c = Math.floor(c / vowels.length)
|
||||
}
|
||||
const candidate = chars.join('')
|
||||
const score = scoreCandidate(candidate)
|
||||
if (!best || score > best.score) {
|
||||
best = { word: candidate, score }
|
||||
}
|
||||
}
|
||||
|
||||
if (!best || best.score === 0) return null
|
||||
return best.word
|
||||
}
|
||||
|
||||
/**
|
||||
* Repair every U+FFFD-containing word in `text` via dictionary-backed
|
||||
* substitution. Returns the repaired string when *every* corrupted word
|
||||
* resolved to a confident candidate; returns null if any word remains
|
||||
* ambiguous (operator must review the whole string by hand).
|
||||
*
|
||||
* Idempotent on clean input.
|
||||
*/
|
||||
export function recoverStringWithFFFD(text: string): string | null {
|
||||
if (!text.includes(REPLACEMENT)) return text
|
||||
|
||||
// Split on runs of non-letter/non-digit characters so punctuation,
|
||||
// whitespace, and structural characters are preserved as-is.
|
||||
const tokens = text.split(/([^\p{L}\p{N}\uFFFD]+)/u)
|
||||
const out: string[] = []
|
||||
for (const token of tokens) {
|
||||
if (!token.includes(REPLACEMENT)) {
|
||||
out.push(token)
|
||||
continue
|
||||
}
|
||||
const recovered = recoverWordWithFFFD(token)
|
||||
if (recovered === null) return null
|
||||
out.push(recovered)
|
||||
}
|
||||
return out.join('')
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import * as XLSX from 'xlsx'
|
||||
import { decodeFileContent } from './encoding'
|
||||
|
||||
/**
|
||||
* Read a workbook from a raw file buffer, with correct encoding handling
|
||||
* for CSV files.
|
||||
*
|
||||
* For binary spreadsheet formats (.xlsx, .xls, .ods), xlsx handles encoding
|
||||
* via the embedded codepage and we pass the buffer through as `type: 'array'`.
|
||||
*
|
||||
* For CSV files, xlsx with `type: 'array'` decodes bytes as Latin-1, which
|
||||
* mangles UTF-8 multi-byte sequences (e.g. Ö → Ö). We instead detect the
|
||||
* source encoding (UTF-8 with optional BOM, or Windows-1252) and decode to
|
||||
* a string before handing it to xlsx as `type: 'string'`.
|
||||
*/
|
||||
export function readWorkbookFromBuffer(buffer: ArrayBuffer, filename: string): XLSX.WorkBook {
|
||||
const ext = filename.toLowerCase().split('.').pop() ?? ''
|
||||
if (ext === 'csv') {
|
||||
const content = decodeFileContent(buffer)
|
||||
return XLSX.read(content, { type: 'string' })
|
||||
}
|
||||
return XLSX.read(buffer, { type: 'array' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the workbook from `buffer` and return raw rows from its largest sheet.
|
||||
*
|
||||
* Picks the sheet with the most rows (a heuristic that handles files where
|
||||
* the header sheet isn't the first one). Returns rows as a 2D string array
|
||||
* with the header row included; cells default to empty string.
|
||||
*/
|
||||
export function readBestSheet(
|
||||
buffer: ArrayBuffer,
|
||||
filename: string,
|
||||
): { sheetName: string; rawData: string[][] } {
|
||||
const workbook = readWorkbookFromBuffer(buffer, filename)
|
||||
|
||||
let bestSheet = workbook.SheetNames[0]
|
||||
let bestRowCount = 0
|
||||
for (const name of workbook.SheetNames) {
|
||||
const sheet = workbook.Sheets[name]
|
||||
const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1')
|
||||
const rowCount = range.e.r - range.s.r + 1
|
||||
if (rowCount > bestRowCount) {
|
||||
bestRowCount = rowCount
|
||||
bestSheet = name
|
||||
}
|
||||
}
|
||||
|
||||
const sheet = workbook.Sheets[bestSheet]
|
||||
const rawData: string[][] = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: '',
|
||||
raw: false,
|
||||
})
|
||||
|
||||
return { sheetName: bestSheet, rawData }
|
||||
}
|
||||
Reference in New Issue
Block a user