feat: enhance supplier invoices, entity-aware categorization, and new tests

Expand supplier invoice module with overdue cron job, credit note journal
entries, and event emissions on approve/mark-paid/create flows. Add entity
type (EF/AB) awareness to transaction categorization UI and category
mapping logic. Add comprehensive tests for supplier-invoice-entries,
transaction-entries, and expanded API route coverage.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-03-03 17:08:26 +01:00
co-authored by Claude Opus 4.6
parent f6a9889f0a
commit a9bf24ce0b
23 changed files with 2293 additions and 113 deletions
@@ -7,7 +7,7 @@ import {
buildMappingResultFromCategory,
} from '../category-mapping'
import { makeTransaction } from '@/tests/helpers'
import type { TransactionCategory } from '@/types'
import type { TransactionCategory, VatTreatment } from '@/types'
describe('getCategoryAccountMapping', () => {
describe('income_products uses correct account', () => {
@@ -182,6 +182,7 @@ 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', () => {
@@ -192,3 +193,80 @@ describe('getDefaultVatTreatmentForCategory', () => {
expect(getDefaultVatTreatmentForCategory('uncategorized')).toBeNull()
})
})
describe('representation VAT (ML 8:9 — illegal since 2017)', () => {
it('getDefaultVatTreatmentForCategory returns null for representation', () => {
expect(getDefaultVatTreatmentForCategory('expense_representation')).toBeNull()
})
it('getCategoryAccountMapping has vatTreatment: null for representation', () => {
const result = getCategoryAccountMapping('expense_representation', -500, true)
expect(result.vatTreatment).toBeNull()
expect(result.vatDebitAccount).toBeNull()
})
it('buildMappingResultFromCategory generates no VAT lines for representation', () => {
const tx = makeTransaction({ amount: -500 })
const result = buildMappingResultFromCategory('expense_representation', tx, true)
expect(result.vat_lines).toHaveLength(0)
})
})
describe('income account resolves by VAT treatment', () => {
const cases: [VatTreatment, string][] = [
['standard_25', '3001'],
['reduced_12', '3002'],
['reduced_6', '3003'],
['export', '3305'],
['reverse_charge', '3308'],
['exempt', '3004'],
]
it.each(cases)('income_services with %s maps to %s', (vat, expectedAccount) => {
const result = getCategoryAccountMapping('income_services', 1000, true, 'enskild_firma', vat)
expect(result.creditAccount).toBe(expectedAccount)
})
it.each(cases)('income_products with %s maps to %s', (vat, expectedAccount) => {
const result = getCategoryAccountMapping('income_products', 1000, true, 'enskild_firma', vat)
expect(result.creditAccount).toBe(expectedAccount)
})
it('income_other always returns 3900 regardless of VAT treatment', () => {
for (const vat of ['standard_25', 'reduced_12', 'reduced_6', 'export', 'reverse_charge', 'exempt'] as VatTreatment[]) {
const result = getCategoryAccountMapping('income_other', 1000, true, 'enskild_firma', vat)
expect(result.creditAccount).toBe('3900')
}
})
it('defaults to 3001 when no vatTreatment provided', () => {
const result = getCategoryAccountMapping('income_services', 1000, true)
expect(result.creditAccount).toBe('3001')
})
})
describe('private transaction accounts by entity type and direction', () => {
it('EF withdrawal (amount < 0) uses 2013', () => {
const result = getCategoryAccountMapping('private', -500, false, 'enskild_firma')
expect(result.debitAccount).toBe('2013')
expect(result.creditAccount).toBe('1930')
})
it('EF deposit (amount > 0) uses 2018', () => {
const result = getCategoryAccountMapping('private', 500, false, 'enskild_firma')
expect(result.debitAccount).toBe('1930')
expect(result.creditAccount).toBe('2018')
})
it('AB uses 2893 for both withdrawal and deposit', () => {
const withdrawal = getCategoryAccountMapping('private', -500, false, 'aktiebolag')
expect(withdrawal.debitAccount).toBe('2893')
const deposit = getCategoryAccountMapping('private', 500, false, 'aktiebolag')
expect(deposit.creditAccount).toBe('2893')
})
it('getDefaultAccountForCategory still returns 2013 for EF (default/withdrawal account)', () => {
expect(getDefaultAccountForCategory('private', 'enskild_firma')).toBe('2013')
})
})
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+38 -5
View File
@@ -72,6 +72,30 @@ function getExpenseAccount(category: string, entityType: EntityType = 'enskild_f
return EXPENSE_ACCOUNTS[category] || '6991'
}
/**
* Get the income account for a category, resolving by VAT treatment.
* BAS mandates revenue account segregation by VAT rate:
* 3001=25%, 3002=12%, 3003=6%, 3305=Export, 3308=EU services, 3004=Exempt.
*/
function getIncomeAccount(category: string, vatTreatment?: VatTreatment): string {
// income_other always maps to 3900 regardless of VAT treatment
if (category === 'income_other') return '3900'
if (vatTreatment) {
switch (vatTreatment) {
case 'standard_25': return '3001'
case 'reduced_12': return '3002'
case 'reduced_6': return '3003'
case 'export': return '3305'
case 'reverse_charge': return '3308'
case 'exempt': return '3004'
}
}
// No vatTreatment provided — fall back to static mapping
return INCOME_ACCOUNTS[category] || '3900'
}
/**
* Get account mapping for a transaction category
*
@@ -86,8 +110,15 @@ export function getCategoryAccountMapping(
vatTreatment?: VatTreatment
): CategoryAccountMapping {
// Private/owner transactions use entity-specific accounts
// EF: 2013 for withdrawals (uttag), 2018 for deposits (insättningar)
// AB: 2893 for both directions
if (!isBusiness) {
const privateAccount = PRIVATE_ACCOUNTS[entityType] || PRIVATE_ACCOUNTS.enskild_firma
let privateAccount: string
if (entityType === 'enskild_firma') {
privateAccount = amount < 0 ? '2013' : '2018'
} else {
privateAccount = PRIVATE_ACCOUNTS[entityType] || PRIVATE_ACCOUNTS.enskild_firma
}
return {
debitAccount: amount < 0 ? privateAccount : BANK_ACCOUNT,
creditAccount: amount < 0 ? BANK_ACCOUNT : privateAccount,
@@ -101,8 +132,9 @@ export function getCategoryAccountMapping(
if (category.startsWith('expense_')) {
const expenseAccount = getExpenseAccount(category, entityType)
// Bank fees, card fees, and currency exchange are VAT-exempt in Sweden
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange']
// 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']
const isVatExempt = vatExemptCategories.includes(category)
// Use provided vatTreatment, or default based on category
@@ -119,7 +151,7 @@ export function getCategoryAccountMapping(
// Check if it's an income category
if (category.startsWith('income_')) {
const incomeAccount = INCOME_ACCOUNTS[category] || '3900'
const incomeAccount = getIncomeAccount(category, vatTreatment)
// Use provided vatTreatment, or default to standard_25
const resolvedVat = vatTreatment ?? 'standard_25'
@@ -313,7 +345,8 @@ export function getDefaultVatTreatmentForCategory(
return null
}
const vatExemptCategories = ['expense_bank_fees', 'expense_card_fees', 'expense_currency_exchange']
// 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']
if (vatExemptCategories.includes(category)) {
return null
}
+2
View File
@@ -11,6 +11,7 @@ const ACCOUNT_NAMES: Record<string, string> = {
// Equity & Liabilities (2xxx)
'2013': 'Ovriga egna uttag',
'2018': 'Egna insattningar',
'2440': 'Leverantorsskulder',
'2611': 'Utg. moms 25%',
'2621': 'Utg. moms 12%',
@@ -24,6 +25,7 @@ const ACCOUNT_NAMES: Record<string, string> = {
'3001': 'Forsaljning 25%',
'3002': 'Forsaljning 12%',
'3003': 'Forsaljning 6%',
'3004': 'Momsfri forsaljning',
'3305': 'Exportforsaljning',
'3308': 'EU-tjanster',
'3900': 'Ovriga rorelseintakter',
+116 -70
View File
@@ -18,14 +18,17 @@ const log = createLogger('supplier-invoice-entries')
*
* Swedish domestic (25% VAT):
* Debit 5xxx/6xxx (per item's account_number) [item line_total]
* Debit 2641 Ingående moms [total VAT]
* Debit 2641 Ingående moms (per rate) [VAT per rate group]
* Credit 2440 Leverantörsskulder [total incl VAT]
*
* EU reverse charge (supplier_type = 'eu_business'):
* EU/non-EU reverse charge (services):
* Debit 5xxx/6xxx (per item) [total]
* Debit 2645 Beräknad ingående moms [fiktiv VAT]
* Credit 2614 Utgående moms omvänd [fiktiv VAT]
* Debit 2645 Beräknad ingående moms (per rate) [fiktiv VAT per rate]
* Credit 26x4 Utgående moms omvänd (per rate) [fiktiv VAT per rate]
* Credit 2440 Leverantörsskulder [total]
*
* Note: Goods imports via Tullverket (customs) use a different accounting path
* (2615/2645) and are not handled here — only services use reverse charge.
*/
export async function createSupplierInvoiceRegistrationEntry(
supabase: SupabaseClient,
@@ -64,29 +67,40 @@ export async function createSupplierInvoiceRegistrationEntry(
}
lines.push(...debitLines)
if (supplierType === 'eu_business' && invoice.reverse_charge) {
// EU reverse charge: fiktiv moms entries (computed on SEK subtotal)
const vatRate = getDefaultVatRate(invoice.vat_treatment)
const subtotalSek = resolveSekAmount(invoice.subtotal, invoice.subtotal_sek, invoice.currency, invoice.exchange_rate)
const reverseChargeLines = generateReverseChargeLines(subtotalSek, vatRate)
lines.push(...reverseChargeLines)
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && invoice.reverse_charge
if (isReverseCharge) {
// EU/non-EU reverse charge: fiktiv moms entries per rate group
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)
lines.push(...rcLines)
}
}
} else if (invoice.vat_amount > 0) {
// Domestic: Debit ingående moms (in SEK)
const vatSek = resolveSekAmount(invoice.vat_amount, invoice.vat_amount_sek, invoice.currency, invoice.exchange_rate)
lines.push({
account_number: '2641',
debit_amount: Math.round(vatSek * 100) / 100,
credit_amount: 0,
line_description: `Ingående moms ${desc}`,
})
// Domestic: 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) {
lines.push({
account_number: '2641',
debit_amount: Math.round(amount * 100) / 100,
credit_amount: 0,
line_description: `Ingående moms ${Math.round(rate * 100)}% ${desc}`,
})
}
}
}
// Credit: Leverantörsskulder — balance guarantee: credit = sum of all debit lines
// Credit: Leverantörsskulder — balance guarantee: ensures sum(debits) === sum(credits)
// For reverse charge, intermediate credits (2614/2624/2634) already exist, so we subtract them
const totalDebits = lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredits = lines.reduce((sum, l) => sum + l.credit_amount, 0)
lines.push({
account_number: '2440',
debit_amount: 0,
credit_amount: Math.round(totalDebits * 100) / 100,
credit_amount: Math.round((totalDebits - totalCredits) * 100) / 100,
line_description: desc,
...buildCurrencyMetadata(invoice.currency, isForeign ? invoice.total : undefined, invoice.exchange_rate),
})
@@ -242,29 +256,40 @@ export async function createSupplierInvoiceCashEntry(
})
}
if (supplierType === 'eu_business' && invoice.reverse_charge) {
// EU reverse charge: fiktiv moms entries (computed on SEK subtotal)
const vatRate = getDefaultVatRate(invoice.vat_treatment)
const subtotalSek = resolveSekAmount(invoice.subtotal, invoice.subtotal_sek, invoice.currency, invoice.exchange_rate)
const reverseChargeLines = generateReverseChargeLines(subtotalSek, vatRate)
lines.push(...reverseChargeLines)
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && invoice.reverse_charge
if (isReverseCharge) {
// EU/non-EU reverse charge: fiktiv moms entries per rate group
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)
lines.push(...rcLines)
}
}
} else if (invoice.vat_amount > 0) {
// Domestic: Debit ingående moms (in SEK)
const vatSek = resolveSekAmount(invoice.vat_amount, invoice.vat_amount_sek, invoice.currency, invoice.exchange_rate)
lines.push({
account_number: '2641',
debit_amount: Math.round(vatSek * 100) / 100,
credit_amount: 0,
line_description: `Ingående moms ${desc}`,
})
// Domestic: 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) {
lines.push({
account_number: '2641',
debit_amount: Math.round(amount * 100) / 100,
credit_amount: 0,
line_description: `Ingående moms ${Math.round(rate * 100)}% ${desc}`,
})
}
}
}
// Credit: Företagskonto — balance guarantee: credit = sum of all debit lines
// Credit: Företagskonto — balance guarantee: ensures sum(debits) === sum(credits)
// For reverse charge, intermediate credits (2614/2624/2634) already exist, so we subtract them
const totalDebits = lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredits = lines.reduce((sum, l) => sum + l.credit_amount, 0)
lines.push({
account_number: '1930',
debit_amount: 0,
credit_amount: Math.round(totalDebits * 100) / 100,
credit_amount: Math.round((totalDebits - totalCredits) * 100) / 100,
line_description: desc,
})
@@ -321,34 +346,46 @@ export async function createSupplierCreditNoteEntry(
})
}
if (supplierType === 'eu_business' && creditNote.reverse_charge) {
// Reverse the fiktiv moms (swap debit/credit from registration)
const vatRate = getDefaultVatRate(creditNote.vat_treatment)
const absSubtotalSek = Math.abs(resolveSekAmount(creditNote.subtotal, creditNote.subtotal_sek, creditNote.currency, creditNote.exchange_rate))
const vatAmount = Math.round(absSubtotalSek * vatRate * 100) / 100
creditLines.push({
account_number: '2645',
debit_amount: 0,
credit_amount: vatAmount,
line_description: `Omvänd fiktiv ingående moms ${desc}`,
})
// 2614 is a debit (reversal of the output VAT credit)
lines.push({
account_number: '2614',
debit_amount: vatAmount,
credit_amount: 0,
line_description: `Omvänd fiktiv utgående moms ${desc}`,
})
const isReverseCharge = (supplierType === 'eu_business' || supplierType === 'non_eu_business') && creditNote.reverse_charge
if (isReverseCharge) {
// Reverse the fiktiv moms per rate group (swap debit/credit from registration)
const vatByRate = groupVatByRate(items, creditNote.currency, creditNote.exchange_rate, true)
for (const [rate, amount] of vatByRate) {
if (rate > 0 && amount > 0) {
// Determine the output account for this rate
let outputAccount: string
switch (rate) {
case 0.12: outputAccount = '2624'; break
case 0.06: outputAccount = '2634'; break
default: outputAccount = '2614'; break
}
creditLines.push({
account_number: '2645',
debit_amount: 0,
credit_amount: amount,
line_description: `Omvänd fiktiv ingående moms ${Math.round(rate * 100)}% ${desc}`,
})
lines.push({
account_number: outputAccount,
debit_amount: amount,
credit_amount: 0,
line_description: `Omvänd fiktiv utgående moms ${Math.round(rate * 100)}% ${desc}`,
})
}
}
} else {
const absVat = Math.abs(resolveSekAmount(creditNote.vat_amount, creditNote.vat_amount_sek, creditNote.currency, creditNote.exchange_rate))
if (absVat > 0) {
// Credit: Ingående moms (reverse)
creditLines.push({
account_number: '2641',
debit_amount: 0,
credit_amount: Math.round(absVat * 100) / 100,
line_description: `Ingående moms ${desc}`,
})
// Domestic: Credit ingående moms per rate group (reverse)
const vatByRate = groupVatByRate(items, creditNote.currency, creditNote.exchange_rate, true)
for (const [rate, amount] of vatByRate) {
if (amount > 0) {
creditLines.push({
account_number: '2641',
debit_amount: 0,
credit_amount: amount,
line_description: `Ingående moms ${Math.round(rate * 100)}% ${desc}`,
})
}
}
}
@@ -377,13 +414,22 @@ export async function createSupplierCreditNoteEntry(
}
/**
* Get default VAT rate from treatment string
* Group items by VAT rate and sum the VAT amount per rate.
* Returns a Map<rate, totalVatAmount> for generating per-rate journal lines.
*/
function getDefaultVatRate(vatTreatment: string): number {
switch (vatTreatment) {
case 'standard_25': return 0.25
case 'reduced_12': return 0.12
case 'reduced_6': return 0.06
default: return 0.25
function groupVatByRate(
items: SupplierInvoiceItem[],
currency: string,
exchangeRate: number | null,
useAbsoluteValues = false
): Map<number, number> {
const vatByRate = new Map<number, number>()
for (const item of items) {
const rate = item.vat_rate ?? 0.25
let itemSek = resolveSekAmount(item.line_total, null, currency, exchangeRate)
if (useAbsoluteValues) itemSek = Math.abs(itemSek)
const itemVat = Math.round(itemSek * rate * 100) / 100
vatByRate.set(rate, (vatByRate.get(rate) || 0) + itemVat)
}
return vatByRate
}
+5
View File
@@ -56,6 +56,11 @@ export type CoreEvent =
privateTotal: number;
userId: string;
}}
// Supplier Invoice Lifecycle
| { type: 'supplier_invoice.registered'; payload: { supplierInvoice: SupplierInvoice; userId: string } }
| { type: 'supplier_invoice.approved'; payload: { supplierInvoice: SupplierInvoice; userId: string } }
| { type: 'supplier_invoice.paid'; payload: { supplierInvoice: SupplierInvoice; paymentAmount: number; userId: string } }
| { type: 'supplier_invoice.credited'; payload: { supplierInvoice: SupplierInvoice; creditNote: SupplierInvoice; userId: string } }
// Supplier Invoice Inbox
| { type: 'supplier_invoice.received'; payload: { inboxItem: InvoiceInboxItem; userId: string } }
| { type: 'supplier_invoice.extracted'; payload: { inboxItem: InvoiceInboxItem; confidence: number; userId: string } }
+3 -3
View File
@@ -53,9 +53,9 @@ const warningPatterns: {
pattern: /restaurang|lunch|middag|dinner|café|fika/i,
warning: {
category: 'Representation',
warningLevel: 'info',
message: 'Måltider kan vara avdragsgilla som representation med max 300 kr per person (exkl. moms)',
legalBasis: 'IL 16 kap 2§',
warningLevel: 'warning',
message: 'Måltider kan vara avdragsgilla som representation med max 300 kr per person (exkl. moms). Momsen är inte avdragsgill sedan 2017.',
legalBasis: 'IL 16 kap 2§, ML 8:9',
},
},
{