Files
accounted/lib/bookkeeping/__tests__/transaction-entries.test.ts
T
Jakob WennbergandClaude Fable 5 8e8b63a200 fix(bookkeeping): honor underlag VAT via vat_amount override in categorize flow (#717)
* fix(bookkeeping): honor underlag VAT via vat_amount override in categorize flow

The categorize flow always derived VAT as rate × gross/(1+rate) from the
transaction amount, with no way to use the underlag's actual moms. On e.g.
a restaurant receipt with dricks (no VAT on the tip), the agent could see
the document's correct VAT but the staged booking recomputed the wrong
rate-based amount on every attempt.

- buildMappingResultFromCategory: optional vatAmountOverride replaces the
  rate-derived VAT line ("Ingående/Utgående moms (enligt underlag)"; 0 =
  no VAT line). Rejects negatives, amounts above the 25%-extraction bound,
  and combination with reverse_charge / VAT-less treatments / private.
- gnubok_categorize_transaction: new vat_amount input, threaded into the
  staged preview and persisted in the operation params.
- commitCategorizeTransaction: reads params.vat_amount so the approved
  posting matches the staged preview exactly.
- PATCH /api/pending-operations/[id]: accepts vat_amount (null clears);
  preserves a staged override across category edits while the treatment
  still carries rate-based VAT, drops it when it no longer does.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* review: guard order + agent guidance on vat_amount (PR #717 bots)

- Check treatment compatibility before the 25%-extraction bound so an
  oversized override on reverse_charge reports the actual mistake (the
  treatment), not the amount. Document why the typeof re-check stays:
  commit-time params come from jsonb, so TS types don't hold at runtime.
- vat_amount property description now warns that foreign VAT is never
  deductible as ingående moms and that a 0-moms document should use
  vat_treatment="exempt" rather than vat_amount=0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mcp): tools/list payload budget + reject vat_amount 0

core-only failed: the verbose vat_amount descriptions pushed the projected
tools/list payload to 36,051 tokens (ceiling 36,000; main is at 35,862).
Per the guard's own guidance, trim descriptions instead of bumping:
now 35,943.

Folds in the Swedish review's round-2 point while trimming: vat_amount 0
is now rejected with a pointer to vat_treatment "exempt". A 0-moms
document is an exempt supply — "exempt" produces the identical expense
booking and the correct income account (3004), so 0 had no use case and
only created a silent momsdeklaration misclassification path. Schema
declares exclusiveMinimum: 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(bookkeeping): use roundOre for vat_amount math (antipattern ratchet)

Second core-only failure: the naive-ore-round ratchet caught the new
Math.round(x*100)/100 lines (662 > baseline 661). Switch the override
path to roundOre from lib/money — including the pre-existing computed-VAT
line this PR touched — and ratchet the baseline down (659, raw-route-auth
168 locked in from main-side fixes).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 11:42:21 +02:00

556 lines
20 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { makeTransaction } from '@/tests/helpers'
import type { CreateJournalEntryInput, MappingResult, VatJournalLine } from '@/types'
// Mock engine
vi.mock('../engine', () => ({
findFiscalPeriod: vi.fn().mockResolvedValue('period-1'),
createJournalEntry: vi.fn().mockImplementation(
async (_supabase: unknown, _companyId: string, _userId: string, input: CreateJournalEntryInput) => ({
id: 'entry-1',
...input,
lines: input.lines,
})
),
}))
// Mock currency-utils with real logic
vi.mock('../currency-utils', () => ({
resolveSekAmount: vi.fn().mockImplementation(
(amount: number, amountSek: number | null, currency: string | null, exchangeRate: number | null) => {
if (!currency || currency === 'SEK') return amount
if (amountSek != null) return Math.round(amountSek * 100) / 100
if (exchangeRate != null && exchangeRate > 0) return Math.round(amount * exchangeRate * 100) / 100
return amount
}
),
buildCurrencyMetadata: vi.fn().mockImplementation(
(currency: string | null, amountInCurrency: number | null | undefined, exchangeRate: number | null) => {
if (!currency || currency === 'SEK') return {}
return {
...(currency ? { currency } : {}),
...(amountInCurrency != null ? { amount_in_currency: amountInCurrency } : {}),
...(exchangeRate != null && exchangeRate > 0 ? { exchange_rate: exchangeRate } : {}),
}
}
),
}))
// Mock vat-entries with real logic
vi.mock('../vat-entries', () => ({
generateInputVatLine: vi.fn().mockImplementation(
(totalAmount: number, vatRate: number = 0.25) => {
if (vatRate === 0) return null
const vatAmount = Math.round((totalAmount * vatRate) / (1 + vatRate) * 100) / 100
return {
account_number: '2641',
debit_amount: vatAmount,
credit_amount: 0,
line_description: `Ingående moms ${vatRate * 100}%`,
}
}
),
generateReverseChargeLines: vi.fn().mockImplementation(
(baseAmount: number, vatRate: number = 0.25) => {
const vatAmount = Math.round(baseAmount * vatRate * 100) / 100
let outputAccount: string
switch (vatRate) {
case 0.12: outputAccount = '2624'; break
case 0.06: outputAccount = '2634'; break
default: outputAccount = '2614'; break
}
return [
{ account_number: '2645', debit_amount: vatAmount, credit_amount: 0, line_description: `Fiktiv ingående moms` },
{ account_number: outputAccount, debit_amount: 0, credit_amount: vatAmount, line_description: `Fiktiv utgående moms` },
]
}
),
extractNetAmount: vi.fn().mockImplementation(
(totalAmount: number, vatRate: number) => {
if (vatRate === 0) return totalAmount
return Math.round((totalAmount / (1 + vatRate)) * 100) / 100
}
),
extractVatAmount: vi.fn().mockImplementation(
(totalAmount: number, vatRate: number) => {
if (vatRate === 0) return 0
return Math.round((totalAmount - totalAmount / (1 + vatRate)) * 100) / 100
}
),
}))
const { createJournalEntry, findFiscalPeriod } = await import('../engine')
const mockedCreateEntry = vi.mocked(createJournalEntry)
const mockedFindFiscalPeriod = vi.mocked(findFiscalPeriod)
const { createTransactionJournalEntry, buildDomesticExpenseLines } = await import('../transaction-entries')
function makeMappingResult(overrides: Partial<MappingResult> = {}): MappingResult {
return {
rule: null,
debit_account: '5410',
credit_account: '1930',
risk_level: 'LOW',
confidence: 0.95,
requires_review: false,
default_private: false,
vat_lines: [],
description: 'Test mapping',
...overrides,
}
}
/** Balance check helper */
function assertBalanced(input: CreateJournalEntryInput) {
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBeCloseTo(totalCredit, 2)
expect(totalDebit).toBeGreaterThan(0)
}
describe('createTransactionJournalEntry', () => {
beforeEach(() => {
vi.clearAllMocks()
mockedFindFiscalPeriod.mockResolvedValue('period-1')
})
// --- Validation ---
it('throws when debit_account is missing', async () => {
const tx = makeTransaction()
const mapping = makeMappingResult({ debit_account: '' })
await expect(
createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
).rejects.toThrow('Invalid mapping result')
})
it('throws when credit_account is missing', async () => {
const tx = makeTransaction()
const mapping = makeMappingResult({ credit_account: '' })
await expect(
createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
).rejects.toThrow('Invalid mapping result')
})
// --- Fiscal period ---
it('returns null when no fiscal period found', async () => {
mockedFindFiscalPeriod.mockResolvedValue(null)
const tx = makeTransaction()
const mapping = makeMappingResult()
const result = await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
expect(result).toBeNull()
expect(mockedCreateEntry).not.toHaveBeenCalled()
})
// --- Private expense ---
it('creates private expense entry for EF (2013)', async () => {
const tx = makeTransaction({ amount: -500, description: 'Lunch privat' })
const mapping = makeMappingResult({
debit_account: '2013',
credit_account: '1930',
default_private: true,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(2)
const debit2013 = input.lines.find(l => l.account_number === '2013')
expect(debit2013?.debit_amount).toBe(500)
expect(debit2013?.credit_amount).toBe(0)
expect(debit2013?.line_description).toMatch(/^Privat:/)
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(500)
expect(credit1930?.debit_amount).toBe(0)
assertBalanced(input)
})
it('creates private expense entry for AB (2893)', async () => {
const tx = makeTransaction({ amount: -1200, description: 'Privat uttag' })
const mapping = makeMappingResult({
debit_account: '2893',
credit_account: '1930',
default_private: true,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(2)
const debit2893 = input.lines.find(l => l.account_number === '2893')
expect(debit2893?.debit_amount).toBe(1200)
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(1200)
assertBalanced(input)
})
// --- Business expense ---
it('creates business expense without VAT (2 lines)', async () => {
const tx = makeTransaction({ amount: -299, description: 'Office supplies' })
const mapping = makeMappingResult({
debit_account: '5410',
credit_account: '1930',
vat_lines: [],
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(2)
const debit5410 = input.lines.find(l => l.account_number === '5410')
expect(debit5410?.debit_amount).toBe(299)
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(299)
assertBalanced(input)
})
it('creates business expense with 25% input VAT (3 lines)', async () => {
const tx = makeTransaction({ amount: -1250, description: 'Software license' })
const vatLines: VatJournalLine[] = [
{ account_number: '2641', debit_amount: 250, credit_amount: 0, description: 'Ingående moms 25%' },
]
const mapping = makeMappingResult({
debit_account: '5410',
credit_account: '1930',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(3)
const debit2641 = input.lines.find(l => l.account_number === '2641')
expect(debit2641?.debit_amount).toBe(250)
const debit5410 = input.lines.find(l => l.account_number === '5410')
expect(debit5410?.debit_amount).toBe(1000) // 1250 - 250 VAT
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(1250)
assertBalanced(input)
})
it('nets the expense line against an underlag VAT override below the rate amount', async () => {
// Restaurant receipt 415.80 kr incl. dricks: the document's 12% VAT is
// 42.43 kr (not rate-extraction 44.55) because dricks carries no moms.
// The expense line must absorb the difference so the entry balances.
const tx = makeTransaction({ amount: -415.80, description: 'LEONH Repr' })
const vatLines: VatJournalLine[] = [
{ account_number: '2641', debit_amount: 42.43, credit_amount: 0, description: 'Ingående moms (enligt underlag)' },
]
const mapping = makeMappingResult({
debit_account: '6071',
credit_account: '1930',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(3)
const debit2641 = input.lines.find(l => l.account_number === '2641')
expect(debit2641?.debit_amount).toBe(42.43)
const debit6071 = input.lines.find(l => l.account_number === '6071')
expect(debit6071?.debit_amount).toBe(373.37) // 415.80 - 42.43
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(415.80)
assertBalanced(input)
})
it('handles VAT rounding precision on expense', async () => {
const tx = makeTransaction({ amount: -997.50, description: 'Expense with rounding' })
const vatLines: VatJournalLine[] = [
{ account_number: '2641', debit_amount: 199.50, credit_amount: 0, description: 'Ingående moms 25%' },
]
const mapping = makeMappingResult({
debit_account: '5410',
credit_account: '1930',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
const debit5410 = input.lines.find(l => l.account_number === '5410')
// net = Math.round((997.50 - 199.50) * 100) / 100 = 798
expect(debit5410?.debit_amount).toBe(Math.round((997.50 - 199.50) * 100) / 100)
assertBalanced(input)
})
it('creates expense with EU reverse charge (2645/2614)', async () => {
const tx = makeTransaction({ amount: -5000, description: 'EU SaaS service' })
const vatLines: VatJournalLine[] = [
{ account_number: '2645', debit_amount: 1250, credit_amount: 0, description: 'Fiktiv ingående moms' },
{ account_number: '2614', debit_amount: 0, credit_amount: 1250, description: 'Fiktiv utgående moms' },
]
const mapping = makeMappingResult({
debit_account: '5410',
credit_account: '1930',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
const debit2645 = input.lines.find(l => l.account_number === '2645')
expect(debit2645?.debit_amount).toBe(1250)
const credit2614 = input.lines.find(l => l.account_number === '2614')
expect(credit2614?.credit_amount).toBe(1250)
// Expense: For reverse charge, no 2641 line means netAmount = absAmount - 0 = 5000
const debit5410 = input.lines.find(l => l.account_number === '5410')
expect(debit5410?.debit_amount).toBe(5000)
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.credit_amount).toBe(5000)
assertBalanced(input)
})
// --- Income ---
it('creates income entry without VAT (2 lines)', async () => {
const tx = makeTransaction({ amount: 8000, description: 'Export revenue' })
const mapping = makeMappingResult({
debit_account: '1930',
credit_account: '3001',
vat_lines: [],
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.lines).toHaveLength(2)
const debit1930 = input.lines.find(l => l.account_number === '1930')
expect(debit1930?.debit_amount).toBe(8000)
const credit3001 = input.lines.find(l => l.account_number === '3001')
expect(credit3001?.credit_amount).toBe(8000)
assertBalanced(input)
})
it('creates income entry with output VAT', async () => {
const tx = makeTransaction({ amount: 12500, description: 'Sales income' })
const vatLines: VatJournalLine[] = [
{ account_number: '2611', debit_amount: 0, credit_amount: 2500, description: 'Utgående moms 25%' },
]
const mapping = makeMappingResult({
debit_account: '1930',
credit_account: '3001',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
const debit1930 = input.lines.find(l => l.account_number === '1930')
expect(debit1930?.debit_amount).toBe(12500)
const credit3001 = input.lines.find(l => l.account_number === '3001')
expect(credit3001?.credit_amount).toBe(10000) // 12500 - 2500 VAT
const credit2611 = input.lines.find(l => l.account_number === '2611')
expect(credit2611?.credit_amount).toBe(2500)
assertBalanced(input)
})
it('handles VAT rounding precision on income', async () => {
const tx = makeTransaction({ amount: 333.33, description: 'Small sale' })
const vatLines: VatJournalLine[] = [
{ account_number: '2611', debit_amount: 0, credit_amount: 66.67, description: 'Utgående moms 25%' },
]
const mapping = makeMappingResult({
debit_account: '1930',
credit_account: '3001',
vat_lines: vatLines,
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
const credit3001 = input.lines.find(l => l.account_number === '3001')
// net = Math.round((333.33 - 66.67) * 100) / 100 = 266.66
expect(credit3001?.credit_amount).toBe(Math.round((333.33 - 66.67) * 100) / 100)
assertBalanced(input)
})
// --- Foreign currency ---
it('adds currency metadata to 1930 line for EUR expense', async () => {
const tx = makeTransaction({
amount: -100,
currency: 'EUR',
amount_sek: null,
exchange_rate: 11.50,
description: 'EUR purchase',
})
const mapping = makeMappingResult({
debit_account: '5410',
credit_account: '1930',
vat_lines: [],
})
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
const credit1930 = input.lines.find(l => l.account_number === '1930')
expect(credit1930?.currency).toBe('EUR')
expect(credit1930?.amount_in_currency).toBe(100)
expect(credit1930?.exchange_rate).toBe(11.50)
// All amounts in SEK
expect(credit1930?.credit_amount).toBe(1150) // 100 * 11.50
const debit5410 = input.lines.find(l => l.account_number === '5410')
expect(debit5410?.debit_amount).toBe(1150)
assertBalanced(input)
})
it('SEK transaction has no currency metadata', async () => {
const tx = makeTransaction({ amount: -500, currency: 'SEK' })
const mapping = makeMappingResult()
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
for (const line of input.lines) {
expect(line.currency).toBeUndefined()
expect(line.amount_in_currency).toBeUndefined()
expect(line.exchange_rate).toBeUndefined()
}
})
// --- Metadata ---
it('sets source_type and source_id correctly', async () => {
const tx = makeTransaction({ id: 'tx-abc-123', amount: -100 })
const mapping = makeMappingResult()
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.source_type).toBe('bank_transaction')
expect(input.source_id).toBe('tx-abc-123')
})
it('uses transaction.date as entry_date', async () => {
const tx = makeTransaction({ date: '2024-09-15', amount: -100 })
const mapping = makeMappingResult()
await createTransactionJournalEntry(null as never, 'company-1', 'user-1', tx, mapping)
const input = mockedCreateEntry.mock.calls[0][3]
expect(input.entry_date).toBe('2024-09-15')
})
})
describe('buildDomesticExpenseLines', () => {
it('25% VAT: 3 lines (expense net + 2641 + 1930)', () => {
const lines = buildDomesticExpenseLines(1250, '5410', 'Office supplies', 0.25)
expect(lines).toHaveLength(3)
const expense = lines.find(l => l.account_number === '5410')
expect(expense?.debit_amount).toBe(1000) // 1250 / 1.25
const vat = lines.find(l => l.account_number === '2641')
expect(vat?.debit_amount).toBe(250) // 1250 - 1000
const bank = lines.find(l => l.account_number === '1930')
expect(bank?.credit_amount).toBe(1250)
const totalDebit = lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBeCloseTo(totalCredit, 2)
})
it('12% VAT: correct amounts', () => {
const lines = buildDomesticExpenseLines(1120, '5400', 'Food supplies', 0.12)
expect(lines).toHaveLength(3)
const expense = lines.find(l => l.account_number === '5400')
expect(expense?.debit_amount).toBe(1000) // 1120 / 1.12
const vat = lines.find(l => l.account_number === '2641')
expect(vat?.debit_amount).toBe(120) // 1120 - 1000
const bank = lines.find(l => l.account_number === '1930')
expect(bank?.credit_amount).toBe(1120)
const totalDebit = lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBeCloseTo(totalCredit, 2)
})
it('vatRate=0: 2 lines, no 2641', () => {
const lines = buildDomesticExpenseLines(500, '5410', 'No VAT expense', 0)
expect(lines).toHaveLength(2)
const expense = lines.find(l => l.account_number === '5410')
expect(expense?.debit_amount).toBe(500)
const bank = lines.find(l => l.account_number === '1930')
expect(bank?.credit_amount).toBe(500)
const vatLine = lines.find(l => l.account_number === '2641')
expect(vatLine).toBeUndefined()
const totalDebit = lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBe(totalCredit)
})
it('negative amount uses Math.abs', () => {
const lines = buildDomesticExpenseLines(-750, '5410', 'Negative test', 0)
expect(lines).toHaveLength(2)
const expense = lines.find(l => l.account_number === '5410')
expect(expense?.debit_amount).toBe(750)
const bank = lines.find(l => l.account_number === '1930')
expect(bank?.credit_amount).toBe(750)
// All amounts positive
for (const line of lines) {
expect(line.debit_amount).toBeGreaterThanOrEqual(0)
expect(line.credit_amount).toBeGreaterThanOrEqual(0)
}
})
})