Files
accounted/lib/reconciliation/__tests__/gl-balance.test.ts
T
0a8544e0cb 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>
2026-08-24 13:55:08 +02:00

65 lines
2.7 KiB
TypeScript

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()
})
})