Files
accounted/lib/reconciliation/gl-balance.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

82 lines
3.1 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
import { createLogger } from '@/lib/logger'
import { roundOre } from '@/lib/money'
const log = createLogger('reconciliation/gl-balance')
/**
* The journal_entries statuses that make up a ledger balance.
*
* Storno keeps the original entry in the books with status 'reversed' and
* posts a separate reversal (source_type 'storno', status 'posted'). A
* balance therefore has to count BOTH: the trial balance
* (lib/reports/trial-balance.ts) and the bank reconciliation engine
* (lib/reconciliation/bank-reconciliation.ts) already do. Summing 'posted'
* alone excludes the reversed original while including its reversal, which
* double-cancels the movement and misstates the account by the reversed
* amount. The skattekonto drift check did exactly that until 2026-08-23.
*/
export const LEDGER_BALANCE_STATUSES = ['posted', 'reversed'] as const
export interface SumAccountBalanceOptions {
/** Inclusive upper bound on entry_date (YYYY-MM-DD). */
cutoffDate?: string
/** Inclusive lower bound on entry_date (YYYY-MM-DD). */
fromDate?: string
/** Exclusive upper bound on entry_date (YYYY-MM-DD); combines with fromDate. */
beforeDate?: string
}
/**
* Sum debit - credit on one BAS account over posted + reversed entries.
*
* Returns null (NOT 0) when the read fails: 0 is a real balance claim
* ("nothing booked on this account"), and substituting it for a failed read
* turns a transient DB blip into a full-balance difference. Callers decide
* whether to skip or to surface the failure.
*
* Driven from the journal_entries side via fetchEntryLines so the tenant
* scope never compiles into a cross-tenant LATERAL scan, and both steps
* paginate (PostgREST caps at 1000 rows).
*/
export async function sumAccountBalance(
supabase: SupabaseClient,
companyId: string,
accountNumber: string,
options: SumAccountBalanceOptions = {},
): Promise<number | null> {
let rows: Array<{ debit_amount: number | string | null; credit_amount: number | string | null }>
try {
rows = await fetchEntryLines({
supabase,
lineColumns: 'debit_amount, credit_amount',
filterEntries: (q: EntryLinesQuery) => {
let query = q
.eq('company_id', companyId)
.in('status', [...LEDGER_BALANCE_STATUSES])
if (options.cutoffDate) query = query.lte('entry_date', options.cutoffDate)
if (options.fromDate) query = query.gte('entry_date', options.fromDate)
if (options.beforeDate) query = query.lt('entry_date', options.beforeDate)
return query
},
filterLines: (q: EntryLinesQuery) => q.eq('account_number', accountNumber),
attachEntriesAs: null,
})
} catch (err) {
log.warn('sumAccountBalance failed', {
companyId,
accountNumber,
options,
error: err instanceof Error ? err.message : String(err),
})
return null
}
let sum = 0
for (const row of rows) {
sum += Number(row.debit_amount || 0) - Number(row.credit_amount || 0)
}
return roundOre(sum)
}