feat(reconciliation): account-keyed engine: one bridge for bank and skattekonto (#1813)
* feat(reconciliation): skattekonto bridge engine, sync-time twin proposals, account-keyed facade The engine half of the reconciliation page (design: Avstämningsmotorn). - lib/reconciliation/skattekonto-reconciliation.ts: getSkattekontoReconciliationStatus anchors at the saldo snapshot and returns the bridge (saldo hos Skatteverket, händelser som saknas, 1630-rader utan händelse, ignorerade, ingående skillnad, bokfört), the item buckets the page shows (proposed, unmatched external, unmatched ledger, matched, ignored, upcoming), opening_difference, unexplained_difference (0,00 by construction when data is consistent), dead-link handling (a link to a reversed/draft entry counts as unlinked and is flagged), awaiting_external for ledger lines within 5 days of the snapshot, staleness, and a window that scopes item lists without hiding older rows. Core reads skattekonto_transactions and the extension's snapshot row directly; no @/extensions import. - lib/reconciliation/gl-balance.ts: one ledger-balance helper with the trial-balance predicate status IN (posted, reversed). The drift check summed posted only, which misstated 1630 for any company with a storno on the account; skattekonto-drift.ts now delegates to the helper. - Proposals at sync: migration 20260823120000 adds suggested_journal_entry_id / suggested_at (ON DELETE SET NULL, partial index on open rows); the sync calls refreshSkattekontoProposals after the upsert. findMatchSuggestionsBulk now assigns one-to-one across rows (AGI period first, then nearest date) and falls back to an entry whose 1630 lines net to the amount (split lines); a proposal is never a link. - lib/reconciliation/service.ts + schemas.ts: the account-keyed facade (bank:<cash_account_id> | skattekonto | manual:NNNN) with listReconciliationAccounts (enabled cash accounts folded per IBAN, skattekonto when configured) and getAccountStatus dispatching to the bank engine or the new one; shared Zod shapes for the v1 registry, MCP schemas and the UI (PR 2). Tests: identity on a mixed fixture, storno pair, stale snapshot, awaiting window, window scoping, failed ledger read, live-linked entries never proposed; matcher one-to-one and split-line cases; proposal refresh writes/clears; service dedupe and dispatch. No UI in this PR. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): roundOre instead of inline öre rounding (guard ratchet) The antipattern ratchet counts Math.round(x*100)/100; the new engine used it in five places. Switch to roundOre from @/lib/money and ratchet the baseline down by the three occurrences this removes net of the matcher rewrite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
7cf15a105f
commit
0a8544e0cb
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { LEDGER_BALANCE_STATUSES, sumAccountBalance } from '../gl-balance'
|
||||
|
||||
/**
|
||||
* The two-step entry-lines fetch (lib/bookkeeping/entry-lines.ts) reads the
|
||||
* parent entries first, then the bare lines keyed by journal_entry_id.
|
||||
*/
|
||||
function enqueueGl(
|
||||
enqueue: (r: { data?: unknown; error?: unknown }) => void,
|
||||
rows: Array<{ debit_amount: number; credit_amount: number }>,
|
||||
) {
|
||||
enqueue({ data: rows.length ? [{ id: 'entry-1' }] : [] })
|
||||
if (rows.length === 0) return
|
||||
enqueue({
|
||||
data: rows.map((r, i) => ({ id: `line-${i}`, journal_entry_id: 'entry-1', ...r })),
|
||||
})
|
||||
}
|
||||
|
||||
describe('sumAccountBalance', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('sums debit - credit over posted AND reversed entries (the trial-balance predicate)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueGl(enqueue, [
|
||||
{ debit_amount: 1000, credit_amount: 0 },
|
||||
{ debit_amount: 0, credit_amount: 250.5 },
|
||||
])
|
||||
|
||||
const sum = await sumAccountBalance(supabase as never, 'company-1', '1630', {
|
||||
cutoffDate: '2026-08-20',
|
||||
})
|
||||
|
||||
expect(sum).toBe(749.5)
|
||||
const inCalls = findCalls('journal_entries', 'in')
|
||||
expect(inCalls).toContainEqual(['status', [...LEDGER_BALANCE_STATUSES]])
|
||||
expect(LEDGER_BALANCE_STATUSES).toEqual(['posted', 'reversed'])
|
||||
// The old drift predicate was .eq('status', 'posted'): it must be gone.
|
||||
expect(findCalls('journal_entries', 'eq')).not.toContainEqual(['status', 'posted'])
|
||||
expect(findCalls('journal_entries', 'lte')).toContainEqual(['entry_date', '2026-08-20'])
|
||||
expect(findCalls('journal_entry_lines', 'eq')).toContainEqual(['account_number', '1630'])
|
||||
})
|
||||
|
||||
it('applies beforeDate as an exclusive upper bound', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueGl(enqueue, [{ debit_amount: 10, credit_amount: 0 }])
|
||||
|
||||
await sumAccountBalance(supabase as never, 'company-1', '1630', { beforeDate: '2025-01-17' })
|
||||
|
||||
expect(findCalls('journal_entries', 'lt')).toContainEqual(['entry_date', '2025-01-17'])
|
||||
})
|
||||
|
||||
it('returns 0 when nothing is booked on the account', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueGl(enqueue, [])
|
||||
expect(await sumAccountBalance(supabase as never, 'company-1', '1630')).toBe(0)
|
||||
})
|
||||
|
||||
it('returns null, never 0, when the read fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ error: { message: 'statement timeout' } })
|
||||
expect(await sumAccountBalance(supabase as never, 'company-1', '1630')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,240 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const skattekontoStatusMock = vi.fn()
|
||||
const bankStatusMock = vi.fn()
|
||||
|
||||
vi.mock('../skattekonto-reconciliation', () => ({
|
||||
getSkattekontoReconciliationStatus: (...args: unknown[]) => skattekontoStatusMock(...args),
|
||||
}))
|
||||
vi.mock('../bank-reconciliation', () => ({
|
||||
getReconciliationStatus: (...args: unknown[]) => bankStatusMock(...args),
|
||||
}))
|
||||
|
||||
import { bankAccountKey, parseAccountKey } from '../schemas'
|
||||
import { getAccountStatus, listReconciliationAccounts } from '../service'
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const ID_A = '11111111-1111-4111-8111-111111111111'
|
||||
const ID_B = '22222222-2222-4222-8222-222222222222'
|
||||
const ID_C = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
function cashAccount(id: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
name: `Konto ${id.slice(0, 2)}`,
|
||||
ledger_account: '1930',
|
||||
currency: 'SEK',
|
||||
iban: null,
|
||||
enabled: true,
|
||||
is_primary: false,
|
||||
source: 'enable_banking',
|
||||
bank_connection_id: 'conn-1',
|
||||
updated_at: '2026-08-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function bankStatus(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
currency: 'SEK',
|
||||
bank_transaction_total: 100,
|
||||
ignored_transaction_total: 0,
|
||||
ignored_transaction_count: 0,
|
||||
gl_1930_balance: 100,
|
||||
gl_1930_period_movement: 100,
|
||||
gl_1930_opening_balance: 0,
|
||||
gl_1930_correction_adjustment: 0,
|
||||
difference: 0,
|
||||
is_reconciled: true,
|
||||
matched_count: 3,
|
||||
unmatched_transaction_count: 0,
|
||||
unmatched_transaction_total: 0,
|
||||
unmatched_gl_line_count: 0,
|
||||
unmatched_gl_line_total: 0,
|
||||
unexplained_difference: 0,
|
||||
unconvertible_gl_line_count: 0,
|
||||
not_reconcilable_reason: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('account keys', () => {
|
||||
it('parses the three kinds and rejects anything else', () => {
|
||||
expect(parseAccountKey(bankAccountKey(ID_A))).toEqual({ kind: 'bank', cashAccountId: ID_A })
|
||||
expect(parseAccountKey('skattekonto')).toEqual({ kind: 'skattekonto' })
|
||||
expect(parseAccountKey('manual:1910')).toEqual({ kind: 'manual', accountNumber: '1910' })
|
||||
expect(parseAccountKey('bank:not-a-uuid')).toBeNull()
|
||||
expect(parseAccountKey('1930')).toBeNull()
|
||||
expect(parseAccountKey('')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('listReconciliationAccounts', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
skattekontoStatusMock.mockReset()
|
||||
bankStatusMock.mockReset()
|
||||
})
|
||||
|
||||
it('lists enabled cash accounts, folds reconnect duplicates by IBAN, and appends the skattekonto when configured', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: [
|
||||
cashAccount(ID_A, { is_primary: true, iban: 'SE1', updated_at: '2026-08-10T00:00:00Z' }),
|
||||
cashAccount(ID_B, { iban: 'SE1', updated_at: '2026-06-01T00:00:00Z' }),
|
||||
cashAccount(ID_C, { ledger_account: '1931', iban: 'SE2' }),
|
||||
],
|
||||
})
|
||||
// latestBankSyncAt per account (withStatus=false skips bankStatus): three maybeSingle reads
|
||||
enqueue({ data: { created_at: '2026-08-19T06:00:00Z' } })
|
||||
enqueue({ data: { created_at: '2026-06-01T06:00:00Z' } })
|
||||
enqueue({ data: null })
|
||||
skattekontoStatusMock.mockResolvedValue({
|
||||
account_key: 'skattekonto',
|
||||
kind: 'skattekonto',
|
||||
account_number: '1630',
|
||||
currency: 'SEK',
|
||||
as_of: '2026-08-20T04:00:00.000Z',
|
||||
stale: false,
|
||||
is_reconciled: false,
|
||||
unexplained_difference: 0,
|
||||
counts: { proposed: 2, unmatched_external: 3, unmatched_ledger: 1, matched: 41, ignored: 0 },
|
||||
skattekonto: { fetched_at: '2026-08-20T04:00:00.000Z' },
|
||||
})
|
||||
|
||||
const accounts = await listReconciliationAccounts(supabase as never, COMPANY, {
|
||||
today: '2026-08-20',
|
||||
withStatus: false,
|
||||
})
|
||||
|
||||
expect(accounts.map((a) => a.account_key)).toEqual([
|
||||
bankAccountKey(ID_A),
|
||||
bankAccountKey(ID_B),
|
||||
bankAccountKey(ID_C),
|
||||
'skattekonto',
|
||||
])
|
||||
const byKey = Object.fromEntries(accounts.map((a) => [a.account_key, a]))
|
||||
// The older duplicate is marked, never dropped.
|
||||
expect(byKey[bankAccountKey(ID_B)].superseded_by).toBe(bankAccountKey(ID_A))
|
||||
expect(byKey[bankAccountKey(ID_A)].superseded_by).toBeNull()
|
||||
expect(byKey[bankAccountKey(ID_C)].superseded_by).toBeNull()
|
||||
// Sync age drives staleness (7 days).
|
||||
expect(byKey[bankAccountKey(ID_A)].source).toMatchObject({ type: 'psd2', stale: false })
|
||||
expect(byKey[bankAccountKey(ID_B)].source.stale).toBe(true)
|
||||
expect(byKey[bankAccountKey(ID_C)].source).toMatchObject({ synced_at: null, stale: true })
|
||||
expect(byKey[bankAccountKey(ID_A)].status).toBeNull()
|
||||
// Skattekonto row carries the logo and the open counts.
|
||||
expect(byKey.skattekonto).toMatchObject({
|
||||
logo_url: '/logos/skatteverket_color.svg',
|
||||
source: { type: 'skatteverket_api', stale: false },
|
||||
status: { state: 'open', open_counts: { proposed: 2, unmatched_external: 3, unmatched_ledger: 1 } },
|
||||
})
|
||||
})
|
||||
|
||||
it('omits the skattekonto when the company has neither snapshot nor rows', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [cashAccount(ID_A, { is_primary: true })] })
|
||||
enqueue({ data: null })
|
||||
skattekontoStatusMock.mockResolvedValue(null)
|
||||
|
||||
const accounts = await listReconciliationAccounts(supabase as never, COMPANY, {
|
||||
today: '2026-08-20',
|
||||
withStatus: false,
|
||||
})
|
||||
expect(accounts.map((a) => a.kind)).toEqual(['bank'])
|
||||
})
|
||||
|
||||
it('computes the bank status through the existing engine with the account scope and maps it to the common shape', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [cashAccount(ID_A, { is_primary: true, currency: 'SEK' })] })
|
||||
bankStatusMock.mockResolvedValue(bankStatus({ unmatched_transaction_count: 2, unmatched_transaction_total: -1046, is_reconciled: false }))
|
||||
enqueue({ data: { created_at: '2026-08-20T06:00:00Z' } }) // latestBankSyncAt inside bankStatus
|
||||
enqueue({ data: { created_at: '2026-08-20T06:00:00Z' } }) // latestBankSyncAt for the account row
|
||||
skattekontoStatusMock.mockResolvedValue(null)
|
||||
|
||||
const accounts = await listReconciliationAccounts(supabase as never, COMPANY, {
|
||||
today: '2026-08-20',
|
||||
windowFrom: '2026-01-01',
|
||||
windowTo: '2026-08-20',
|
||||
})
|
||||
|
||||
expect(bankStatusMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
COMPANY,
|
||||
'2026-01-01',
|
||||
'2026-08-20',
|
||||
'1930',
|
||||
'SEK',
|
||||
ID_A,
|
||||
true,
|
||||
)
|
||||
expect(accounts[0].status).toMatchObject({
|
||||
state: 'open',
|
||||
open_counts: { proposed: 0, unmatched_external: 2, unmatched_ledger: 0 },
|
||||
unexplained_difference: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAccountStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
skattekontoStatusMock.mockReset()
|
||||
bankStatusMock.mockReset()
|
||||
})
|
||||
|
||||
it('returns null for an invalid key and for an unknown cash account', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
expect(await getAccountStatus(supabase as never, COMPANY, 'nope')).toBeNull()
|
||||
enqueue({ data: null })
|
||||
expect(await getAccountStatus(supabase as never, COMPANY, bankAccountKey(ID_A))).toBeNull()
|
||||
})
|
||||
|
||||
it('dispatches skattekonto to its engine with the window', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
skattekontoStatusMock.mockResolvedValue({ account_key: 'skattekonto' })
|
||||
const s = await getAccountStatus(supabase as never, COMPANY, 'skattekonto', {
|
||||
today: '2026-08-20',
|
||||
windowFrom: '2026-07-01',
|
||||
windowTo: '2026-07-31',
|
||||
})
|
||||
expect(s).toEqual({ account_key: 'skattekonto' })
|
||||
expect(skattekontoStatusMock).toHaveBeenCalledWith(supabase, COMPANY, {
|
||||
today: '2026-08-20',
|
||||
windowFrom: '2026-07-01',
|
||||
windowTo: '2026-07-31',
|
||||
})
|
||||
})
|
||||
|
||||
it('builds the bank bridge in the #1737 shape', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: cashAccount(ID_A, { is_primary: true }) })
|
||||
bankStatusMock.mockResolvedValue(
|
||||
bankStatus({
|
||||
bank_transaction_total: 122288,
|
||||
gl_1930_period_movement: 122334,
|
||||
difference: -46,
|
||||
unmatched_transaction_total: -1046,
|
||||
unmatched_transaction_count: 1,
|
||||
unmatched_gl_line_total: -1000,
|
||||
unmatched_gl_line_count: 1,
|
||||
unexplained_difference: 0,
|
||||
is_reconciled: false,
|
||||
}),
|
||||
)
|
||||
enqueue({ data: { created_at: '2026-08-20T06:00:00Z' } })
|
||||
|
||||
const s = await getAccountStatus(supabase as never, COMPANY, bankAccountKey(ID_A), { today: '2026-08-20' })
|
||||
if (!s) throw new Error('expected status')
|
||||
expect(s.kind).toBe('bank')
|
||||
expect(s.bridge.map((b) => [b.key, b.amount])).toEqual([
|
||||
['bank_transactions', 122288],
|
||||
['unmatched_external', 1046],
|
||||
['unmatched_ledger', -1000],
|
||||
['ledger_balance', 122334],
|
||||
])
|
||||
expect(s.unexplained_difference).toBe(0)
|
||||
expect(s.bank).toMatchObject({ bank_transaction_total: 122288 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,309 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
const fetchEntryLinesMock = vi.fn()
|
||||
const sumAccountBalanceMock = vi.fn()
|
||||
|
||||
vi.mock('@/lib/bookkeeping/entry-lines', () => ({
|
||||
fetchEntryLines: (...args: unknown[]) => fetchEntryLinesMock(...args),
|
||||
}))
|
||||
vi.mock('../gl-balance', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../gl-balance')>()
|
||||
return {
|
||||
...actual,
|
||||
sumAccountBalance: (...args: unknown[]) => sumAccountBalanceMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
import { getSkattekontoReconciliationStatus } from '../skattekonto-reconciliation'
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const TODAY = '2026-08-20'
|
||||
const FETCHED_AT = Date.UTC(2026, 7, 20, 4, 0, 0)
|
||||
|
||||
type Head = {
|
||||
id: string
|
||||
status: 'draft' | 'posted' | 'reversed'
|
||||
voucher_number: number | null
|
||||
voucher_series: string | null
|
||||
entry_date: string
|
||||
description: string
|
||||
source_type: string | null
|
||||
}
|
||||
|
||||
function head(id: string, entry_date: string, overrides: Partial<Head> = {}): Head {
|
||||
return {
|
||||
id,
|
||||
status: 'posted',
|
||||
voucher_number: Number(id.replace(/\D/g, '')) || null,
|
||||
voucher_series: 'A',
|
||||
entry_date,
|
||||
description: `Verifikat ${id}`,
|
||||
source_type: 'manual',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** A 1630 line as fetchEntryLines returns it: amounts + the parent entry attached. */
|
||||
function ledgerLine(h: Head, amount: number) {
|
||||
return {
|
||||
id: `line-${h.id}-${amount}`,
|
||||
journal_entry_id: h.id,
|
||||
debit_amount: amount > 0 ? amount : 0,
|
||||
credit_amount: amount < 0 ? -amount : 0,
|
||||
journal_entries: h,
|
||||
}
|
||||
}
|
||||
|
||||
function row(
|
||||
id: string,
|
||||
transaktionsdatum: string,
|
||||
belopp: number,
|
||||
overrides: Partial<{
|
||||
status: 'booked' | 'upcoming'
|
||||
journal_entry_id: string | null
|
||||
suggested_journal_entry_id: string | null
|
||||
is_ignored: boolean
|
||||
transaktionstext: string
|
||||
forfallodatum: string | null
|
||||
}> = {},
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
transaktionsdatum,
|
||||
forfallodatum: null,
|
||||
transaktionstext: `Händelse ${id}`,
|
||||
belopp_skatteverket: belopp,
|
||||
status: 'booked',
|
||||
journal_entry_id: null,
|
||||
suggested_journal_entry_id: null,
|
||||
is_ignored: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query order in getSkattekontoReconciliationStatus:
|
||||
* 1. extension_data snapshot (maybeSingle)
|
||||
* 2. skattekonto_transactions page (fetchAllRows)
|
||||
* 3. journal_entries heads for linked + suggested ids (one chunk) when any
|
||||
* The ledger lines come from the mocked fetchEntryLines, the balances from the
|
||||
* mocked sumAccountBalance.
|
||||
*/
|
||||
function enqueueBase(
|
||||
enqueue: (r: { data?: unknown; error?: unknown }) => void,
|
||||
opts: {
|
||||
saldo: number | null
|
||||
rows: ReturnType<typeof row>[]
|
||||
heads?: Head[]
|
||||
fetchedAt?: number
|
||||
},
|
||||
) {
|
||||
enqueue({
|
||||
data:
|
||||
opts.saldo === null
|
||||
? null
|
||||
: { value: { saldo: { saldoSkatteverket: opts.saldo }, fetchedAt: opts.fetchedAt ?? FETCHED_AT } },
|
||||
})
|
||||
enqueue({ data: opts.rows })
|
||||
const referenced = opts.rows.some((r) => r.journal_entry_id || r.suggested_journal_entry_id)
|
||||
if (referenced) enqueue({ data: opts.heads ?? [] })
|
||||
}
|
||||
|
||||
function ledger(lines: ReturnType<typeof ledgerLine>[], balances: { cutoff: number | null; before: number | null }) {
|
||||
fetchEntryLinesMock.mockResolvedValue(lines)
|
||||
sumAccountBalanceMock.mockImplementation(
|
||||
async (_s: unknown, _c: unknown, _a: unknown, options: { cutoffDate?: string; beforeDate?: string }) =>
|
||||
options.beforeDate ? balances.before : balances.cutoff,
|
||||
)
|
||||
}
|
||||
|
||||
describe('getSkattekontoReconciliationStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
fetchEntryLinesMock.mockReset()
|
||||
sumAccountBalanceMock.mockReset()
|
||||
})
|
||||
|
||||
it('returns null when the company has neither a snapshot nor rows', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueBase(enqueue, { saldo: null, rows: [] })
|
||||
ledger([], { cutoff: 0, before: 0 })
|
||||
expect(await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })).toBeNull()
|
||||
})
|
||||
|
||||
it('closes the identity to 0,00 on a mixed fixture and buckets every row where the page shows it', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const A190 = head('A190', '2026-07-12')
|
||||
const A214 = head('A214', '2026-08-11')
|
||||
const A219 = head('A219', '2026-08-12')
|
||||
const A181 = head('A181', '2026-06-30')
|
||||
const rows = [
|
||||
row('r-agi', '2026-07-12', -9142, { journal_entry_id: 'A190' }),
|
||||
row('r-71106', '2026-08-14', 71106),
|
||||
row('r-18', '2026-08-03', 18),
|
||||
row('r-moms', '2026-07-12', -35571),
|
||||
row('r-30000', '2026-08-12', 30000, { suggested_journal_entry_id: 'A214' }),
|
||||
row('r-5447', '2026-08-12', -5447, { suggested_journal_entry_id: 'A219' }),
|
||||
row('r-ign', '2026-07-01', -100, { is_ignored: true }),
|
||||
row('r-up', '2026-09-12', -5447, { status: 'upcoming', forfallodatum: '2026-09-12' }),
|
||||
]
|
||||
enqueueBase(enqueue, { saldo: 53395, rows, heads: [A190, A214, A219] })
|
||||
// Ledger in [history start 2026-07-01, cutoff]: linked A190, the two twins, A181 without event.
|
||||
ledger(
|
||||
[ledgerLine(A190, -9142), ledgerLine(A214, 30000), ledgerLine(A219, -5447), ledgerLine(A181, 12500)],
|
||||
{ cutoff: 27911, before: 0 },
|
||||
)
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
expect(s).not.toBeNull()
|
||||
if (!s) return
|
||||
|
||||
expect(s.external_balance).toBe(53395)
|
||||
expect(s.ledger_balance).toBe(27911)
|
||||
expect(s.difference).toBe(25484)
|
||||
// saldo_at_start = 53 395 - (sum of all booked rows = 50 864) = 2 531; ledger before start = 0
|
||||
expect(s.skattekonto?.opening_difference).toBe(2531)
|
||||
expect(s.unexplained_difference).toBe(0)
|
||||
expect(s.is_reconciled).toBe(false)
|
||||
expect(s.stale).toBe(false)
|
||||
|
||||
expect(s.counts).toEqual({ proposed: 2, unmatched_external: 3, unmatched_ledger: 3, matched: 1, ignored: 1 })
|
||||
expect(s.items.proposed.map((i) => i.item_id).sort()).toEqual(['r-30000', 'r-5447'])
|
||||
expect(s.items.proposed[0].proposal?.journal_entry_id).toBeDefined()
|
||||
expect(s.items.proposed[0].proposal?.reasons[0]).toMatch(/exakt belopp/)
|
||||
expect(s.items.unmatched_external.map((i) => i.item_id).sort()).toEqual(['r-18', 'r-71106', 'r-moms'])
|
||||
expect(s.items.unmatched_ledger.map((i) => i.item_id).sort()).toEqual(['A181', 'A214', 'A219'])
|
||||
expect(s.items.matched[0]).toMatchObject({ item_id: 'r-agi', linked_journal_entry_id: 'A190', voucher_number: 190 })
|
||||
expect(s.items.ignored[0].item_id).toBe('r-ign')
|
||||
expect(s.items.upcoming).toHaveLength(1)
|
||||
expect(s.skattekonto?.upcoming_total).toBe(-5447)
|
||||
|
||||
const byKey = Object.fromEntries(s.bridge.map((b) => [b.key, b]))
|
||||
expect(byKey.external_balance.amount).toBe(53395)
|
||||
expect(byKey.unmatched_external.amount).toBe(-60106)
|
||||
expect(byKey.unmatched_external.count).toBe(5)
|
||||
expect(byKey.unmatched_ledger.amount).toBe(37053)
|
||||
expect(byKey.ignored.amount).toBe(100)
|
||||
expect(byKey.opening_difference.amount).toBe(-2531)
|
||||
expect(byKey.ledger_balance.amount).toBe(27911)
|
||||
// The bridge lines sum to the ledger balance: saldo - unlinked - ignored + unlinked ledger - opening
|
||||
const sum = s.bridge
|
||||
.filter((b) => b.key !== 'ledger_balance')
|
||||
.reduce((acc, b) => roundOre(acc + b.amount), 0)
|
||||
expect(sum).toBe(27911)
|
||||
})
|
||||
|
||||
it('treats a link to a reversed entry as a dead link, and the storno pair nets out of the residual', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const E1 = head('E1', '2026-08-01', { status: 'reversed' })
|
||||
const E2 = head('E2', '2026-08-02', { source_type: 'storno' })
|
||||
enqueueBase(enqueue, {
|
||||
saldo: 1000,
|
||||
rows: [row('r1', '2026-08-01', 1000, { journal_entry_id: 'E1' })],
|
||||
heads: [E1],
|
||||
})
|
||||
ledger([ledgerLine(E1, 1000), ledgerLine(E2, -1000)], { cutoff: 0, before: 0 })
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
if (!s) throw new Error('expected status')
|
||||
|
||||
expect(s.counts.matched).toBe(0)
|
||||
expect(s.counts.unmatched_external).toBe(1)
|
||||
expect(s.items.unmatched_external[0]).toMatchObject({ item_id: 'r1', link_problem: 'entry_reversed' })
|
||||
expect(s.items.unmatched_external[0].actions).toContain('unmatch')
|
||||
expect(s.counts.unmatched_ledger).toBe(2)
|
||||
expect(s.unexplained_difference).toBe(0)
|
||||
expect(s.difference).toBe(1000)
|
||||
})
|
||||
|
||||
it('marks a stale snapshot and never claims reconciled on one', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueBase(enqueue, { saldo: 0, rows: [], fetchedAt: Date.UTC(2026, 6, 1) })
|
||||
ledger([], { cutoff: 0, before: 0 })
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
if (!s) throw new Error('expected status')
|
||||
expect(s.stale).toBe(true)
|
||||
expect(s.as_of).toBe(new Date(Date.UTC(2026, 6, 1)).toISOString())
|
||||
// Nothing open and the identity closes, but the data is 50 days old: reconciled is still true
|
||||
// (the state machine in the service reports it as stale; staleness is not a mismatch).
|
||||
expect(s.is_reconciled).toBe(true)
|
||||
})
|
||||
|
||||
it('flags a ledger line dated within 5 days of the snapshot as possibly awaiting Skatteverket', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const recent = head('R1', '2026-08-18')
|
||||
const old = head('R2', '2026-07-01')
|
||||
enqueueBase(enqueue, { saldo: 0, rows: [row('r1', '2026-07-01', 10)] })
|
||||
ledger([ledgerLine(recent, 500), ledgerLine(old, 10)], { cutoff: 510, before: 0 })
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
if (!s) throw new Error('expected status')
|
||||
const byId = Object.fromEntries(s.items.unmatched_ledger.map((i) => [i.item_id, i]))
|
||||
expect(byId.R1.awaiting_external).toBe(true)
|
||||
expect(byId.R2.awaiting_external).toBe(false)
|
||||
})
|
||||
|
||||
it('a window scopes the item lists only; older unmatched rows are counted, never hidden', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const old = head('O1', '2026-03-10')
|
||||
enqueueBase(enqueue, {
|
||||
saldo: 5000,
|
||||
rows: [row('r-old', '2026-03-01', 2000), row('r-new', '2026-08-10', 3000)],
|
||||
})
|
||||
ledger([ledgerLine(old, 700)], { cutoff: 700, before: 0 })
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, {
|
||||
today: TODAY,
|
||||
windowFrom: '2026-07-01',
|
||||
windowTo: '2026-08-31',
|
||||
})
|
||||
if (!s) throw new Error('expected status')
|
||||
expect(s.items.unmatched_external.map((i) => i.item_id)).toEqual(['r-new'])
|
||||
expect(s.items.unmatched_ledger).toHaveLength(0)
|
||||
expect(s.counts.unmatched_external).toBe(2)
|
||||
expect(s.counts.unmatched_ledger).toBe(1)
|
||||
expect(s.older_unmatched_count).toBe(2)
|
||||
// Totals are unwindowed: 5000 - 5000 (unlinked) + 700 (unlinked ledger) - opening(5000-5000-0=0) = 700 = ledger
|
||||
expect(s.unexplained_difference).toBe(0)
|
||||
})
|
||||
|
||||
it('reports a failed ledger read as null balances and a null residual, never a fabricated 0', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueBase(enqueue, { saldo: 1000, rows: [row('r1', '2026-08-01', 1000)] })
|
||||
fetchEntryLinesMock.mockResolvedValue([])
|
||||
sumAccountBalanceMock.mockResolvedValue(null)
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
if (!s) throw new Error('expected status')
|
||||
expect(s.ledger_read_failed).toBe(true)
|
||||
expect(s.ledger_balance).toBeNull()
|
||||
expect(s.difference).toBeNull()
|
||||
expect(s.unexplained_difference).toBeNull()
|
||||
expect(s.is_reconciled).toBe(false)
|
||||
// The SKV side is still listed so the user can work.
|
||||
expect(s.counts.unmatched_external).toBe(1)
|
||||
})
|
||||
|
||||
it('does not propose an entry that another row already links live', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const E = head('E9', '2026-08-01')
|
||||
enqueueBase(enqueue, {
|
||||
saldo: 2000,
|
||||
rows: [
|
||||
row('r-linked', '2026-08-01', 1000, { journal_entry_id: 'E9' }),
|
||||
row('r-open', '2026-08-01', 1000, { suggested_journal_entry_id: 'E9' }),
|
||||
],
|
||||
heads: [E],
|
||||
})
|
||||
ledger([ledgerLine(E, 1000)], { cutoff: 1000, before: 0 })
|
||||
|
||||
const s = await getSkattekontoReconciliationStatus(supabase as never, COMPANY, { today: TODAY })
|
||||
if (!s) throw new Error('expected status')
|
||||
expect(s.counts.proposed).toBe(0)
|
||||
expect(s.counts.unmatched_external).toBe(1)
|
||||
expect(s.items.unmatched_external[0].item_id).toBe('r-open')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user