feat(reconciliation): sign-off, period picker, Hem row and the three doors for it (#1835)
* 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> * feat(reconciliation): three doors over one engine: dashboard routes, v1 API and MCP tools for account-keyed reconciliation PR 2 of the Avstämning build (design: Avstämning via API och MCP). Every door calls lib/reconciliation/{service,items,actions}.ts; none re-implements a link. - lib/reconciliation/items.ts: listAccountItems per account_key, the page's buckets (proposed, unmatched_external, unmatched_ledger, matched, ignored, upcoming), limit/offset; skattekonto from the engine, bank from the scoped transactions + unlinked GL lines (netted per entry). - lib/reconciliation/actions.ts: matchPairs (pairs or use_proposals, dry run, partial success with codes), unmatchLink, setItemIgnored; emits reconciliation.matched / reconciliation.unmatched. - lib/skatteverket/skattekonto-link.ts: canonical core link semantics for a skattekonto row (single line or entry net on 1630, live-link guard, race-safe update, unlink, ignore); the extension keeps its own matchSkattekontoToEntry until its tests are ported. - Dashboard routes /api/reconciliation/accounts[...]: list, status, items, links (POST), links/{linkId} (DELETE), items/{itemId}/ignore (POST); apply directly (a human clicked). - v1 routes /api/v1/companies/{id}/reconciliation/accounts[...]: same six, withApiV1, new scopes reconciliation:read / reconciliation:write (write is a staging scope for SoD), Idempotency-Key + dry_run on writes, registered for OpenAPI, load-routes, skills/accounted-api regenerated. Legacy bank routes and their transactions:* scopes unchanged. - MCP: gnubok_get_reconciliation_status takes account_key (legacy bank path untouched), new gnubok_list_reconciliation_items (default catalog), gnubok_reconcile_match (stages reconciliation_match, preflight = status) and gnubok_reconcile_unmatch (stages reconciliation_unmatch), both search-only to stay under the tools/list payload ceiling; gnubok_link_transaction_to_journal_entry moved to search. Executors in commit.ts; risk tiers medium/low; migration pair 20260823130000/130001 adds the two op types to the CHECK constraint (value list = live prod as of 2026-08-23 + the two); close_period loadout updated. Tests: service/actions/items/link unit tests, v1 route tests (401/403/400/404/ happy, idempotency, dry run), dashboard route tests, MCP tool tests + the guard suite (payload ceiling, descriptions, staging meta, qualified ids). Guards and apiskill:check green; no type errors in changed files. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): refresh the v1 spec snapshot and keep the ignore update readable by the phantom-column guard The six new v1 reconciliation endpoints and the two new scopes were not recorded in the spec snapshot, and setSkattekontoRowIgnored updated through one conditional payload, which the phantom-column scanner cannot read (ceiling 380 -> 381). Two literal payloads instead; snapshot updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(reconciliation): the Avstämning page, one body for every account with an outside truth /reconciliation in Arbeta (after Transaktioner), on the approved layout: an account rail on the left (bank accounts and the skattekonto, logo or monogram, last fetch, status dot, URL-owned selection), and for the selected account four tiles (outside, ledger, difference, unexplained), the bridge that explains the difference, an actions row (link the proposed pairs, book the unbooked skattekonto events, run the bank matcher) and a full-width table banded by bucket with proposal rows linkable one by one. Every read and write goes through the PR 2 dashboard routes, so the page shows exactly what the v1 API and the MCP tools see. Also: nav item, command palette entry, sv/en strings. Period picker, manual match mode and sign-off are deliberately not here (PR 4/5). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(reconciliation): sign-off, period picker, Hem row and the three doors for it "Markera som avstämd t.o.m. <datum>" as an append-only attestation: account_reconciliations (who signed which account through which date, with the numbers as they stood; reopen stamps instead of deletes; RLS members write as themselves, viewers read). Policy in one place (lib/reconciliation/signoff.ts): refused with an unexplained difference unless forced with a note, refused past today or past the skattekonto snapshot, refused at or before an active sign-off; reopen is the undo. Every status read now carries the latest active sign-off and the rail shows "avstämt t.o.m.". Three doors: dashboard routes (GET/POST .../signoff, POST .../reopen), v1 (same, scope reconciliation:signoff, Idempotency-Key, dry-run, registry + regenerated API skill), MCP gnubok_reconcile_signoff (search catalog, stages reconciliation_signoff after a policy dry run; executor + risk tier + op-type CHECK migration pair). Events reconciliation.signed_off / reconciliation.reopened, and the four reconciliation events join the public webhook set (additive; API version unchanged, changelog section added). Page: räkenskapsår + range picker in the header (own preset memory, opens on this month) scoping the bridge, the items and the default sign-off date; sign-off dialog with the forced-with-note path; reopen on hover. Hem: worklist category reconciliation_due ("Konton att stämma av"), zero until the company has signed anything off. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): classify reconciliation:signoff as a tenant write for the MCP role guard gnubok_reconcile_signoff carries the deliberately separate reconciliation:signoff scope; the central viewer guard keys on the :write/:approve/:manage suffixes, so a viewer could reach the tool (RLS would still refuse the row, but the guard is the intended layer). Add :signoff to the classifier; the strictness test that caught it now passes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(providers): serve local rate-limiter waiters in arrival order Two callers that both found the in-memory bucket empty each set their own timeout; the timeouts expired at the same instant from different timer lists and which woke first was platform-dependent. hydrateInvoices relies on "started first, requested first" to serve open invoices before paid ones, so lib/providers/__tests__/hydrate-invoices.test.ts flipped on CI (twice on #1817) while holding locally. A promise queue makes the local waiters FIFO without changing the rate; the Upstash path is untouched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> (cherry picked from commit 14a7599bf2c6fa7f97de6ffab3dc4cf4d0e1827d) --------- 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
Jakob Wennberg
Claude Fable 5
parent
c609dbb228
commit
f40795896f
@@ -1,6 +1,6 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `131`;
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `134`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
|
||||
[
|
||||
@@ -36,6 +36,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff",
|
||||
"GET /api/v1/companies/:companyId/reconciliation/bank/status",
|
||||
"GET /api/v1/companies/:companyId/reports/ar-ledger",
|
||||
"GET /api/v1/companies/:companyId/reports/avgifter-basis",
|
||||
@@ -105,6 +106,8 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"POST /api/v1/companies/:companyId/journal-entries/batch-create",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items/:itemId/ignore",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff/:signoffId/reopen",
|
||||
"POST /api/v1/companies/:companyId/reconciliation/bank/run",
|
||||
"POST /api/v1/companies/:companyId/salary-runs",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/approve",
|
||||
@@ -155,6 +158,7 @@ exports[`v1 spec snapshot > matches the recorded scope catalogue > endpoint-scop
|
||||
"payroll:write",
|
||||
"public",
|
||||
"reconciliation:read",
|
||||
"reconciliation:signoff",
|
||||
"reconciliation:write",
|
||||
"reports:read",
|
||||
"suppliers:read",
|
||||
|
||||
@@ -160,6 +160,8 @@ import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/signoff/route'
|
||||
import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/signoff/[signoffId]/reopen/route'
|
||||
|
||||
// Dimensions PR2: registry list + value creation (kostnadsställe/projekt).
|
||||
import '@/app/api/v1/companies/[companyId]/dimensions/route'
|
||||
|
||||
@@ -40,6 +40,7 @@ export const API_KEY_SCOPES = {
|
||||
// (match/unmatch) and ignore flags. Links never touch the ledger.
|
||||
'reconciliation:read': { label: 'Avstämning: läs', description: 'Konton att stämma av, bryggan per konto och raderna bakom den (bank + skattekonto)' },
|
||||
'reconciliation:write': { label: 'Avstämning: skriv', description: 'Koppla och koppla bort händelser mot verifikat, ignorera rader (MCP stagar; REST skriver direkt)' },
|
||||
'reconciliation:signoff': { label: 'Avstämning: signera', description: 'Markera ett konto som avstämt t.o.m. ett datum och öppna en signering igen (MCP stagar; REST skriver direkt)' },
|
||||
} as const
|
||||
|
||||
export type ApiKeyScope = keyof typeof API_KEY_SCOPES
|
||||
@@ -133,6 +134,8 @@ export const STAGING_SCOPES: ApiKeyScope[] = [
|
||||
// gnubok_reconcile_match / gnubok_reconcile_unmatch stage reconciliation_*
|
||||
// operations; same SoD reasoning.
|
||||
'reconciliation:write',
|
||||
// gnubok_reconcile_signoff stages reconciliation_signoff.
|
||||
'reconciliation:signoff',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -190,6 +193,7 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_list_reconciliation_items: 'reconciliation:read',
|
||||
gnubok_reconcile_match: 'reconciliation:write',
|
||||
gnubok_reconcile_unmatch: 'reconciliation:write',
|
||||
gnubok_reconcile_signoff: 'reconciliation:signoff',
|
||||
gnubok_bulk_book_transactions: 'transactions:write',
|
||||
gnubok_bulk_book_inbox_items: 'transactions:write',
|
||||
gnubok_auto_match_period: 'transactions:write',
|
||||
|
||||
@@ -142,6 +142,9 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
'POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links': 'reconciliation:write',
|
||||
'DELETE /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links/:linkId': 'reconciliation:write',
|
||||
'POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items/:itemId/ignore': 'reconciliation:write',
|
||||
'GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff': 'reconciliation:read',
|
||||
'POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff': 'reconciliation:signoff',
|
||||
'POST /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/signoff/:signoffId/reopen': 'reconciliation:signoff',
|
||||
|
||||
// Phase 5 PR-3: Reports + import async. Reports are read-only over
|
||||
// existing lib/reports/* generators; imports are async over the Phase 4
|
||||
|
||||
@@ -35,6 +35,14 @@ The first stable release of the public REST API. Six phases of development cover
|
||||
- **Reads**: \`GET /accounts\`, \`GET /fiscal-periods\`.
|
||||
- All write surfaces honour strict-mode (commit fully or error with no side effects).
|
||||
|
||||
### Reconciliation, account-keyed (2026-08)
|
||||
|
||||
- **Accounts**: \`GET /reconciliation/accounts\` lists every account with an outside truth (bank accounts as \`bank:<cash_account_id>\`, the skattekonto as \`skattekonto\`) with status; \`GET .../accounts/{accountKey}\` is the bridge (outside balance, ledger, difference, unexplained, explanatory lines, counts, latest sign-off); \`GET .../accounts/{accountKey}/items\` the rows behind it, bucketed (proposed, unmatched_external, unmatched_ledger, matched, ignored, upcoming).
|
||||
- **Links**: \`POST .../accounts/{accountKey}/links\` (pairs or \`use_proposals\`), \`DELETE .../links/{linkId}\`, \`POST .../items/{itemId}/ignore\`. Links never touch the ledger.
|
||||
- **Sign-off**: \`POST .../accounts/{accountKey}/signoff\` ("avstämt t.o.m." a date; refused with an unexplained difference unless forced with a note), \`GET .../signoff\` history, \`POST .../signoff/{signoffId}/reopen\`.
|
||||
- New scopes \`reconciliation:read\`, \`reconciliation:write\`, \`reconciliation:signoff\`. The legacy \`/reconciliation/bank/*\` endpoints and their \`transactions:*\` scopes are unchanged.
|
||||
- **Webhooks**: new event types \`reconciliation.matched\`, \`reconciliation.unmatched\`, \`reconciliation.signed_off\`, \`reconciliation.reopened\`. Additive: existing subscriptions are unaffected and the API version date is unchanged.
|
||||
|
||||
### Bookkeeping primitives + AP + compliance (Phase 4)
|
||||
|
||||
- **Suppliers + supplier-invoices** vertical (mirror of Phase 2 invoices on the AP side).
|
||||
|
||||
@@ -76,6 +76,10 @@ export type CoreEvent =
|
||||
// signals the flows builder triggers on.
|
||||
| { type: 'reconciliation.matched'; payload: { accountKey: string; externalId: string; journalEntryId: string; method: 'manual' | 'proposal'; userId: string; companyId: string } }
|
||||
| { type: 'reconciliation.unmatched'; payload: { accountKey: string; externalId: string; previousJournalEntryId: string | null; userId: string; companyId: string } }
|
||||
// Sign-off: the human (or agent-staged, user-approved) assertion "reconciled
|
||||
// through this date" on one account (lib/reconciliation/signoff.ts), and its undo.
|
||||
| { type: 'reconciliation.signed_off'; payload: { accountKey: string; signoffId: string; throughDate: string; unexplainedDifference: number | null; userId: string; companyId: string } }
|
||||
| { type: 'reconciliation.reopened'; payload: { accountKey: string; signoffId: string; throughDate: string; reason: string | null; userId: string; companyId: string } }
|
||||
// Bank connection lifecycle: consent + account selection are the
|
||||
// GDPR/PSD2 audit points; emitted to event_log for compliance trail.
|
||||
| { type: 'bank_connection.consent_granted'; payload: { connectionId: string; bankName: string | null; accountCount: number; consentExpiresAt: string | null; userId: string; companyId: string } }
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from '@/lib/currency/supplier-invoice-rate'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { matchPairs, unmatchLink } from '@/lib/reconciliation/actions'
|
||||
import { signOffAccount } from '@/lib/reconciliation/signoff'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import {
|
||||
@@ -6046,6 +6047,44 @@ async function commitReconciliationUnmatch(
|
||||
}
|
||||
}
|
||||
|
||||
/** reconciliation_signoff: "avstämt t.o.m." on one account; policy in lib/reconciliation/signoff.ts. */
|
||||
async function commitReconciliationSignoff(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
const accountKey = params.account_key as string | undefined
|
||||
const throughDate = params.through_date as string | undefined
|
||||
if (!accountKey || !throughDate) {
|
||||
return { error: 'account_key and through_date are required', status: 400 }
|
||||
}
|
||||
try {
|
||||
const result = await signOffAccount(
|
||||
supabase,
|
||||
companyId,
|
||||
userId,
|
||||
accountKey,
|
||||
{
|
||||
through_date: throughDate,
|
||||
note: (params.note as string | null | undefined) ?? null,
|
||||
force: params.force === true,
|
||||
},
|
||||
{ dryRun: false },
|
||||
)
|
||||
if (!result) return { error: `Unknown account_key ${accountKey}`, status: 404 }
|
||||
if (result.dry_run) return { error: 'Unexpected dry-run result', status: 500 }
|
||||
return { data: { account_key: accountKey, signoff: result.signoff } }
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code
|
||||
return {
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
errorCode: code,
|
||||
status: code === 'SIGNOFF_NOT_FOUND' ? 404 : code === 'ALREADY_SIGNED_OFF' || code === 'SIGNOFF_RACE' ? 409 : 400,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function commitLinkTransactionJournalEntry(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -6387,6 +6426,9 @@ async function commitPendingOperationInner(
|
||||
case 'reconciliation_unmatch':
|
||||
result = await commitReconciliationUnmatch(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'reconciliation_signoff':
|
||||
result = await commitReconciliationSignoff(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'submit_vat_declaration':
|
||||
result = await commitSubmitVatDeclaration(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -207,6 +207,9 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// sibling above. Unmatch only clears a pointer: 'low'.
|
||||
reconciliation_match: 'medium',
|
||||
reconciliation_unmatch: 'low',
|
||||
// Sign-off writes the attestation row others rely on (overview, Hem, auditor)
|
||||
// but nothing in the ledger, and reopen undoes it: 'medium'.
|
||||
reconciliation_signoff: 'medium',
|
||||
|
||||
// ── Körjournal (mileage) ───────────────────────────────────────────
|
||||
// A trip row is pure travel documentation: no booking impact until a
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TokenBucketRateLimiter } from '../rate-limiter';
|
||||
|
||||
/**
|
||||
* The local (no-Upstash) limiter must serve waiters in arrival order. Two
|
||||
* callers that both find the bucket empty used to set their own timeouts
|
||||
* that expired at the same instant; which woke first was platform-dependent,
|
||||
* which made "open invoices are requested before paid ones" (hydrateInvoices)
|
||||
* flip on CI while holding locally.
|
||||
*/
|
||||
describe('TokenBucketRateLimiter (local fallback)', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('UPSTASH_REDIS_REST_URL', '');
|
||||
vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', '');
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('grants tokens immediately while the bucket has them', async () => {
|
||||
const limiter = new TokenBucketRateLimiter({ maxRequests: 2, windowMs: 1000 });
|
||||
await expect(limiter.acquire()).resolves.toBeUndefined();
|
||||
await expect(limiter.acquire()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('serves waiters in arrival order once the bucket is empty', async () => {
|
||||
const limiter = new TokenBucketRateLimiter({ maxRequests: 1, windowMs: 1000 });
|
||||
await limiter.acquire(); // bucket empty
|
||||
|
||||
const order: string[] = [];
|
||||
const a = limiter.acquire().then(() => order.push('a'));
|
||||
const b = limiter.acquire().then(() => order.push('b'));
|
||||
const c = limiter.acquire().then(() => order.push('c'));
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
await Promise.all([a, b, c]);
|
||||
expect(order).toEqual(['a', 'b', 'c']);
|
||||
});
|
||||
});
|
||||
@@ -78,7 +78,22 @@ export class TokenBucketRateLimiter {
|
||||
}
|
||||
}
|
||||
|
||||
private async acquireLocal(): Promise<void> {
|
||||
// Local waiters are served in arrival order. Two callers that both find the
|
||||
// bucket empty would otherwise race on timer tie-breaking: their timeouts
|
||||
// expire at the same instant from different timer lists, and which wakes
|
||||
// first is platform-dependent. Callers rely on "started first, requested
|
||||
// first" (hydrateInvoices serves open invoices before paid ones), so the
|
||||
// queue makes that guarantee hold without changing the rate.
|
||||
private localQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
private acquireLocal(): Promise<void> {
|
||||
const turn = this.localQueue.then(() => this.acquireLocalInOrder());
|
||||
// Keep the chain alive even if a turn rejects (nothing throws today).
|
||||
this.localQueue = turn.catch(() => undefined);
|
||||
return turn;
|
||||
}
|
||||
|
||||
private async acquireLocalInOrder(): Promise<void> {
|
||||
this.refill();
|
||||
if (this.tokens > 0) {
|
||||
this.tokens--;
|
||||
|
||||
@@ -86,6 +86,7 @@ describe('listReconciliationAccounts', () => {
|
||||
cashAccount(ID_C, { ledger_account: '1931', iban: 'SE2' }),
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] }) // latest sign-offs (none)
|
||||
// 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' } })
|
||||
@@ -135,6 +136,7 @@ describe('listReconciliationAccounts', () => {
|
||||
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: [] }) // latest sign-offs (none)
|
||||
enqueue({ data: null })
|
||||
skattekontoStatusMock.mockResolvedValue(null)
|
||||
|
||||
@@ -148,6 +150,7 @@ describe('listReconciliationAccounts', () => {
|
||||
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' })] })
|
||||
enqueue({ data: [] }) // latest sign-offs (none)
|
||||
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
|
||||
@@ -199,7 +202,7 @@ describe('getAccountStatus', () => {
|
||||
windowFrom: '2026-07-01',
|
||||
windowTo: '2026-07-31',
|
||||
})
|
||||
expect(s).toEqual({ account_key: 'skattekonto' })
|
||||
expect(s).toEqual({ account_key: 'skattekonto', signoff: null })
|
||||
expect(skattekontoStatusMock).toHaveBeenCalledWith(supabase, COMPANY, {
|
||||
today: '2026-08-20',
|
||||
windowFrom: '2026-07-01',
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { getLatestSignoffs, insertSignoff, listSignoffs, mapSignoffRow, stampReopen } from '../signoff-store'
|
||||
|
||||
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
const COMPANY = 'company-1'
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'sig-1',
|
||||
account_key: 'skattekonto',
|
||||
through_date: '2026-07-31',
|
||||
external_balance: '1000.00',
|
||||
ledger_balance: 1000,
|
||||
unexplained_difference: '0.004',
|
||||
note: null,
|
||||
signed_by: 'user-1',
|
||||
signed_at: '2026-08-23T10:00:00Z',
|
||||
reopened_at: null,
|
||||
reopened_by: null,
|
||||
reopen_reason: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
describe('signoff-store', () => {
|
||||
it('maps numeric strings to öre-rounded numbers', () => {
|
||||
const mapped = mapSignoffRow(row())
|
||||
expect(mapped.external_balance).toBe(1000)
|
||||
expect(mapped.ledger_balance).toBe(1000)
|
||||
expect(mapped.unexplained_difference).toBe(0)
|
||||
})
|
||||
|
||||
it('getLatestSignoffs keeps the first (newest) active row per account', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
row({ id: 'a', account_key: 'skattekonto', through_date: '2026-07-31' }),
|
||||
row({ id: 'b', account_key: 'skattekonto', through_date: '2026-06-30' }),
|
||||
row({ id: 'c', account_key: 'bank:11111111-1111-4111-8111-111111111111', through_date: '2026-07-31' }),
|
||||
],
|
||||
})
|
||||
const latest = await getLatestSignoffs(supabase as never, COMPANY)
|
||||
expect(latest.get('skattekonto')?.id).toBe('a')
|
||||
expect(latest.get('bank:11111111-1111-4111-8111-111111111111')?.id).toBe('c')
|
||||
expect(supabase.from).toHaveBeenCalledWith('account_reconciliations')
|
||||
})
|
||||
|
||||
it('listSignoffs excludes reopened rows unless asked and clamps the limit', async () => {
|
||||
enqueue({ data: [row()] })
|
||||
await listSignoffs(supabase as never, COMPANY, 'skattekonto', { limit: 5000 })
|
||||
expect(findCall('account_reconciliations', 'is')).toEqual(['reopened_at', null])
|
||||
expect(findCall('account_reconciliations', 'limit')).toEqual([200])
|
||||
|
||||
reset()
|
||||
enqueue({ data: [row()] })
|
||||
await listSignoffs(supabase as never, COMPANY, 'skattekonto', { includeReopened: true })
|
||||
expect(findCall('account_reconciliations', 'is')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('insertSignoff returns the mapped row and throws on error', async () => {
|
||||
enqueue({ data: row() })
|
||||
const inserted = await insertSignoff(supabase as never, COMPANY, {
|
||||
account_key: 'skattekonto',
|
||||
through_date: '2026-07-31',
|
||||
external_balance: 1000,
|
||||
ledger_balance: 1000,
|
||||
unexplained_difference: 0,
|
||||
note: null,
|
||||
signed_by: 'user-1',
|
||||
})
|
||||
expect(inserted.id).toBe('sig-1')
|
||||
|
||||
enqueue({ data: null, error: { message: 'duplicate key value violates unique constraint "ux_account_reconciliations_active"' } })
|
||||
await expect(
|
||||
insertSignoff(supabase as never, COMPANY, {
|
||||
account_key: 'skattekonto',
|
||||
through_date: '2026-07-31',
|
||||
external_balance: 1000,
|
||||
ledger_balance: 1000,
|
||||
unexplained_difference: 0,
|
||||
note: null,
|
||||
signed_by: 'user-1',
|
||||
}),
|
||||
).rejects.toThrow(/ux_account_reconciliations_active/)
|
||||
})
|
||||
|
||||
it('stampReopen guards on reopened_at IS NULL and returns null when nothing matched', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await stampReopen(supabase as never, COMPANY, 'sig-1', { reopened_by: 'user-1', reason: null })
|
||||
expect(result).toBeNull()
|
||||
expect(findCall('account_reconciliations', 'is')).toEqual(['reopened_at', null])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const statusMock = vi.fn()
|
||||
const latestMock = vi.fn()
|
||||
const byIdMock = vi.fn()
|
||||
const insertMock = vi.fn()
|
||||
const stampMock = vi.fn()
|
||||
const emitMock = vi.fn()
|
||||
|
||||
vi.mock('../service', () => ({
|
||||
getAccountStatus: (...args: unknown[]) => statusMock(...args),
|
||||
}))
|
||||
vi.mock('../signoff-store', () => ({
|
||||
getLatestSignoff: (...args: unknown[]) => latestMock(...args),
|
||||
getSignoffById: (...args: unknown[]) => byIdMock(...args),
|
||||
insertSignoff: (...args: unknown[]) => insertMock(...args),
|
||||
stampReopen: (...args: unknown[]) => stampMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/events/bus', () => ({ eventBus: { emit: (...args: unknown[]) => emitMock(...args) } }))
|
||||
|
||||
import { ReconciliationSignoffError, reopenSignoff, signOffAccount } from '../signoff'
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const USER = 'user-1'
|
||||
const TODAY = '2026-08-23'
|
||||
const SIGNOFF_ID = '77777777-7777-4777-8777-777777777777'
|
||||
|
||||
function status(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
account_key: 'skattekonto',
|
||||
kind: 'skattekonto',
|
||||
account_number: '1630',
|
||||
currency: 'SEK',
|
||||
as_of: '2026-08-20T06:00:00Z',
|
||||
stale: false,
|
||||
external_balance: 1000,
|
||||
ledger_balance: 1000,
|
||||
difference: 0,
|
||||
unexplained_difference: 0,
|
||||
is_reconciled: true,
|
||||
bridge: [],
|
||||
counts: { proposed: 0, unmatched_external: 0, unmatched_ledger: 0, matched: 0, ignored: 0 },
|
||||
skattekonto: null,
|
||||
bank: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: SIGNOFF_ID,
|
||||
account_key: 'skattekonto',
|
||||
through_date: '2026-07-31',
|
||||
external_balance: 1000,
|
||||
ledger_balance: 1000,
|
||||
unexplained_difference: 0,
|
||||
note: null,
|
||||
signed_by: USER,
|
||||
signed_at: '2026-08-23T10:00:00Z',
|
||||
reopened_at: null,
|
||||
reopened_by: null,
|
||||
reopen_reason: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('signOffAccount', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
statusMock.mockReset()
|
||||
latestMock.mockReset()
|
||||
insertMock.mockReset()
|
||||
emitMock.mockResolvedValue(undefined)
|
||||
statusMock.mockResolvedValue(status())
|
||||
latestMock.mockResolvedValue(null)
|
||||
insertMock.mockImplementation(async (_s: unknown, _c: unknown, input: Record<string, unknown>) =>
|
||||
row({ through_date: input.through_date, note: input.note, unexplained_difference: input.unexplained_difference }),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for an unknown or manual account key', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
expect(await signOffAccount(supabase as never, COMPANY, USER, 'nope', { through_date: '2026-07-31' })).toBeNull()
|
||||
expect(await signOffAccount(supabase as never, COMPANY, USER, 'manual:1910', { through_date: '2026-07-31' })).toBeNull()
|
||||
expect(statusMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a malformed date and a date in the future', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '31/07/2026' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'INVALID_DATE' })
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-09-01' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'DATE_IN_FUTURE' })
|
||||
expect(insertMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('signs a reconciled account, records the numbers, and emits reconciliation.signed_off', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const result = await signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'skattekonto',
|
||||
{ through_date: '2026-07-31' },
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(result).toMatchObject({ dry_run: false, signoff: { through_date: '2026-07-31', unexplained_difference: 0 } })
|
||||
// The bridge is asked for through the requested date.
|
||||
expect(statusMock).toHaveBeenCalledWith(supabase, COMPANY, 'skattekonto', { today: TODAY, windowTo: '2026-07-31' })
|
||||
expect(insertMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
COMPANY,
|
||||
expect.objectContaining({ account_key: 'skattekonto', through_date: '2026-07-31', signed_by: USER, note: null }),
|
||||
)
|
||||
expect(emitMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'reconciliation.signed_off',
|
||||
payload: expect.objectContaining({ accountKey: 'skattekonto', throughDate: '2026-07-31', signoffId: SIGNOFF_ID }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('dry run previews without writing', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const result = await signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'skattekonto',
|
||||
{ through_date: '2026-07-31' },
|
||||
{ today: TODAY, dryRun: true },
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
dry_run: true,
|
||||
would_sign: { through_date: '2026-07-31', is_reconciled: true, forced: false, previous_through_date: null },
|
||||
})
|
||||
expect(insertMock).not.toHaveBeenCalled()
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses an unexplained difference unless forced with a note, then records the difference', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
statusMock.mockResolvedValue(status({ unexplained_difference: 12.5, is_reconciled: false }))
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-07-31' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'NOT_RECONCILED' })
|
||||
await expect(
|
||||
signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'skattekonto',
|
||||
{ through_date: '2026-07-31', force: true },
|
||||
{ today: TODAY },
|
||||
),
|
||||
).rejects.toMatchObject({ code: 'NOTE_REQUIRED' })
|
||||
const forced = await signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'skattekonto',
|
||||
{ through_date: '2026-07-31', force: true, note: 'Bankavgift 12,50 bokförs i augusti.' },
|
||||
{ today: TODAY },
|
||||
)
|
||||
expect(forced).toMatchObject({ dry_run: false })
|
||||
expect(insertMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
COMPANY,
|
||||
expect.objectContaining({ unexplained_difference: 12.5, note: 'Bankavgift 12,50 bokförs i augusti.' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses when the outside balance is unknown', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
statusMock.mockResolvedValue(status({ external_balance: null, unexplained_difference: null, is_reconciled: false }))
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-07-31' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'OUTSIDE_UNKNOWN' })
|
||||
})
|
||||
|
||||
it('refuses a skattekonto date past the snapshot', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
statusMock.mockResolvedValue(status({ as_of: '2026-07-15T06:00:00Z' }))
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-07-31' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'NOT_FETCHED_THROUGH' })
|
||||
})
|
||||
|
||||
it('refuses a date at or before the latest active sign-off', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
latestMock.mockResolvedValue(row({ through_date: '2026-07-31' }))
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-07-31' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'ALREADY_SIGNED_OFF' })
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-06-30' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'ALREADY_SIGNED_OFF' })
|
||||
// A later date is fine and the preview names what it supersedes.
|
||||
const later = await signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'skattekonto',
|
||||
{ through_date: '2026-08-15' },
|
||||
{ today: TODAY, dryRun: true },
|
||||
)
|
||||
expect(later).toMatchObject({ dry_run: true, would_sign: { previous_through_date: '2026-07-31' } })
|
||||
})
|
||||
|
||||
it('maps a unique-index collision to SIGNOFF_RACE', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
insertMock.mockRejectedValue(new Error('duplicate key value violates unique constraint "ux_account_reconciliations_active"'))
|
||||
await expect(
|
||||
signOffAccount(supabase as never, COMPANY, USER, 'skattekonto', { through_date: '2026-07-31' }, { today: TODAY }),
|
||||
).rejects.toMatchObject({ code: 'SIGNOFF_RACE' })
|
||||
})
|
||||
|
||||
it('404s (null) when the status says the account does not exist for the company', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
statusMock.mockResolvedValue(null)
|
||||
expect(
|
||||
await signOffAccount(
|
||||
supabase as never,
|
||||
COMPANY,
|
||||
USER,
|
||||
'bank:11111111-1111-4111-8111-111111111111',
|
||||
{ through_date: '2026-07-31' },
|
||||
{ today: TODAY },
|
||||
),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('reopenSignoff', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
byIdMock.mockReset()
|
||||
stampMock.mockReset()
|
||||
emitMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('stamps the row, emits reconciliation.reopened, and returns the updated row', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
byIdMock.mockResolvedValue(row())
|
||||
stampMock.mockResolvedValue(row({ reopened_at: '2026-08-24T08:00:00Z', reopened_by: USER, reopen_reason: 'sen rad' }))
|
||||
const result = await reopenSignoff(supabase as never, COMPANY, USER, 'skattekonto', SIGNOFF_ID, { reason: ' sen rad ' })
|
||||
expect(result).toMatchObject({ reopened_by: USER, reopen_reason: 'sen rad' })
|
||||
expect(stampMock).toHaveBeenCalledWith(supabase, COMPANY, SIGNOFF_ID, { reopened_by: USER, reason: 'sen rad' })
|
||||
expect(emitMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'reconciliation.reopened', payload: expect.objectContaining({ signoffId: SIGNOFF_ID, reason: 'sen rad' }) }),
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a missing or already reopened sign-off, and reports a lost race', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
byIdMock.mockResolvedValue(null)
|
||||
await expect(reopenSignoff(supabase as never, COMPANY, USER, 'skattekonto', SIGNOFF_ID)).rejects.toMatchObject({
|
||||
code: 'SIGNOFF_NOT_FOUND',
|
||||
})
|
||||
byIdMock.mockResolvedValue(row({ reopened_at: '2026-08-24T08:00:00Z', reopened_by: USER }))
|
||||
await expect(reopenSignoff(supabase as never, COMPANY, USER, 'skattekonto', SIGNOFF_ID)).rejects.toMatchObject({
|
||||
code: 'ALREADY_REOPENED',
|
||||
})
|
||||
byIdMock.mockResolvedValue(row())
|
||||
stampMock.mockResolvedValue(null)
|
||||
await expect(reopenSignoff(supabase as never, COMPANY, USER, 'skattekonto', SIGNOFF_ID)).rejects.toBeInstanceOf(
|
||||
ReconciliationSignoffError,
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for an unknown account key', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
expect(await reopenSignoff(supabase as never, COMPANY, USER, 'nope', SIGNOFF_ID)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -57,6 +57,23 @@ export const ReconciliationStateSchema = z.enum([
|
||||
'not_configured',
|
||||
])
|
||||
|
||||
/** The latest active sign-off on an account: "avstämt t.o.m. through_date" with the numbers as they stood. */
|
||||
export const ReconciliationSignoffSchema = z.object({
|
||||
id: z.string(),
|
||||
account_key: AccountKeySchema,
|
||||
through_date: z.string(),
|
||||
external_balance: z.number().nullable(),
|
||||
ledger_balance: z.number().nullable(),
|
||||
unexplained_difference: z.number().nullable(),
|
||||
note: z.string().nullable(),
|
||||
signed_by: z.string(),
|
||||
signed_at: z.string(),
|
||||
reopened_at: z.string().nullable(),
|
||||
reopened_by: z.string().nullable(),
|
||||
reopen_reason: z.string().nullable(),
|
||||
})
|
||||
export type ReconciliationSignoff = z.infer<typeof ReconciliationSignoffSchema>
|
||||
|
||||
export const ReconciliationAccountSchema = z.object({
|
||||
account_key: AccountKeySchema,
|
||||
kind: ReconciliationKindSchema,
|
||||
@@ -80,6 +97,8 @@ export const ReconciliationAccountSchema = z.object({
|
||||
.nullable(),
|
||||
/** Another enabled cash account shares this IBAN and currency (reconnect duplicate). */
|
||||
superseded_by: AccountKeySchema.nullable(),
|
||||
/** through_date of the latest active sign-off, null when the account was never signed off. */
|
||||
signed_off_through: z.string().nullable().optional(),
|
||||
})
|
||||
export type ReconciliationAccount = z.infer<typeof ReconciliationAccountSchema>
|
||||
|
||||
@@ -190,6 +209,8 @@ export const ReconciliationStatusSchema = z.object({
|
||||
skattekonto: SkattekontoStatusBlockSchema.nullable(),
|
||||
/** Today's bank status fields, unchanged, for the bank kind (see bank-reconciliation.ts). */
|
||||
bank: z.record(z.string(), z.unknown()).nullable(),
|
||||
/** Latest active sign-off on the account (lib/reconciliation/signoff.ts); null when none. */
|
||||
signoff: ReconciliationSignoffSchema.nullable().optional(),
|
||||
})
|
||||
export type ReconciliationStatus = z.infer<typeof ReconciliationStatusSchema>
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type ReconciliationAccount,
|
||||
type ReconciliationStatus,
|
||||
} from './schemas'
|
||||
import { getLatestSignoff, getLatestSignoffs } from './signoff-store'
|
||||
|
||||
const log = createLogger('reconciliation/service')
|
||||
|
||||
@@ -242,6 +243,15 @@ export async function listReconciliationAccounts(
|
||||
for (const other of sorted.slice(1)) supersededBy.set(other.id, bankAccountKey(keep.id))
|
||||
}
|
||||
|
||||
// Latest active sign-off per account, one query; the rail shows "avstämt
|
||||
// t.o.m." next to the live status. A failed read must not hide the accounts.
|
||||
let signoffs = new Map<string, Awaited<ReturnType<typeof getLatestSignoff>>>()
|
||||
try {
|
||||
signoffs = await getLatestSignoffs(supabase, companyId)
|
||||
} catch (err) {
|
||||
log.warn('sign-off read failed', { companyId, error: err instanceof Error ? err.message : String(err) })
|
||||
}
|
||||
|
||||
const bankAccounts = await Promise.all(
|
||||
cashAccounts.map(async (a): Promise<ReconciliationAccount> => {
|
||||
let status: ReconciliationStatus | null = null
|
||||
@@ -277,6 +287,7 @@ export async function listReconciliationAccounts(
|
||||
},
|
||||
status: stateOf(status),
|
||||
superseded_by: supersededBy.get(a.id) ?? null,
|
||||
signed_off_through: signoffs.get(bankAccountKey(a.id))?.through_date ?? null,
|
||||
}
|
||||
}),
|
||||
)
|
||||
@@ -299,6 +310,7 @@ export async function listReconciliationAccounts(
|
||||
},
|
||||
status: s.skattekonto?.fetched_at ? stateOf(s) : { ...stateOf(s)!, state: 'not_configured' },
|
||||
superseded_by: null,
|
||||
signed_off_through: signoffs.get(SKATTEKONTO_ACCOUNT_KEY)?.through_date ?? null,
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -331,8 +343,9 @@ export async function getAccountStatus(
|
||||
if (!parsed) return null
|
||||
const today = options.today ?? isoDate(new Date())
|
||||
|
||||
let status: ReconciliationStatus | null = null
|
||||
if (parsed.kind === 'skattekonto') {
|
||||
return getSkattekontoReconciliationStatus(supabase, companyId, {
|
||||
status = await getSkattekontoReconciliationStatus(supabase, companyId, {
|
||||
today,
|
||||
windowFrom: options.windowFrom ?? null,
|
||||
windowTo: options.windowTo ?? null,
|
||||
@@ -352,9 +365,18 @@ export async function getAccountStatus(
|
||||
from: options.windowFrom ?? defaultWindow(today).from,
|
||||
to: options.windowTo ?? defaultWindow(today).to,
|
||||
}
|
||||
return bankStatus(supabase, companyId, data as CashAccountRow, window, today)
|
||||
status = await bankStatus(supabase, companyId, data as CashAccountRow, window, today)
|
||||
}
|
||||
|
||||
// manual accounts: later adapter
|
||||
return null
|
||||
if (!status) return null
|
||||
|
||||
// The latest active sign-off rides along on every status read (page, v1,
|
||||
// MCP) so "avstämt t.o.m." never needs a second call.
|
||||
try {
|
||||
status.signoff = await getLatestSignoff(supabase, companyId, accountKey)
|
||||
} catch (err) {
|
||||
log.warn('sign-off read failed', { companyId, accountKey, error: err instanceof Error ? err.message : String(err) })
|
||||
status.signoff = null
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { ReconciliationSignoff } from './schemas'
|
||||
|
||||
/**
|
||||
* The account_reconciliations table, read and written in one place. Pure
|
||||
* storage: no policy (that is signoff.ts) and no status computation (that is
|
||||
* service.ts), so service.ts can read the latest sign-offs without a module
|
||||
* cycle.
|
||||
*/
|
||||
|
||||
interface SignoffRow {
|
||||
id: string
|
||||
account_key: string
|
||||
through_date: string
|
||||
external_balance: number | string | null
|
||||
ledger_balance: number | string | null
|
||||
unexplained_difference: number | string | null
|
||||
note: string | null
|
||||
signed_by: string
|
||||
signed_at: string
|
||||
reopened_at: string | null
|
||||
reopened_by: string | null
|
||||
reopen_reason: string | null
|
||||
}
|
||||
|
||||
function num(v: number | string | null): number | null {
|
||||
if (v == null) return null
|
||||
const n = typeof v === 'number' ? v : Number(v)
|
||||
return Number.isFinite(n) ? roundOre(n) : null
|
||||
}
|
||||
|
||||
export function mapSignoffRow(row: SignoffRow): ReconciliationSignoff {
|
||||
return {
|
||||
id: row.id,
|
||||
account_key: row.account_key,
|
||||
through_date: row.through_date,
|
||||
external_balance: num(row.external_balance),
|
||||
ledger_balance: num(row.ledger_balance),
|
||||
unexplained_difference: num(row.unexplained_difference),
|
||||
note: row.note,
|
||||
signed_by: row.signed_by,
|
||||
signed_at: row.signed_at,
|
||||
reopened_at: row.reopened_at,
|
||||
reopened_by: row.reopened_by,
|
||||
reopen_reason: row.reopen_reason,
|
||||
}
|
||||
}
|
||||
|
||||
/** Latest active sign-off per account key, one query for the whole company. */
|
||||
export async function getLatestSignoffs(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<Map<string, ReconciliationSignoff>> {
|
||||
const { data, error } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.is('reopened_at', null)
|
||||
.order('through_date', { ascending: false })
|
||||
if (error) throw new Error(`Kunde inte hämta avstämningssigneringar: ${error.message}`)
|
||||
const out = new Map<string, ReconciliationSignoff>()
|
||||
for (const row of (data ?? []) as SignoffRow[]) {
|
||||
if (!out.has(row.account_key)) out.set(row.account_key, mapSignoffRow(row))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Latest active sign-off on one account, or null. */
|
||||
export async function getLatestSignoff(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
accountKey: string,
|
||||
): Promise<ReconciliationSignoff | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_key', accountKey)
|
||||
.is('reopened_at', null)
|
||||
.order('through_date', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`Kunde inte hämta avstämningssignering: ${error.message}`)
|
||||
return data ? mapSignoffRow(data as SignoffRow) : null
|
||||
}
|
||||
|
||||
/** One sign-off by id (any state), scoped to company + account. */
|
||||
export async function getSignoffById(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
accountKey: string,
|
||||
signoffId: string,
|
||||
): Promise<ReconciliationSignoff | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_key', accountKey)
|
||||
.eq('id', signoffId)
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`Kunde inte hämta avstämningssignering: ${error.message}`)
|
||||
return data ? mapSignoffRow(data as SignoffRow) : null
|
||||
}
|
||||
|
||||
/** Sign-off history for one account, newest first; reopened ones included when asked. */
|
||||
export async function listSignoffs(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
accountKey: string,
|
||||
options: { limit?: number; includeReopened?: boolean } = {},
|
||||
): Promise<ReconciliationSignoff[]> {
|
||||
const limit = Math.min(Math.max(options.limit ?? 50, 1), 200)
|
||||
let query = supabase
|
||||
.from('account_reconciliations')
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_key', accountKey)
|
||||
.order('through_date', { ascending: false })
|
||||
.order('signed_at', { ascending: false })
|
||||
.limit(limit)
|
||||
if (!options.includeReopened) query = query.is('reopened_at', null)
|
||||
const { data, error } = await query
|
||||
if (error) throw new Error(`Kunde inte hämta avstämningssigneringar: ${error.message}`)
|
||||
return ((data ?? []) as SignoffRow[]).map(mapSignoffRow)
|
||||
}
|
||||
|
||||
export interface InsertSignoffInput {
|
||||
account_key: string
|
||||
through_date: string
|
||||
external_balance: number | null
|
||||
ledger_balance: number | null
|
||||
unexplained_difference: number | null
|
||||
note: string | null
|
||||
signed_by: string
|
||||
}
|
||||
|
||||
export async function insertSignoff(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
input: InsertSignoffInput,
|
||||
): Promise<ReconciliationSignoff> {
|
||||
const { data, error } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
account_key: input.account_key,
|
||||
through_date: input.through_date,
|
||||
external_balance: input.external_balance,
|
||||
ledger_balance: input.ledger_balance,
|
||||
unexplained_difference: input.unexplained_difference,
|
||||
note: input.note,
|
||||
signed_by: input.signed_by,
|
||||
})
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.single()
|
||||
if (error || !data) {
|
||||
throw new Error(`Kunde inte spara signeringen: ${error?.message ?? 'okänt fel'}`)
|
||||
}
|
||||
return mapSignoffRow(data as SignoffRow)
|
||||
}
|
||||
|
||||
/** Stamp a sign-off as reopened; the guarded `.is('reopened_at', null)` makes it race-safe. */
|
||||
export async function stampReopen(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
signoffId: string,
|
||||
input: { reopened_by: string; reason: string | null },
|
||||
): Promise<ReconciliationSignoff | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.update({ reopened_at: new Date().toISOString(), reopened_by: input.reopened_by, reopen_reason: input.reason })
|
||||
.eq('company_id', companyId)
|
||||
.eq('id', signoffId)
|
||||
.is('reopened_at', null)
|
||||
.select(
|
||||
'id, account_key, through_date, external_balance, ledger_balance, unexplained_difference, note, signed_by, signed_at, reopened_at, reopened_by, reopen_reason',
|
||||
)
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`Kunde inte öppna signeringen igen: ${error.message}`)
|
||||
return data ? mapSignoffRow(data as SignoffRow) : null
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { parseAccountKey, type ReconciliationSignoff, type ReconciliationStatus } from './schemas'
|
||||
import { getAccountStatus } from './service'
|
||||
import { getLatestSignoff, getSignoffById, insertSignoff, stampReopen } from './signoff-store'
|
||||
|
||||
const log = createLogger('reconciliation/signoff')
|
||||
|
||||
/**
|
||||
* Sign-off ("Markera som avstämd t.o.m. <datum>") and reopen on one
|
||||
* reconcilable account. The policy layer over signoff-store.ts: a sign-off
|
||||
* is refused unless the engine says the account is reconciled through that
|
||||
* date, or the signer explicitly overrides with a note. Writes nothing to
|
||||
* the ledger; the row is the attestation the overview, the Hem row and an
|
||||
* auditor read.
|
||||
*
|
||||
* Same function for the dashboard routes, the v1 API and the MCP executor,
|
||||
* so the rule is one rule.
|
||||
*/
|
||||
|
||||
export type SignoffErrorCode =
|
||||
| 'INVALID_DATE'
|
||||
| 'DATE_IN_FUTURE'
|
||||
| 'NOT_FETCHED_THROUGH'
|
||||
| 'OUTSIDE_UNKNOWN'
|
||||
| 'NOT_RECONCILED'
|
||||
| 'NOTE_REQUIRED'
|
||||
| 'ALREADY_SIGNED_OFF'
|
||||
| 'SIGNOFF_NOT_FOUND'
|
||||
| 'ALREADY_REOPENED'
|
||||
| 'SIGNOFF_RACE'
|
||||
|
||||
export class ReconciliationSignoffError extends Error {
|
||||
readonly code: SignoffErrorCode
|
||||
constructor(message: string, code: SignoffErrorCode) {
|
||||
super(message)
|
||||
this.name = 'ReconciliationSignoffError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export interface SignoffInput {
|
||||
/** Inclusive ISO date the account is asserted reconciled through. */
|
||||
through_date: string
|
||||
/** Free text; required when signing with an unexplained difference (force). */
|
||||
note?: string | null
|
||||
/** Sign even though the engine reports an unexplained difference or an unknown outside balance. Needs a note. */
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export interface SignoffOptions {
|
||||
dryRun?: boolean
|
||||
/** ISO date for "today" (tests). */
|
||||
today?: string
|
||||
}
|
||||
|
||||
export interface SignoffPreview {
|
||||
account_key: string
|
||||
through_date: string
|
||||
external_balance: number | null
|
||||
ledger_balance: number | null
|
||||
unexplained_difference: number | null
|
||||
is_reconciled: boolean
|
||||
forced: boolean
|
||||
/** The active sign-off this one supersedes in the rail, when any (earlier through_date). */
|
||||
previous_through_date: string | null
|
||||
}
|
||||
|
||||
export type SignoffResult =
|
||||
| { dry_run: true; would_sign: SignoffPreview }
|
||||
| { dry_run: false; signoff: ReconciliationSignoff }
|
||||
|
||||
function isoToday(): string {
|
||||
return new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign one account off through a date. Returns null when the account key does
|
||||
* not resolve for this company (callers map that to 404); throws
|
||||
* ReconciliationSignoffError for every policy refusal.
|
||||
*/
|
||||
export async function signOffAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
accountKey: string,
|
||||
input: SignoffInput,
|
||||
options: SignoffOptions = {},
|
||||
): Promise<SignoffResult | null> {
|
||||
const parsed = parseAccountKey(accountKey)
|
||||
// Manual accounts get their adapter later; until then they are not reconcilable.
|
||||
if (!parsed || parsed.kind === 'manual') return null
|
||||
const today = options.today ?? isoToday()
|
||||
const throughDate = input.through_date
|
||||
if (!ISO_DATE_RE.test(throughDate) || Number.isNaN(Date.parse(throughDate))) {
|
||||
throw new ReconciliationSignoffError('Ogiltigt datum. Ange ÅÅÅÅ-MM-DD.', 'INVALID_DATE')
|
||||
}
|
||||
if (throughDate > today) {
|
||||
throw new ReconciliationSignoffError('Du kan inte stämma av framåt i tiden.', 'DATE_IN_FUTURE')
|
||||
}
|
||||
const note = input.note?.trim() ? input.note.trim() : null
|
||||
const force = input.force === true
|
||||
if (force && !note) {
|
||||
throw new ReconciliationSignoffError(
|
||||
'Skriv en rad om varför du signerar trots att allt inte är förklarat.',
|
||||
'NOTE_REQUIRED',
|
||||
)
|
||||
}
|
||||
|
||||
// The engine's view through the requested date. The skattekonto bridge is
|
||||
// anchored at the saldo snapshot, so the date cannot pass it; the bank
|
||||
// bridge is a period movement, so the window simply ends on the date.
|
||||
const status: ReconciliationStatus | null = await getAccountStatus(supabase, companyId, accountKey, {
|
||||
today,
|
||||
windowTo: throughDate,
|
||||
})
|
||||
if (!status) return null
|
||||
const asOfDate = status.as_of.slice(0, 10)
|
||||
if (status.kind === 'skattekonto' && throughDate > asOfDate) {
|
||||
throw new ReconciliationSignoffError(
|
||||
`Skattekontot är hämtat t.o.m. ${asOfDate}. Hämta igen innan du stämmer av ett senare datum.`,
|
||||
'NOT_FETCHED_THROUGH',
|
||||
)
|
||||
}
|
||||
|
||||
const unexplained = status.unexplained_difference
|
||||
const reconciled = unexplained != null && Math.abs(unexplained) < 0.005
|
||||
if (!reconciled && !force) {
|
||||
if (unexplained == null) {
|
||||
throw new ReconciliationSignoffError(
|
||||
'Saldot utanför bokföringen är okänt, så kontot kan inte stämmas av. Hämta det först, eller signera med en notering.',
|
||||
'OUTSIDE_UNKNOWN',
|
||||
)
|
||||
}
|
||||
throw new ReconciliationSignoffError(
|
||||
'Kontot har en oförklarad differens. Koppla eller bokför raderna först, eller signera med en notering.',
|
||||
'NOT_RECONCILED',
|
||||
)
|
||||
}
|
||||
|
||||
const latest = await getLatestSignoff(supabase, companyId, accountKey)
|
||||
if (latest && latest.through_date >= throughDate) {
|
||||
throw new ReconciliationSignoffError(
|
||||
`Kontot är redan avstämt t.o.m. ${latest.through_date}. Öppna den signeringen igen om du vill ändra.`,
|
||||
'ALREADY_SIGNED_OFF',
|
||||
)
|
||||
}
|
||||
|
||||
const preview: SignoffPreview = {
|
||||
account_key: accountKey,
|
||||
through_date: throughDate,
|
||||
external_balance: status.external_balance,
|
||||
ledger_balance: status.ledger_balance,
|
||||
unexplained_difference: unexplained,
|
||||
is_reconciled: reconciled,
|
||||
forced: !reconciled,
|
||||
previous_through_date: latest?.through_date ?? null,
|
||||
}
|
||||
if (options.dryRun) return { dry_run: true, would_sign: preview }
|
||||
|
||||
let signoff: ReconciliationSignoff
|
||||
try {
|
||||
signoff = await insertSignoff(supabase, companyId, {
|
||||
account_key: accountKey,
|
||||
through_date: throughDate,
|
||||
external_balance: status.external_balance,
|
||||
ledger_balance: status.ledger_balance,
|
||||
unexplained_difference: unexplained,
|
||||
note,
|
||||
signed_by: userId,
|
||||
})
|
||||
} catch (err) {
|
||||
// The partial unique index turns a concurrent identical sign-off into a
|
||||
// constraint error; surface it as a race rather than a 500.
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (/ux_account_reconciliations_active|duplicate key/i.test(message)) {
|
||||
throw new ReconciliationSignoffError('Kontot signerades precis av någon annan. Ladda om.', 'SIGNOFF_RACE')
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'reconciliation.signed_off',
|
||||
payload: {
|
||||
accountKey,
|
||||
signoffId: signoff.id,
|
||||
throughDate,
|
||||
unexplainedDifference: unexplained,
|
||||
userId,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
log.warn('reconciliation.signed_off emit failed', { companyId, accountKey, error: err instanceof Error ? err.message : String(err) })
|
||||
}
|
||||
return { dry_run: false, signoff }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopen a sign-off (the undo). The row stays as history with the reopen
|
||||
* stamp; the account shows its previous active sign-off, if any, afterwards.
|
||||
*/
|
||||
export async function reopenSignoff(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
accountKey: string,
|
||||
signoffId: string,
|
||||
input: { reason?: string | null } = {},
|
||||
): Promise<ReconciliationSignoff | null> {
|
||||
const parsed = parseAccountKey(accountKey)
|
||||
if (!parsed || parsed.kind === 'manual') return null
|
||||
const existing = await getSignoffById(supabase, companyId, accountKey, signoffId)
|
||||
if (!existing) {
|
||||
throw new ReconciliationSignoffError('Signeringen hittades inte.', 'SIGNOFF_NOT_FOUND')
|
||||
}
|
||||
if (existing.reopened_at) {
|
||||
throw new ReconciliationSignoffError('Signeringen är redan öppnad igen.', 'ALREADY_REOPENED')
|
||||
}
|
||||
const reason = input.reason?.trim() ? input.reason.trim() : null
|
||||
const updated = await stampReopen(supabase, companyId, signoffId, { reopened_by: userId, reason })
|
||||
if (!updated) {
|
||||
throw new ReconciliationSignoffError('Signeringen öppnades precis av någon annan.', 'SIGNOFF_RACE')
|
||||
}
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'reconciliation.reopened',
|
||||
payload: { accountKey, signoffId, throughDate: updated.through_date, reason, userId, companyId },
|
||||
})
|
||||
} catch (err) {
|
||||
log.warn('reconciliation.reopened emit failed', { companyId, accountKey, error: err instanceof Error ? err.message : String(err) })
|
||||
}
|
||||
return updated
|
||||
}
|
||||
@@ -984,6 +984,10 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
|
||||
// lines and the old description/date, i.e. the preserved side of every
|
||||
// in-verifikat rättelse — räkenskapsinformation, not an operation log.
|
||||
{ name: 'journal_entry_rattelse_log', file: 'journal_entry_rattelse_log.json', orderBy: 'created_at' },
|
||||
// Reconciliation sign-offs ("avstämt t.o.m."): who attested which account
|
||||
// through which date with the numbers as they stood, plus reopen stamps.
|
||||
// Part of the avstämningsdokumentation an auditor asks for; kept.
|
||||
{ name: 'account_reconciliations', file: 'account_reconciliations.json', orderBy: 'signed_at' },
|
||||
{ name: 'journal_entry_no_doc_required', file: 'journal_entry_no_doc_required.json', pageKey: 'journal_entry_id' },
|
||||
{ name: 'rot_rut_payout_requests', file: 'rot_rut_payout_requests.json', orderBy: 'created_at' },
|
||||
// No `denormalize`: rot_rut_payout_requests has no currency column either.
|
||||
|
||||
@@ -54,6 +54,10 @@ const PUBLIC_WEBHOOK_EVENTS = new Set<CoreEventType>([
|
||||
'supplier_invoice.uncredited',
|
||||
'transaction.categorized',
|
||||
'transaction.reconciled',
|
||||
'reconciliation.matched',
|
||||
'reconciliation.unmatched',
|
||||
'reconciliation.signed_off',
|
||||
'reconciliation.reopened',
|
||||
'journal_entry.committed',
|
||||
'journal_entry.reversed',
|
||||
'journal_entry.corrected',
|
||||
|
||||
@@ -10,6 +10,7 @@ vi.mock('../categories', () => ({
|
||||
countOverdueInvoices: vi.fn().mockResolvedValue(5),
|
||||
countDeadlinesNeedingAction: vi.fn().mockResolvedValue(1),
|
||||
countPendingOperations: vi.fn().mockResolvedValue(2),
|
||||
countReconciliationDue: vi.fn().mockResolvedValue(1),
|
||||
}))
|
||||
|
||||
import { getWorklistCounts } from '../aggregate'
|
||||
@@ -32,12 +33,13 @@ describe('getWorklistCounts', () => {
|
||||
overdue_invoice: 5,
|
||||
deadline_action: 1,
|
||||
pending_operations: 2,
|
||||
reconciliation_due: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('excludes suggested_match from the total (subset of book_transaction)', async () => {
|
||||
const { total } = await getWorklistCounts(supabase, 'company-1')
|
||||
// 4 + 6 + 1 + 3 + 5 + 1 + 2, without the 2 suggested matches.
|
||||
expect(total).toBe(22)
|
||||
// 4 + 6 + 1 + 3 + 5 + 1 + 2 + 1, without the 2 suggested matches.
|
||||
expect(total).toBe(23)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
countInboxDocuments,
|
||||
countOverdueInvoices,
|
||||
countPendingOperations,
|
||||
countReconciliationDue,
|
||||
countSuggestedMatches,
|
||||
countSupplierInvoicesAwaitingApproval,
|
||||
countUnbookedTransactions,
|
||||
@@ -413,3 +414,56 @@ describe('listSuggestedMatches', () => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('countReconciliationDue', () => {
|
||||
const CASH_A = '11111111-1111-4111-8111-111111111111'
|
||||
const CASH_B = '22222222-2222-4222-8222-222222222222'
|
||||
const CASH_B_DUP = '33333333-3333-4333-8333-333333333333'
|
||||
// Today 2026-08-23 → previous month end 2026-07-31.
|
||||
const TODAY = new Date('2026-08-23T10:00:00Z')
|
||||
|
||||
it('is zero for a company that never signed anything off (adoption gate)', async () => {
|
||||
enqueue({ data: [] })
|
||||
await expect(countReconciliationDue(supabase, COMPANY, TODAY)).resolves.toBe(0)
|
||||
expect(mockSupabase.from).toHaveBeenCalledTimes(1)
|
||||
expect(mockSupabase.from).toHaveBeenCalledWith('account_reconciliations')
|
||||
})
|
||||
|
||||
it('counts reconcilable accounts without an active sign-off through the previous month end', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
// bank A signed through July: covered.
|
||||
{ account_key: `bank:${CASH_A}`, through_date: '2026-07-31', reopened_at: null },
|
||||
// skattekonto signed through June only: due.
|
||||
{ account_key: 'skattekonto', through_date: '2026-06-30', reopened_at: null },
|
||||
// bank B signed through July but reopened: due.
|
||||
{ account_key: `bank:${CASH_B}`, through_date: '2026-07-31', reopened_at: '2026-08-02T08:00:00Z' },
|
||||
],
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: CASH_A, iban: 'SE1', currency: 'SEK', updated_at: '2026-08-01' },
|
||||
{ id: CASH_B, iban: 'SE2', currency: 'SEK', updated_at: '2026-08-01' },
|
||||
// Reconnect duplicate of B (same IBAN + currency): counts once.
|
||||
{ id: CASH_B_DUP, iban: 'SE2', currency: 'SEK', updated_at: '2026-07-01' },
|
||||
],
|
||||
})
|
||||
enqueue({ count: 12 })
|
||||
// Due: skattekonto + bank B (deduplicated) = 2.
|
||||
await expect(countReconciliationDue(supabase, COMPANY, TODAY)).resolves.toBe(2)
|
||||
expect(mockSupabase.from).toHaveBeenCalledWith('cash_accounts')
|
||||
expect(mockSupabase.from).toHaveBeenCalledWith('skattekonto_transactions')
|
||||
})
|
||||
|
||||
it('ignores the skattekonto when it has no rows', async () => {
|
||||
enqueue({ data: [{ account_key: `bank:${CASH_A}`, through_date: '2026-05-31', reopened_at: null }] })
|
||||
enqueue({ data: [{ id: CASH_A, iban: null, currency: 'SEK', updated_at: null }] })
|
||||
enqueue({ count: 0 })
|
||||
await expect(countReconciliationDue(supabase, COMPANY, TODAY)).resolves.toBe(1)
|
||||
})
|
||||
|
||||
it('soft-fails to 0 on a query error', async () => {
|
||||
enqueue({ error: { message: 'boom' } })
|
||||
await expect(countReconciliationDue(supabase, COMPANY, TODAY)).resolves.toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
countInboxDocuments,
|
||||
countOverdueInvoices,
|
||||
countPendingOperations,
|
||||
countReconciliationDue,
|
||||
countSuggestedMatches,
|
||||
countSupplierInvoicesAwaitingApproval,
|
||||
countUnbookedTransactions,
|
||||
@@ -34,6 +35,7 @@ export async function getWorklistCounts(
|
||||
overdueInvoice,
|
||||
deadlineAction,
|
||||
pendingOperations,
|
||||
reconciliationDue,
|
||||
] = await Promise.all([
|
||||
countUnbookedTransactions(supabase, companyId),
|
||||
countInboxDocuments(supabase, companyId),
|
||||
@@ -43,6 +45,7 @@ export async function getWorklistCounts(
|
||||
countOverdueInvoices(supabase, companyId),
|
||||
countDeadlinesNeedingAction(supabase, companyId),
|
||||
countPendingOperations(supabase, companyId),
|
||||
countReconciliationDue(supabase, companyId),
|
||||
])
|
||||
|
||||
return {
|
||||
@@ -55,6 +58,7 @@ export async function getWorklistCounts(
|
||||
overdue_invoice: overdueInvoice,
|
||||
deadline_action: deadlineAction,
|
||||
pending_operations: pendingOperations,
|
||||
reconciliation_due: reconciliationDue,
|
||||
},
|
||||
total:
|
||||
bookTransaction +
|
||||
@@ -63,6 +67,7 @@ export async function getWorklistCounts(
|
||||
verifikatMissingDocument +
|
||||
overdueInvoice +
|
||||
deadlineAction +
|
||||
pendingOperations,
|
||||
pendingOperations +
|
||||
reconciliationDue,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,3 +428,67 @@ export async function listSuggestedMatches(
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts not signed off through the end of the previous month. Cheap by
|
||||
* construction (three small reads, no bridge computation) and zero for
|
||||
* companies that never signed off anything, so the Hem row only appears
|
||||
* once the ritual is adopted. Mirrors lib/reconciliation/service.ts's account
|
||||
* set: enabled cash accounts deduplicated per IBAN + currency, plus the
|
||||
* skattekonto when it has rows.
|
||||
*/
|
||||
export async function countReconciliationDue(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
today: Date = new Date(),
|
||||
): Promise<number> {
|
||||
// Last day of the previous month, as ISO date (UTC: the day boundary only
|
||||
// needs to be stable, not local).
|
||||
const prevMonthEnd = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 0))
|
||||
.toISOString()
|
||||
.slice(0, 10)
|
||||
|
||||
const { data: signoffRows, error: signoffError } = await supabase
|
||||
.from('account_reconciliations')
|
||||
.select('account_key, through_date, reopened_at')
|
||||
.eq('company_id', companyId)
|
||||
.order('through_date', { ascending: false })
|
||||
.limit(500)
|
||||
if (signoffError) return logAndZero('reconciliation_due', companyId, signoffError)
|
||||
const signoffs = (signoffRows ?? []) as Array<{ account_key: string; through_date: string; reopened_at: string | null }>
|
||||
// Adoption gate: no sign-off ever (active or reopened) means no nudge.
|
||||
if (signoffs.length === 0) return 0
|
||||
const coveredKeys = new Set(
|
||||
signoffs.filter((s) => s.reopened_at === null && s.through_date >= prevMonthEnd).map((s) => s.account_key),
|
||||
)
|
||||
|
||||
const { data: cashRows, error: cashError } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, iban, currency, updated_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('enabled', true)
|
||||
if (cashError) return logAndZero('reconciliation_due', companyId, cashError)
|
||||
const cash = (cashRows ?? []) as Array<{ id: string; iban: string | null; currency: string | null; updated_at: string | null }>
|
||||
// Reconnect duplicates (same IBAN + currency) count once: the newest row.
|
||||
const byIban = new Map<string, typeof cash[number]>()
|
||||
const keys: string[] = []
|
||||
for (const a of cash) {
|
||||
if (!a.iban) {
|
||||
keys.push(`bank:${a.id}`)
|
||||
continue
|
||||
}
|
||||
const k = `${a.iban}|${a.currency ?? 'SEK'}`
|
||||
const prev = byIban.get(k)
|
||||
if (!prev || (a.updated_at ?? '') > (prev.updated_at ?? '')) byIban.set(k, a)
|
||||
}
|
||||
for (const a of byIban.values()) keys.push(`bank:${a.id}`)
|
||||
|
||||
const { count: skvCount, error: skvError } = await supabase
|
||||
.from('skattekonto_transactions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
if (skvError) return logAndZero('reconciliation_due', companyId, skvError)
|
||||
if ((skvCount ?? 0) > 0) keys.push('skattekonto')
|
||||
|
||||
return keys.filter((k) => !coveredKeys.has(k)).length
|
||||
}
|
||||
|
||||
@@ -77,6 +77,19 @@ export const WORKLIST_CATEGORIES = [
|
||||
* Done: committed or rejected.
|
||||
*/
|
||||
'pending_operations',
|
||||
/**
|
||||
* Accounts not signed off through the end of the previous month
|
||||
* ("N konton att stämma av"), only for companies that have adopted the
|
||||
* sign-off ritual (at least one account_reconciliations row ever).
|
||||
* Pending: an enabled cash account (deduplicated per IBAN + currency) or a
|
||||
* configured skattekonto whose latest ACTIVE sign-off has
|
||||
* through_date before the last day of the previous month.
|
||||
* Done: a sign-off through that date or later (POST .../signoff), or
|
||||
* the account stops being reconcilable (disabled cash account).
|
||||
* Zero for companies with no sign-off at all: the nudge is for those who
|
||||
* reconcile monthly, not a new chore for everyone.
|
||||
*/
|
||||
'reconciliation_due',
|
||||
] as const
|
||||
|
||||
export type WorklistCategory = (typeof WORKLIST_CATEGORIES)[number]
|
||||
|
||||
Reference in New Issue
Block a user