Files
accounted/lib/reports/__tests__/balansrapport.test.ts
T
Jakob WennbergandClaude Opus 4.7 4822649c26 feat(reports): split operational Resultatrapport/Balansrapport from formal Räkning views (#363)
* feat(reports): add Resultatrapport and Balansrapport (operational reports)

Per user feedback (Anders Gengård): Swedish accounting practice (BFL 6 kap,
ÅRL Bilaga 1-3) distinguishes operational reports (Resultatrapport /
Balansrapport, used during the year for reconciliation, account-level
detail with numbers) from formal statements (Resultaträkning /
Balansräkning, part of årsbokslut/årsredovisning, ÅRL uppställningsform,
no account numbers). Until now gnubok only had a hybrid version under
"Bokslut" that did neither well.

This adds the operational pair as their own reports under a new "Löpande
rapporter" section on the Reports page. Resultaträkning and Balansräkning
under "Bokslut" are kept untouched (their yellow ÅRL 2:7 § draft
disclaimer stays — it's appropriate there). Saldobalans moves into the
new operational section.

Both new generators reuse generateTrialBalance — Balansrapport filters to
classes 1-2 with IB/UB/förändring; Resultatrapport filters to classes 3-8,
calls trial balance for the previous period (via fiscal_periods.previous_period_id)
and joins per account so the user sees current vs prior side-by-side.
Account 8999 is excluded the same way generateIncomeStatement excludes it.

13 new unit tests cover grouping, prior-period join, account-class
exclusions, zero-row filtering, and the missing-period fallback.

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

* feat(reports): show Balanscheck on Balansrapport

Addresses the most material PR review finding (raised by both the Swedish
compliance bot and Greptile): BalansrapportReport returned total_assets_ub
and total_equity_liabilities_ub but the UI never displayed them, so the
user could not verify that books balance.

generateBalansrapport now also returns:
  - beraknat_resultat = total_assets - total_eq_liab (Fortnox/Visma
    convention: residual on the balance side; equals current-year P&L
    during a running year, drops to 0 once year-end closing posts
    8999 → 2099)
  - is_balanced from the underlying trial balance — that's the meaningful
    integrity check (a missing IB row or continuity break shows up as an
    imbalanced TB)

UI gets a Balanscheck card showing the three totals plus a Balanserar /
Balanserar ej verdict.

Other PR review items (Föregående header polish, inline subtotal diff
rounding, class-8 filter scope, 2099 caveat, terminology disclaimer) are
non-blocking and deferred.

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

* fix(reports): correct BAS class labels and add bokslut caveat

Addresses three findings from the Swedish compliance bot's review of the
prior commit:

  - Class 6 label dropped the informal '(forts.)' marker — '6 Övriga
    externa kostnader' is the BAS-correct heading.
  - Balansrapport class 2 label expanded to 'Eget kapital, obeskattade
    reserver, avsättningar och skulder' to match ÅRL Bilaga 1. The old
    label hid 21xx (periodiseringsfond, överavskrivningar) and 22xx
    (avsättningar) which matter for AB users.
  - Beräknat resultat row in the Balanscheck card now reads 'Beräknat
    resultat (ej bokslutsjusterat)' so the residual is not misread as
    a confirmed profit figure pre-closing.

Skipped the bot's 8910/8999 finding: 8910 is 'Skatt på årets resultat'
(regular tax expense), not a closing account; 8999 is the only BAS
closing account, so the existing exclusion is correct.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 14:16:17 +02:00

292 lines
9.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('../trial-balance', () => ({
generateTrialBalance: vi.fn(),
}))
import { generateBalansrapport } from '../balansrapport'
import { generateTrialBalance } from '../trial-balance'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { TrialBalanceRow } from '@/types'
const mockTrialBalance = vi.mocked(generateTrialBalance)
beforeEach(() => {
vi.clearAllMocks()
})
function makeRow(overrides: Partial<TrialBalanceRow>): TrialBalanceRow {
return {
account_number: '1930',
account_name: 'Bank',
account_class: 1,
opening_debit: 0,
opening_credit: 0,
period_debit: 0,
period_credit: 0,
closing_debit: 0,
closing_credit: 0,
...overrides,
}
}
function tb(rows: TrialBalanceRow[]) {
const totalDebit = rows.reduce((s, r) => s + r.closing_debit, 0)
const totalCredit = rows.reduce((s, r) => s + r.closing_credit, 0)
return {
rows,
totalDebit: Math.round(totalDebit * 100) / 100,
totalCredit: Math.round(totalCredit * 100) / 100,
isBalanced: Math.abs(totalDebit - totalCredit) < 0.01,
}
}
describe('generateBalansrapport', () => {
it('groups balance accounts into class 1 (assets) and class 2 (equity & liabilities)', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
mockTrialBalance.mockResolvedValueOnce(
tb([
makeRow({
account_number: '1930',
account_name: 'Bank',
account_class: 1,
opening_debit: 50000,
opening_credit: 0,
closing_debit: 75000,
closing_credit: 0,
}),
makeRow({
account_number: '1510',
account_name: 'Kundfordringar',
account_class: 1,
opening_debit: 10000,
opening_credit: 0,
closing_debit: 12500,
closing_credit: 0,
}),
makeRow({
account_number: '2440',
account_name: 'Lev.skulder',
account_class: 2,
opening_credit: 8000,
opening_debit: 0,
closing_credit: 15000,
closing_debit: 0,
}),
makeRow({
account_number: '2099',
account_name: 'Årets resultat',
account_class: 2,
opening_credit: 52000,
opening_debit: 0,
closing_credit: 72500,
closing_debit: 0,
}),
])
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.groups).toHaveLength(2)
expect(report.groups[0].class).toBe(1)
expect(report.groups[1].class).toBe(2)
// Assets sorted by account number
const assets = report.groups[0]
expect(assets.rows.map((r) => r.account_number)).toEqual(['1510', '1930'])
expect(assets.rows[1]).toEqual({
account_number: '1930',
account_name: 'Bank',
ib: 50000,
ub: 75000,
period_change: 25000,
})
expect(assets.subtotal_ib).toBe(60000)
expect(assets.subtotal_ub).toBe(87500)
// Equity & liabilities — credit-positive
const equity = report.groups[1]
expect(equity.rows[0]).toEqual({
account_number: '2099',
account_name: 'Årets resultat',
ib: 52000,
ub: 72500,
period_change: 20500,
})
expect(equity.subtotal_ub).toBe(87500)
expect(report.total_assets_ub).toBe(87500)
expect(report.total_equity_liabilities_ub).toBe(87500)
// 2099 already absorbs prior+current result, residual is 0
expect(report.beraknat_resultat).toBe(0)
expect(report.is_balanced).toBe(true)
})
it('beräknat resultat equals total_assets - total_eq_liab during running year', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
// Mid-year, before any 2099 update: assets 80 000, liabs 30 000.
// P&L (3001 - 5010) = 50 000 sits in P&L accounts and equals the residual.
mockTrialBalance.mockResolvedValueOnce(
tb([
makeRow({ account_number: '1930', account_name: 'Bank', account_class: 1, closing_debit: 80000 }),
makeRow({ account_number: '2440', account_name: 'Lev.skuld', account_class: 2, closing_credit: 30000 }),
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 70000 }),
makeRow({ account_number: '5010', account_name: 'Rent', account_class: 5, closing_debit: 20000 }),
])
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.total_assets_ub).toBe(80000)
expect(report.total_equity_liabilities_ub).toBe(30000)
expect(report.beraknat_resultat).toBe(50000)
// Trial balance still balances — double-entry guarantees this.
expect(report.is_balanced).toBe(true)
})
it('is_balanced reflects trial balance balance state', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
// Manually construct an unbalanced trial balance (in practice the DB
// trigger prevents this, but a continuity break or missing IB row would
// surface here).
mockTrialBalance.mockResolvedValueOnce({
rows: [
makeRow({ account_number: '1930', account_name: 'Bank', account_class: 1, closing_debit: 80000 }),
makeRow({ account_number: '2440', account_name: 'Lev.skuld', account_class: 2, closing_credit: 70000 }),
],
totalDebit: 80000,
totalCredit: 70000,
isBalanced: false,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.is_balanced).toBe(false)
})
it('ignores P&L accounts (class 3-8)', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
mockTrialBalance.mockResolvedValueOnce(
tb([
makeRow({ account_number: '1930', account_name: 'Bank', account_class: 1, closing_debit: 10000 }),
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 50000 }),
makeRow({ account_number: '5010', account_name: 'Rent', account_class: 5, closing_debit: 8000 }),
makeRow({ account_number: '8410', account_name: 'Räntekostnad', account_class: 8, closing_debit: 100 }),
])
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.groups).toHaveLength(1)
expect(report.groups[0].class).toBe(1)
expect(report.groups[0].rows.map((r) => r.account_number)).toEqual(['1930'])
})
it('drops accounts where both IB and UB are zero', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
mockTrialBalance.mockResolvedValueOnce(
tb([
makeRow({ account_number: '1930', account_name: 'Bank', account_class: 1, closing_debit: 10000 }),
makeRow({ account_number: '1940', account_name: 'Inactive', account_class: 1 }),
])
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.groups[0].rows).toHaveLength(1)
expect(report.groups[0].rows[0].account_number).toBe('1930')
})
it('handles accounts that closed during the period (UB=0, IB>0)', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
mockTrialBalance.mockResolvedValueOnce(
tb([
makeRow({
account_number: '1510',
account_name: 'Kundfordran (betald)',
account_class: 1,
opening_debit: 10000,
period_credit: 10000,
closing_debit: 10000,
closing_credit: 10000,
}),
])
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.groups[0].rows[0]).toEqual({
account_number: '1510',
account_name: 'Kundfordran (betald)',
ib: 10000,
ub: 0,
period_change: -10000,
})
})
it('throws when fiscal period not found', async () => {
const q = createQueuedMockSupabase()
q.enqueue({ data: null, error: null })
await expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
generateBalansrapport(q.supabase as any, 'company-1', 'missing')
).rejects.toThrow('Fiscal period not found')
})
it('returns empty groups when there are no balance accounts at all', async () => {
const q = createQueuedMockSupabase()
q.enqueue({
data: { period_start: '2026-01-01', period_end: '2026-12-31' },
error: null,
})
mockTrialBalance.mockResolvedValueOnce(tb([]))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const report = await generateBalansrapport(q.supabase as any, 'company-1', 'period-1')
expect(report.groups).toEqual([])
expect(report.total_assets_ub).toBe(0)
expect(report.total_equity_liabilities_ub).toBe(0)
expect(report.beraknat_resultat).toBe(0)
expect(report.is_balanced).toBe(true)
})
})