fix: Swedish VAT compliance — representation, domestic RC, full 26xx mapping, SIE (#206)

* feat: add INK2 declaration improvements, invoice delivery date, and Swedish compliance skills

Expand INK2 engine with full INK2S/INK2R support and improved SRU generation.
Add delivery_date field to invoices and corresponding PDF/migration support.
Add Claude skills for Swedish asset accounting, invoice compliance, SIE import/export, SRU filing, and tax planning.

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

* fix: address PR review — map BAS 4500–4899, strip CRLF in SRU, document P3

- Map BAS accounts 4500–4599 (legoarbeten), 4700–4899 (diverse
  varuinköpskostnader) to SRU 7512 so they are not silently dropped
  from INK2R declarations
- Strip \r\n in sanitizeString to prevent CRLF injection in SRU fields
- Document P3 period suffix limitation for brutet räkenskapsår

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

* fix: correct BAS 4500-4599, 4700-4899 mapping from 7512 to 7511

Per the official BAS-to-SRU mapping, these account ranges are cost of
goods (legoarbeten, inkurans, svinn) and belong under 7511 (Råvaror
och förnödenheter), not 7512 (Handelsvaror). 7512 remains 4600-4699.

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

* fix: Swedish VAT compliance — representation VAT, domestic RC, full BAS 26xx mapping, SIE encoding

- Representation expenses now default to reduced_12 VAT (ML 13 kap 24-25 §§);
  income tax deduction was abolished 2017 but VAT deduction at 12% remains
- Domestic reverse charge (byggtjänster etc.) uses 2647 instead of 2645,
  with distinct line descriptions for Swedish vs EU/non-EU RC
- VAT declaration maps all BAS 26xx variant accounts (egna uttag 2612/2622/2632,
  uthyrning 2613/2623/2633, VMB 2616/2626/2636, import 2615/2625/2635,
  domestic RC 2647, frivillig skattskyldighet 2642) and revenue variants
  (3108/3105/3004/3100) to correct momsdeklaration rutor
- SIE parser: remove unreliable #FORMAT PC8 encoding detection (most software
  exports UTF-8 with PC8 header), parse #FLAGGA for import-already-done warning,
  default SIE type to 1 when absent, fix RTRANS/BTRANS documentation
- SIE export: add #RAR -1 (previous fiscal year), fix UB = IB + movements
- Error messages: add pattern matching for locked period trigger errors

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

* fix: address Greptile review — update ruta49 JSDoc, use null sentinel in error map

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-04-09 14:13:15 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 7a18d89c70
commit 6ccd4f429c
15 changed files with 445 additions and 128 deletions
@@ -182,7 +182,6 @@ describe('getDefaultVatTreatmentForCategory', () => {
expect(getDefaultVatTreatmentForCategory('expense_bank_fees')).toBeNull()
expect(getDefaultVatTreatmentForCategory('expense_card_fees')).toBeNull()
expect(getDefaultVatTreatmentForCategory('expense_currency_exchange')).toBeNull()
expect(getDefaultVatTreatmentForCategory('expense_representation')).toBeNull()
})
it('returns null for private transactions', () => {
@@ -194,21 +193,22 @@ describe('getDefaultVatTreatmentForCategory', () => {
})
})
describe('representation VAT (ML 8:9 — illegal since 2017)', () => {
it('getDefaultVatTreatmentForCategory returns null for representation', () => {
expect(getDefaultVatTreatmentForCategory('expense_representation')).toBeNull()
describe('representation VAT (reduced 12%, ML 13 kap 24-25 §§)', () => {
it('getDefaultVatTreatmentForCategory returns reduced_12 for representation', () => {
expect(getDefaultVatTreatmentForCategory('expense_representation')).toBe('reduced_12')
})
it('getCategoryAccountMapping has vatTreatment: null for representation', () => {
it('getCategoryAccountMapping has vatTreatment: reduced_12 for representation', () => {
const result = getCategoryAccountMapping('expense_representation', -500, true)
expect(result.vatTreatment).toBeNull()
expect(result.vatDebitAccount).toBeNull()
expect(result.vatTreatment).toBe('reduced_12')
expect(result.vatDebitAccount).toBe('2641')
})
it('buildMappingResultFromCategory generates no VAT lines for representation', () => {
it('buildMappingResultFromCategory generates 12% VAT line for representation', () => {
const tx = makeTransaction({ amount: -500 })
const result = buildMappingResultFromCategory('expense_representation', tx, true)
expect(result.vat_lines).toHaveLength(0)
expect(result.vat_lines).toHaveLength(1)
expect(result.vat_lines[0].account_number).toBe('2641')
})
})
@@ -39,17 +39,19 @@ vi.mock('../currency-utils', () => ({
// Mock vat-entries with real reverse charge logic
vi.mock('../vat-entries', () => ({
generateReverseChargeLines: vi.fn().mockImplementation(
(baseAmount: number, vatRate: number = 0.25) => {
(baseAmount: number, vatRate: number = 0.25, isDomestic: boolean = false) => {
const vatAmount = Math.round(baseAmount * vatRate * 100) / 100
const inputAccount = isDomestic ? '2647' : '2645'
let outputAccount: string
switch (vatRate) {
case 0.12: outputAccount = '2624'; break
case 0.06: outputAccount = '2634'; break
default: outputAccount = '2614'; break
}
const context = isDomestic ? 'omvänd skattskyldighet i Sverige' : 'omvänd skattskyldighet'
return [
{ account_number: '2645', debit_amount: vatAmount, credit_amount: 0, line_description: `Fiktiv ingående moms ${vatRate * 100}% (omvänd skattskyldighet)` },
{ account_number: outputAccount, debit_amount: 0, credit_amount: vatAmount, line_description: `Fiktiv utgående moms ${vatRate * 100}% (omvänd skattskyldighet)` },
{ account_number: inputAccount, debit_amount: vatAmount, credit_amount: 0, line_description: `Fiktiv ingående moms ${vatRate * 100}% (${context})` },
{ account_number: outputAccount, debit_amount: 0, credit_amount: vatAmount, line_description: `Fiktiv utgående moms ${vatRate * 100}% (${context})` },
]
}
),
@@ -420,6 +422,66 @@ describe('createSupplierInvoiceRegistrationEntry', () => {
assertBalanced(input)
})
it('creates domestic reverse charge entry using 2647 (byggtjänster etc.)', async () => {
const invoice = makeSupplierInvoice({
subtotal: 20000,
vat_amount: 0,
total: 20000,
reverse_charge: true,
})
const items = [makeItem({ line_total: 20000, vat_rate: 0.25, account_number: '4425' })]
await createSupplierInvoiceRegistrationEntry(
null as never, 'company-1', 'user-1', invoice, items, 'swedish_business'
)
const input = mockedCreateEntry.mock.calls[0][3]
// Domestic RC uses 2647 (not 2645) for input VAT
const debit2647 = findByAccount(input.lines, '2647')
expect(debit2647).toHaveLength(1)
expect(debit2647[0].debit_amount).toBe(5000) // 20000 * 0.25
const credit2614 = findByAccount(input.lines, '2614')
expect(credit2614).toHaveLength(1)
expect(credit2614[0].credit_amount).toBe(5000)
// No EU reverse charge account used
expect(findByAccount(input.lines, '2645')).toHaveLength(0)
// No regular input VAT
expect(findByAccount(input.lines, '2641')).toHaveLength(0)
// 2440 = expense only (RC is offsetting)
const credit2440 = findByAccount(input.lines, '2440')
expect(credit2440[0].credit_amount).toBe(20000)
assertBalanced(input)
})
it('does NOT create RC entry for swedish_business when reverse_charge is false', async () => {
const invoice = makeSupplierInvoice({
subtotal: 8000,
vat_amount: 2000,
total: 10000,
reverse_charge: false,
})
const items = [makeItem({ line_total: 8000, vat_rate: 0.25, account_number: '4010' })]
await createSupplierInvoiceRegistrationEntry(
null as never, 'company-1', 'user-1', invoice, items, 'swedish_business'
)
const input = mockedCreateEntry.mock.calls[0][3]
// Should use standard domestic path with 2641
expect(findByAccount(input.lines, '2641')).toHaveLength(1)
expect(findByAccount(input.lines, '2647')).toHaveLength(0)
expect(findByAccount(input.lines, '2645')).toHaveLength(0)
expect(findByAccount(input.lines, '2614')).toHaveLength(0)
assertBalanced(input)
})
it('creates per-rate 2645/26x4 pairs for mixed-rate reverse charge', async () => {
const invoice = makeSupplierInvoice({
subtotal: 15000,
+12 -7
View File
@@ -132,13 +132,13 @@ export function getCategoryAccountMapping(
if (category.startsWith('expense_')) {
const expenseAccount = getExpenseAccount(category, entityType)
// Bank fees, card fees, currency exchange, and representation are VAT-exempt in Sweden
// Representation has zero input VAT deduction since 2017-01-01 (ML 8:9)
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange', 'expense_representation']
// Bank fees, card fees, and currency exchange are VAT-exempt in Sweden
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange']
const isVatExempt = vatExemptCategories.includes(category)
// Use provided vatTreatment, or default based on category
const resolvedVat = vatTreatment ?? (isVatExempt ? null : 'standard_25')
// Representation defaults to reduced_12 (ML 13 kap 24-25 §§, max 300 SEK/person).
// Note: income tax deduction was abolished 2017 (IL 16 kap 2 §), but VAT deduction remains.
const resolvedVat = vatTreatment ?? (isVatExempt ? null : category === 'expense_representation' ? 'reduced_12' : 'standard_25')
return {
debitAccount: expenseAccount,
@@ -345,11 +345,16 @@ export function getDefaultVatTreatmentForCategory(
return null
}
// Representation has zero input VAT deduction since 2017-01-01 (ML 8:9)
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange', 'expense_representation']
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange']
if (vatExemptCategories.includes(category)) {
return null
}
// Representation defaults to reduced_12 (ML 13 kap 24-25 §§, max 300 SEK/person).
// Note: income tax deduction was abolished 2017 (IL 16 kap 2 §), but VAT deduction remains.
if (category === 'expense_representation') {
return 'reduced_12'
}
return 'standard_25'
}
+17 -10
View File
@@ -82,19 +82,21 @@ export async function createSupplierInvoiceRegistrationEntry(
}
lines.push(...debitLines)
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && invoice.reverse_charge
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business' || supplierType === 'swedish_business') && invoice.reverse_charge
const isDomesticRC = supplierType === 'swedish_business' && invoice.reverse_charge
if (isReverseCharge) {
// EU/non-EU reverse charge: fiktiv moms entries per rate group
// Reverse charge: fiktiv moms entries per rate group
// Domestic (byggtjänster etc.): 2647/26x4, EU/non-EU: 2645/26x4
const vatByRate = groupVatByRate(items, invoice.currency, invoice.exchange_rate)
for (const [rate, amount] of vatByRate) {
if (rate > 0 && amount > 0) {
const rcLines = generateReverseChargeLines(amount / rate, rate)
const rcLines = generateReverseChargeLines(amount / rate, rate, isDomesticRC)
lines.push(...rcLines)
}
}
} else if (invoice.vat_amount > 0) {
// Domestic: Debit ingående moms per rate group
// Domestic standard: Debit ingående moms per rate group
const vatByRate = groupVatByRate(items, invoice.currency, invoice.exchange_rate)
for (const [rate, amount] of vatByRate) {
if (amount > 0) {
@@ -275,19 +277,21 @@ export async function createSupplierInvoiceCashEntry(
})
}
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && invoice.reverse_charge
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business' || supplierType === 'swedish_business') && invoice.reverse_charge
const isDomesticRC = supplierType === 'swedish_business' && invoice.reverse_charge
if (isReverseCharge) {
// EU/non-EU reverse charge: fiktiv moms entries per rate group
// Reverse charge: fiktiv moms entries per rate group
// Domestic (byggtjänster etc.): 2647/26x4, EU/non-EU: 2645/26x4
const vatByRate = groupVatByRate(items, invoice.currency, invoice.exchange_rate)
for (const [rate, amount] of vatByRate) {
if (rate > 0 && amount > 0) {
const rcLines = generateReverseChargeLines(amount / rate, rate)
const rcLines = generateReverseChargeLines(amount / rate, rate, isDomesticRC)
lines.push(...rcLines)
}
}
} else if (invoice.vat_amount > 0) {
// Domestic: Debit ingående moms per rate group
// Domestic standard: Debit ingående moms per rate group
const vatByRate = groupVatByRate(items, invoice.currency, invoice.exchange_rate)
for (const [rate, amount] of vatByRate) {
if (amount > 0) {
@@ -367,10 +371,13 @@ export async function createSupplierCreditNoteEntry(
})
}
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && creditNote.reverse_charge
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business' || supplierType === 'swedish_business') && creditNote.reverse_charge
const isDomesticRC = supplierType === 'swedish_business' && creditNote.reverse_charge
if (isReverseCharge) {
// Reverse the fiktiv moms per rate group (swap debit/credit from registration)
// Input VAT account: 2647 for domestic RC, 2645 for EU/non-EU
const inputAccount = isDomesticRC ? '2647' : '2645'
const vatByRate = groupVatByRate(items, creditNote.currency, creditNote.exchange_rate, true)
for (const [rate, amount] of vatByRate) {
if (rate > 0 && amount > 0) {
@@ -382,7 +389,7 @@ export async function createSupplierCreditNoteEntry(
default: outputAccount = '2614'; break
}
creditLines.push({
account_number: '2645',
account_number: inputAccount,
debit_amount: 0,
credit_amount: amount,
line_description: `Omvänd fiktiv ingående moms ${Math.round(rate * 100)}% ${desc}`,
+13 -7
View File
@@ -79,16 +79,18 @@ export function generateSalesVatLines(config: VatEntryConfig): CreateJournalEntr
}
/**
* Generate EU reverse charge lines (fiktiv moms)
* For purchases from EU: Debit 2645 + Credit 2614 (offsetting entries)
* Generate reverse charge lines (fiktiv moms)
* For EU/non-EU purchases: Debit 2645 + Credit 26x4 (offsetting entries)
* For domestic reverse charge: Debit 2647 + Credit 26x4 (offsetting entries)
*/
export function generateReverseChargeLines(
baseAmount: number,
vatRate: number = 0.25
vatRate: number = 0.25,
isDomestic: boolean = false
): CreateJournalEntryLineInput[] {
const vatAmount = Math.round(baseAmount * vatRate * 100) / 100
// Determine accounts based on rate
// Determine output account based on rate
let outputAccount: string
switch (vatRate) {
case 0.25:
@@ -104,18 +106,22 @@ export function generateReverseChargeLines(
outputAccount = '2614'
}
// Input VAT account: 2647 for domestic RC (ML 16 kap), 2645 for EU/non-EU
const inputAccount = isDomestic ? '2647' : '2645'
const context = isDomestic ? 'omvänd skattskyldighet i Sverige' : 'omvänd skattskyldighet'
return [
{
account_number: '2645', // Beräknad ingående moms förvärv utlandet
account_number: inputAccount,
debit_amount: vatAmount,
credit_amount: 0,
line_description: `Fiktiv ingående moms ${vatRate * 100}% (omvänd skattskyldighet)`,
line_description: `Fiktiv ingående moms ${vatRate * 100}% (${context})`,
},
{
account_number: outputAccount,
debit_amount: 0,
credit_amount: vatAmount,
line_description: `Fiktiv utgående moms ${vatRate * 100}% (omvänd skattskyldighet)`,
line_description: `Fiktiv utgående moms ${vatRate * 100}% (${context})`,
},
]
}
+43
View File
@@ -66,6 +66,38 @@ const CONTEXT_FALLBACKS: Record<ErrorContext, string> = {
const GENERIC_FALLBACK = 'Något gick fel. Försök igen.'
// Known error patterns → user-friendly Swedish messages
const ERROR_PATTERN_MAP: [RegExp, string | null][] = [
[
/locked\/closed fiscal period/i,
'Perioden är låst. Verifikationen kan inte skapas i en stängd eller låst period.',
],
[
/Bokföringen är låst t\.o\.m\./,
null, // null = extract the Swedish message directly from the raw error text
],
[
/Cannot attach documents to entries in a locked/i,
'Kan inte bifoga dokument till verifikationer i en låst period.',
],
]
/**
* Check if a message matches a known error pattern and return the Swedish translation.
* Returns null if no pattern matches.
*/
function tryMatchKnownError(message: string): string | null {
for (const [pattern, translation] of ERROR_PATTERN_MAP) {
if (pattern.test(message)) {
if (translation !== null) return translation
// Extract the Swedish part from the message
const match = message.match(/Bokföringen är låst t\.o\.m\. [^.]+\./)
return match ? match[0] : 'Bokföringen är låst för denna period.'
}
}
return null
}
/**
* Simple heuristic to detect already-translated Swedish messages.
* If the message contains common Swedish words/patterns, pass it through.
@@ -83,6 +115,7 @@ function isSwedishUserMessage(message: string): boolean {
/session/i,
/förfrågan/i,
/obligatorisk/i,
/bokföringen är låst/i,
]
return swedishPatterns.some((p) => p.test(message))
}
@@ -155,6 +188,14 @@ export function getErrorMessage(
return POSTGRES_ERROR_MAP[obj.code]
}
// Try known error patterns (e.g. locked period triggers)
for (const field of ['error', 'message'] as const) {
if (typeof obj[field] === 'string' && obj[field].trim()) {
const knownError = tryMatchKnownError(obj[field])
if (knownError) return knownError
}
}
// Try error.message if it's already a good Swedish message
if (typeof obj.error === 'string' && obj.error.trim()) {
if (isSwedishUserMessage(obj.error)) return obj.error
@@ -167,6 +208,8 @@ export function getErrorMessage(
// 3. Error instance
if (error instanceof Error && error.message.trim()) {
const knownError = tryMatchKnownError(error.message)
if (knownError) return knownError
if (isSwedishUserMessage(error.message)) return error.message
}
+1
View File
@@ -8,6 +8,7 @@ function makeParsedFile(overrides?: Partial<ParsedSIEFile>): ParsedSIEFile {
return {
header: {
sieType: 4,
flagga: 0,
program: 'TestProg',
programVersion: '1.0',
generatedDate: '2024-01-01',
+18 -7
View File
@@ -440,16 +440,19 @@ describe('validateSIEFile', () => {
// --- Fix 2: Windows-1252 encoding detection and decoding ---
describe('detectEncoding — #FORMAT PC8 detection', () => {
it('returns cp437 when #FORMAT PC8 is present in the first 500 bytes', () => {
const text = '#FLAGGA 0\n#FORMAT PC8\n#SIETYP 4\n'
const encoder = new TextEncoder()
it('ignores #FORMAT PC8 and detects UTF-8 from byte patterns', () => {
// #FORMAT PC8 is unreliable — most cloud software (Fortnox, Bokio etc.)
// exports UTF-8 but still declares #FORMAT PC8.
// UTF-8 encoded: "Företagskonto" → 0xC3 0xB6 for ö
const text = '#FLAGGA 0\n#FORMAT PC8\n#FNAMN "Företagskonto"\n'
const encoder = new TextEncoder() // TextEncoder outputs UTF-8
const buf = encoder.encode(text)
const encoding = detectEncoding(buf.buffer)
expect(encoding).toBe('cp437')
expect(encoding).toBe('utf8')
})
it('returns cp437 even when Win-1252 bytes follow #FORMAT PC8', () => {
// #FORMAT PC8 header should take priority over any byte analysis
it('detects Win-1252 when actual byte values are in Win-1252 range', () => {
// Win-1252 bytes for Swedish chars: ö=0xF6, ä=0xE4, å=0xE5
const prefix = new TextEncoder().encode('#FORMAT PC8\n#FNAMN F')
const buf = new Uint8Array(prefix.length + 3)
buf.set(prefix)
@@ -457,7 +460,15 @@ describe('detectEncoding — #FORMAT PC8 detection', () => {
buf[prefix.length + 1] = 0xe4 // ä in Win-1252
buf[prefix.length + 2] = 0xe5 // å in Win-1252
const encoding = detectEncoding(buf.buffer)
expect(encoding).toBe('cp437')
expect(encoding).toBe('windows1252')
})
it('returns utf8 for pure ASCII files (no high bytes)', () => {
const text = '#FLAGGA 0\n#FORMAT PC8\n#SIETYP 4\n'
const encoder = new TextEncoder()
const buf = encoder.encode(text)
const encoding = detectEncoding(buf.buffer)
expect(encoding).toBe('utf8')
})
})
+32 -34
View File
@@ -94,24 +94,13 @@ export function detectEncoding(buffer: ArrayBuffer): SIEEncoding {
return 'utf8'
}
// Check for #FORMAT PC8 in the first 500 bytes (ASCII-safe, works regardless of encoding)
const headerSize = Math.min(bytes.length, 500)
const FORMAT_PC8 = [0x23, 0x46, 0x4f, 0x52, 0x4d, 0x41, 0x54, 0x20, 0x50, 0x43, 0x38]
for (let i = 0; i <= headerSize - FORMAT_PC8.length; i++) {
let match = true
for (let j = 0; j < FORMAT_PC8.length; j++) {
if (bytes[i + j] !== FORMAT_PC8[j]) {
match = false
break
}
}
if (match) {
return 'cp437'
}
}
// NOTE: #FORMAT PC8 is NOT used for encoding detection.
// Almost all SIE files declare #FORMAT PC8 regardless of actual encoding
// (Fortnox, Bokio, Dooer etc. export UTF-8 with #FORMAT PC8).
// Instead, we detect encoding from actual byte patterns.
// Scan sample for encoding-specific byte ranges
const sampleSize = Math.min(bytes.length, 2000)
const sampleSize = Math.min(bytes.length, 4000)
let cp437Count = 0 // Swedish chars in 0x80-0x9F (CP437 range)
let utf8Count = 0 // Valid UTF-8 multi-byte Swedish sequences
let win1252Count = 0 // Swedish chars in 0xC0-0xFF (Win-1252 range)
@@ -119,33 +108,35 @@ export function detectEncoding(buffer: ArrayBuffer): SIEEncoding {
for (let i = 0; i < sampleSize; i++) {
const byte = bytes[i]
// Check for CP437 Swedish characters
if (CP437_MAP[byte]) {
cp437Count++
}
// Check for Windows-1252 Swedish characters
if (WIN1252_SWEDISH_BYTES.has(byte)) {
win1252Count++
}
// Check for UTF-8 multi-byte sequences for Swedish chars
// Ä = C3 84, Å = C3 85, Ö = C3 96, ä = C3 A4, å = C3 A5, ö = C3 B6
// Check for UTF-8 multi-byte sequences for Swedish chars FIRST
// to avoid false CP437/Win-1252 counts from continuation bytes.
// Ä = C3 84, Å = C3 85, Ö = C3 96, ä = C3 A4, å = C3 A5, ö = C3 B6, é = C3 A9
if (byte === 0xc3 && i + 1 < sampleSize) {
const nextByte = bytes[i + 1]
if ([0x84, 0x85, 0x96, 0xa4, 0xa5, 0xb6].includes(nextByte)) {
if ([0x84, 0x85, 0x96, 0xa4, 0xa5, 0xb6, 0xa9].includes(nextByte)) {
utf8Count++
i++ // Skip continuation byte to avoid false CP437 count (e.g. 0x84 = ä in CP437)
continue
}
}
// Check for CP437 Swedish characters (0x80-0x9F range)
if (CP437_MAP[byte]) {
cp437Count++
}
// Check for Windows-1252 Swedish characters (0xC0-0xFF range)
if (WIN1252_SWEDISH_BYTES.has(byte)) {
win1252Count++
}
}
if (utf8Count > cp437Count && utf8Count > win1252Count) return 'utf8'
if (cp437Count > win1252Count) return 'cp437'
if (win1252Count > 0) return 'windows1252'
return 'cp437'
// Pure ASCII (no high bytes) — UTF-8 is a superset of ASCII
return 'utf8'
}
/**
@@ -348,8 +339,10 @@ export function parseSIEFile(content: string): ParsedSIEFile {
const issues: ParseIssue[] = []
// Initialize header with defaults
// Per SIE spec: if #SIETYP is absent, assume type 1 (closing balances only)
const header: SIEHeader = {
sieType: 4,
sieType: 1,
flagga: null,
program: null,
programVersion: null,
generatedDate: null,
@@ -415,7 +408,7 @@ export function parseSIEFile(content: string): ParsedSIEFile {
try {
switch (tag) {
case 'FLAGGA':
// Flag for file handling - ignore
header.flagga = parseInt(fields[1], 10) || 0
break
case 'FORMAT':
@@ -607,8 +600,8 @@ export function parseSIEFile(content: string): ParsedSIEFile {
case 'RTRANS':
case 'BTRANS': {
// #TRANS = final transaction lines (the current state of the voucher)
// #RTRANS = removed lines (correction audit trail — original lines that were undone)
// #BTRANS = added lines (correction audit trail — new lines that replaced removed ones)
// #RTRANS = supplementary/corrected transaction (must be followed by identical #TRANS for backward compat)
// #BTRANS = removed/cancelled transaction (programs not understanding BTRANS simply ignore it)
//
// When a voucher has been corrected, Fortnox/Visma emit all three types.
// Only #TRANS represents the final voucher state; #RTRANS and #BTRANS are
@@ -732,6 +725,11 @@ export function validateSIEFile(parsed: ParsedSIEFile): ValidationResult {
const errors: string[] = []
const warnings: string[] = []
// Check #FLAGGA for already-imported files
if (parsed.header.flagga === 1) {
warnings.push('Filen är markerad som redan importerad (#FLAGGA 1). Kontrollera att den inte redan har importerats i ett annat system.')
}
// Check for SIE type
if (!parsed.header.sieType) {
errors.push('SIE-typ saknas (#SIETYP). Filen kanske inte är en giltig SIE-fil — kontrollera att du exporterat i rätt format.')
+1
View File
@@ -26,6 +26,7 @@ export type ParseIssueSeverity = 'error' | 'warning' | 'info'
export interface SIEHeader {
// File metadata
sieType: SIEType
flagga: number | null // #FLAGGA (0 = not imported, 1 = already imported)
program: string | null // #PROGRAM
programVersion: string | null
generatedDate: string | null // #GEN — "YYYY-MM-DD"
+20 -18
View File
@@ -9,7 +9,7 @@ let results: Array<{ data?: unknown; error?: unknown }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'in', 'order', 'range']) {
for (const m of ['select', 'eq', 'in', 'order', 'range', 'lt', 'lte', 'gte', 'gt', 'limit']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
@@ -57,13 +57,15 @@ describe('generateSIEExport', () => {
results = [
// 0: fiscal_periods
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
// 1: chart_of_accounts (empty)
// 1: previous fiscal period (#RAR -1)
{ data: null, error: null },
// 2: chart_of_accounts (empty)
{ data: [], error: null },
// 2: journal_entries (empty)
// 3: journal_entries (empty)
{ data: [], error: null },
// 3: cost_centers (empty)
// 4: cost_centers (empty)
{ data: [], error: null },
// 4: projects (empty)
// 5: projects (empty)
{ data: [], error: null },
]
@@ -83,6 +85,7 @@ describe('generateSIEExport', () => {
it('omits #ORGNR when org_number is null', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
@@ -100,7 +103,7 @@ describe('generateSIEExport', () => {
it('generates #KONTO and #SRU for accounts', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
// 1: chart_of_accounts
{ data: null, error: null }, // prevPeriod
{
data: [
{ account_number: '1930', account_name: 'Företagskonto', sru_code: '7301', is_active: true },
@@ -108,11 +111,8 @@ describe('generateSIEExport', () => {
],
error: null,
},
// 2: journal_entries (empty)
{ data: [], error: null },
// 3: cost_centers
{ data: [], error: null },
// 4: projects
{ data: [], error: null },
]
@@ -128,9 +128,8 @@ describe('generateSIEExport', () => {
it('generates #VER and #TRANS for journal entries', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
// 1: accounts
{ data: [], error: null },
// 2: journal_entries with lines
{ data: null, error: null }, // prevPeriod
{ data: [], error: null }, // accounts
{
data: [
{
@@ -149,10 +148,8 @@ describe('generateSIEExport', () => {
],
error: null,
},
// 3: cost_centers
{ data: [], error: null },
// 4: projects
{ data: [], error: null },
{ data: [], error: null }, // cost_centers
{ data: [], error: null }, // projects
]
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
@@ -168,16 +165,15 @@ describe('generateSIEExport', () => {
it('generates #DIM and #OBJEKT for dimensions', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
// 3: cost_centers
{
data: [
{ code: 'CC1', name: 'Avdelning 1', is_active: true },
],
error: null,
},
// 4: projects
{
data: [
{ code: 'P001', name: 'Projekt Alpha', is_active: true },
@@ -197,6 +193,7 @@ describe('generateSIEExport', () => {
it('includes dimension objects in #TRANS lines', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
@@ -228,6 +225,7 @@ describe('generateSIEExport', () => {
it('generates #UB for class 1-2 and #RES for class 3-8', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
@@ -264,6 +262,7 @@ describe('generateSIEExport', () => {
it('escapes quotes in descriptions', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{
data: [
@@ -294,6 +293,7 @@ describe('generateSIEExport', () => {
it('uses \\r\\n line endings', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
@@ -316,6 +316,7 @@ describe('generateSIEExport', () => {
it('produces no #VER lines when no entries exist', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
@@ -331,6 +332,7 @@ describe('generateSIEExport', () => {
it('produces no #DIM lines when no dimensions exist', async () => {
results = [
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
{ data: null, error: null }, // prevPeriod
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null },
@@ -682,6 +682,100 @@ describe('calculateVatDeclaration — reverse charge', () => {
expect(result.rutor.ruta30).toBe(1000)
})
it('maps domestic reverse charge input VAT (2647) to ruta48', async () => {
results = [
{
data: [
// Domestic RC: D 2647 + C 2614 (offsetting), D expense
{ account_number: '2647', debit_amount: 500, credit_amount: 0 },
{ account_number: '2614', debit_amount: 0, credit_amount: 500 },
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
// 2647 debit maps to ruta48
expect(result.rutor.ruta48).toBe(500)
// 2614 credit maps to ruta30
expect(result.rutor.ruta30).toBe(500)
// Net VAT = 500 - 500 = 0 (reverse charge is neutral)
expect(result.rutor.ruta49).toBe(0)
})
it('maps import VAT accounts (2615/2625/2635) to ruta60/61/62', async () => {
results = [
{
data: [
{ account_number: '2615', debit_amount: 0, credit_amount: 2500 },
{ account_number: '2625', debit_amount: 0, credit_amount: 600 },
{ account_number: '2635', debit_amount: 0, credit_amount: 180 },
// Input VAT from imports
{ account_number: '2641', debit_amount: 3280, credit_amount: 0 },
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
expect(result.rutor.ruta60).toBe(2500)
expect(result.rutor.ruta61).toBe(600)
expect(result.rutor.ruta62).toBe(180)
// ruta49 = (ruta60 + ruta61 + ruta62) - ruta48 = 3280 - 3280 = 0
expect(result.rutor.ruta49).toBe(0)
})
it('maps EU/export revenue variants (3108/3105/3004) to ruta35/36/42', async () => {
results = [
{
data: [
{ account_number: '3108', debit_amount: 0, credit_amount: 15000 },
{ account_number: '3105', debit_amount: 0, credit_amount: 8000 },
{ account_number: '3004', debit_amount: 0, credit_amount: 5000 },
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
expect(result.rutor.ruta35).toBe(15000)
expect(result.rutor.ruta36).toBe(8000)
expect(result.rutor.ruta42).toBe(5000)
})
it('maps output VAT variant accounts (2612/2622/2632) to correct rutor', async () => {
results = [
{
data: [
// Egna uttag 25%
{ account_number: '2612', debit_amount: 0, credit_amount: 1000 },
// Uthyrning 12%
{ account_number: '2623', debit_amount: 0, credit_amount: 200 },
// VMB 6%
{ account_number: '2636', debit_amount: 0, credit_amount: 50 },
],
error: null,
},
{ data: [], error: null },
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'company-1', 'monthly', 2024, 1)
expect(result.rutor.ruta10).toBe(1000)
expect(result.rutor.ruta11).toBe(200)
expect(result.rutor.ruta12).toBe(50)
})
it('only includes posted journal entries for reverse charge bases (reversed filtered at DB level)', async () => {
// The query uses .eq('status', 'posted'), so reversed entries never appear
results = [
+39 -8
View File
@@ -29,6 +29,16 @@ export async function generateSIEExport(
throw new Error('Fiscal period not found')
}
// Fetch previous fiscal year for #RAR -1 (per SIE spec, both years should be present)
const { data: prevPeriod } = await supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('company_id', companyId)
.lt('period_end', period.period_start)
.order('period_end', { ascending: false })
.limit(1)
.single()
// Fetch all accounts
const accounts = await fetchAllRows(({ from, to }) =>
supabase
@@ -81,10 +91,14 @@ export async function generateSIEExport(
lines.push(`#FNAMN "${escapeQuotes(options.company_name)}"`)
// === Fiscal year ===
// #RAR 0 start end (current year)
// #RAR 0 = current year, #RAR -1 = previous year (both should be present per spec)
// Use date strings directly to avoid timezone conversion issues
lines.push(`#RAR 0 ${dateStringToSIE(period.period_start)} ${dateStringToSIE(period.period_end)}`)
if (prevPeriod) {
lines.push(`#RAR -1 ${dateStringToSIE(prevPeriod.period_start)} ${dateStringToSIE(prevPeriod.period_end)}`)
}
// === Dimension definitions ===
// SIE standard: dimension 1 = kostnadsställe, dimension 6 = projekt
const hasCostCenters = costCenters && costCenters.length > 0
@@ -116,6 +130,9 @@ export async function generateSIEExport(
}
// === Opening balances (IB) ===
// Collect IB per account for UB calculation (UB = IB + movements)
const openingBalancesByAccount = new Map<string, number>()
if (period.opening_balance_entry_id) {
const { data: obEntry } = await supabase
.from('journal_entries')
@@ -128,6 +145,10 @@ export async function generateSIEExport(
for (const line of (obEntry.lines as JournalEntryLine[])) {
const amount = (Number(line.debit_amount) || 0) - (Number(line.credit_amount) || 0)
lines.push(`#IB 0 ${line.account_number} ${formatAmount(amount)}`)
openingBalancesByAccount.set(
line.account_number,
(openingBalancesByAccount.get(line.account_number) || 0) + amount
)
}
}
}
@@ -169,17 +190,27 @@ export async function generateSIEExport(
}
// === Closing balances (UB for balance sheet, RES for income statement) ===
// Calculate balances from journal entries
const accountBalances = calculateBalances(entries as JournalEntry[])
// Movement balances from journal entries
const movementBalances = calculateBalances(entries as JournalEntry[])
for (const [accountNumber, balance] of accountBalances) {
// Merge all accounts that have either IB or movements
const allAccountNumbers = new Set([
...openingBalancesByAccount.keys(),
...movementBalances.keys(),
])
for (const accountNumber of [...allAccountNumbers].sort()) {
const accountClass = parseInt(accountNumber[0])
const ib = openingBalancesByAccount.get(accountNumber) || 0
const movement = movementBalances.get(accountNumber) || 0
if (accountClass <= 2) {
// Balance sheet account: #UB
lines.push(`#UB 0 ${accountNumber} ${formatAmount(balance)}`)
// Balance sheet: UB = IB + movements during period
const ub = Math.round((ib + movement) * 100) / 100
lines.push(`#UB 0 ${accountNumber} ${formatAmount(ub)}`)
} else {
// Income statement account: #RES
lines.push(`#RES 0 ${accountNumber} ${formatAmount(balance)}`)
// Income statement: RES = movements only (IB should be zero)
lines.push(`#RES 0 ${accountNumber} ${formatAmount(movement)}`)
}
}
+45 -18
View File
@@ -22,30 +22,61 @@ import type {
/**
* Account-to-ruta mapping for the Swedish momsdeklaration (SKV 4700).
*
* Revenue (3001/3002/3003): net credit balance feeds ruta 05 (total domestic taxable sales).
* Output VAT (2611/2621/2631): net credit balance feeds ruta 10/11/12 (output VAT per rate).
* Input VAT (2641/2645): net debit balance feeds ruta 48.
* EU/Export (3308/3305): net credit balance feeds ruta 39/40.
* Covers all BAS 26xx VAT accounts and 3xxx revenue accounts that feed the
* momsdeklaration. Includes variant accounts (egna uttag, uthyrning, VMB,
* import, domestic reverse charge) that may appear from manual entries or
* SIE imports, not just accounts generated by the system.
*
* Output VAT (261x/262x/263x) → ruta 10/11/12 per rate
* Reverse charge output (2614/2624/2634) → ruta 30/31/32
* Import VAT (2615/2625/2635) → ruta 60/61/62
* Input VAT (2641-2649) → ruta 48
* Revenue (3001-3003) → ruta 05; EU (3108/3308) → ruta 35/39;
* Export (3105/3305) → ruta 36/40; Exempt (3004/3100) → ruta 42
*/
const ACCOUNT_RUTA: Record<string, { box: keyof VatDeclarationRutor; side: 'credit' | 'debit' }> = {
// Output VAT accounts → ruta 10/11/12
'2611': { box: 'ruta10', side: 'credit' },
// Output VAT 25% → ruta 10
'2611': { box: 'ruta10', side: 'credit' }, // Försäljning inom Sverige
'2612': { box: 'ruta10', side: 'credit' }, // Egna uttag
'2613': { box: 'ruta10', side: 'credit' }, // Uthyrning (frivillig skattskyldighet)
'2616': { box: 'ruta10', side: 'credit' }, // Vinstmarginalbeskattning
// Output VAT 12% → ruta 11
'2621': { box: 'ruta11', side: 'credit' },
'2622': { box: 'ruta11', side: 'credit' }, // Egna uttag
'2623': { box: 'ruta11', side: 'credit' }, // Uthyrning
'2626': { box: 'ruta11', side: 'credit' }, // VMB
// Output VAT 6% → ruta 12
'2631': { box: 'ruta12', side: 'credit' },
'2632': { box: 'ruta12', side: 'credit' }, // Egna uttag
'2633': { box: 'ruta12', side: 'credit' }, // Uthyrning
'2636': { box: 'ruta12', side: 'credit' }, // VMB
// Reverse charge output VAT → ruta 30/31/32
'2614': { box: 'ruta30', side: 'credit' },
'2624': { box: 'ruta31', side: 'credit' },
'2634': { box: 'ruta32', side: 'credit' },
// Input VAT → ruta 48
'2641': { box: 'ruta48', side: 'debit' },
'2645': { box: 'ruta48', side: 'debit' },
// Revenue accounts → ruta 05 (all domestic taxable sales combined)
'2641': { box: 'ruta48', side: 'debit' }, // Debiterad ingående moms
'2642': { box: 'ruta48', side: 'debit' }, // Frivillig skattskyldighet
'2645': { box: 'ruta48', side: 'debit' }, // Förvärv utlandet (EU/non-EU RC)
'2646': { box: 'ruta48', side: 'debit' }, // Uthyrning
'2647': { box: 'ruta48', side: 'debit' }, // Omvänd skattskyldighet i Sverige
'2649': { box: 'ruta48', side: 'debit' }, // Blandad verksamhet
// Import VAT (since 2015, via momsdeklaration) → ruta 60/61/62
'2615': { box: 'ruta60', side: 'credit' }, // Import 25%
'2625': { box: 'ruta61', side: 'credit' }, // Import 12%
'2635': { box: 'ruta62', side: 'credit' }, // Import 6%
// Revenue: domestic taxable sales → ruta 05
'3001': { box: 'ruta05', side: 'credit' },
'3002': { box: 'ruta05', side: 'credit' },
'3003': { box: 'ruta05', side: 'credit' },
// EU/Export → ruta 39/40
'3305': { box: 'ruta40', side: 'credit' },
'3308': { box: 'ruta39', side: 'credit' },
// Revenue: EU goods/services → ruta 35/39
'3108': { box: 'ruta35', side: 'credit' }, // Varuförsäljning till EU
'3308': { box: 'ruta39', side: 'credit' }, // Tjänsteförsäljning till EU
// Revenue: export/other → ruta 36/40/42
'3105': { box: 'ruta36', side: 'credit' }, // Varuförsäljning export
'3305': { box: 'ruta40', side: 'credit' }, // Tjänsteförsäljning export
'3004': { box: 'ruta42', side: 'credit' }, // Momsfri försäljning (AB)
'3100': { box: 'ruta42', side: 'credit' }, // Momsfria intäkter (EF)
}
const VAT_ACCOUNTS = Object.keys(ACCOUNT_RUTA)
@@ -111,12 +142,8 @@ function round(value: number): number {
/**
* Calculate VAT declaration from the general ledger.
*
* Sums posted journal entry lines on 26xx and 3xxx accounts:
* - 3001/3002/3003 credit balance -> ruta 05 (total domestic taxable sales)
* - 2611/2621/2631 credit balance -> ruta 10/11/12 (output VAT per rate)
* - 2641/2645 debit balance -> ruta 48 (input VAT)
* - 3308/3305 credit balance -> ruta 39/40 (EU/export)
* - ruta 49 = (10 + 11 + 12) - 48
* Sums posted journal entry lines on 26xx and 3xxx accounts per ACCOUNT_RUTA mapping.
* - ruta 49 = (10 + 11 + 12 + 30 + 31 + 32 + 60 + 61 + 62) - 48
*
* The accounting method parameter is accepted for backward compatibility
* but not used — the method is already baked into journal entry timing.
+36 -7
View File
@@ -42,7 +42,7 @@ export type MomsBox =
| '61' // Importmoms 12%
| '62' // Importmoms 6%
/** Map BAS revenue account to momsdeklaration box */
/** Map BAS account to momsdeklaration box */
export const ACCOUNT_TO_BOX: Record<string, MomsBox> = {
// Domestic revenue (taxable) → Box 05
'3001': '05', // Försäljning varor/tjänster 25%
@@ -66,14 +66,43 @@ export const ACCOUNT_TO_BOX: Record<string, MomsBox> = {
// Non-EU services → Box 40
'3305': '40', // Försäljning tjänster export utanför EU
// Output VAT → Boxes 10, 11, 12
'2611': '10', // Utgående moms 25%
'2621': '11', // Utgående moms 12%
'2631': '12', // Utgående moms 6%
// VAT-exempt sales → Box 42
'3004': '42', // Momsfri försäljning (AB)
'3100': '42', // Momsfria intäkter (EF)
// Output VAT 25% → Box 10
'2611': '10', // Försäljning inom Sverige
'2612': '10', // Egna uttag
'2613': '10', // Uthyrning (frivillig skattskyldighet)
'2616': '10', // Vinstmarginalbeskattning
// Output VAT 12% → Box 11
'2621': '11',
'2622': '11', // Egna uttag
'2623': '11', // Uthyrning
'2626': '11', // VMB
// Output VAT 6% → Box 12
'2631': '12',
'2632': '12', // Egna uttag
'2633': '12', // Uthyrning
'2636': '12', // VMB
// Reverse charge output VAT → Boxes 30, 31, 32
'2614': '30',
'2624': '31',
'2634': '32',
// Import VAT (since 2015, via momsdeklaration) → Boxes 60, 61, 62
'2615': '60', // Import 25%
'2625': '61', // Import 12%
'2635': '62', // Import 6%
// Input VAT → Box 48
'2641': '48', // Ingående moms
'2645': '48', // Beräknad ingående moms (EU förvärv)
'2641': '48', // Debiterad ingående moms
'2642': '48', // Frivillig skattskyldighet
'2645': '48', // Beräknad ingående moms (EU/non-EU förvärv)
'2646': '48', // Uthyrning
'2647': '48', // Omvänd skattskyldighet i Sverige
'2649': '48', // Blandad verksamhet
}
/** Swedish labels for each momsdeklaration box */