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
+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.