From 3a62c5419ea06ec8797f2b732c833f0ebf69a240 Mon Sep 17 00:00:00 2001 From: Jakob Wennberg Date: Mon, 24 Aug 2026 14:03:20 +0200 Subject: [PATCH] feat(reconciliation): three doors over one engine: dashboard routes, v1 API and MCP tools (#1833) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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: | 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 * 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 * 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 * 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 --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 --- DECISIONS.md | 1 + .../items/[itemId]/ignore/route.ts | 52 ++++ .../accounts/[accountKey]/items/route.ts | 48 +++ .../[accountKey]/links/[linkId]/route.ts | 37 +++ .../accounts/[accountKey]/links/route.ts | 51 +++ .../accounts/[accountKey]/route.ts | 37 +++ .../accounts/__tests__/route.test.ts | 156 ++++++++++ app/api/reconciliation/accounts/route.ts | 32 ++ .../items/[itemId]/ignore/route.ts | 98 ++++++ .../accounts/[accountKey]/items/route.ts | 175 +++++++++++ .../[accountKey]/links/[linkId]/route.ts | 78 +++++ .../accounts/[accountKey]/links/route.ts | 150 +++++++++ .../accounts/[accountKey]/route.ts | 118 +++++++ .../accounts/__tests__/route.test.ts | 244 +++++++++++++++ .../reconciliation/accounts/route.ts | 122 ++++++++ .../__tests__/reconciliation-tools.test.ts | 162 ++++++++++ .../general/mcp-server/recommended-tools.ts | 4 + extensions/general/mcp-server/server.ts | 234 +++++++++++++- .../__snapshots__/spec-snapshot.test.ts.snap | 10 +- lib/api/v1/load-routes.ts | 9 + lib/auth/api-keys.ts | 13 + lib/auth/scopes.ts | 11 +- lib/events/types.ts | 7 + lib/pending-operations/commit.ts | 74 +++++ lib/pending-operations/risk-tiers.ts | 7 + lib/reconciliation/__tests__/actions.test.ts | 182 +++++++++++ lib/reconciliation/__tests__/items.test.ts | 97 ++++++ lib/reconciliation/actions.ts | 291 ++++++++++++++++++ lib/reconciliation/items.ts | 235 ++++++++++++++ .../__tests__/skattekonto-link.test.ts | 136 ++++++++ lib/skatteverket/skattekonto-link.ts | 240 +++++++++++++++ skills/accounted-api/SKILL.md | 12 +- skills/accounted-api/references/banking.md | 264 ++++++++++++++++ ...ding_operations_add_reconciliation_ops.sql | 99 ++++++ ..._pending_operations_reconciliation_ops.sql | 6 + types/index.ts | 4 + 36 files changed, 3488 insertions(+), 8 deletions(-) create mode 100644 app/api/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts create mode 100644 app/api/reconciliation/accounts/[accountKey]/items/route.ts create mode 100644 app/api/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts create mode 100644 app/api/reconciliation/accounts/[accountKey]/links/route.ts create mode 100644 app/api/reconciliation/accounts/[accountKey]/route.ts create mode 100644 app/api/reconciliation/accounts/__tests__/route.test.ts create mode 100644 app/api/reconciliation/accounts/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/reconciliation/accounts/route.ts create mode 100644 extensions/general/mcp-server/__tests__/reconciliation-tools.test.ts create mode 100644 lib/reconciliation/__tests__/actions.test.ts create mode 100644 lib/reconciliation/__tests__/items.test.ts create mode 100644 lib/reconciliation/actions.ts create mode 100644 lib/reconciliation/items.ts create mode 100644 lib/skatteverket/__tests__/skattekonto-link.test.ts create mode 100644 lib/skatteverket/skattekonto-link.ts create mode 100644 supabase/migrations/20260823130000_pending_operations_add_reconciliation_ops.sql create mode 100644 supabase/migrations/20260823130001_validate_pending_operations_reconciliation_ops.sql diff --git a/DECISIONS.md b/DECISIONS.md index 8d44cef7..012af294 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -1177,3 +1177,4 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and [2026-08-24] Issue #1820 self-billed credit fix: creditConfirmNumber()/originalRef fall back invoice_number -> external_invoice_number (typed 400 INVOICE_CREDIT_NO_NUMBER if both null) instead of relaxing the DB numbering constraint or dropping the type-the-number confirm step; the confirm step stays (dropping it is a founder call). The invoice-date Forval chip surfaces in ALL editor modes, not only self-billed: the silent today-default exists in every mode and the chip line already carries the due date. In self-billed mode fakturadatum + mottagningsdatum render uncollapsed next to the external number (transcription fields, not defaults); the panel rows are hidden there because registering the same RHF field twice desyncs the inputs. The v1 credit route's existing id-slice fallback was left unchanged (public API behavior). [2026-08-24] No-IBAN reconnect pairing (issue #1709) uses only per-currency exactly-one-each-side elimination, deliberately WITHOUT name equality: ASPSPs reformat product names between consents, so requiring it would silently disable the fix for the banks that need it, while the one-per-currency guard already bounds a mis-pair to skipping rows whose account+date+amount+occurrence all collide. upsertFromPsd2 needed no change: its explicit reuse_cash_account_id promote path already covers a same-connection holder, so the fix only names the paired row from the callback. [2026-08-23] Reconciliation engine (PR 1): the skattekonto status engine lives in core lib/reconciliation (reads the core table + the extension snapshot row in extension_data directly) instead of in the skatteverket extension: core must never import @/extensions/*, and the reconciliation facade must work with zero extensions; the matcher stays in the extension and writes its proposals to the row at sync time. Proposals are propose-only (suggested_journal_entry_id is never a link); the same per-entry one-to-one assignment replaces per-row "exactly one candidate". Ledger balances everywhere in reconciliation use the trial-balance predicate status IN (posted, reversed): the drift check summed posted only, which misstated 1630 for every company with a storno on the account. +[2026-08-23] Reconciliation doors (PR 2): dashboard routes, the v1 API and the MCP tools all call lib/reconciliation/{service,items,actions}.ts; no door re-implements a link. Policy lives in the door: page + REST apply directly, MCP stages (reconciliation_match / reconciliation_unmatch pending operations, executors in commit.ts). The MCP write tools are catalogVisibility search (and gnubok_link_transaction_to_journal_entry moved to search) because the tools/list payload ceiling (59 900 tokens) left no room for them in the default catalog; the reads (status with account_key, items) stay default and the items description points at the write. The skattekonto link now has its canonical implementation in core lib/skatteverket/skattekonto-link.ts (needed by core doors; core must not import the extension); the extension route still uses its own matchSkattekontoToEntry until its queued-mock tests are ported, then it delegates. New scopes reconciliation:read/write; gnubok_get_reconciliation_status keeps reports:read and the legacy bank routes keep transactions:* so no existing key is cut off. diff --git a/app/api/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts b/app/api/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts new file mode 100644 index 00000000..f1f78302 --- /dev/null +++ b/app/api/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts @@ -0,0 +1,52 @@ +import { NextResponse } from 'next/server' +import { z } from 'zod' +import { withRouteContext } from '@/lib/api/with-route-context' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { setItemIgnored } from '@/lib/reconciliation/actions' +import { SkattekontoLinkError } from '@/lib/skatteverket/skattekonto-link' +import { getErrorMessage } from '@/lib/errors/get-error-message' + +const IgnoreBodySchema = z.object({ ignored: z.boolean().optional() }) + +/** + * POST /api/reconciliation/accounts/{accountKey}/items/{itemId}/ignore + * + * The page's "Ignorera" / "Återställ" on one outside row. Body + * { ignored: boolean } (default true). + */ +export const POST = withRouteContext<{ params: Promise<{ accountKey: string; itemId: string }> }>( + 'reconciliation.accounts.items.ignore', + async (request, { supabase, companyId }, { params }) => { + const { accountKey, itemId } = await params + if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(itemId).success) { + return NextResponse.json({ error: 'Okänd rad' }, { status: 404 }) + } + // Empty body = ignore; `{ ignored: false }` restores. + let body: unknown = {} + try { + const text = await request.text() + body = text ? JSON.parse(text) : {} + } catch { + return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 }) + } + const parsed = IgnoreBodySchema.safeParse(body) + if (!parsed.success) { + return NextResponse.json({ error: 'Ogiltig body' }, { status: 400 }) + } + const ignored = parsed.data.ignored ?? true + try { + const result = await setItemIgnored(supabase, companyId, accountKey, itemId, ignored) + if (!result) { + return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 }) + } + return NextResponse.json({ data: result }) + } catch (err) { + if (err instanceof SkattekontoLinkError) { + const status = err.code === 'TRANSACTION_NOT_FOUND' ? 404 : 400 + return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status }) + } + throw err + } + }, + { requireWrite: true }, +) diff --git a/app/api/reconciliation/accounts/[accountKey]/items/route.ts b/app/api/reconciliation/accounts/[accountKey]/items/route.ts new file mode 100644 index 00000000..47751cd8 --- /dev/null +++ b/app/api/reconciliation/accounts/[accountKey]/items/route.ts @@ -0,0 +1,48 @@ +import { NextResponse } from 'next/server' +import { withRouteContext } from '@/lib/api/with-route-context' +import { AccountKeySchema, ReconciliationItemBucketSchema } from '@/lib/reconciliation/schemas' +import { listAccountItems, MAX_ITEMS_LIMIT } from '@/lib/reconciliation/items' +import { ISO_DATE_RE } from '@/lib/invariants' + +const DATE = ISO_DATE_RE + +/** + * GET /api/reconciliation/accounts/{accountKey}/items + * + * The rows behind one account's bridge, bucketed and paginated + * (?bucket, ?date_from, ?date_to, ?limit, ?offset). + */ +export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>( + 'reconciliation.accounts.items', + async (request, { supabase, companyId }, { params }) => { + const { accountKey } = await params + if (!AccountKeySchema.safeParse(accountKey).success) { + return NextResponse.json({ error: 'Okänt konto' }, { status: 404 }) + } + const { searchParams } = new URL(request.url) + const bucketRaw = searchParams.get('bucket') + const bucket = bucketRaw ? ReconciliationItemBucketSchema.safeParse(bucketRaw) : null + if (bucket && !bucket.success) { + return NextResponse.json({ error: 'Ogiltig bucket' }, { status: 400 }) + } + const dateFrom = searchParams.get('date_from') || null + const dateTo = searchParams.get('date_to') || null + if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) { + return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 }) + } + const limit = Math.min(Number(searchParams.get('limit') ?? 50) || 50, MAX_ITEMS_LIMIT) + const offset = Math.max(0, Number(searchParams.get('offset') ?? 0) || 0) + + const result = await listAccountItems(supabase, companyId, accountKey, { + bucket: bucket?.success ? bucket.data : undefined, + windowFrom: dateFrom, + windowTo: dateTo, + limit, + offset, + }) + if (!result) { + return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 }) + } + return NextResponse.json({ data: result }) + }, +) diff --git a/app/api/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts b/app/api/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts new file mode 100644 index 00000000..14fc0d28 --- /dev/null +++ b/app/api/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from 'next/server' +import { z } from 'zod' +import { withRouteContext } from '@/lib/api/with-route-context' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { unmatchLink } from '@/lib/reconciliation/actions' +import { SkattekontoLinkError } from '@/lib/skatteverket/skattekonto-link' +import { getErrorMessage } from '@/lib/errors/get-error-message' + +/** + * DELETE /api/reconciliation/accounts/{accountKey}/links/{linkId} + * + * The page's "Koppla bort": clears the link on one outside row (linkId = the + * row id). The verifikat is untouched. + */ +export const DELETE = withRouteContext<{ params: Promise<{ accountKey: string; linkId: string }> }>( + 'reconciliation.accounts.links.delete', + async (_request, { supabase, user, companyId }, { params }) => { + const { accountKey, linkId } = await params + if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(linkId).success) { + return NextResponse.json({ error: 'Okänd koppling' }, { status: 404 }) + } + try { + const result = await unmatchLink(supabase, companyId, user.id, accountKey, linkId) + if (!result) { + return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 }) + } + return NextResponse.json({ data: result }) + } catch (err) { + if (err instanceof SkattekontoLinkError) { + const status = err.code === 'TRANSACTION_NOT_FOUND' ? 404 : 400 + return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status }) + } + throw err + } + }, + { requireWrite: true }, +) diff --git a/app/api/reconciliation/accounts/[accountKey]/links/route.ts b/app/api/reconciliation/accounts/[accountKey]/links/route.ts new file mode 100644 index 00000000..e97388c0 --- /dev/null +++ b/app/api/reconciliation/accounts/[accountKey]/links/route.ts @@ -0,0 +1,51 @@ +import { NextResponse } from 'next/server' +import { z } from 'zod' +import { withRouteContext } from '@/lib/api/with-route-context' +import { validateBody } from '@/lib/api/validate' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { matchPairs } from '@/lib/reconciliation/actions' + +const PairSchema = z.object({ + external_ids: z.array(z.string().uuid()).min(1).max(50), + journal_entry_ids: z.array(z.string().uuid()).min(1).max(50), +}) + +const ReconciliationLinksBodySchema = z + .object({ + pairs: z.array(PairSchema).max(200).optional(), + use_proposals: z.boolean().optional(), + confidence_threshold: z.number().min(0).max(1).optional(), + dry_run: z.boolean().optional(), + }) + .refine((b) => (b.pairs && b.pairs.length > 0) || b.use_proposals === true, { + message: 'Ange pairs eller use_proposals: true.', + }) + +/** + * POST /api/reconciliation/accounts/{accountKey}/links + * + * The page's "Koppla" and "Koppla N föreslagna": link outside rows to existing + * verifikat. A human clicked, so this applies directly (dry_run: true for the + * preview). Same service function as v1 and the MCP commit executor. + */ +export const POST = withRouteContext<{ params: Promise<{ accountKey: string }> }>( + 'reconciliation.accounts.links.create', + async (request, { supabase, user, companyId }, { params }) => { + const { accountKey } = await params + if (!AccountKeySchema.safeParse(accountKey).success) { + return NextResponse.json({ error: 'Okänt konto' }, { status: 404 }) + } + const validation = await validateBody(request, ReconciliationLinksBodySchema) + if (!validation.success) return validation.response + const { dry_run, ...input } = validation.data + + const result = await matchPairs(supabase, companyId, user.id, accountKey, input, { + dryRun: dry_run === true, + }) + if (!result) { + return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 }) + } + return NextResponse.json({ data: result }) + }, + { requireWrite: true }, +) diff --git a/app/api/reconciliation/accounts/[accountKey]/route.ts b/app/api/reconciliation/accounts/[accountKey]/route.ts new file mode 100644 index 00000000..33bf79e2 --- /dev/null +++ b/app/api/reconciliation/accounts/[accountKey]/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from 'next/server' +import { withRouteContext } from '@/lib/api/with-route-context' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { getAccountStatus } from '@/lib/reconciliation/service' +import { ISO_DATE_RE } from '@/lib/invariants' + +const DATE = ISO_DATE_RE + +/** + * GET /api/reconciliation/accounts/{accountKey} + * + * The bridge for one account (plus, for the skattekonto, the item buckets the + * page renders under it). Same service function as v1 and MCP. + */ +export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>( + 'reconciliation.accounts.status', + async (request, { supabase, companyId }, { params }) => { + const { accountKey } = await params + if (!AccountKeySchema.safeParse(accountKey).success) { + return NextResponse.json({ error: 'Okänt konto' }, { status: 404 }) + } + const { searchParams } = new URL(request.url) + const dateFrom = searchParams.get('date_from') || null + const dateTo = searchParams.get('date_to') || null + if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) { + return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 }) + } + const status = await getAccountStatus(supabase, companyId, accountKey, { + windowFrom: dateFrom, + windowTo: dateTo, + }) + if (!status) { + return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 }) + } + return NextResponse.json({ data: status }) + }, +) diff --git a/app/api/reconciliation/accounts/__tests__/route.test.ts b/app/api/reconciliation/accounts/__tests__/route.test.ts new file mode 100644 index 00000000..3abcd5ba --- /dev/null +++ b/app/api/reconciliation/accounts/__tests__/route.test.ts @@ -0,0 +1,156 @@ +/** + * Tests for the dashboard reconciliation routes (cookie session, withRouteContext): + * GET /api/reconciliation/accounts, GET .../accounts/{accountKey}, + * GET .../accounts/{accountKey}/items, POST .../links, DELETE .../links/{linkId}, + * POST .../items/{itemId}/ignore. The service layer is mocked; the wrapper is real. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { NextResponse } from 'next/server' +import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers' + +const { supabase, reset } = createQueuedMockSupabase() + +const requireAuthMock = vi.fn() +vi.mock('@/lib/auth/require-auth', () => ({ + requireAuth: (...args: unknown[]) => requireAuthMock(...args), +})) +vi.mock('@/lib/company/context', () => ({ + getActiveCompanyId: vi.fn().mockResolvedValue('company-1'), + requireCompanyId: vi.fn().mockResolvedValue('company-1'), +})) +const requireWriteMock = vi.fn() +vi.mock('@/lib/auth/require-write', () => ({ + requireWritePermission: (...args: unknown[]) => requireWriteMock(...args), +})) +vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() })) + +const listAccountsMock = vi.fn() +const statusMock = vi.fn() +const itemsMock = vi.fn() +const matchMock = vi.fn() +const unmatchMock = vi.fn() +const ignoreMock = vi.fn() +vi.mock('@/lib/reconciliation/service', () => ({ + listReconciliationAccounts: (...args: unknown[]) => listAccountsMock(...args), + getAccountStatus: (...args: unknown[]) => statusMock(...args), +})) +vi.mock('@/lib/reconciliation/items', async () => { + const actual = await vi.importActual('@/lib/reconciliation/items') + return { ...actual, listAccountItems: (...args: unknown[]) => itemsMock(...args) } +}) +vi.mock('@/lib/reconciliation/actions', () => ({ + matchPairs: (...args: unknown[]) => matchMock(...args), + unmatchLink: (...args: unknown[]) => unmatchMock(...args), + setItemIgnored: (...args: unknown[]) => ignoreMock(...args), +})) + +import { GET as listGET } from '../route' +import { GET as statusGET } from '../[accountKey]/route' +import { GET as itemsGET } from '../[accountKey]/items/route' +import { POST as linksPOST } from '../[accountKey]/links/route' +import { DELETE as linkDELETE } from '../[accountKey]/links/[linkId]/route' +import { POST as ignorePOST } from '../[accountKey]/items/[itemId]/ignore/route' + +const ROW = '22222222-2222-4222-8222-222222222222' +const ENTRY = '33333333-3333-4333-8333-333333333333' +// Dynamic-route params for the handlers under test; `never` keeps each +// handler's own params type while letting one helper serve all of them. +const p = (obj: Record) => ({ params: Promise.resolve(obj) }) as never + +describe('dashboard reconciliation routes', () => { + beforeEach(() => { + vi.clearAllMocks() + reset() + requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase }) + requireWriteMock.mockResolvedValue({ ok: true }) + listAccountsMock.mockResolvedValue([{ account_key: 'skattekonto' }]) + statusMock.mockResolvedValue({ account_key: 'skattekonto', bridge: [] }) + itemsMock.mockResolvedValue({ items: [], count: 0, total_count: 0, has_more: false, older_unmatched_count: 0 }) + matchMock.mockResolvedValue({ dry_run: false, considered: 1, applied: [], skipped: [] }) + unmatchMock.mockResolvedValue({ external_id: ROW, previous_journal_entry_id: ENTRY }) + ignoreMock.mockResolvedValue({ external_id: ROW, is_ignored: true }) + }) + + it('401 when unauthenticated', async () => { + requireAuthMock.mockResolvedValue({ + user: null, + supabase, + error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }), + }) + const res = await listGET(createMockRequest('/api/reconciliation/accounts'), { params: Promise.resolve({}) }) + expect(res.status).toBe(401) + }) + + it('lists accounts, forwarding the window and with_status', async () => { + const res = await listGET( + createMockRequest('/api/reconciliation/accounts?date_from=2026-01-01&date_to=2026-08-20&with_status=false'), + { params: Promise.resolve({}) }, + ) + expect(res.status).toBe(200) + const { body } = await parseJsonResponse<{ data: { accounts: unknown[] } }>(res) + expect(body.data.accounts).toHaveLength(1) + expect(listAccountsMock).toHaveBeenCalledWith(supabase, 'company-1', { + windowFrom: '2026-01-01', + windowTo: '2026-08-20', + withStatus: false, + }) + }) + + it('status: 404 on an invalid key, 404 when the service finds nothing, 200 otherwise', async () => { + expect((await statusGET(createMockRequest('/api/reconciliation/accounts/1930'), p({ accountKey: '1930' }))).status).toBe(404) + statusMock.mockResolvedValueOnce(null) + expect((await statusGET(createMockRequest('/api/reconciliation/accounts/skattekonto'), p({ accountKey: 'skattekonto' }))).status).toBe(404) + const res = await statusGET(createMockRequest('/api/reconciliation/accounts/skattekonto?date_from=2026-07-01'), p({ accountKey: 'skattekonto' })) + expect(res.status).toBe(200) + expect(statusMock).toHaveBeenLastCalledWith(supabase, 'company-1', 'skattekonto', { windowFrom: '2026-07-01', windowTo: null }) + }) + + it('items: validates the bucket and forwards paging', async () => { + expect((await itemsGET(createMockRequest('/api/reconciliation/accounts/skattekonto/items?bucket=x'), p({ accountKey: 'skattekonto' }))).status).toBe(400) + const res = await itemsGET(createMockRequest('/api/reconciliation/accounts/skattekonto/items?bucket=proposed&limit=10&offset=20'), p({ accountKey: 'skattekonto' })) + expect(res.status).toBe(200) + expect(itemsMock).toHaveBeenCalledWith(supabase, 'company-1', 'skattekonto', expect.objectContaining({ bucket: 'proposed', limit: 10, offset: 20 })) + }) + + it('links: requires write, validates the body, forwards dry_run', async () => { + requireWriteMock.mockResolvedValueOnce({ ok: false, response: NextResponse.json({ error: 'Read only' }, { status: 403 }) }) + const forbidden = await linksPOST( + createMockRequest('/api/reconciliation/accounts/skattekonto/links', { method: 'POST', body: { use_proposals: true } }), + p({ accountKey: 'skattekonto' }), + ) + expect(forbidden.status).toBe(403) + + const invalid = await linksPOST( + createMockRequest('/api/reconciliation/accounts/skattekonto/links', { method: 'POST', body: { pairs: [] } }), + p({ accountKey: 'skattekonto' }), + ) + expect(invalid.status).toBe(400) + + const res = await linksPOST( + createMockRequest('/api/reconciliation/accounts/skattekonto/links', { + method: 'POST', + body: { pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }], dry_run: true }, + }), + p({ accountKey: 'skattekonto' }), + ) + expect(res.status).toBe(200) + expect(matchMock).toHaveBeenCalledWith( + supabase, + 'company-1', + 'user-1', + 'skattekonto', + { pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }] }, + { dryRun: true }, + ) + }) + + it('unlink and ignore call the service with the ids', async () => { + const del = await linkDELETE(createMockRequest(`/api/reconciliation/accounts/skattekonto/links/${ROW}`, { method: 'DELETE' }), p({ accountKey: 'skattekonto', linkId: ROW })) + expect(del.status).toBe(200) + expect(unmatchMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', 'skattekonto', ROW) + + const ign = await ignorePOST(createMockRequest(`/api/reconciliation/accounts/skattekonto/items/${ROW}/ignore`, { method: 'POST', body: { ignored: false } }), p({ accountKey: 'skattekonto', itemId: ROW })) + expect(ign.status).toBe(200) + expect(ignoreMock).toHaveBeenCalledWith(supabase, 'company-1', 'skattekonto', ROW, false) + }) +}) diff --git a/app/api/reconciliation/accounts/route.ts b/app/api/reconciliation/accounts/route.ts new file mode 100644 index 00000000..1a81722f --- /dev/null +++ b/app/api/reconciliation/accounts/route.ts @@ -0,0 +1,32 @@ +import { NextResponse } from 'next/server' +import { withRouteContext } from '@/lib/api/with-route-context' +import { listReconciliationAccounts } from '@/lib/reconciliation/service' +import { ISO_DATE_RE } from '@/lib/invariants' + +const DATE = ISO_DATE_RE + +/** + * GET /api/reconciliation/accounts + * + * The side list of the Avstämning page: every account with an outside truth + * and its status. Same service function the v1 API and the MCP resource use. + * ?date_from / ?date_to scope the bank bridge; ?with_status=false skips the + * per-account status reads when only the list is needed. + */ +export const GET = withRouteContext( + 'reconciliation.accounts.list', + async (request, { supabase, companyId }) => { + const { searchParams } = new URL(request.url) + const dateFrom = searchParams.get('date_from') || undefined + const dateTo = searchParams.get('date_to') || undefined + if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) { + return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 }) + } + const accounts = await listReconciliationAccounts(supabase, companyId, { + windowFrom: dateFrom, + windowTo: dateTo, + withStatus: searchParams.get('with_status') !== 'false', + }) + return NextResponse.json({ data: { accounts } }) + }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts new file mode 100644 index 00000000..757feb23 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/[itemId]/ignore/route.ts @@ -0,0 +1,98 @@ +/** + * POST /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/items/{itemId}/ignore + * + * Ignore or restore one outside row. Body { ignored: boolean } (default true). + * Ignored rows leave the unmatched totals and surface on the bridge's + * exclusion line; nothing is deleted and the flag is reversible. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { dryRunPreview } from '@/lib/api/v1/dry-run' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { setItemIgnored } from '@/lib/reconciliation/actions' + +const IgnoreRequest = z.object({ ignored: z.boolean().optional() }) +const IgnoreResponse = z.object({ external_id: z.string(), is_ignored: z.boolean() }) + +registerEndpoint({ + operation: 'reconciliation.accounts.items.ignore', + method: 'POST', + path: '/api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items/:itemId/ignore', + summary: 'Ignore or restore one outside row.', + description: + 'Sets the ignore flag on one outside row (bank transaction or skattekonto row). Body { ignored: true | false }, default true. An ignored row never has a link; ignoring a linked row is refused (unlink first). Ignored rows are excluded from the unmatched totals and listed on the bridge\'s exclusion line so they never disappear silently.', + useWhen: + 'A row will never have a counterpart (a duplicate from a reconnect, an event that predates the books) and should stop counting as work.', + doNotUseFor: + 'Rows that should be booked or linked; ignoring is triage, not settlement.', + pitfalls: [ + 'Ignoring is reversible (ignored: false) and audited through the row itself; nothing is deleted.', + 'For the skattekonto, an ignored row still counts toward the derived opening balance (it is a real Skatteverket movement); the bridge shows it on its own line.', + ], + example: { + request: { ignored: true }, + response: { + data: { external_id: '33333333-3333-4333-8333-333333333333', is_ignored: true }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:write', + risk: 'low', + idempotent: true, + reversible: true, + dryRunSupported: true, + request: { body: IgnoreRequest }, + response: { success: dataEnvelope(IgnoreResponse) }, +}) + +export const POST = withApiV1<{ params: Promise<{ companyId: string; accountKey: string; itemId: string }> }>( + 'reconciliation.accounts.items.ignore', + async (request, ctx, params) => { + const { accountKey, itemId } = await params.params + if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(itemId).success) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'itemId', message: 'Okänd rad.' }, + }) + } + let body: unknown = {} + try { + const text = await request.text() + body = text ? JSON.parse(text) : {} + } catch { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { field: 'body', message: 'Body is not valid JSON.' }, + }) + } + const parsed = IgnoreRequest.safeParse(body) + if (!parsed.success) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { + issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })), + }, + }) + } + const ignored = parsed.data.ignored ?? true + try { + if (ctx.dryRun) { + return dryRunPreview({ external_id: itemId, would_set_ignored: ignored }, { requestId: ctx.requestId, log: ctx.log }) + } + const result = await setItemIgnored(ctx.supabase, ctx.companyId!, accountKey, itemId, ignored) + if (!result) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto för det här företaget.' }, + }) + } + return ok(result, { requestId: ctx.requestId }) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, + { requireIdempotencyKey: true }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route.ts new file mode 100644 index 00000000..354437c8 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route.ts @@ -0,0 +1,175 @@ +/** + * GET /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/items + * + * The rows behind the bridge, in the page's buckets, with proposals and the + * actions each row allows. Offset pagination carried in an opaque cursor. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { + AccountKeySchema, + ReconciliationItemBucketSchema, + ReconciliationItemSchema, +} from '@/lib/reconciliation/schemas' +import { listAccountItems, MAX_ITEMS_LIMIT } from '@/lib/reconciliation/items' +import { ISO_DATE_RE } from '@/lib/invariants' + +const DATE = ISO_DATE_RE + +function encodeOffsetCursor(offset: number): string { + return Buffer.from(JSON.stringify({ o: offset }), 'utf8').toString('base64url') +} +function decodeOffsetCursor(cursor: string | null | undefined): number | null { + if (!cursor) return 0 + try { + const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as { o?: unknown } + return typeof parsed.o === 'number' && parsed.o >= 0 ? Math.floor(parsed.o) : null + } catch { + return null + } +} + +const ItemsResponse = z.object({ + items: z.array(ReconciliationItemSchema), + count: z.number().int(), + total_count: z.number().int(), + has_more: z.boolean(), + next_cursor: z.string().nullable(), + /** Unmatched rows dated before date_from: counted so a window can never hide work. */ + older_unmatched_count: z.number().int(), +}) + +registerEndpoint({ + operation: 'reconciliation.accounts.items', + method: 'GET', + path: '/api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items', + summary: 'List the rows behind one account\'s bridge, bucketed.', + description: + 'Returns reconciliation items for one account. ?bucket selects one of proposed | unmatched_external | unmatched_ledger | matched | ignored | upcoming (default: all open buckets first, then matched). Each item carries its side (external | ledger), a qualified item_id (skattekonto_transaction / transaction / journal_entry), date, description, signed amount, the proposal when one exists (journal_entry_id, voucher, confidence, reasons[]), link_problem when a link points at a reversed or draft entry, awaiting_external for fresh ledger lines, and the actions the row allows. ?date_from / ?date_to scope the lists; rows outside the window are never hidden from the counts (older_unmatched_count).', + useWhen: + 'You are about to link, book or ignore rows and need to see what is open and what is proposed.', + doNotUseFor: + 'The totals: those are on GET /reconciliation/accounts/{accountKey}.', + pitfalls: [ + 'An item in bucket proposed is NOT linked: it carries a proposal to link. Apply it with POST .../links { use_proposals: true } or explicit pairs.', + 'actions lists what the row allows right now; an action not listed returns a structured error rather than silently doing nothing.', + 'Ledger items are one per verifikat: several 1630/1930 lines of the same entry are netted, because a link settles the whole entry.', + 'Pagination is ?limit (max 200) + ?cursor; next_cursor is null on the last page.', + ], + example: { + response: { + data: { + items: [ + { + item_id: '33333333-3333-4333-8333-333333333333', + item_type: 'skattekonto_transaction', + side: 'external', + bucket: 'proposed', + date: '2026-08-12', + description: 'Inbetalning bokförd', + amount: 30000, + currency: 'SEK', + proposal: { + journal_entry_id: '44444444-4444-4444-8444-444444444444', + voucher_number: 214, + voucher_series: 'A', + entry_date: '2026-08-11', + description: 'Inbetalning skattekonto', + entry_status: 'posted', + confidence: 0.95, + reasons: ['exakt belopp på 1630', '1 dagars avstånd'], + }, + actions: ['match', 'book', 'ignore'], + }, + ], + count: 1, + total_count: 1, + has_more: false, + next_cursor: null, + older_unmatched_count: 0, + }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:read', + risk: 'low', + idempotent: true, + reversible: false, + dryRunSupported: false, + response: { success: dataEnvelope(ItemsResponse) }, +}) + +export const GET = withApiV1<{ params: Promise<{ companyId: string; accountKey: string }> }>( + 'reconciliation.accounts.items', + async (request, ctx, params) => { + const { accountKey } = await params.params + if (!AccountKeySchema.safeParse(accountKey).success) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto.' }, + }) + } + const url = new URL(request.url) + const Filters = z.object({ + bucket: ReconciliationItemBucketSchema.optional(), + date_from: z.string().regex(DATE).optional(), + date_to: z.string().regex(DATE).optional(), + limit: z.coerce.number().int().min(1).max(MAX_ITEMS_LIMIT).optional(), + cursor: z.string().optional(), + }) + const parsed = Filters.safeParse({ + bucket: url.searchParams.get('bucket') ?? undefined, + date_from: url.searchParams.get('date_from') ?? undefined, + date_to: url.searchParams.get('date_to') ?? undefined, + limit: url.searchParams.get('limit') ?? undefined, + cursor: url.searchParams.get('cursor') ?? undefined, + }) + if (!parsed.success) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { + issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })), + }, + }) + } + const offset = decodeOffsetCursor(parsed.data.cursor) + if (offset === null) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { field: 'cursor', message: 'Ogiltig cursor.' }, + }) + } + try { + const result = await listAccountItems(ctx.supabase, ctx.companyId!, accountKey, { + bucket: parsed.data.bucket, + windowFrom: parsed.data.date_from ?? null, + windowTo: parsed.data.date_to ?? null, + limit: parsed.data.limit, + offset, + }) + if (!result) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto för det här företaget.' }, + }) + } + return ok( + { + items: result.items, + count: result.count, + total_count: result.total_count, + has_more: result.has_more, + next_cursor: + result.has_more && result.next_offset !== undefined ? encodeOffsetCursor(result.next_offset) : null, + older_unmatched_count: result.older_unmatched_count, + }, + { requestId: ctx.requestId }, + ) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts new file mode 100644 index 00000000..20be5507 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/[linkId]/route.ts @@ -0,0 +1,78 @@ +/** + * DELETE /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/links/{linkId} + * + * Remove one link. linkId is the outside row's id (transaction id on a bank + * account, skattekonto_transaction id on the skattekonto): one row holds at + * most one link, so the row id is the link id. The verifikat is untouched. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { dryRunPreview } from '@/lib/api/v1/dry-run' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { unmatchLink } from '@/lib/reconciliation/actions' + +const UnlinkResponse = z.object({ + external_id: z.string(), + previous_journal_entry_id: z.string().nullable(), +}) + +registerEndpoint({ + operation: 'reconciliation.accounts.links.delete', + method: 'DELETE', + path: '/api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links/:linkId', + summary: 'Remove a link between an outside row and a verifikat.', + description: + 'Clears the link on one outside row (bank transaction or skattekonto row). The verifikat is never edited or deleted (BFL); only the row\'s pointer is cleared, so the pair returns to the open buckets and proposals are recomputed on the next sync. Allowed in locked periods. ?dry_run=true reports what would be unlinked.', + useWhen: + 'A link was wrong (a bulk proposal apply that paired the wrong verifikat, a manual mistake).', + doNotUseFor: + 'Undoing a booking: a residual or categorization booking is reversed through the journal-entry reverse endpoint, not by unlinking.', + pitfalls: [ + 'linkId is the outside row id, not a separate link entity.', + 'Unlinking a row whose verifikat was stornoed is the expected fix for a link_problem = entry_reversed item; the row then shows under unmatched_external again.', + ], + example: { + response: { + data: { external_id: '33333333-3333-4333-8333-333333333333', previous_journal_entry_id: '44444444-4444-4444-8444-444444444444' }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:write', + risk: 'low', + idempotent: true, + reversible: true, + dryRunSupported: true, + response: { success: dataEnvelope(UnlinkResponse) }, +}) + +export const DELETE = withApiV1<{ params: Promise<{ companyId: string; accountKey: string; linkId: string }> }>( + 'reconciliation.accounts.links.delete', + async (_request, ctx, params) => { + const { accountKey, linkId } = await params.params + if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(linkId).success) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'linkId', message: 'Okänd koppling.' }, + }) + } + try { + if (ctx.dryRun) { + return dryRunPreview({ external_id: linkId, would_unlink: true }, { requestId: ctx.requestId, log: ctx.log }) + } + const result = await unmatchLink(ctx.supabase, ctx.companyId!, ctx.userId, accountKey, linkId) + if (!result) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto för det här företaget.' }, + }) + } + return ok(result, { requestId: ctx.requestId }) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, + { requireIdempotencyKey: true }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route.ts new file mode 100644 index 00000000..907b17e0 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/links/route.ts @@ -0,0 +1,150 @@ +/** + * POST /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/links + * + * Link outside rows to existing verifikat on one account. Pairs, or the + * persisted proposals. Writes nothing to the ledger: a link only points a + * row at a verifikat, so it is allowed in locked periods and reversible by + * DELETE .../links/{linkId}. Dry-runnable; Idempotency-Key required. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { dryRunPreview } from '@/lib/api/v1/dry-run' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { AccountKeySchema } from '@/lib/reconciliation/schemas' +import { matchPairs } from '@/lib/reconciliation/actions' + +const PairSchema = z.object({ + external_ids: z.array(z.string().uuid()).min(1).max(50), + journal_entry_ids: z.array(z.string().uuid()).min(1).max(50), +}) + +const LinksRequest = z + .object({ + pairs: z.array(PairSchema).max(200).optional(), + use_proposals: z.boolean().optional(), + confidence_threshold: z.number().min(0).max(1).optional(), + }) + .refine((b) => (b.pairs && b.pairs.length > 0) || b.use_proposals === true, { + message: 'Ange pairs eller use_proposals: true.', + }) + +const LinksResponse = z.object({ + dry_run: z.boolean(), + considered: z.number().int(), + applied: z.array( + z.object({ + external_id: z.string(), + journal_entry_id: z.string(), + via: z.enum(['line', 'entry_total']).optional(), + }), + ), + skipped: z.array( + z.object({ + pair: PairSchema, + code: z.string(), + message: z.string(), + }), + ), +}) + +registerEndpoint({ + operation: 'reconciliation.accounts.links.create', + method: 'POST', + path: '/api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links', + summary: 'Link outside rows to existing verifikat (pairs or proposals).', + description: + 'Body: { pairs: [{ external_ids: [id], journal_entry_ids: [id] }] } and/or { use_proposals: true, confidence_threshold? }. Each pair is validated as the single-link paths validate (row open and not ignored, entry posted and not reversed, the entry\'s account lines settle the amount, entry not already linked) and applied independently: the response lists applied[] and skipped[{pair, code, message}] so partial success is explicit. Codes: UNSUPPORTED_PAIR_SHAPE, ALREADY_LINKED, ENTRY_NOT_FOUND, PAIR_NOT_CLOSED, ROW_IGNORED, NOT_FOUND, LINK_RACE. ?dry_run=true returns the pairs that would be attempted without writing.', + useWhen: + 'An agent or integration has decided which rows explain each other, or wants to apply the proposals the sync already computed.', + doNotUseFor: + 'Booking new verifikat for rows that have no counterpart (use the transactions or skattekonto booking endpoints); reconciling across accounts.', + pitfalls: [ + 'This version links one outside row to one verifikat per pair; other shapes come back as UNSUPPORTED_PAIR_SHAPE, never silently reduced.', + 'A pair must close to the row\'s amount on the expected side (a single matching line, or the entry\'s lines on the account netting to it); a fee or rounding difference is PAIR_NOT_CLOSED here and needs a residual booking first.', + 'Links never touch the ledger, so they succeed in locked periods; unlink with DELETE .../links/{linkId} (linkId = the outside row id).', + 'Idempotency-Key is required; repeating the same key replays the first response.', + ], + example: { + request: { use_proposals: true, confidence_threshold: 0.9 }, + response: { + data: { + dry_run: false, + considered: 2, + applied: [ + { external_id: '33333333-3333-4333-8333-333333333333', journal_entry_id: '44444444-4444-4444-8444-444444444444', via: 'line' }, + ], + skipped: [ + { + pair: { external_ids: ['55555555-5555-4555-8555-555555555555'], journal_entry_ids: ['66666666-6666-4666-8666-666666666666'] }, + code: 'ALREADY_LINKED', + message: 'Verifikatet är redan kopplat till en annan skattekonto-transaktion.', + }, + ], + }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:write', + risk: 'medium', + idempotent: false, + reversible: true, + dryRunSupported: true, + request: { body: LinksRequest }, + response: { success: dataEnvelope(LinksResponse) }, +}) + +export const POST = withApiV1<{ params: Promise<{ companyId: string; accountKey: string }> }>( + 'reconciliation.accounts.links.create', + async (request, ctx, params) => { + const { accountKey } = await params.params + if (!AccountKeySchema.safeParse(accountKey).success) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto.' }, + }) + } + let rawBody: unknown + try { + rawBody = await request.json() + } catch { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { field: 'body', message: 'Body is not valid JSON.' }, + }) + } + const parsed = LinksRequest.safeParse(rawBody) + if (!parsed.success) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { + issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })), + }, + }) + } + try { + const result = await matchPairs( + ctx.supabase, + ctx.companyId!, + ctx.userId, + accountKey, + parsed.data, + { dryRun: ctx.dryRun }, + ) + if (!result) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto för det här företaget.' }, + }) + } + if (ctx.dryRun) { + return dryRunPreview(result, { requestId: ctx.requestId, log: ctx.log }) + } + return ok(result, { requestId: ctx.requestId }) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, + { requireIdempotencyKey: true }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route.ts new file mode 100644 index 00000000..8fe8a8ed --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route.ts @@ -0,0 +1,118 @@ +/** + * GET /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey} + * + * The bridge for one account: what the outside says, what the ledger says, + * the difference, and the lines that explain it. Read-only. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { ISO_DATE_RE } from '@/lib/invariants' +import { AccountKeySchema, ReconciliationStatusSchema } from '@/lib/reconciliation/schemas' +import { getAccountStatus } from '@/lib/reconciliation/service' + +const DATE = ISO_DATE_RE + +registerEndpoint({ + operation: 'reconciliation.accounts.status', + method: 'GET', + path: '/api/v1/companies/:companyId/reconciliation/accounts/:accountKey', + summary: 'The reconciliation bridge for one account.', + description: + 'Returns external_balance (Skatteverket saldo; null for bank accounts until a statement balance exists), ledger_balance (1630 balance at the snapshot for skattekonto; period movement on the bank account), difference, unexplained_difference, is_reconciled, the bridge lines (label, amount, count, items_bucket) that explain the difference row by row, counts per bucket, and a kind block (skattekonto: saldo, fetched_at, history_start, opening_difference, upcoming; bank: today\'s bank status fields). Optional ?date_from / ?date_to: for skattekonto they scope the item lists only (the bridge is anchored at the snapshot); for bank they scope the bridge window.', + useWhen: + 'You need to know whether an account reconciles and why not: the bridge is the explanation, the buckets are the work.', + doNotUseFor: + 'Listing the rows themselves (use .../items) or linking (POST .../links).', + pitfalls: [ + 'Judge health on unexplained_difference, never on difference. The difference is expected to be non-zero while rows are unmatched; unexplained_difference is what is left once every bridge line is accounted for, and for skattekonto it is 0,00 whenever the data is consistent (a non-zero value is an integrity finding, not a task).', + 'stale = true means the outside truth is older than 7 days (Skatteverket connection needing re-consent is the usual cause). is_reconciled can still be true on stale data; read both.', + 'skattekonto.opening_difference is the gap between the derived saldo at history_start and the ledger before it; it belongs to migrated ledgers and is accepted once at sign-off, not worked down.', + 'Bank accounts carry the legacy field set in the bank block (bank_transaction_total, gl_1930_period_movement, …) unchanged from /reconciliation/bank/status.', + ], + example: { + response: { + data: { + account_key: 'skattekonto', + kind: 'skattekonto', + account_number: '1630', + currency: 'SEK', + window: { from: null, to: null }, + as_of: '2026-08-20T04:00:12.000Z', + stale: false, + external_balance: 53395, + ledger_balance: 30342, + difference: 23053, + unexplained_difference: 0, + is_reconciled: false, + bridge: [ + { key: 'external_balance', label_sv: 'Saldo hos Skatteverket', label_en: 'Balance at Skatteverket', amount: 53395, count: null, items_bucket: null }, + { key: 'unmatched_external', label_sv: 'Händelser som saknas i bokföringen', label_en: 'Events missing from the ledger', amount: -35553, count: 5, items_bucket: 'unmatched_external' }, + { key: 'unmatched_ledger', label_sv: 'Rader på 1630 utan händelse hos Skatteverket', label_en: '1630 lines without a Skatteverket event', amount: 12500, count: 1, items_bucket: 'unmatched_ledger' }, + { key: 'ledger_balance', label_sv: 'Bokfört på 1630', label_en: 'Booked on 1630', amount: 30342, count: null, items_bucket: null }, + ], + counts: { proposed: 2, unmatched_external: 3, unmatched_ledger: 1, matched: 41, ignored: 0 }, + skattekonto: { saldo_skatteverket: 53395, fetched_at: '2026-08-20T04:00:12.000Z', history_start: '2025-01-17', opening_difference: 0, upcoming_count: 3, upcoming_total: -18450, ledger_balance_before_start: 0 }, + bank: null, + }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:read', + risk: 'low', + idempotent: true, + reversible: false, + dryRunSupported: false, + response: { success: dataEnvelope(ReconciliationStatusSchema) }, +}) + +export const GET = withApiV1<{ params: Promise<{ companyId: string; accountKey: string }> }>( + 'reconciliation.accounts.status', + async (request, ctx, params) => { + const { accountKey } = await params.params + if (!AccountKeySchema.safeParse(accountKey).success) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto.' }, + }) + } + const url = new URL(request.url) + const Filters = z.object({ + date_from: z.string().regex(DATE).optional(), + date_to: z.string().regex(DATE).optional(), + }) + const parsed = Filters.safeParse({ + date_from: url.searchParams.get('date_from') ?? undefined, + date_to: url.searchParams.get('date_to') ?? undefined, + }) + if (!parsed.success) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { + issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })), + }, + }) + } + try { + const status = await getAccountStatus(ctx.supabase, ctx.companyId!, accountKey, { + windowFrom: parsed.data.date_from ?? null, + windowTo: parsed.data.date_to ?? null, + }) + if (!status) { + return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, { + requestId: ctx.requestId, + details: { field: 'accountKey', message: 'Okänt konto för det här företaget.' }, + }) + } + // The skattekonto engine returns its item lists too; the status route is + // the bridge only. Items live at .../items. + const { items: _items, ...rest } = status as typeof status & { items?: unknown } + void _items + return ok(rest, { requestId: ctx.requestId }) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, +) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/__tests__/route.test.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/__tests__/route.test.ts new file mode 100644 index 00000000..16d51be7 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/__tests__/route.test.ts @@ -0,0 +1,244 @@ +/** + * Tests for the account-keyed reconciliation v1 routes: + * GET .../reconciliation/accounts + * GET .../reconciliation/accounts/{accountKey} + * GET .../reconciliation/accounts/{accountKey}/items + * POST .../reconciliation/accounts/{accountKey}/links + * DELETE .../reconciliation/accounts/{accountKey}/links/{linkId} + * POST .../reconciliation/accounts/{accountKey}/items/{itemId}/ignore + * + * Exercises the real withApiV1 wrapper (auth, scope, company membership, + * idempotency, dry-run) with the service layer mocked. + */ +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +beforeAll(() => { + if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required') + process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321' + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key' +}) + +vi.mock('@/lib/auth/api-keys', async () => { + const actual = await vi.importActual('@/lib/auth/api-keys') + return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() } +}) +vi.mock('@supabase/supabase-js', async () => { + const actual = await vi.importActual('@supabase/supabase-js') + return { ...actual, createClient: vi.fn().mockReturnValue({}) } +}) + +const { listAccountsMock, statusMock, itemsMock, matchMock, unmatchMock, ignoreMock } = vi.hoisted(() => ({ + listAccountsMock: vi.fn(), + statusMock: vi.fn(), + itemsMock: vi.fn(), + matchMock: vi.fn(), + unmatchMock: vi.fn(), + ignoreMock: vi.fn(), +})) + +vi.mock('@/lib/reconciliation/service', () => ({ + listReconciliationAccounts: listAccountsMock, + getAccountStatus: statusMock, +})) +vi.mock('@/lib/reconciliation/items', async () => { + const actual = await vi.importActual('@/lib/reconciliation/items') + return { ...actual, listAccountItems: itemsMock } +}) +vi.mock('@/lib/reconciliation/actions', () => ({ + matchPairs: matchMock, + unmatchLink: unmatchMock, + setItemIgnored: ignoreMock, +})) + +import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys' +import { GET as listGET } from '../route' +import { GET as statusGET } from '../[accountKey]/route' +import { GET as itemsGET } from '../[accountKey]/items/route' +import { POST as linksPOST } from '../[accountKey]/links/route' +import { DELETE as linkDELETE } from '../[accountKey]/links/[linkId]/route' +import { POST as ignorePOST } from '../[accountKey]/items/[itemId]/ignore/route' + +const mockValidate = validateApiKey as ReturnType +const mockServiceClient = createServiceClientNoCookies as ReturnType + +type MockResult = { data?: unknown; error?: unknown } +function makeFlexibleSupabase(byTable: Record) { + const queues = new Map() + for (const [t, val] of Object.entries(byTable)) queues.set(t, Array.isArray(val) ? [...val] : [val]) + const buildChain = (table: string): unknown => { + const handler: ProxyHandler = { + get(_target, prop) { + if (prop === 'then') { + return (resolve: (v: unknown) => void) => { + const q = queues.get(table) + const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null }) + resolve(next) + } + } + return (..._args: unknown[]) => buildChain(table) + }, + } + return new Proxy({}, handler) + } + return { from: vi.fn((table: string) => buildChain(table)) } +} + +const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const CASH = '11111111-1111-4111-8111-111111111111' +const ROW = '22222222-2222-4222-8222-222222222222' +const ENTRY = '33333333-3333-4333-8333-333333333333' +const BASE = `http://localhost/api/v1/companies/${COMPANY_ID}/reconciliation/accounts` + +function req(url: string, init: { method?: string; body?: unknown; idem?: boolean; dryRun?: boolean } = {}): Request { + const headers: Record = { + Authorization: 'Bearer test-fixture-not-a-real-key', + 'Content-Type': 'application/json', + } + if (init.idem !== false && init.method && init.method !== 'GET') headers['Idempotency-Key'] = `idem-${Math.random().toString(36).slice(2)}-aaaa-4abc-8def-1234567890ab` + if (init.dryRun) headers['X-Dry-Run'] = 'true' + return new Request(url, { + method: init.method ?? 'GET', + headers, + body: init.body !== undefined ? JSON.stringify(init.body) : undefined, + }) +} + +function authOk(scopes: string[]) { + mockValidate.mockResolvedValue({ + valid: true, + userId: 'user-1', + keyId: 'key-1', + keyName: 'Test key', + scopes, + mode: 'live', + }) +} + +// Dynamic-route params for the handlers under test; `never` keeps each +// handler's own params type while letting one helper serve all of them. +const params = (extra: Record = {}) => + ({ params: Promise.resolve({ companyId: COMPANY_ID, ...extra }) }) as never + +describe('v1 reconciliation accounts', () => { + beforeEach(() => { + vi.clearAllMocks() + mockServiceClient.mockReturnValue( + makeFlexibleSupabase({ + company_members: { data: { role: 'owner' } }, + idempotency_keys: { data: null }, + }), + ) + listAccountsMock.mockResolvedValue([{ account_key: 'skattekonto', kind: 'skattekonto' }]) + statusMock.mockResolvedValue({ account_key: 'skattekonto', kind: 'skattekonto', items: { proposed: [] }, bridge: [] }) + itemsMock.mockResolvedValue({ items: [], count: 0, total_count: 0, has_more: false, older_unmatched_count: 0 }) + matchMock.mockResolvedValue({ dry_run: false, considered: 1, applied: [{ external_id: ROW, journal_entry_id: ENTRY }], skipped: [] }) + unmatchMock.mockResolvedValue({ external_id: ROW, previous_journal_entry_id: ENTRY }) + ignoreMock.mockResolvedValue({ external_id: ROW, is_ignored: true }) + }) + + it('401 without a valid key', async () => { + mockValidate.mockResolvedValue({ valid: false, error: 'invalid' }) + const res = await listGET(req(BASE), params()) + expect(res.status).toBe(401) + }) + + it('403 INSUFFICIENT_SCOPE when the key lacks reconciliation:read', async () => { + authOk(['transactions:read']) + const res = await listGET(req(BASE), params()) + expect(res.status).toBe(403) + }) + + it('GET accounts returns the list', async () => { + authOk(['reconciliation:read']) + const res = await listGET(req(`${BASE}?with_status=false`), params()) + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data.accounts[0].account_key).toBe('skattekonto') + expect(listAccountsMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, expect.objectContaining({ withStatus: false })) + }) + + it('GET accounts rejects a malformed date with VALIDATION_ERROR', async () => { + authOk(['reconciliation:read']) + const res = await listGET(req(`${BASE}?date_from=20260101`), params()) + expect(res.status).toBe(400) + }) + + it('GET status strips the item lists and 404s an unknown account key', async () => { + authOk(['reconciliation:read']) + const ok = await statusGET(req(`${BASE}/skattekonto`), params({ accountKey: 'skattekonto' })) + expect(ok.status).toBe(200) + const body = await ok.json() + expect(body.data.items).toBeUndefined() + expect(body.data.bridge).toEqual([]) + + const bad = await statusGET(req(`${BASE}/1930`), params({ accountKey: '1930' })) + expect(bad.status).toBe(404) + + statusMock.mockResolvedValueOnce(null) + const missing = await statusGET(req(`${BASE}/bank:${CASH}`), params({ accountKey: `bank:${CASH}` })) + expect(missing.status).toBe(404) + }) + + it('GET items pages through an opaque cursor and validates the bucket', async () => { + authOk(['reconciliation:read']) + itemsMock.mockResolvedValue({ items: [{ item_id: ROW }], count: 1, total_count: 3, has_more: true, next_offset: 1, older_unmatched_count: 0 }) + const res = await itemsGET(req(`${BASE}/skattekonto/items?bucket=proposed&limit=1`), params({ accountKey: 'skattekonto' })) + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data.next_cursor).toBeTruthy() + expect(itemsMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'skattekonto', expect.objectContaining({ bucket: 'proposed', limit: 1, offset: 0 })) + + const page2 = await itemsGET(req(`${BASE}/skattekonto/items?cursor=${body.data.next_cursor}`), params({ accountKey: 'skattekonto' })) + expect(page2.status).toBe(200) + expect(itemsMock).toHaveBeenLastCalledWith(expect.anything(), COMPANY_ID, 'skattekonto', expect.objectContaining({ offset: 1 })) + + const bad = await itemsGET(req(`${BASE}/skattekonto/items?bucket=nope`), params({ accountKey: 'skattekonto' })) + expect(bad.status).toBe(400) + }) + + it('POST links requires reconciliation:write and an Idempotency-Key, applies, and previews on dry run', async () => { + authOk(['reconciliation:read']) + const forbidden = await linksPOST(req(`${BASE}/skattekonto/links`, { method: 'POST', body: { use_proposals: true } }), params({ accountKey: 'skattekonto' })) + expect(forbidden.status).toBe(403) + + authOk(['reconciliation:write']) + const noIdem = await linksPOST(req(`${BASE}/skattekonto/links`, { method: 'POST', body: { use_proposals: true }, idem: false }), params({ accountKey: 'skattekonto' })) + expect(noIdem.status).toBe(400) + + const invalid = await linksPOST(req(`${BASE}/skattekonto/links`, { method: 'POST', body: {} }), params({ accountKey: 'skattekonto' })) + expect(invalid.status).toBe(400) + + const applied = await linksPOST( + req(`${BASE}/skattekonto/links`, { method: 'POST', body: { pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }] } }), + params({ accountKey: 'skattekonto' }), + ) + expect(applied.status).toBe(200) + expect(matchMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'user-1', 'skattekonto', expect.objectContaining({ pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }] }), { dryRun: false }) + + const preview = await linksPOST( + req(`${BASE}/skattekonto/links`, { method: 'POST', body: { use_proposals: true }, dryRun: true }), + params({ accountKey: 'skattekonto' }), + ) + expect(preview.status).toBe(200) + expect(preview.headers.get('X-Dry-Run')).toBe('true') + expect(matchMock).toHaveBeenLastCalledWith(expect.anything(), COMPANY_ID, 'user-1', 'skattekonto', expect.anything(), { dryRun: true }) + }) + + it('DELETE link unmatches and 404s a non-uuid link id', async () => { + authOk(['reconciliation:write']) + const ok = await linkDELETE(req(`${BASE}/skattekonto/links/${ROW}`, { method: 'DELETE' }), params({ accountKey: 'skattekonto', linkId: ROW })) + expect(ok.status).toBe(200) + expect(unmatchMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'user-1', 'skattekonto', ROW) + const bad = await linkDELETE(req(`${BASE}/skattekonto/links/abc`, { method: 'DELETE' }), params({ accountKey: 'skattekonto', linkId: 'abc' })) + expect(bad.status).toBe(404) + }) + + it('POST ignore defaults to ignored: true and accepts an explicit restore', async () => { + authOk(['reconciliation:write']) + const res = await ignorePOST(req(`${BASE}/skattekonto/items/${ROW}/ignore`, { method: 'POST' }), params({ accountKey: 'skattekonto', itemId: ROW })) + expect(res.status).toBe(200) + expect(ignoreMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'skattekonto', ROW, true) + await ignorePOST(req(`${BASE}/skattekonto/items/${ROW}/ignore`, { method: 'POST', body: { ignored: false } }), params({ accountKey: 'skattekonto', itemId: ROW })) + expect(ignoreMock).toHaveBeenLastCalledWith(expect.anything(), COMPANY_ID, 'skattekonto', ROW, false) + }) +}) diff --git a/app/api/v1/companies/[companyId]/reconciliation/accounts/route.ts b/app/api/v1/companies/[companyId]/reconciliation/accounts/route.ts new file mode 100644 index 00000000..8cda76c4 --- /dev/null +++ b/app/api/v1/companies/[companyId]/reconciliation/accounts/route.ts @@ -0,0 +1,122 @@ +/** + * GET /api/v1/companies/{companyId}/reconciliation/accounts + * + * Every account with an outside truth, as the Avstämning page lists them: + * enabled cash accounts (deduplicated per IBAN) and the skattekonto when the + * company has a saldo snapshot or rows. One row per account with its source, + * sync age and status (state, unexplained difference, open counts). + * Read-only, no dry-run, no idempotency. + */ +import { z } from 'zod' +import { ok } from '@/lib/api/v1/response' +import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry' +import { withApiV1 } from '@/lib/api/v1/with-api-v1' +import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' +import { ISO_DATE_RE } from '@/lib/invariants' +import { ReconciliationAccountSchema } from '@/lib/reconciliation/schemas' +import { listReconciliationAccounts } from '@/lib/reconciliation/service' + +const DATE = ISO_DATE_RE + +const AccountsResponse = z.object({ accounts: z.array(ReconciliationAccountSchema) }) + +registerEndpoint({ + operation: 'reconciliation.accounts.list', + method: 'GET', + path: '/api/v1/companies/:companyId/reconciliation/accounts', + summary: 'List the accounts that can be reconciled, with status per account.', + description: + 'Returns one row per reconcilable account (bank: for each enabled cash account, skattekonto when configured) with kind, number, currency, source (psd2 / bank_file / skatteverket_api / manual, synced_at, stale), status (reconciled | open | stale | not_configured, unexplained_difference, open_counts) and superseded_by for reconnect duplicates. Optional ?date_from / ?date_to scope the bank bridge (default: the calendar year to date). Pass ?with_status=false for a cheap list without status.', + useWhen: + 'You need the side list of the Avstämning page, a month-end checklist, or to find the account_key to pass to the other reconciliation endpoints.', + doNotUseFor: + 'The bridge and rows for one account: use GET /reconciliation/accounts/{accountKey} and .../items.', + pitfalls: [ + 'account_key is the identifier every other reconciliation endpoint takes: bank: or skattekonto. Do not pass the BAS number.', + 'status.state = stale means the outside truth is older than 7 days; the numbers are still computed, but judge them accordingly.', + 'superseded_by is set on an older cash account that shares IBAN + currency with a newer one (reconnect duplicate); it is kept in the list because it may still hold unlinked rows.', + 'Computing status per account runs one reconciliation per account; with_status=false skips that when you only need the list.', + ], + example: { + response: { + data: { + accounts: [ + { + account_key: 'bank:11111111-1111-4111-8111-111111111111', + kind: 'bank', + account_number: '1930', + name: 'Swedbank företagskonto', + currency: 'SEK', + logo_url: null, + source: { type: 'psd2', synced_at: '2026-08-20T06:40:00.000Z', stale: false }, + status: { + state: 'open', + as_of: '2026-08-20T09:00:00.000Z', + unexplained_difference: 0, + open_counts: { proposed: 0, unmatched_external: 1, unmatched_ledger: 1 }, + }, + superseded_by: null, + }, + { + account_key: 'skattekonto', + kind: 'skattekonto', + account_number: '1630', + name: 'Skattekonto', + currency: 'SEK', + logo_url: '/logos/skatteverket_color.svg', + source: { type: 'skatteverket_api', synced_at: '2026-08-20T04:00:12.000Z', stale: false }, + status: { + state: 'open', + as_of: '2026-08-20T04:00:12.000Z', + unexplained_difference: 0, + open_counts: { proposed: 2, unmatched_external: 3, unmatched_ledger: 1 }, + }, + superseded_by: null, + }, + ], + }, + meta: { request_id: 'req_…', api_version: '2026-05-12' }, + }, + }, + scope: 'reconciliation:read', + risk: 'low', + idempotent: true, + reversible: false, + dryRunSupported: false, + response: { success: dataEnvelope(AccountsResponse) }, +}) + +export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>( + 'reconciliation.accounts.list', + async (request, ctx) => { + const url = new URL(request.url) + const Filters = z.object({ + date_from: z.string().regex(DATE).optional(), + date_to: z.string().regex(DATE).optional(), + with_status: z.enum(['true', 'false']).optional(), + }) + const parsed = Filters.safeParse({ + date_from: url.searchParams.get('date_from') ?? undefined, + date_to: url.searchParams.get('date_to') ?? undefined, + with_status: url.searchParams.get('with_status') ?? undefined, + }) + if (!parsed.success) { + return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, { + requestId: ctx.requestId, + details: { + issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })), + }, + }) + } + try { + const accounts = await listReconciliationAccounts(ctx.supabase, ctx.companyId!, { + windowFrom: parsed.data.date_from, + windowTo: parsed.data.date_to, + withStatus: parsed.data.with_status !== 'false', + }) + return ok({ accounts }, { requestId: ctx.requestId }) + } catch (err) { + return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId }) + } + }, +) diff --git a/extensions/general/mcp-server/__tests__/reconciliation-tools.test.ts b/extensions/general/mcp-server/__tests__/reconciliation-tools.test.ts new file mode 100644 index 00000000..6fef81b9 --- /dev/null +++ b/extensions/general/mcp-server/__tests__/reconciliation-tools.test.ts @@ -0,0 +1,162 @@ +/** + * The account-keyed reconciliation tools: status (account_key branch), items, + * reconcile_match (stages; dry_run previews), reconcile_unmatch (search-only). + * Service functions are mocked; the staging path runs for real in dry_run + * mode (no insert), so the STAGED_OPERATION_SCHEMA contract is exercised. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createQueuedMockSupabase } from '@/tests/helpers' + +const statusMock = vi.fn() +const itemsMock = vi.fn() +const matchMock = vi.fn() + +vi.mock('@/lib/reconciliation/service', () => ({ + getAccountStatus: (...args: unknown[]) => statusMock(...args), + listReconciliationAccounts: vi.fn(), +})) +vi.mock('@/lib/reconciliation/items', async () => { + const actual = await vi.importActual('@/lib/reconciliation/items') + return { ...actual, listAccountItems: (...args: unknown[]) => itemsMock(...args) } +}) +vi.mock('@/lib/reconciliation/actions', () => ({ + matchPairs: (...args: unknown[]) => matchMock(...args), + unmatchLink: vi.fn(), + setItemIgnored: vi.fn(), +})) + +import { tools, isDefaultCatalogTool, deriveToolMeta } from '../server' + +const COMPANY = 'company-1' +const USER = 'user-1' +const ROW = '22222222-2222-4222-8222-222222222222' +const ENTRY = '33333333-3333-4333-8333-333333333333' + +function tool(name: string) { + const t = tools.find((x) => x.name === name) + if (!t) throw new Error(`tool ${name} not registered`) + return t +} + +describe('reconciliation MCP tools', () => { + beforeEach(() => { + vi.clearAllMocks() + statusMock.mockReset() + itemsMock.mockReset() + matchMock.mockReset() + }) + + it('registers the four tools with the intended catalog visibility and staging contract', () => { + expect(isDefaultCatalogTool(tool('gnubok_get_reconciliation_status'))).toBe(true) + expect(isDefaultCatalogTool(tool('gnubok_list_reconciliation_items'))).toBe(true) + // Writes sit behind search to respect the tools/list payload ceiling. + expect(isDefaultCatalogTool(tool('gnubok_reconcile_match'))).toBe(false) + expect(isDefaultCatalogTool(tool('gnubok_reconcile_unmatch'))).toBe(false) + expect(isDefaultCatalogTool(tool('gnubok_link_transaction_to_journal_entry'))).toBe(false) + expect(deriveToolMeta(tool('gnubok_reconcile_match'))).toMatchObject({ + requires_approval: true, + preflight: 'gnubok_get_reconciliation_status', + }) + expect(deriveToolMeta(tool('gnubok_reconcile_unmatch'))).toMatchObject({ requires_approval: true }) + expect(deriveToolMeta(tool('gnubok_list_reconciliation_items'))).toBeUndefined() + }) + + it('status with account_key dispatches to the service and strips item lists', async () => { + const { supabase } = createQueuedMockSupabase() + statusMock.mockResolvedValue({ account_key: 'skattekonto', bridge: [{ key: 'x' }], items: { proposed: [] } }) + const out = (await tool('gnubok_get_reconciliation_status').execute( + { account_key: 'skattekonto', date_from: '2026-07-01' }, + COMPANY, + USER, + supabase as never, + )) as Record + expect(statusMock).toHaveBeenCalledWith(supabase, COMPANY, 'skattekonto', { windowFrom: '2026-07-01', windowTo: null }) + expect(out.items).toBeUndefined() + expect(out.bridge).toEqual([{ key: 'x' }]) + }) + + it('status with an unknown account_key throws', async () => { + const { supabase } = createQueuedMockSupabase() + statusMock.mockResolvedValue(null) + await expect( + tool('gnubok_get_reconciliation_status').execute({ account_key: 'skattekonto' }, COMPANY, USER, supabase as never), + ).rejects.toThrow(/Unknown account_key/) + }) + + it('items forwards bucket and paging', async () => { + const { supabase } = createQueuedMockSupabase() + itemsMock.mockResolvedValue({ items: [], count: 0, total_count: 0, has_more: false, older_unmatched_count: 0 }) + const out = await tool('gnubok_list_reconciliation_items').execute( + { account_key: 'skattekonto', bucket: 'proposed', limit: 10, offset: 5 }, + COMPANY, + USER, + supabase as never, + ) + expect(itemsMock).toHaveBeenCalledWith(supabase, COMPANY, 'skattekonto', { + bucket: 'proposed', + windowFrom: null, + windowTo: null, + limit: 10, + offset: 5, + }) + expect(out).toMatchObject({ count: 0, total_count: 0, has_more: false }) + }) + + it('reconcile_match resolves pairs through a dry-run preview and stages them (dry_run returns staged: false)', async () => { + const { supabase } = createQueuedMockSupabase() + matchMock.mockResolvedValue({ + dry_run: true, + considered: 2, + applied: [{ external_id: ROW, journal_entry_id: ENTRY }], + skipped: [{ pair: { external_ids: ['x'], journal_entry_ids: ['y'] }, code: 'ALREADY_LINKED', message: 'redan' }], + }) + const out = (await tool('gnubok_reconcile_match').execute( + { account_key: 'skattekonto', use_proposals: true, dry_run: true }, + COMPANY, + USER, + supabase as never, + { type: 'api_key', id: 'key-1' } as never, + )) as Record + expect(matchMock).toHaveBeenCalledWith( + supabase, + COMPANY, + USER, + 'skattekonto', + { pairs: [], use_proposals: true, confidence_threshold: 0.9 }, + { dryRun: true }, + ) + expect(out).toMatchObject({ staged: false, dry_run: true, risk_level: 'medium' }) + const preview = out.preview as Record + expect(preview).toMatchObject({ account_key: 'skattekonto', pair_count: 1, source: 'proposals' }) + expect(preview.pairs).toEqual([{ external_ids: [ROW], journal_entry_ids: [ENTRY] }]) + expect(out.next).toMatchObject({ tool: 'gnubok_get_reconciliation_status' }) + }) + + it('reconcile_match refuses an empty request and a request with nothing linkable', async () => { + const { supabase } = createQueuedMockSupabase() + await expect( + tool('gnubok_reconcile_match').execute({ account_key: 'skattekonto' }, COMPANY, USER, supabase as never), + ).rejects.toThrow(/pairs|use_proposals/) + matchMock.mockResolvedValue({ dry_run: true, considered: 1, applied: [], skipped: [] }) + await expect( + tool('gnubok_reconcile_match').execute( + { account_key: 'skattekonto', pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }] }, + COMPANY, + USER, + supabase as never, + ), + ).rejects.toThrow(/nothing to stage/i) + }) + + it('reconcile_unmatch dry-run returns the low-risk staging preview', async () => { + const { supabase } = createQueuedMockSupabase() + const out = (await tool('gnubok_reconcile_unmatch').execute( + { account_key: 'skattekonto', external_id: ROW, dry_run: true }, + COMPANY, + USER, + supabase as never, + )) as Record + expect(out).toMatchObject({ staged: false, dry_run: true, risk_level: 'low' }) + expect(out.preview).toEqual({ account_key: 'skattekonto', external_id: ROW }) + }) +}) diff --git a/extensions/general/mcp-server/recommended-tools.ts b/extensions/general/mcp-server/recommended-tools.ts index ac8a8761..0ae1b0c5 100644 --- a/extensions/general/mcp-server/recommended-tools.ts +++ b/extensions/general/mcp-server/recommended-tools.ts @@ -64,6 +64,10 @@ export const RECOMMENDED_WORKFLOW_LOADOUTS: readonly WorkflowLoadout[] = [ 'gnubok_list_fiscal_periods', 'gnubok_list_uncategorized_transactions', 'gnubok_get_reconciliation_status', + // Account-keyed reconciliation: the rows behind the bridge and the + // staged link (bank accounts and skattekonto alike). + 'gnubok_list_reconciliation_items', + 'gnubok_reconcile_match', 'gnubok_list_voucher_gaps', 'gnubok_explain_voucher_gap', 'gnubok_lock_period', diff --git a/extensions/general/mcp-server/server.ts b/extensions/general/mcp-server/server.ts index dcaaff2d..86dc5d01 100644 --- a/extensions/general/mcp-server/server.ts +++ b/extensions/general/mcp-server/server.ts @@ -167,6 +167,12 @@ import { import { assertNoPlaintextPersonnummer } from './staging-pii-guard' import { generateBalanceSheet } from '@/lib/reports/balance-sheet' import { generateGeneralLedger } from '@/lib/reports/general-ledger' +// Account-keyed reconciliation (one engine, three doors): the same service +// the dashboard routes and the v1 API call. +import { getAccountStatus } from '@/lib/reconciliation/service' +import { listAccountItems } from '@/lib/reconciliation/items' +import { matchPairs } from '@/lib/reconciliation/actions' +import { parseAccountKey, type ReconciliationItemBucket } from '@/lib/reconciliation/schemas' import { decryptPersonnummer, maskEmployeeForResponse, maskPersonnummer } from '@/lib/salary/personnummer' import { deriveAgiFilingState, @@ -1358,6 +1364,7 @@ const TOOL_PREFLIGHT_MAP: Record = { gnubok_vat_declaration_submit: 'gnubok_vat_declaration_validate', gnubok_post_annual_depreciation: 'gnubok_propose_annual_depreciation', gnubok_book_salary_run: 'gnubok_get_salary_run', + gnubok_reconcile_match: 'gnubok_get_reconciliation_status', } /** @@ -8665,6 +8672,10 @@ export const tools: McpTool[] = [ { name: 'gnubok_link_transaction_to_journal_entry', title: 'Link Transaction to Verifikat', + // Search-only since the account-keyed gnubok_reconcile_match covers the + // same link (one pair) for bank AND skattekonto; kept callable for clients + // that already use it, and reachable via gnubok_search_tools. + catalogVisibility: 'search', description: 'Link 1 bank tx to an already-posted verifikat (no new bokföring). Use when the user booked the affärshändelse manually. Pass invoice_id to also settle a kundfaktura. Stages.', inputSchema: { type: 'object', @@ -9794,17 +9805,21 @@ export const tools: McpTool[] = [ { name: 'gnubok_get_reconciliation_status', - title: 'Bank Reconciliation Status', - description: 'Bank reconciliation for one cash account: matched/unmatched counts and totals. Judge health on unexplained_difference, not difference (large mid-year by design). Defaults to 1930, else the primary cash account; pass account_number for 1940/1932. Optional date range.', + title: 'Reconciliation Status', + description: 'Reconciliation bridge for one account. Pass account_key ("skattekonto" or "bank:") for bridge lines + counts; without it, the legacy bank status for account_number (default 1930). Judge health on unexplained_difference, not difference.', inputSchema: { type: 'object', additionalProperties: false, properties: { + account_key: { + type: 'string', + description: '"skattekonto" or "bank:". When set, returns the account-keyed status (bridge[], counts, kind block).', + }, date_from: { type: 'string', description: 'Start date YYYY-MM-DD' }, date_to: { type: 'string', description: 'End date YYYY-MM-DD' }, account_number: { type: 'string', - description: 'Cash-account BAS code to reconcile, e.g. "1940". Defaults to "1930".', + description: 'Legacy: cash-account BAS code to reconcile, e.g. "1940". Defaults to "1930". Ignored when account_key is set.', }, }, }, @@ -9818,6 +9833,21 @@ export const tools: McpTool[] = [ async execute(args, companyId, userId, supabase) { const dateFrom = args.date_from as string | undefined const dateTo = args.date_to as string | undefined + const accountKey = args.account_key as string | undefined + + if (accountKey) { + const status = await getAccountStatus(supabase, companyId, accountKey, { + windowFrom: dateFrom ?? null, + windowTo: dateTo ?? null, + }) + if (!status) throw new Error(`Unknown account_key "${accountKey}" for this company`) + // The skattekonto engine also returns its item lists; this tool is the + // bridge. Items live in gnubok_list_reconciliation_items. + const { items: _items, ...rest } = status as typeof status & { items?: unknown } + void _items + return rest + } + // Passed through as-is, undefined included: an omitted account_number is // "the company's bank account", which resolves to 1930 and, for a company // with no 1930 row, to its primary cash account. Substituting a literal @@ -9835,6 +9865,204 @@ export const tools: McpTool[] = [ }, }, + { + name: 'gnubok_list_reconciliation_items', + title: 'Reconciliation Items', + description: 'Rows behind one account\'s reconciliation bridge, bucketed (proposed, unmatched_external, unmatched_ledger, matched, ignored, upcoming): side, qualified id, amount, proposal with confidence + reasons, allowed actions. Link via gnubok_reconcile_match (search).', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + account_key: { type: 'string', description: '"skattekonto" or "bank:".' }, + bucket: { + type: 'string', + enum: ['proposed', 'unmatched_external', 'unmatched_ledger', 'matched', 'ignored', 'upcoming'], + }, + date_from: { type: 'string', description: 'YYYY-MM-DD; scopes lists, never counts' }, + date_to: { type: 'string', description: 'YYYY-MM-DD' }, + limit: { type: 'number', description: 'Default 50, max 200' }, + offset: { type: 'number' }, + }, + required: ['account_key'], + }, + outputSchema: paginatedSchema('items', { + type: 'object', + properties: { + item_id: { type: 'string' }, + item_type: { type: 'string' }, + side: { type: 'string' }, + bucket: { type: 'string' }, + amount: { type: 'number' }, + proposal: { type: ['object', 'null'] }, + actions: { type: 'array', items: { type: 'string' } }, + }, + }), + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, companyId, userId, supabase) { + const accountKey = args.account_key as string + const result = await listAccountItems(supabase, companyId, accountKey, { + bucket: args.bucket as ReconciliationItemBucket | undefined, + windowFrom: (args.date_from as string | undefined) ?? null, + windowTo: (args.date_to as string | undefined) ?? null, + limit: args.limit as number | undefined, + offset: args.offset as number | undefined, + }) + if (!result) throw new Error(`Unknown account_key "${accountKey}" for this company`) + return result + }, + }, + + { + name: 'gnubok_reconcile_match', + title: 'Reconcile: Link Pairs', + description: 'Link outside rows (bank or skattekonto) to existing verifikat on one account; no new bokföring. Pass pairs, or use_proposals to apply the persisted proposals. Stages. dry_run previews.', + // Search-only to stay under the tools/list payload ceiling: the default + // catalog carries the reads (status + items); this write is reached via + // gnubok_search_tools, the close_period loadout and the items tool's hint. + catalogVisibility: 'search', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + account_key: { type: 'string', description: '"skattekonto" or "bank:"' }, + pairs: { + type: 'array', + description: 'One outside row id + one journal_entry_id per pair', + items: { + type: 'object', + additionalProperties: false, + properties: { + external_ids: { type: 'array', items: { type: 'string' } }, + journal_entry_ids: { type: 'array', items: { type: 'string' } }, + }, + required: ['external_ids', 'journal_entry_ids'], + }, + }, + use_proposals: { type: 'boolean' }, + confidence_threshold: { type: 'number', description: 'Default 0.9' }, + dry_run: { type: 'boolean' }, + idempotency_key: { type: 'string' }, + }, + required: ['account_key'], + }, + outputSchema: STAGED_OPERATION_SCHEMA, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + async execute(args, companyId, userId, supabase, actor) { + const accountKey = args.account_key as string + const pairs = (args.pairs as Array<{ external_ids: string[]; journal_entry_ids: string[] }> | undefined) ?? [] + const useProposals = args.use_proposals === true + if (pairs.length === 0 && !useProposals) { + throw new Error('Pass pairs, or use_proposals: true') + } + const confidenceThreshold = + typeof args.confidence_threshold === 'number' ? (args.confidence_threshold as number) : 0.9 + + // Resolve and validate at stage time so the reviewer sees exactly which + // pairs will be linked; the commit executor re-validates every pair. + const preview = await matchPairs( + supabase, + companyId, + userId, + accountKey, + { pairs, use_proposals: useProposals, confidence_threshold: confidenceThreshold }, + { dryRun: true }, + ) + if (!preview) throw new Error(`Unknown account_key "${accountKey}" for this company`) + const resolvedPairs = preview.applied.map((a) => ({ + external_ids: [a.external_id], + journal_entry_ids: [a.journal_entry_id], + })) + if (resolvedPairs.length === 0) { + throw new Error('No linkable pairs: nothing to stage') + } + + return stagePendingOperation( + supabase, + companyId, + userId, + 'reconciliation_match', + `Koppla ${resolvedPairs.length} rad(er) på ${accountKey}`, + { account_key: accountKey, pairs: resolvedPairs }, + { + account_key: accountKey, + pair_count: resolvedPairs.length, + pairs: resolvedPairs, + skipped_at_stage: preview.skipped, + source: useProposals ? 'proposals' : 'explicit', + }, + actor, + { + description: 'After approval, re-read the bridge to confirm the residual.', + tool: 'gnubok_get_reconciliation_status', + args: { account_key: accountKey }, + }, + { + dryRun: args.dry_run === true, + idempotencyKey: args.idempotency_key as string | undefined, + }, + ) + }, + }, + + { + name: 'gnubok_reconcile_unmatch', + title: 'Reconcile: Unlink', + description: 'Remove the link between one outside row (bank transaction or skattekonto row) and its verifikat on an account. The verifikat is untouched. Stages (low risk).', + catalogVisibility: 'search', + inputSchema: { + type: 'object', + additionalProperties: false, + properties: { + account_key: { type: 'string', description: '"skattekonto" or "bank:".' }, + external_id: { type: 'string', description: 'The linked outside row id (transaction_id or skattekonto_transaction_id).' }, + dry_run: { type: 'boolean' }, + idempotency_key: { type: 'string' }, + }, + required: ['account_key', 'external_id'], + }, + outputSchema: STAGED_OPERATION_SCHEMA, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, companyId, userId, supabase, actor) { + const accountKey = args.account_key as string + const externalId = args.external_id as string + if (!parseAccountKey(accountKey)) throw new Error(`Invalid account_key "${accountKey}"`) + return stagePendingOperation( + supabase, + companyId, + userId, + 'reconciliation_unmatch', + `Koppla bort rad ${externalId} på ${accountKey}`, + { account_key: accountKey, external_id: externalId }, + { account_key: accountKey, external_id: externalId }, + actor, + { + description: 'After approval, the row is back in the open buckets.', + tool: 'gnubok_list_reconciliation_items', + args: { account_key: accountKey, bucket: 'unmatched_external' }, + }, + { + dryRun: args.dry_run === true, + idempotencyKey: args.idempotency_key as string | undefined, + }, + ) + }, + }, + { name: 'gnubok_list_cash_accounts', diff --git a/lib/api/v1/__tests__/__snapshots__/spec-snapshot.test.ts.snap b/lib/api/v1/__tests__/__snapshots__/spec-snapshot.test.ts.snap index f206c2b6..75edd2b4 100644 --- a/lib/api/v1/__tests__/__snapshots__/spec-snapshot.test.ts.snap +++ b/lib/api/v1/__tests__/__snapshots__/spec-snapshot.test.ts.snap @@ -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`] = `125`; +exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `131`; exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = ` [ @@ -8,6 +8,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key "DELETE /api/v1/companies/:companyId/dimensions/:id/values/:valueId", "DELETE /api/v1/companies/:companyId/employees/:id", "DELETE /api/v1/companies/:companyId/employees/:id/absence", + "DELETE /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/links/:linkId", "DELETE /api/v1/companies/:companyId/salary-runs/:id", "DELETE /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId", "DELETE /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId", @@ -32,6 +33,9 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key "GET /api/v1/companies/:companyId/invoices/:id/pdf", "GET /api/v1/companies/:companyId/journal-entries", "GET /api/v1/companies/:companyId/journal-entries/:id", + "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/bank/status", "GET /api/v1/companies/:companyId/reports/ar-ledger", "GET /api/v1/companies/:companyId/reports/avgifter-basis", @@ -99,6 +103,8 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key "POST /api/v1/companies/:companyId/journal-entries/:id/correct", "POST /api/v1/companies/:companyId/journal-entries/:id/reverse", "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/bank/run", "POST /api/v1/companies/:companyId/salary-runs", "POST /api/v1/companies/:companyId/salary-runs/:id/approve", @@ -148,6 +154,8 @@ exports[`v1 spec snapshot > matches the recorded scope catalogue > endpoint-scop "payroll:read", "payroll:write", "public", + "reconciliation:read", + "reconciliation:write", "reports:read", "suppliers:read", "suppliers:write", diff --git a/lib/api/v1/load-routes.ts b/lib/api/v1/load-routes.ts index 02f4c783..1a4b9b36 100644 --- a/lib/api/v1/load-routes.ts +++ b/lib/api/v1/load-routes.ts @@ -152,6 +152,15 @@ import '@/app/api/v1/companies/[companyId]/webhooks/[id]/rotate-secret/route' // Inbox item stamp. import '@/app/api/v1/companies/[companyId]/inbox-items/[id]/stamp/route' +// Reconciliation, account-keyed (bank: | skattekonto): the +// account list, the bridge per account, item buckets, links and ignore flags. +import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/route' +import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/route' +import '@/app/api/v1/companies/[companyId]/reconciliation/accounts/[accountKey]/items/route' +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' + // Dimensions PR2: registry list + value creation (kostnadsställe/projekt). import '@/app/api/v1/companies/[companyId]/dimensions/route' import '@/app/api/v1/companies/[companyId]/dimensions/[id]/values/route' diff --git a/lib/auth/api-keys.ts b/lib/auth/api-keys.ts index b0fd3c47..9614ef07 100644 --- a/lib/auth/api-keys.ts +++ b/lib/auth/api-keys.ts @@ -35,6 +35,11 @@ export const API_KEY_SCOPES = { 'agent:write': { label: 'Agent: skriv', description: 'Spara och ta bort agentens minnen om företaget (remember_fact, forget_fact)' }, 'pending_operations:read': { label: 'Stagade operationer: läs', description: 'Lista pending_operations (staged writes awaiting approval)' }, 'pending_operations:approve': { label: 'Stagade operationer: godkänn', description: 'Godkänn eller avvisa stagade operationer via API/MCP: agenten ersätter web-UI:s granskning' }, + // Reconciliation (account-keyed: bank accounts + skattekonto). Reads cover + // the account list, the bridge and the item buckets; writes cover links + // (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)' }, } as const export type ApiKeyScope = keyof typeof API_KEY_SCOPES @@ -125,6 +130,9 @@ export const STAGING_SCOPES: ApiKeyScope[] = [ // key holding both this and pending_operations:approve is a SoD conflict: // findStageApproveConflict picks it up automatically from this list. 'skatteverket:write', + // gnubok_reconcile_match / gnubok_reconcile_unmatch stage reconciliation_* + // operations; same SoD reasoning. + 'reconciliation:write', ] /** @@ -177,6 +185,11 @@ export const TOOL_SCOPE_MAP: Record = { gnubok_match_transaction_to_invoice: 'transactions:write', gnubok_link_transaction_to_journal_entry: 'transactions:write', gnubok_match_batch_allocate: 'transactions:write', + // Reconciliation (account-keyed). gnubok_get_reconciliation_status keeps its + // historical reports:read so existing keys are not cut off. + gnubok_list_reconciliation_items: 'reconciliation:read', + gnubok_reconcile_match: 'reconciliation:write', + gnubok_reconcile_unmatch: 'reconciliation:write', gnubok_bulk_book_transactions: 'transactions:write', gnubok_bulk_book_inbox_items: 'transactions:write', gnubok_auto_match_period: 'transactions:write', diff --git a/lib/auth/scopes.ts b/lib/auth/scopes.ts index 81ea2fc0..f9b1ed5b 100644 --- a/lib/auth/scopes.ts +++ b/lib/auth/scopes.ts @@ -130,9 +130,18 @@ export const V1_ENDPOINT_SCOPES: Record = { // Writes: bulk 'POST /api/v1/companies/:companyId/transactions/ingest': 'transactions:write', 'POST /api/v1/companies/:companyId/transactions/batch-categorize': 'transactions:write', - // Reconciliation + // Reconciliation (legacy bank-only routes; kept as aliases of the + // account-keyed routes below, with their original scopes) 'POST /api/v1/companies/:companyId/reconciliation/bank/run': 'transactions:write', 'GET /api/v1/companies/:companyId/reconciliation/bank/status': 'transactions:read', + // Reconciliation, account-keyed (bank: | skattekonto): + // the account list, the bridge, the item buckets, links and ignore flags. + 'GET /api/v1/companies/:companyId/reconciliation/accounts': 'reconciliation:read', + 'GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey': 'reconciliation:read', + 'GET /api/v1/companies/:companyId/reconciliation/accounts/:accountKey/items': 'reconciliation:read', + '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', // Phase 5 PR-3: Reports + import async. Reports are read-only over // existing lib/reports/* generators; imports are async over the Phase 4 diff --git a/lib/events/types.ts b/lib/events/types.ts index 8610b417..19afc8b3 100644 --- a/lib/events/types.ts +++ b/lib/events/types.ts @@ -69,6 +69,13 @@ export type CoreEvent = | { type: 'transaction.synced'; payload: { transactions: Transaction[]; userId: string; companyId: string } } | { type: 'transaction.categorized'; payload: { transaction: Transaction; account: string; taxCode: string; userId: string; companyId: string } } | { type: 'transaction.reconciled'; payload: { transaction: Transaction; journalEntryId: string; method: ReconciliationMethod; userId: string; companyId: string } } + // Account-keyed reconciliation (lib/reconciliation/actions.ts): one event per + // link made or removed on any reconcilable account (bank:, + // skattekonto, later manual:NNNN). `transaction.reconciled` keeps firing for + // bank links made through the bank engine; these are the kind-agnostic + // 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 } } // 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 } } diff --git a/lib/pending-operations/commit.ts b/lib/pending-operations/commit.ts index 69b56e4f..8a3e380c 100644 --- a/lib/pending-operations/commit.ts +++ b/lib/pending-operations/commit.ts @@ -23,6 +23,7 @@ import { supplierInvoiceSekAmounts, } from '@/lib/currency/supplier-invoice-rate' import { roundOre } from '@/lib/money' +import { matchPairs, unmatchLink } from '@/lib/reconciliation/actions' import { getErrorMessage } from '@/lib/errors/get-error-message' import { validateVatNumber } from '@/lib/vat/vies-client' import { @@ -5978,6 +5979,73 @@ async function commitBulkBookInboxItems( } } +/** + * reconciliation_match: link the staged pairs on one account through the + * same service the page and the v1 API use. Every pair is re-validated at + * commit time (row still open, entry still posted and unlinked, amounts + * close); partial success is reported in data.applied / data.skipped rather + * than failing the whole operation, because the pairs are independent. + */ +async function commitReconciliationMatch( + supabase: SupabaseClient, + userId: string, + companyId: string, + params: Record +): Promise { + const accountKey = params.account_key as string | undefined + const pairs = params.pairs as Array<{ external_ids: string[]; journal_entry_ids: string[] }> | undefined + if (!accountKey || !Array.isArray(pairs) || pairs.length === 0) { + return { error: 'account_key and pairs are required', status: 400 } + } + const result = await matchPairs(supabase, companyId, userId, accountKey, { pairs }, { dryRun: false }) + if (!result) { + return { error: `Unknown account_key ${accountKey}`, status: 404 } + } + if (result.applied.length === 0) { + return { + error: `Ingen koppling kunde göras: ${result.skipped.map((s) => s.code).join(', ')}`, + errorCode: result.skipped[0]?.code, + status: 409, + data: { account_key: accountKey, applied: result.applied, skipped: result.skipped }, + } + } + return { + data: { + account_key: accountKey, + applied: result.applied, + skipped: result.skipped, + applied_count: result.applied.length, + skipped_count: result.skipped.length, + }, + } +} + +/** reconciliation_unmatch: clear one link. The verifikat is untouched. */ +async function commitReconciliationUnmatch( + supabase: SupabaseClient, + userId: string, + companyId: string, + params: Record +): Promise { + const accountKey = params.account_key as string | undefined + const externalId = params.external_id as string | undefined + if (!accountKey || !externalId) { + return { error: 'account_key and external_id are required', status: 400 } + } + try { + const result = await unmatchLink(supabase, companyId, userId, accountKey, externalId) + if (!result) return { error: `Unknown account_key ${accountKey}`, status: 404 } + return { data: { account_key: accountKey, ...result } } + } catch (err) { + const code = (err as { code?: string }).code + return { + error: err instanceof Error ? err.message : String(err), + errorCode: code, + status: code === 'TRANSACTION_NOT_FOUND' ? 404 : 400, + } + } +} + async function commitLinkTransactionJournalEntry( supabase: SupabaseClient, userId: string, @@ -6313,6 +6381,12 @@ async function commitPendingOperationInner( case 'link_transaction_journal_entry': result = await commitLinkTransactionJournalEntry(supabase, userId, companyId, pendingOp.params) break + case 'reconciliation_match': + result = await commitReconciliationMatch(supabase, userId, companyId, pendingOp.params) + break + case 'reconciliation_unmatch': + result = await commitReconciliationUnmatch(supabase, userId, companyId, pendingOp.params) + break case 'submit_vat_declaration': result = await commitSubmitVatDeclaration(supabase, userId, companyId, pendingOp.params) break diff --git a/lib/pending-operations/risk-tiers.ts b/lib/pending-operations/risk-tiers.ts index 4c4aa2a5..e21a4b63 100644 --- a/lib/pending-operations/risk-tiers.ts +++ b/lib/pending-operations/risk-tiers.ts @@ -200,6 +200,13 @@ export const OPERATION_RISK_TIERS: Record = { // invoice_payments row: sits next to link_invoice_voucher semantically; // both attach an existing booking to a different entity. link_transaction_journal_entry: 'medium', + // Account-keyed reconciliation (lib/reconciliation/actions.ts). A match + // pairs outside rows with existing verifikat across any reconcilable + // account (bank or skattekonto); it writes nothing to the ledger and is + // undone by reconciliation_unmatch, so 'medium' like its single-bank-tx + // sibling above. Unmatch only clears a pointer: 'low'. + reconciliation_match: 'medium', + reconciliation_unmatch: 'low', // ── Körjournal (mileage) ─────────────────────────────────────────── // A trip row is pure travel documentation: no booking impact until a diff --git a/lib/reconciliation/__tests__/actions.test.ts b/lib/reconciliation/__tests__/actions.test.ts new file mode 100644 index 00000000..52db716c --- /dev/null +++ b/lib/reconciliation/__tests__/actions.test.ts @@ -0,0 +1,182 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createQueuedMockSupabase } from '@/tests/helpers' + +const linkMock = vi.fn() +const unlinkMock = vi.fn() +const setIgnoredMock = vi.fn() +const manualLinkMock = vi.fn() +const unlinkReconciliationMock = vi.fn() +const skvStatusMock = vi.fn() +const emitMock = vi.fn() + +vi.mock('@/lib/skatteverket/skattekonto-link', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + linkSkattekontoRow: (...args: unknown[]) => linkMock(...args), + unlinkSkattekontoRow: (...args: unknown[]) => unlinkMock(...args), + setSkattekontoRowIgnored: (...args: unknown[]) => setIgnoredMock(...args), + } +}) +vi.mock('../bank-reconciliation', () => ({ + manualLink: (...args: unknown[]) => manualLinkMock(...args), + unlinkReconciliation: (...args: unknown[]) => unlinkReconciliationMock(...args), +})) +vi.mock('../skattekonto-reconciliation', () => ({ + getSkattekontoReconciliationStatus: (...args: unknown[]) => skvStatusMock(...args), +})) +vi.mock('@/lib/events/bus', () => ({ eventBus: { emit: (...args: unknown[]) => emitMock(...args) } })) + +import { SkattekontoLinkError } from '@/lib/skatteverket/skattekonto-link' +import { matchPairs, setItemIgnored, unmatchLink } from '../actions' + +const COMPANY = 'company-1' +const USER = 'user-1' +const CASH = '11111111-1111-4111-8111-111111111111' +const R1 = '22222222-2222-4222-8222-222222222222' +const R2 = '33333333-3333-4333-8333-333333333333' +const E1 = '44444444-4444-4444-8444-444444444444' +const E2 = '55555555-5555-4555-8555-555555555555' + +describe('matchPairs', () => { + beforeEach(() => { + vi.clearAllMocks() + linkMock.mockReset() + manualLinkMock.mockReset() + skvStatusMock.mockReset() + emitMock.mockResolvedValue(undefined) + }) + + it('returns null for an unknown or manual account key', async () => { + const { supabase } = createQueuedMockSupabase() + expect(await matchPairs(supabase as never, COMPANY, USER, 'nope', { pairs: [] })).toBeNull() + expect(await matchPairs(supabase as never, COMPANY, USER, 'manual:1910', { pairs: [] })).toBeNull() + }) + + it('links skattekonto pairs one by one, reports skips with codes, and emits one event per link', async () => { + const { supabase } = createQueuedMockSupabase() + linkMock + .mockResolvedValueOnce({ skattekonto_transaction_id: R1, journal_entry_id: E1, via: 'line' }) + .mockRejectedValueOnce(new SkattekontoLinkError('redan kopplat', 'ENTRY_ALREADY_LINKED')) + + const result = await matchPairs(supabase as never, COMPANY, USER, 'skattekonto', { + pairs: [ + { external_ids: [R1], journal_entry_ids: [E1] }, + { external_ids: [R2], journal_entry_ids: [E1] }, + { external_ids: [R1, R2], journal_entry_ids: [E2] }, + ], + }) + + expect(result).toMatchObject({ dry_run: false, considered: 3 }) + expect(result?.applied).toEqual([{ external_id: R1, journal_entry_id: E1, via: 'line' }]) + expect(result?.skipped.map((s) => s.code)).toEqual(['ALREADY_LINKED', 'UNSUPPORTED_PAIR_SHAPE']) + expect(emitMock).toHaveBeenCalledTimes(1) + expect(emitMock.mock.calls[0][0]).toMatchObject({ + type: 'reconciliation.matched', + payload: { accountKey: 'skattekonto', externalId: R1, journalEntryId: E1, method: 'manual' }, + }) + }) + + it('dry run resolves proposals into pairs without writing', async () => { + const { supabase } = createQueuedMockSupabase() + skvStatusMock.mockResolvedValue({ + items: { + proposed: [ + { item_id: R1, proposal: { journal_entry_id: E1, confidence: 0.95 } }, + { item_id: R2, proposal: { journal_entry_id: E2, confidence: 0.8 } }, + ], + }, + }) + + const result = await matchPairs( + supabase as never, + COMPANY, + USER, + 'skattekonto', + { use_proposals: true, confidence_threshold: 0.9 }, + { dryRun: true }, + ) + + expect(result).toMatchObject({ dry_run: true, considered: 1 }) + expect(result?.applied).toEqual([{ external_id: R1, journal_entry_id: E1 }]) + expect(linkMock).not.toHaveBeenCalled() + expect(emitMock).not.toHaveBeenCalled() + }) + + it('links bank pairs through manualLink with the account ledger number', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { ledger_account: '1931' } }) // cash_accounts lookup + manualLinkMock.mockResolvedValue({ success: true }) + + const result = await matchPairs(supabase as never, COMPANY, USER, `bank:${CASH}`, { + pairs: [{ external_ids: [R1], journal_entry_ids: [E1] }], + }) + + expect(manualLinkMock).toHaveBeenCalledWith(supabase, COMPANY, R1, E1, USER, '1931') + expect(result?.applied).toHaveLength(1) + }) + + it('a failed bank link is a PAIR_NOT_CLOSED skip, not a throw', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { ledger_account: '1930' } }) + manualLinkMock.mockResolvedValue({ success: false, error: 'Beloppen stämmer inte' }) + + const result = await matchPairs(supabase as never, COMPANY, USER, `bank:${CASH}`, { + pairs: [{ external_ids: [R1], journal_entry_ids: [E1] }], + }) + expect(result?.skipped[0]).toMatchObject({ code: 'PAIR_NOT_CLOSED', message: 'Beloppen stämmer inte' }) + }) +}) + +describe('unmatchLink / setItemIgnored', () => { + beforeEach(() => { + vi.clearAllMocks() + unlinkMock.mockReset() + unlinkReconciliationMock.mockReset() + setIgnoredMock.mockReset() + emitMock.mockResolvedValue(undefined) + }) + + it('unlinks a skattekonto row and emits reconciliation.unmatched', async () => { + const { supabase } = createQueuedMockSupabase() + unlinkMock.mockResolvedValue({ skattekonto_transaction_id: R1, previous_journal_entry_id: E1 }) + const result = await unmatchLink(supabase as never, COMPANY, USER, 'skattekonto', R1) + expect(result).toEqual({ external_id: R1, previous_journal_entry_id: E1 }) + expect(emitMock.mock.calls[0][0]).toMatchObject({ type: 'reconciliation.unmatched', payload: { externalId: R1 } }) + }) + + it('unlinks a bank transaction through the bank engine', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { journal_entry_id: E1 } }) + unlinkReconciliationMock.mockResolvedValue({ success: true }) + const result = await unmatchLink(supabase as never, COMPANY, USER, `bank:${CASH}`, R1) + expect(unlinkReconciliationMock).toHaveBeenCalledWith(supabase, COMPANY, R1, USER) + expect(result).toEqual({ external_id: R1, previous_journal_entry_id: E1 }) + }) + + it('ignores a skattekonto row via the core helper', async () => { + const { supabase } = createQueuedMockSupabase() + setIgnoredMock.mockResolvedValue({ skattekonto_transaction_id: R1, is_ignored: true }) + expect(await setItemIgnored(supabase as never, COMPANY, 'skattekonto', R1, true)).toEqual({ + external_id: R1, + is_ignored: true, + }) + }) + + it('refuses to ignore a booked bank transaction', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { id: R1, journal_entry_id: E1, is_ignored: false } }) + await expect(setItemIgnored(supabase as never, COMPANY, `bank:${CASH}`, R1, true)).rejects.toMatchObject({ + code: 'ALREADY_BOOKED', + }) + }) + + it('ignores an unbooked bank transaction', async () => { + const { supabase, enqueue, findCalls } = createQueuedMockSupabase() + enqueue({ data: { id: R1, journal_entry_id: null, is_ignored: false } }) + enqueue({ data: null }) // update + const result = await setItemIgnored(supabase as never, COMPANY, `bank:${CASH}`, R1, true) + expect(result).toEqual({ external_id: R1, is_ignored: true }) + expect(findCalls('transactions', 'update')[0][0]).toEqual({ is_ignored: true }) + }) +}) diff --git a/lib/reconciliation/__tests__/items.test.ts b/lib/reconciliation/__tests__/items.test.ts new file mode 100644 index 00000000..e4f506b8 --- /dev/null +++ b/lib/reconciliation/__tests__/items.test.ts @@ -0,0 +1,97 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createQueuedMockSupabase } from '@/tests/helpers' + +const skvStatusMock = vi.fn() +const fetchUnlinkedMock = vi.fn() + +vi.mock('../skattekonto-reconciliation', () => ({ + getSkattekontoReconciliationStatus: (...args: unknown[]) => skvStatusMock(...args), +})) +vi.mock('../bank-reconciliation', () => ({ + fetchUnlinkedGLLines: (...args: unknown[]) => fetchUnlinkedMock(...args), + scopeTransactionsToAccount: (q: unknown) => q, +})) + +import { listAccountItems } from '../items' + +const COMPANY = 'company-1' +const CASH = '11111111-1111-4111-8111-111111111111' + +function item(id: string, bucket: string) { + return { item_id: id, bucket, side: 'external', item_type: 'skattekonto_transaction', date: '2026-08-01', description: id, amount: 1, currency: 'SEK', actions: [] } +} + +describe('listAccountItems', () => { + beforeEach(() => { + vi.clearAllMocks() + skvStatusMock.mockReset() + fetchUnlinkedMock.mockReset() + }) + + it('returns null for an invalid key', async () => { + const { supabase } = createQueuedMockSupabase() + expect(await listAccountItems(supabase as never, COMPANY, 'nope')).toBeNull() + }) + + it('pages skattekonto buckets in work order and carries the older count', async () => { + const { supabase } = createQueuedMockSupabase() + skvStatusMock.mockResolvedValue({ + older_unmatched_count: 2, + items: { + proposed: [item('p1', 'proposed')], + unmatched_external: [item('u1', 'unmatched_external'), item('u2', 'unmatched_external')], + unmatched_ledger: [item('l1', 'unmatched_ledger')], + matched: [item('m1', 'matched')], + ignored: [], + upcoming: [], + }, + }) + + const all = await listAccountItems(supabase as never, COMPANY, 'skattekonto', { limit: 3, offset: 0 }) + expect(all?.items.map((i) => i.item_id)).toEqual(['p1', 'u1', 'u2']) + expect(all).toMatchObject({ count: 3, total_count: 5, has_more: true, next_offset: 3, older_unmatched_count: 2 }) + + const page2 = await listAccountItems(supabase as never, COMPANY, 'skattekonto', { limit: 3, offset: 3 }) + expect(page2?.items.map((i) => i.item_id)).toEqual(['l1', 'm1']) + expect(page2?.has_more).toBe(false) + + const onlyLedger = await listAccountItems(supabase as never, COMPANY, 'skattekonto', { bucket: 'unmatched_ledger' }) + expect(onlyLedger?.items.map((i) => i.item_id)).toEqual(['l1']) + expect(skvStatusMock).toHaveBeenLastCalledWith(supabase, COMPANY, { today: undefined, windowFrom: null, windowTo: null }) + }) + + it('buckets bank transactions by ignored / linked / proposed / open and nets unlinked ledger lines per entry', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { id: CASH, ledger_account: '1930', currency: 'SEK', is_primary: true } }) + enqueue({ + data: [ + { id: 't-ign', date: '2026-08-04', description: 'Dubblett', merchant_name: null, amount: -10, currency: 'SEK', journal_entry_id: null, potential_journal_entry_id: null, potential_match_method: null, potential_match_confidence: null, is_ignored: true, reconciliation_method: null }, + { id: 't-link', date: '2026-08-03', description: 'Lön', merchant_name: null, amount: -31200, currency: 'SEK', journal_entry_id: 'e-1', potential_journal_entry_id: null, potential_match_method: 'manual', potential_match_confidence: null, is_ignored: false, reconciliation_method: 'manual' }, + { id: 't-prop', date: '2026-08-02', description: 'Swish', merchant_name: 'Swish 123', amount: 2400, currency: 'SEK', journal_entry_id: null, potential_journal_entry_id: 'e-2', potential_match_method: 'auto_fuzzy', potential_match_confidence: '0.82', is_ignored: false, reconciliation_method: null }, + { id: 't-open', date: '2026-08-01', description: 'Elgiganten', merchant_name: null, amount: -1046, currency: 'SEK', journal_entry_id: null, potential_journal_entry_id: null, potential_match_method: null, potential_match_confidence: null, is_ignored: false, reconciliation_method: null }, + ], + }) + fetchUnlinkedMock.mockResolvedValue([ + { line_id: 'l1', journal_entry_id: 'e-3', debit_amount: 0, credit_amount: 600, line_description: null, entry_date: '2026-08-18', voucher_number: 231, voucher_series: 'A', entry_description: 'Elgiganten', source_type: 'manual' }, + { line_id: 'l2', journal_entry_id: 'e-3', debit_amount: 0, credit_amount: 400, line_description: null, entry_date: '2026-08-18', voucher_number: 231, voucher_series: 'A', entry_description: 'Elgiganten', source_type: 'manual' }, + ]) + + const result = await listAccountItems(supabase as never, COMPANY, `bank:${CASH}`, { limit: 50 }) + const byId = Object.fromEntries((result?.items ?? []).map((i) => [i.item_id, i])) + + expect(byId['t-prop']).toMatchObject({ bucket: 'proposed', description: 'Swish 123', proposal: { journal_entry_id: 'e-2', confidence: 0.82 } }) + expect(byId['t-open']).toMatchObject({ bucket: 'unmatched_external', actions: ['book', 'match', 'ignore'] }) + expect(byId['t-link']).toMatchObject({ bucket: 'matched', linked_journal_entry_id: 'e-1', actions: ['unmatch'] }) + expect(byId['t-ign']).toMatchObject({ bucket: 'ignored', actions: ['unignore'] }) + expect(byId['e-3']).toMatchObject({ bucket: 'unmatched_ledger', side: 'ledger', amount: -1000, voucher_number: 231 }) + // Work order: proposed, unmatched external, unmatched ledger, ignored, upcoming, matched + expect(result?.items.map((i) => i.bucket)).toEqual(['proposed', 'unmatched_external', 'unmatched_ledger', 'ignored', 'matched']) + expect(result?.total_count).toBe(5) + }) + + it('returns null for an unknown cash account', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: null }) + expect(await listAccountItems(supabase as never, COMPANY, `bank:${CASH}`)).toBeNull() + }) +}) diff --git a/lib/reconciliation/actions.ts b/lib/reconciliation/actions.ts new file mode 100644 index 00000000..f15830c1 --- /dev/null +++ b/lib/reconciliation/actions.ts @@ -0,0 +1,291 @@ +import type { SupabaseClient } from '@supabase/supabase-js' +import { eventBus } from '@/lib/events/bus' +import { createLogger } from '@/lib/logger' +import { + linkSkattekontoRow, + setSkattekontoRowIgnored, + SkattekontoLinkError, + unlinkSkattekontoRow, +} from '@/lib/skatteverket/skattekonto-link' +import { manualLink, unlinkReconciliation } from './bank-reconciliation' +import { getSkattekontoReconciliationStatus } from './skattekonto-reconciliation' +import { parseAccountKey } from './schemas' + +const log = createLogger('reconciliation/actions') + +/** + * Write actions of the account-keyed reconciliation surface. Every door (page + * route, v1, MCP commit executor) calls these; none of them links on its own. + * + * Links never touch the ledger: they pair an outside row with an existing + * verifikat, so they are allowed in locked periods and reversible by + * unmatch. Bookings (residual postings) are a separate, later action. + */ + +export interface ReconciliationPair { + /** Outside rows: transaction ids (bank) or skattekonto_transaction ids. */ + external_ids: string[] + journal_entry_ids: string[] +} + +export type PairSkipCode = + | 'UNSUPPORTED_PAIR_SHAPE' + | 'ALREADY_LINKED' + | 'ENTRY_NOT_FOUND' + | 'ENTRY_REVERSED' + | 'PAIR_NOT_CLOSED' + | 'ROW_IGNORED' + | 'NOT_FOUND' + | 'LINK_RACE' + | 'UNKNOWN' + +export interface AppliedLink { + external_id: string + journal_entry_id: string + via?: 'line' | 'entry_total' +} + +export interface SkippedPair { + pair: ReconciliationPair + code: PairSkipCode + message: string +} + +export interface MatchPairsInput { + pairs?: ReconciliationPair[] + /** Use the persisted proposals (skattekonto) or potential matches (bank) as pairs. */ + use_proposals?: boolean + /** Only with use_proposals: skip proposals below this confidence. */ + confidence_threshold?: number +} + +export interface MatchPairsResult { + dry_run: boolean + applied: AppliedLink[] + skipped: SkippedPair[] + considered: number +} + +function skipCodeFor(err: unknown): { code: PairSkipCode; message: string } { + if (err instanceof SkattekontoLinkError) { + const map: Record = { + TRANSACTION_NOT_FOUND: 'NOT_FOUND', + ALREADY_BOOKED: 'ALREADY_LINKED', + ROW_IGNORED: 'ROW_IGNORED', + ENTRY_NOT_FOUND: 'ENTRY_NOT_FOUND', + ENTRY_ALREADY_LINKED: 'ALREADY_LINKED', + INVALID_CANDIDATE: 'PAIR_NOT_CLOSED', + NOT_LINKED: 'UNKNOWN', + LINK_RACE: 'LINK_RACE', + } + return { code: map[err.code] ?? 'UNKNOWN', message: err.message } + } + return { code: 'UNKNOWN', message: err instanceof Error ? err.message : String(err) } +} + +async function proposalsAsPairs( + supabase: SupabaseClient, + companyId: string, + accountKey: string, + threshold: number, +): Promise { + const parsed = parseAccountKey(accountKey) + if (!parsed) return [] + if (parsed.kind === 'skattekonto') { + const status = await getSkattekontoReconciliationStatus(supabase, companyId) + if (!status) return [] + return status.items.proposed + .filter((i) => i.proposal && i.proposal.confidence >= threshold) + .map((i) => ({ external_ids: [i.item_id], journal_entry_ids: [i.proposal!.journal_entry_id] })) + } + if (parsed.kind === 'bank') { + const { data } = await supabase + .from('transactions') + .select('id, potential_journal_entry_id, potential_match_confidence') + .eq('company_id', companyId) + .eq('cash_account_id', parsed.cashAccountId) + .is('journal_entry_id', null) + .eq('is_ignored', false) + .not('potential_journal_entry_id', 'is', null) + return ((data ?? []) as Array<{ id: string; potential_journal_entry_id: string; potential_match_confidence: number | string | null }>) + .filter((r) => Number(r.potential_match_confidence ?? 0) >= threshold) + .map((r) => ({ external_ids: [r.id], journal_entry_ids: [r.potential_journal_entry_id] })) + } + return [] +} + +/** + * Link pairs on one account. Today each pair is one outside row and one + * verifikat (the N:M worksheet selection arrives with the manual-match mode); + * other shapes are reported as UNSUPPORTED_PAIR_SHAPE, never silently + * reduced. Dry run validates shapes and resolves proposals without writing. + * Partial success is first-class: `applied` and `skipped` together cover + * every considered pair. + */ +export async function matchPairs( + supabase: SupabaseClient, + companyId: string, + userId: string, + accountKey: string, + input: MatchPairsInput, + options: { dryRun?: boolean } = {}, +): Promise { + const parsed = parseAccountKey(accountKey) + if (!parsed || parsed.kind === 'manual') return null + const dryRun = options.dryRun ?? false + + const pairs: ReconciliationPair[] = [...(input.pairs ?? [])] + if (input.use_proposals) { + pairs.push( + ...(await proposalsAsPairs(supabase, companyId, accountKey, input.confidence_threshold ?? 0)), + ) + } + + const applied: AppliedLink[] = [] + const skipped: SkippedPair[] = [] + + for (const pair of pairs) { + if (pair.external_ids.length !== 1 || pair.journal_entry_ids.length !== 1) { + skipped.push({ + pair, + code: 'UNSUPPORTED_PAIR_SHAPE', + message: 'Ett par är en händelse och ett verifikat i den här versionen.', + }) + continue + } + const [externalId] = pair.external_ids + const [journalEntryId] = pair.journal_entry_ids + + if (dryRun) { + applied.push({ external_id: externalId, journal_entry_id: journalEntryId }) + continue + } + + try { + if (parsed.kind === 'skattekonto') { + const r = await linkSkattekontoRow(supabase, companyId, externalId, journalEntryId) + applied.push({ external_id: externalId, journal_entry_id: journalEntryId, via: r.via }) + } else { + const { data: account } = await supabase + .from('cash_accounts') + .select('ledger_account') + .eq('company_id', companyId) + .eq('id', parsed.cashAccountId) + .maybeSingle<{ ledger_account: string }>() + const r = await manualLink( + supabase, + companyId, + externalId, + journalEntryId, + userId, + account?.ledger_account ?? '1930', + ) + if (!r.success) { + skipped.push({ pair, code: 'PAIR_NOT_CLOSED', message: r.error ?? 'Kunde inte koppla' }) + continue + } + applied.push({ external_id: externalId, journal_entry_id: journalEntryId }) + } + await eventBus.emit({ + type: 'reconciliation.matched', + payload: { + accountKey, + externalId, + journalEntryId, + method: input.use_proposals ? 'proposal' : 'manual', + userId, + companyId, + }, + }) + } catch (err) { + const { code, message } = skipCodeFor(err) + skipped.push({ pair, code, message }) + } + } + + if (!dryRun && applied.length > 0) { + log.info('reconciliation pairs linked', { companyId, accountKey, applied: applied.length, skipped: skipped.length }) + } + + return { dry_run: dryRun, applied, skipped, considered: pairs.length } +} + +export interface UnmatchResult { + external_id: string + previous_journal_entry_id: string | null +} + +/** + * Remove one link. link id = the outside row's id (transaction or + * skattekonto row), which is the one-link-per-row identity both kinds share. + */ +export async function unmatchLink( + supabase: SupabaseClient, + companyId: string, + userId: string, + accountKey: string, + linkId: string, +): Promise { + const parsed = parseAccountKey(accountKey) + if (!parsed || parsed.kind === 'manual') return null + + let previous: string | null = null + if (parsed.kind === 'skattekonto') { + const r = await unlinkSkattekontoRow(supabase, companyId, linkId) + previous = r.previous_journal_entry_id + } else { + const { data: tx } = await supabase + .from('transactions') + .select('journal_entry_id') + .eq('company_id', companyId) + .eq('id', linkId) + .maybeSingle<{ journal_entry_id: string | null }>() + previous = tx?.journal_entry_id ?? null + const r = await unlinkReconciliation(supabase, companyId, linkId, userId) + if (!r.success) throw new Error(r.error ?? 'Kunde inte koppla bort') + } + await eventBus.emit({ + type: 'reconciliation.unmatched', + payload: { accountKey, externalId: linkId, previousJournalEntryId: previous, userId, companyId }, + }) + return { external_id: linkId, previous_journal_entry_id: previous } +} + +/** + * Ignore / restore one outside row. Ignored rows leave the unmatched totals + * and surface on the bridge's exclusion line (bank #1705 precedent). + */ +export async function setItemIgnored( + supabase: SupabaseClient, + companyId: string, + accountKey: string, + itemId: string, + ignored: boolean, +): Promise<{ external_id: string; is_ignored: boolean } | null> { + const parsed = parseAccountKey(accountKey) + if (!parsed || parsed.kind === 'manual') return null + if (parsed.kind === 'skattekonto') { + const r = await setSkattekontoRowIgnored(supabase, companyId, itemId, ignored) + return { external_id: r.skattekonto_transaction_id, is_ignored: r.is_ignored } + } + const { data: tx, error } = await supabase + .from('transactions') + .select('id, journal_entry_id, is_ignored') + .eq('company_id', companyId) + .eq('id', itemId) + .maybeSingle<{ id: string; journal_entry_id: string | null; is_ignored: boolean | null }>() + if (error) throw new Error(`Kunde inte hämta transaktionen: ${error.message}`) + if (!tx) throw new SkattekontoLinkError('Transaktionen hittades inte.', 'TRANSACTION_NOT_FOUND') + if (ignored && tx.journal_entry_id) { + throw new SkattekontoLinkError('En bokförd transaktion kan inte ignoreras.', 'ALREADY_BOOKED') + } + if (Boolean(tx.is_ignored) !== ignored) { + const { error: updateError } = await supabase + .from('transactions') + .update({ is_ignored: ignored }) + .eq('company_id', companyId) + .eq('id', itemId) + if (updateError) throw new Error(`Kunde inte uppdatera: ${updateError.message}`) + } + return { external_id: itemId, is_ignored: ignored } +} diff --git a/lib/reconciliation/items.ts b/lib/reconciliation/items.ts new file mode 100644 index 00000000..40b2cc45 --- /dev/null +++ b/lib/reconciliation/items.ts @@ -0,0 +1,235 @@ +import type { SupabaseClient } from '@supabase/supabase-js' +import { roundOre } from '@/lib/money' +import { fetchUnlinkedGLLines, scopeTransactionsToAccount } from './bank-reconciliation' +import { getSkattekontoReconciliationStatus } from './skattekonto-reconciliation' +import { + parseAccountKey, + type ReconciliationItem, + type ReconciliationItemBucket, +} from './schemas' + +/** + * Item listing for one account, in the page's buckets, paginated with + * limit/offset (the MCP convention; the v1 door wraps this in its cursor). + * + * Skattekonto items come straight from the engine (which already buckets + * and windows them). Bank items are built from the same sources the bank + * page uses: the account-scoped transactions for the external side and the + * unlinked-GL-lines RPC for the ledger side; the bank matcher's proposals are + * the rows carrying potential_journal_entry_id. + */ + +export const DEFAULT_ITEMS_LIMIT = 50 +export const MAX_ITEMS_LIMIT = 200 + +/** Bucket order when no bucket is requested: what to do first, first. */ +export const BUCKET_ORDER: readonly ReconciliationItemBucket[] = [ + 'proposed', + 'unmatched_external', + 'unmatched_ledger', + 'ignored', + 'upcoming', + 'matched', +] + +export interface ListItemsOptions { + bucket?: ReconciliationItemBucket + windowFrom?: string | null + windowTo?: string | null + limit?: number + offset?: number + today?: string +} + +export interface ListItemsResult { + items: ReconciliationItem[] + count: number + total_count: number + has_more: boolean + next_offset?: number + /** Unmatched rows dated before windowFrom (never hidden, only counted). */ + older_unmatched_count: number +} + +interface CashAccountRow { + id: string + ledger_account: string + currency: string | null + is_primary: boolean | null +} + +interface BankTxRow { + id: string + date: string + description: string | null + merchant_name: string | null + amount: number | string + currency: string + journal_entry_id: string | null + potential_journal_entry_id: string | null + potential_match_method: string | null + potential_match_confidence: number | string | null + is_ignored: boolean | null + reconciliation_method: string | null +} + +function clampLimit(limit?: number): number { + if (!limit || !Number.isFinite(limit) || limit < 1) return DEFAULT_ITEMS_LIMIT + return Math.min(Math.floor(limit), MAX_ITEMS_LIMIT) +} + +function page(all: T[], limit: number, offset: number): ListItemsResult & { items: T[] } { + const items = all.slice(offset, offset + limit) + const hasMore = offset + limit < all.length + return { + items, + count: items.length, + total_count: all.length, + has_more: hasMore, + ...(hasMore ? { next_offset: offset + limit } : {}), + older_unmatched_count: 0, + } as ListItemsResult & { items: T[] } +} + +export async function listAccountItems( + supabase: SupabaseClient, + companyId: string, + accountKey: string, + options: ListItemsOptions = {}, +): Promise { + const parsed = parseAccountKey(accountKey) + if (!parsed) return null + const limit = clampLimit(options.limit) + const offset = Math.max(0, Math.floor(options.offset ?? 0)) + + if (parsed.kind === 'skattekonto') { + const status = await getSkattekontoReconciliationStatus(supabase, companyId, { + today: options.today, + windowFrom: options.windowFrom ?? null, + windowTo: options.windowTo ?? null, + }) + if (!status) return null + const all = options.bucket + ? status.items[options.bucket] + : BUCKET_ORDER.flatMap((b) => status.items[b]) + return { ...page(all, limit, offset), older_unmatched_count: status.older_unmatched_count } + } + + if (parsed.kind === 'bank') { + const { data: account, error } = await supabase + .from('cash_accounts') + .select('id, ledger_account, currency, is_primary') + .eq('company_id', companyId) + .eq('id', parsed.cashAccountId) + .maybeSingle() + if (error) throw new Error(`Kunde inte hämta kassakonto: ${error.message}`) + if (!account) return null + const currency = account.currency ?? 'SEK' + const buckets = options.bucket ? [options.bucket] : [...BUCKET_ORDER] + const byBucket = new Map() + const push = (item: ReconciliationItem) => { + byBucket.set(item.bucket, [...(byBucket.get(item.bucket) ?? []), item]) + } + + const wantsExternal = buckets.some((b) => + ['proposed', 'unmatched_external', 'matched', 'ignored'].includes(b), + ) + if (wantsExternal) { + let query = supabase + .from('transactions') + .select( + 'id, date, description, merchant_name, amount, currency, journal_entry_id, potential_journal_entry_id, potential_match_method, potential_match_confidence, is_ignored, reconciliation_method', + ) + .eq('company_id', companyId) + query = scopeTransactionsToAccount(query, account.id, currency, Boolean(account.is_primary)) + if (options.windowFrom) query = query.gte('date', options.windowFrom) + if (options.windowTo) query = query.lte('date', options.windowTo) + const { data, error: txError } = await query.order('date', { ascending: false }).order('id', { ascending: true }) + if (txError) throw new Error(`Kunde inte hämta transaktioner: ${txError.message}`) + const rows = (data ?? []) as BankTxRow[] + { + for (const tx of rows) { + const bucket: ReconciliationItemBucket = tx.is_ignored + ? 'ignored' + : tx.journal_entry_id + ? 'matched' + : tx.potential_journal_entry_id + ? 'proposed' + : 'unmatched_external' + if (!buckets.includes(bucket)) continue + push({ + item_id: tx.id, + item_type: 'transaction', + side: 'external', + bucket, + date: tx.date, + description: tx.merchant_name || tx.description || '', + amount: roundOre(Number(tx.amount)), + currency: tx.currency, + linked_journal_entry_id: tx.journal_entry_id, + proposal: tx.potential_journal_entry_id + ? { + journal_entry_id: tx.potential_journal_entry_id, + voucher_number: null, + voucher_series: null, + entry_date: tx.date, + description: '', + entry_status: 'posted', + confidence: Number(tx.potential_match_confidence ?? 0.75), + reasons: [tx.potential_match_method ?? 'föreslagen av matcharen'], + } + : null, + actions: + bucket === 'matched' + ? ['unmatch'] + : bucket === 'ignored' + ? ['unignore'] + : bucket === 'proposed' + ? ['match', 'book', 'ignore'] + : ['book', 'match', 'ignore'], + }) + } + } + } + + if (buckets.includes('unmatched_ledger')) { + const lines = await fetchUnlinkedGLLines( + supabase, + companyId, + account.ledger_account, + options.windowFrom ?? undefined, + options.windowTo ?? undefined, + ) + // One item per entry: several 1930 lines of one voucher net, as a link settles the voucher. + const byEntry = new Map() + for (const l of lines) { + const amount = roundOre(Number(l.debit_amount || 0) - Number(l.credit_amount || 0)) + const existing = byEntry.get(l.journal_entry_id) + if (existing) { + existing.amount = roundOre(existing.amount + amount) + continue + } + byEntry.set(l.journal_entry_id, { + item_id: l.journal_entry_id, + item_type: 'journal_entry', + side: 'ledger', + bucket: 'unmatched_ledger', + date: l.entry_date, + description: l.entry_description || l.line_description || '', + amount, + currency, + voucher_number: l.voucher_number, + voucher_series: l.voucher_series, + entry_status: 'posted', + actions: ['match', 'review'], + }) + } + for (const it of byEntry.values()) push(it) + } + + const all = buckets.flatMap((b) => byBucket.get(b) ?? []) + return page(all, limit, offset) + } + + return null +} diff --git a/lib/skatteverket/__tests__/skattekonto-link.test.ts b/lib/skatteverket/__tests__/skattekonto-link.test.ts new file mode 100644 index 00000000..317664b0 --- /dev/null +++ b/lib/skatteverket/__tests__/skattekonto-link.test.ts @@ -0,0 +1,136 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { createQueuedMockSupabase } from '@/tests/helpers' +import { + entrySettlesAmount, + linkSkattekontoRow, + setSkattekontoRowIgnored, + SkattekontoLinkError, + unlinkSkattekontoRow, +} from '../skattekonto-link' + +const COMPANY = 'company-1' +const ROW = 'row-1' +const ENTRY = 'entry-1' + +function row(overrides: Record = {}) { + return { id: ROW, belopp_skatteverket: 5000, journal_entry_id: null, is_ignored: false, status: 'booked', ...overrides } +} +function entry(lines: Array<{ account_number: string; debit_amount: number; credit_amount: number }>, status = 'posted') { + return { id: ENTRY, status, lines } +} + +describe('entrySettlesAmount', () => { + it('matches a single line on the expected side', () => { + expect(entrySettlesAmount([{ account_number: '1630', debit_amount: 5000, credit_amount: 0 }], 5000)).toEqual({ ok: true, via: 'line' }) + expect(entrySettlesAmount([{ account_number: '1630', debit_amount: 0, credit_amount: 5447 }], -5447)).toEqual({ ok: true, via: 'line' }) + }) + it('falls back to the entry net over several 1630 lines', () => { + expect( + entrySettlesAmount( + [ + { account_number: '1630', debit_amount: 3000, credit_amount: 0 }, + { account_number: '1630', debit_amount: 2000, credit_amount: 0 }, + { account_number: '1930', debit_amount: 0, credit_amount: 5000 }, + ], + 5000, + ), + ).toEqual({ ok: true, via: 'entry_total' }) + }) + it('rejects the wrong side, a different amount, and entries without 1630 lines', () => { + expect(entrySettlesAmount([{ account_number: '1630', debit_amount: 0, credit_amount: 5000 }], 5000).ok).toBe(false) + expect(entrySettlesAmount([{ account_number: '1630', debit_amount: 4999, credit_amount: 0 }], 5000).ok).toBe(false) + expect(entrySettlesAmount([{ account_number: '1930', debit_amount: 5000, credit_amount: 0 }], 5000).ok).toBe(false) + }) +}) + +describe('linkSkattekontoRow', () => { + beforeEach(() => vi.clearAllMocks()) + + it('links an open row to a posted entry with a matching 1630 line and clears the proposal', async () => { + const { supabase, enqueue, findCalls } = createQueuedMockSupabase() + enqueue({ data: row() }) + enqueue({ data: entry([{ account_number: '1630', debit_amount: 5000, credit_amount: 0 }]) }) + enqueue({ data: null }) // already-linked check + enqueue({ data: [{ id: ROW }] }) // update … select + + const result = await linkSkattekontoRow(supabase as never, COMPANY, ROW, ENTRY) + + expect(result).toEqual({ skattekonto_transaction_id: ROW, journal_entry_id: ENTRY, via: 'line' }) + expect(findCalls('skattekonto_transactions', 'update')[0][0]).toEqual({ + journal_entry_id: ENTRY, + suggested_journal_entry_id: null, + suggested_at: null, + }) + expect(findCalls('skattekonto_transactions', 'is')).toContainEqual(['journal_entry_id', null]) + }) + + it.each([ + ['TRANSACTION_NOT_FOUND', null, undefined], + ['ALREADY_BOOKED', row({ journal_entry_id: 'other' }), undefined], + ['ROW_IGNORED', row({ is_ignored: true }), undefined], + ['INVALID_CANDIDATE', row({ status: 'upcoming' }), undefined], + ['ENTRY_NOT_FOUND', row(), null], + ['INVALID_CANDIDATE', row(), entry([{ account_number: '1630', debit_amount: 5000, credit_amount: 0 }], 'reversed')], + ['INVALID_CANDIDATE', row(), entry([{ account_number: '1630', debit_amount: 4000, credit_amount: 0 }])], + ])('refuses with %s', async (code, rowData, entryData) => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: rowData }) + if (entryData !== undefined) enqueue({ data: entryData }) + await expect(linkSkattekontoRow(supabase as never, COMPANY, ROW, ENTRY)).rejects.toMatchObject({ code }) + }) + + it('refuses an entry already linked by another row', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: row() }) + enqueue({ data: entry([{ account_number: '1630', debit_amount: 5000, credit_amount: 0 }]) }) + enqueue({ data: { id: 'row-9' } }) + await expect(linkSkattekontoRow(supabase as never, COMPANY, ROW, ENTRY)).rejects.toMatchObject({ code: 'ENTRY_ALREADY_LINKED' }) + }) + + it('reports a lost race when the guarded update touches no row', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: row() }) + enqueue({ data: entry([{ account_number: '1630', debit_amount: 5000, credit_amount: 0 }]) }) + enqueue({ data: null }) + enqueue({ data: [] }) + await expect(linkSkattekontoRow(supabase as never, COMPANY, ROW, ENTRY)).rejects.toMatchObject({ code: 'LINK_RACE' }) + }) +}) + +describe('unlinkSkattekontoRow / setSkattekontoRowIgnored', () => { + it('clears the pointer and reports the previous entry', async () => { + const { supabase, enqueue, findCalls } = createQueuedMockSupabase() + enqueue({ data: { id: ROW, journal_entry_id: ENTRY } }) + enqueue({ data: null }) + const result = await unlinkSkattekontoRow(supabase as never, COMPANY, ROW) + expect(result).toEqual({ skattekonto_transaction_id: ROW, previous_journal_entry_id: ENTRY }) + expect(findCalls('skattekonto_transactions', 'update')[0][0]).toEqual({ journal_entry_id: null }) + }) + + it('refuses to unlink an unlinked row', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { id: ROW, journal_entry_id: null } }) + await expect(unlinkSkattekontoRow(supabase as never, COMPANY, ROW)).rejects.toBeInstanceOf(SkattekontoLinkError) + }) + + it('refuses to ignore a linked row and is a no-op when already in the requested state', async () => { + const { supabase, enqueue, findCalls } = createQueuedMockSupabase() + enqueue({ data: { id: ROW, journal_entry_id: ENTRY, is_ignored: false } }) + await expect(setSkattekontoRowIgnored(supabase as never, COMPANY, ROW, true)).rejects.toMatchObject({ code: 'ALREADY_BOOKED' }) + enqueue({ data: { id: ROW, journal_entry_id: null, is_ignored: true } }) + expect(await setSkattekontoRowIgnored(supabase as never, COMPANY, ROW, true)).toEqual({ skattekonto_transaction_id: ROW, is_ignored: true }) + expect(findCalls('skattekonto_transactions', 'update')).toHaveLength(0) + }) + + it('ignoring clears the proposal too', async () => { + const { supabase, enqueue, findCalls } = createQueuedMockSupabase() + enqueue({ data: { id: ROW, journal_entry_id: null, is_ignored: false } }) + enqueue({ data: null }) + await setSkattekontoRowIgnored(supabase as never, COMPANY, ROW, true) + expect(findCalls('skattekonto_transactions', 'update')[0][0]).toEqual({ + is_ignored: true, + suggested_journal_entry_id: null, + suggested_at: null, + }) + }) +}) diff --git a/lib/skatteverket/skattekonto-link.ts b/lib/skatteverket/skattekonto-link.ts new file mode 100644 index 00000000..72854dbe --- /dev/null +++ b/lib/skatteverket/skattekonto-link.ts @@ -0,0 +1,240 @@ +import type { SupabaseClient } from '@supabase/supabase-js' +import { roundOre } from '@/lib/money' +import { SKATTEKONTO_ACCOUNT } from './manual-verifikat-prefill' + +/** + * Link semantics for a skattekonto row (core). + * + * A link pairs ONE SKV-posted row with ONE verifikat whose 1630 movement + * equals the row's amount on the expected side (positive belopp = money + * into the skattekonto = debit 1630). It writes nothing to the verifikat: + * `skattekonto_transactions.journal_entry_id` is the only thing that changes, + * so linking and unlinking are allowed in locked periods and need no storno. + * + * Lives in core so the reconciliation engine (lib/reconciliation), the + * dashboard routes, the v1 API and the MCP executors share one implementation; + * the skatteverket extension's matchSkattekontoToEntry delegates here. + */ + +export type SkattekontoLinkErrorCode = + | 'TRANSACTION_NOT_FOUND' + | 'ALREADY_BOOKED' + | 'ROW_IGNORED' + | 'ENTRY_NOT_FOUND' + | 'ENTRY_ALREADY_LINKED' + | 'INVALID_CANDIDATE' + | 'NOT_LINKED' + | 'LINK_RACE' + +export class SkattekontoLinkError extends Error { + constructor( + message: string, + public readonly code: SkattekontoLinkErrorCode, + ) { + super(message) + this.name = 'SkattekontoLinkError' + } +} + +interface RowForLink { + id: string + belopp_skatteverket: number | string + journal_entry_id: string | null + is_ignored: boolean | null + status: 'booked' | 'upcoming' +} + +interface EntryForLink { + id: string + status: 'draft' | 'posted' | 'reversed' + lines: Array<{ account_number: string; debit_amount: number | string; credit_amount: number | string }> | null +} + +function expectedSide(belopp: number): 'debit' | 'credit' { + return belopp > 0 ? 'debit' : 'credit' +} + +/** + * Does this entry settle the row? True when a single 1630 line equals the + * amount on the expected side, or when the entry's 1630 lines net to it (a + * manual voucher that split the movement over two lines). Exported for the + * engine's pair validation. + */ +export function entrySettlesAmount( + lines: EntryForLink['lines'], + belopp: number, +): { ok: boolean; via: 'line' | 'entry_total' | null } { + const amount = roundOre(Math.abs(belopp)) + const side = expectedSide(belopp) + const onAccount = (lines ?? []).filter((l) => l.account_number === SKATTEKONTO_ACCOUNT) + if (onAccount.length === 0) return { ok: false, via: null } + const single = onAccount.some((l) => { + const debit = roundOre(Number(l.debit_amount)) + const credit = roundOre(Number(l.credit_amount)) + return side === 'debit' ? debit === amount && credit === 0 : credit === amount && debit === 0 + }) + if (single) return { ok: true, via: 'line' } + const net = roundOre( + onAccount.reduce((s, l) => s + Number(l.debit_amount || 0) - Number(l.credit_amount || 0), 0), + ) + const signed = side === 'debit' ? amount : -amount + if (onAccount.length > 1 && net === signed) return { ok: true, via: 'entry_total' } + return { ok: false, via: null } +} + +export interface LinkSkattekontoRowResult { + skattekonto_transaction_id: string + journal_entry_id: string + via: 'line' | 'entry_total' +} + +/** + * Link one open SKV row to one verifikat. Throws SkattekontoLinkError with a + * stable code on every refusal; the write is guarded on journal_entry_id IS + * NULL so a concurrent link loses cleanly (LINK_RACE). + */ +export async function linkSkattekontoRow( + supabase: SupabaseClient, + companyId: string, + transactionId: string, + journalEntryId: string, +): Promise { + const { data: row, error: rowError } = await supabase + .from('skattekonto_transactions') + .select('id, belopp_skatteverket, journal_entry_id, is_ignored, status') + .eq('id', transactionId) + .eq('company_id', companyId) + .maybeSingle() + if (rowError || !row) { + throw new SkattekontoLinkError('Skattekonto-transaktionen hittades inte.', 'TRANSACTION_NOT_FOUND') + } + if (row.journal_entry_id) { + throw new SkattekontoLinkError('Transaktionen är redan kopplad till ett verifikat.', 'ALREADY_BOOKED') + } + if (row.is_ignored) { + throw new SkattekontoLinkError('Transaktionen är ignorerad. Återställ den innan du kopplar.', 'ROW_IGNORED') + } + if (row.status !== 'booked') { + throw new SkattekontoLinkError('En kommande händelse kan inte kopplas ännu.', 'INVALID_CANDIDATE') + } + + const { data: entry, error: entryError } = await supabase + .from('journal_entries') + .select('id, status, lines:journal_entry_lines ( account_number, debit_amount, credit_amount )') + .eq('id', journalEntryId) + .eq('company_id', companyId) + .maybeSingle() + if (entryError || !entry) { + throw new SkattekontoLinkError('Verifikatet hittades inte.', 'ENTRY_NOT_FOUND') + } + if (entry.status === 'reversed') { + throw new SkattekontoLinkError('Verifikatet är makulerat och kan inte kopplas.', 'INVALID_CANDIDATE') + } + const settles = entrySettlesAmount(entry.lines, Number(row.belopp_skatteverket)) + if (!settles.ok || !settles.via) { + throw new SkattekontoLinkError('Verifikatet saknar en matchande rad på 1630.', 'INVALID_CANDIDATE') + } + + const { data: alreadyLinked } = await supabase + .from('skattekonto_transactions') + .select('id') + .eq('company_id', companyId) + .eq('journal_entry_id', journalEntryId) + .maybeSingle() + if (alreadyLinked) { + throw new SkattekontoLinkError( + 'Verifikatet är redan kopplat till en annan skattekonto-transaktion.', + 'ENTRY_ALREADY_LINKED', + ) + } + + const { data: updated, error: updateError } = await supabase + .from('skattekonto_transactions') + .update({ journal_entry_id: journalEntryId, suggested_journal_entry_id: null, suggested_at: null }) + .eq('id', transactionId) + .eq('company_id', companyId) + .is('journal_entry_id', null) + .select('id') + if (updateError) { + throw new SkattekontoLinkError(`Kunde inte koppla: ${updateError.message}`, 'LINK_RACE') + } + if (!updated || (Array.isArray(updated) && updated.length === 0)) { + throw new SkattekontoLinkError('Transaktionen kopplades av någon annan samtidigt.', 'LINK_RACE') + } + + return { skattekonto_transaction_id: transactionId, journal_entry_id: journalEntryId, via: settles.via } +} + +/** + * Remove the link. The verifikat is untouched (BFL: nothing is deleted or + * edited in the ledger); only the row's pointer is cleared. Proposals are + * recomputed on the next sync. + */ +export async function unlinkSkattekontoRow( + supabase: SupabaseClient, + companyId: string, + transactionId: string, +): Promise<{ skattekonto_transaction_id: string; previous_journal_entry_id: string }> { + const { data: row, error } = await supabase + .from('skattekonto_transactions') + .select('id, journal_entry_id') + .eq('id', transactionId) + .eq('company_id', companyId) + .maybeSingle<{ id: string; journal_entry_id: string | null }>() + if (error || !row) { + throw new SkattekontoLinkError('Skattekonto-transaktionen hittades inte.', 'TRANSACTION_NOT_FOUND') + } + if (!row.journal_entry_id) { + throw new SkattekontoLinkError('Transaktionen är inte kopplad till något verifikat.', 'NOT_LINKED') + } + const { error: updateError } = await supabase + .from('skattekonto_transactions') + .update({ journal_entry_id: null }) + .eq('id', transactionId) + .eq('company_id', companyId) + .eq('journal_entry_id', row.journal_entry_id) + if (updateError) { + throw new SkattekontoLinkError(`Kunde inte koppla bort: ${updateError.message}`, 'LINK_RACE') + } + return { skattekonto_transaction_id: transactionId, previous_journal_entry_id: row.journal_entry_id } +} + +/** + * Ignore / restore a row. An ignored row never carries a link (DB CHECK, + * migration 20260819200000), so ignoring a linked row is refused here with a + * clean code instead of a constraint error. + */ +export async function setSkattekontoRowIgnored( + supabase: SupabaseClient, + companyId: string, + transactionId: string, + ignored: boolean, +): Promise<{ skattekonto_transaction_id: string; is_ignored: boolean }> { + const { data: row, error } = await supabase + .from('skattekonto_transactions') + .select('id, journal_entry_id, is_ignored') + .eq('id', transactionId) + .eq('company_id', companyId) + .maybeSingle<{ id: string; journal_entry_id: string | null; is_ignored: boolean | null }>() + if (error || !row) { + throw new SkattekontoLinkError('Skattekonto-transaktionen hittades inte.', 'TRANSACTION_NOT_FOUND') + } + if (ignored && row.journal_entry_id) { + throw new SkattekontoLinkError('En kopplad händelse kan inte ignoreras. Koppla bort den först.', 'ALREADY_BOOKED') + } + if (Boolean(row.is_ignored) === ignored) { + return { skattekonto_transaction_id: transactionId, is_ignored: ignored } + } + // Two literal payloads (not one conditional expression) so the phantom-column + // guard can read the column set; ignoring also drops a standing proposal. + const update = ignored + ? supabase + .from('skattekonto_transactions') + .update({ is_ignored: true, suggested_journal_entry_id: null, suggested_at: null }) + : supabase.from('skattekonto_transactions').update({ is_ignored: false }) + const { error: updateError } = await update.eq('id', transactionId).eq('company_id', companyId) + if (updateError) { + throw new SkattekontoLinkError(`Kunde inte uppdatera: ${updateError.message}`, 'LINK_RACE') + } + return { skattekonto_transaction_id: transactionId, is_ignored: ignored } +} diff --git a/skills/accounted-api/SKILL.md b/skills/accounted-api/SKILL.md index 0a0186ec..92c87095 100644 --- a/skills/accounted-api/SKILL.md +++ b/skills/accounted-api/SKILL.md @@ -8,7 +8,7 @@ description: >- transactions and reconciliation, payroll (lön), VAT/moms and financial reports, SIE import/export, documents, webhooks. Covers auth with gnubok_sk_ API keys, conventions (dry-run, idempotency, cursor - pagination, scopes), and all 125 endpoints. + pagination, scopes), and all 131 endpoints. --- @@ -140,7 +140,7 @@ call can undo it, e.g. invoice credit). ## Endpoint index -API version `2026-05-12`, 125 operations. Paths are shown without +API version `2026-05-12`, 131 operations. Paths are shown without their `/api/v1` prefix (full base URL: `https://app.gnubok.se/api/v1`). ### Core (4) @@ -251,13 +251,19 @@ POST /companies/{companyId}/documents/{id}/link : Link a document to a journal e POST /companies/{companyId}/inbox-items/{id}/stamp : Mark an inbox item as consumed by a journal entry [scope:documents:write risk:low idempotent] ``` -### Banking (12) +### Banking (18) Full detail: [references/banking.md](references/banking.md) ```text POST /companies/{companyId}/imports/bank : Import a bank-file (CSV / XML / CAMT053) [scope:transactions:write risk:medium idempotent] POST /companies/{companyId}/imports/sie : Import a SIE4 file [scope:bookkeeping:write risk:high idempotent] +GET /companies/{companyId}/reconciliation/accounts : List the accounts that can be reconciled, with status per account [scope:reconciliation:read risk:low idempotent] +GET /companies/{companyId}/reconciliation/accounts/{accountKey} : The reconciliation bridge for one account [scope:reconciliation:read risk:low idempotent] +GET /companies/{companyId}/reconciliation/accounts/{accountKey}/items : List the rows behind one account's bridge, bucketed [scope:reconciliation:read risk:low idempotent] +POST /companies/{companyId}/reconciliation/accounts/{accountKey}/items/{itemId}/ignore : Ignore or restore one outside row [scope:reconciliation:write risk:low idempotent dry-run reversible] +POST /companies/{companyId}/reconciliation/accounts/{accountKey}/links : Link outside rows to existing verifikat (pairs or proposals) [scope:reconciliation:write risk:medium dry-run reversible] +DELETE /companies/{companyId}/reconciliation/accounts/{accountKey}/links/{linkId} : Remove a link between an outside row and a verifikat [scope:reconciliation:write risk:low idempotent dry-run reversible] POST /companies/{companyId}/reconciliation/bank/run : Run the bank-reconciliation matcher [scope:transactions:write risk:medium idempotent dry-run] GET /companies/{companyId}/reconciliation/bank/status : Bank-reconciliation health snapshot [scope:transactions:read risk:low idempotent] GET /companies/{companyId}/transactions : List transactions for a company [scope:transactions:read risk:low idempotent] diff --git a/skills/accounted-api/references/banking.md b/skills/accounted-api/references/banking.md index 711acd4b..0e46a516 100644 --- a/skills/accounted-api/references/banking.md +++ b/skills/accounted-api/references/banking.md @@ -83,6 +83,270 @@ Response `200`: --- +### `GET /api/v1/companies/{companyId}/reconciliation/accounts` + +**List the accounts that can be reconciled, with status per account.** +`scope:reconciliation:read · risk:low · idempotent` + +Returns one row per reconcilable account (bank: for each enabled cash account, skattekonto when configured) with kind, number, currency, source (psd2 / bank_file / skatteverket_api / manual, synced_at, stale), status (reconciled | open | stale | not_configured, unexplained_difference, open_counts) and superseded_by for reconnect duplicates. Optional ?date_from / ?date_to scope the bank bridge (default: the calendar year to date). Pass ?with_status=false for a cheap list without status. + +**Use when:** You need the side list of the Avstämning page, a month-end checklist, or to find the account_key to pass to the other reconciliation endpoints. +**Do not use for:** The bridge and rows for one account: use GET /reconciliation/accounts/{accountKey} and .../items. + +**Pitfalls:** +- account_key is the identifier every other reconciliation endpoint takes: bank: or skattekonto. Do not pass the BAS number. +- status.state = stale means the outside truth is older than 7 days; the numbers are still computed, but judge them accordingly. +- superseded_by is set on an older cash account that shares IBAN + currency with a newer one (reconnect duplicate); it is kept in the list because it may still hold unlinked rows. +- Computing status per account runs one reconciliation per account; with_status=false skips that when you only need the list. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | + +Response `200`: +```ts +{ + data: { + accounts: { account_key: string, kind: "bank" | "skattekonto" | "manual", account_number: string, name: string, currency: string, logo_url: string, source: { type: "psd2" | "bank_file" | "skatteverket_api" | "skatteverket_file" | "manual", synced_at: string, stale: boolean }, status: { state: "reconciled" | "open" | "stale" | "not_configured", as_of: string, unexplained_difference: number, open_counts: { proposed: number, unmatched_external: number, unmatched_ledger: number } }, superseded_by: string }[] + }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + +### `GET /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}` + +**The reconciliation bridge for one account.** +`scope:reconciliation:read · risk:low · idempotent` + +Returns external_balance (Skatteverket saldo; null for bank accounts until a statement balance exists), ledger_balance (1630 balance at the snapshot for skattekonto; period movement on the bank account), difference, unexplained_difference, is_reconciled, the bridge lines (label, amount, count, items_bucket) that explain the difference row by row, counts per bucket, and a kind block (skattekonto: saldo, fetched_at, history_start, opening_difference, upcoming; bank: today's bank status fields). Optional ?date_from / ?date_to: for skattekonto they scope the item lists only (the bridge is anchored at the snapshot); for bank they scope the bridge window. + +**Use when:** You need to know whether an account reconciles and why not: the bridge is the explanation, the buckets are the work. +**Do not use for:** Listing the rows themselves (use .../items) or linking (POST .../links). + +**Pitfalls:** +- Judge health on unexplained_difference, never on difference. The difference is expected to be non-zero while rows are unmatched; unexplained_difference is what is left once every bridge line is accounted for, and for skattekonto it is 0,00 whenever the data is consistent (a non-zero value is an integrity finding, not a task). +- stale = true means the outside truth is older than 7 days (Skatteverket connection needing re-consent is the usual cause). is_reconciled can still be true on stale data; read both. +- skattekonto.opening_difference is the gap between the derived saldo at history_start and the ledger before it; it belongs to migrated ledgers and is accepted once at sign-off, not worked down. +- Bank accounts carry the legacy field set in the bank block (bank_transaction_total, gl_1930_period_movement, …) unchanged from /reconciliation/bank/status. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | +| `accountKey` | path | `string` | yes | | + +Response `200`: +```ts +{ + data: { + account_key: string, + kind: "bank" | "skattekonto" | "manual", + account_number: string, + currency: string, + window: { from: string, to: string }, + as_of: string, + stale: boolean, + external_balance: number, + ledger_balance: number, + difference: number, + unexplained_difference: number, + is_reconciled: boolean, + bridge: { key: string, label_sv: string, label_en: string, amount: number, count: number, items_bucket: string }[], + counts: { proposed: number, unmatched_external: number, unmatched_ledger: number, matched: number, ignored: number }, + skattekonto: { saldo_skatteverket: number, fetched_at: string, history_start: string, opening_difference: number, upcoming_count: number, upcoming_total: number, ledger_balance_before_start: number }, + bank: Record + }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + +### `GET /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/items` + +**List the rows behind one account's bridge, bucketed.** +`scope:reconciliation:read · risk:low · idempotent` + +Returns reconciliation items for one account. ?bucket selects one of proposed | unmatched_external | unmatched_ledger | matched | ignored | upcoming (default: all open buckets first, then matched). Each item carries its side (external | ledger), a qualified item_id (skattekonto_transaction / transaction / journal_entry), date, description, signed amount, the proposal when one exists (journal_entry_id, voucher, confidence, reasons[]), link_problem when a link points at a reversed or draft entry, awaiting_external for fresh ledger lines, and the actions the row allows. ?date_from / ?date_to scope the lists; rows outside the window are never hidden from the counts (older_unmatched_count). + +**Use when:** You are about to link, book or ignore rows and need to see what is open and what is proposed. +**Do not use for:** The totals: those are on GET /reconciliation/accounts/{accountKey}. + +**Pitfalls:** +- An item in bucket proposed is NOT linked: it carries a proposal to link. Apply it with POST .../links { use_proposals: true } or explicit pairs. +- actions lists what the row allows right now; an action not listed returns a structured error rather than silently doing nothing. +- Ledger items are one per verifikat: several 1630/1930 lines of the same entry are netted, because a link settles the whole entry. +- Pagination is ?limit (max 200) + ?cursor; next_cursor is null on the last page. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | +| `accountKey` | path | `string` | yes | | + +Response `200`: +```ts +{ + data: { + items: { item_id: string, item_type: "skattekonto_transaction" | "transaction" | "journal_entry", side: "external" | "ledger", bucket: "proposed" | "unmatched_external" | "unmatched_ledger" | "matched" | "ignored" | "upcoming", date: string, description: string, amount: number, currency: string, voucher_number?: number, voucher_series?: string, entry_status?: "draft" | "posted" | "reversed", linked_journal_entry_id?: string, link_problem?: "entry_reversed" | "entry_draft" | "entry_missing", proposal?: { journal_entry_id: string, voucher_number: number, voucher_series: string, entry_date: string, description: string, entry_status: "draft" | "posted" | "reversed", confidence: number, reasons: string[] }, awaiting_external?: boolean, actions: ("match" | "unmatch" | "book" | "ignore" | "unignore" | "review")[] }[], + count: number, + total_count: number, + has_more: boolean, + next_cursor: string, + older_unmatched_count: number + }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + +### `POST /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/items/{itemId}/ignore` + +**Ignore or restore one outside row.** +`scope:reconciliation:write · risk:low · idempotent · dry-run · reversible` + +Sets the ignore flag on one outside row (bank transaction or skattekonto row). Body { ignored: true | false }, default true. An ignored row never has a link; ignoring a linked row is refused (unlink first). Ignored rows are excluded from the unmatched totals and listed on the bridge's exclusion line so they never disappear silently. + +**Use when:** A row will never have a counterpart (a duplicate from a reconnect, an event that predates the books) and should stop counting as work. +**Do not use for:** Rows that should be booked or linked; ignoring is triage, not settlement. + +**Pitfalls:** +- Ignoring is reversible (ignored: false) and audited through the row itself; nothing is deleted. +- For the skattekonto, an ignored row still counts toward the derived opening balance (it is a real Skatteverket movement); the bridge shows it on its own line. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | +| `accountKey` | path | `string` | yes | | +| `itemId` | path | `string` | yes | | + +Request body: +```ts +{ ignored?: boolean } +``` + +Response `200`: +```ts +{ + data: { external_id: string, is_ignored: boolean }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + +### `POST /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/links` + +**Link outside rows to existing verifikat (pairs or proposals).** +`scope:reconciliation:write · risk:medium · dry-run · reversible` + +Body: { pairs: [{ external_ids: [id], journal_entry_ids: [id] }] } and/or { use_proposals: true, confidence_threshold? }. Each pair is validated as the single-link paths validate (row open and not ignored, entry posted and not reversed, the entry's account lines settle the amount, entry not already linked) and applied independently: the response lists applied[] and skipped[{pair, code, message}] so partial success is explicit. Codes: UNSUPPORTED_PAIR_SHAPE, ALREADY_LINKED, ENTRY_NOT_FOUND, PAIR_NOT_CLOSED, ROW_IGNORED, NOT_FOUND, LINK_RACE. ?dry_run=true returns the pairs that would be attempted without writing. + +**Use when:** An agent or integration has decided which rows explain each other, or wants to apply the proposals the sync already computed. +**Do not use for:** Booking new verifikat for rows that have no counterpart (use the transactions or skattekonto booking endpoints); reconciling across accounts. + +**Pitfalls:** +- This version links one outside row to one verifikat per pair; other shapes come back as UNSUPPORTED_PAIR_SHAPE, never silently reduced. +- A pair must close to the row's amount on the expected side (a single matching line, or the entry's lines on the account netting to it); a fee or rounding difference is PAIR_NOT_CLOSED here and needs a residual booking first. +- Links never touch the ledger, so they succeed in locked periods; unlink with DELETE .../links/{linkId} (linkId = the outside row id). +- Idempotency-Key is required; repeating the same key replays the first response. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | +| `accountKey` | path | `string` | yes | | + +Request body: +```ts +{ + pairs?: { external_ids: string[], journal_entry_ids: string[] }[], + use_proposals?: boolean, + confidence_threshold?: number +} +``` + +Response `200`: +```ts +{ + data: { + dry_run: boolean, + considered: number, + applied: { external_id: string, journal_entry_id: string, via?: "line" | "entry_total" }[], + skipped: { pair: { external_ids: string[], journal_entry_ids: string[] }, code: string, message: string }[] + }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + +### `DELETE /api/v1/companies/{companyId}/reconciliation/accounts/{accountKey}/links/{linkId}` + +**Remove a link between an outside row and a verifikat.** +`scope:reconciliation:write · risk:low · idempotent · dry-run · reversible` + +Clears the link on one outside row (bank transaction or skattekonto row). The verifikat is never edited or deleted (BFL); only the row's pointer is cleared, so the pair returns to the open buckets and proposals are recomputed on the next sync. Allowed in locked periods. ?dry_run=true reports what would be unlinked. + +**Use when:** A link was wrong (a bulk proposal apply that paired the wrong verifikat, a manual mistake). +**Do not use for:** Undoing a booking: a residual or categorization booking is reversed through the journal-entry reverse endpoint, not by unlinking. + +**Pitfalls:** +- linkId is the outside row id, not a separate link entity. +- Unlinking a row whose verifikat was stornoed is the expected fix for a link_problem = entry_reversed item; the row then shows under unmatched_external again. + +| Parameter | In | Type | Required | Notes | +|---|---|---|---|---| +| `companyId` | path | `string` | yes | | +| `accountKey` | path | `string` | yes | | +| `linkId` | path | `string` | yes | | + +Response `200`: +```ts +{ + data: { external_id: string, previous_journal_entry_id: string }, + meta: { + request_id: string, + api_version: string, + next_cursor?: string, + audit?: { voucher_number?: string, voucher_url?: string, audit_trail_url?: string, immutable_at?: string }, + partial_expansions?: string[] + } +} +``` + +--- + ### `POST /api/v1/companies/{companyId}/reconciliation/bank/run` **Run the bank-reconciliation matcher.** diff --git a/supabase/migrations/20260823130000_pending_operations_add_reconciliation_ops.sql b/supabase/migrations/20260823130000_pending_operations_add_reconciliation_ops.sql new file mode 100644 index 00000000..e22faebc --- /dev/null +++ b/supabase/migrations/20260823130000_pending_operations_add_reconciliation_ops.sql @@ -0,0 +1,99 @@ +-- Add 'reconciliation_match' and 'reconciliation_unmatch' to the +-- pending_operations operation_type CHECK constraint. +-- +-- The account-keyed reconciliation surface (lib/reconciliation/actions.ts) +-- is staged through pending_operations when an MCP agent drives it: +-- reconciliation_match pairs outside rows (bank transactions or +-- skattekonto rows) with existing verifikat on one +-- account; writes nothing to the ledger. Risk +-- 'medium', same tier as link_transaction_journal_entry. +-- reconciliation_unmatch clears one such link. Risk 'low'. +-- Executors: commitReconciliationMatch / commitReconciliationUnmatch in +-- lib/pending-operations/commit.ts. +-- +-- NOTE on the value list: this constraint is re-created wholesale (the +-- established pattern here; see 20260727110000's own note), so the list +-- below is every value of the LIVE prod constraint as read on 2026-08-23 +-- (64 values, identical to 20260817130000) PLUS the two new values. Dropping +-- any existing value here would silently revoke it. +-- +-- NOT VALID + separate VALIDATE migration (paired file, same pattern as +-- 20260817130000 / 20260817130001): avoids a full-table scan under the +-- stronger lock this ALTER already holds. +-- +-- pg-test: tests/pg/pending-operations-op-type-audit.pg.test.ts asserts every +-- op type staged in server.ts or tiered in risk-tiers.ts is accepted here. + +ALTER TABLE public.pending_operations + DROP CONSTRAINT IF EXISTS pending_operations_operation_type_check; + +ALTER TABLE public.pending_operations + ADD CONSTRAINT pending_operations_operation_type_check + CHECK (operation_type IN ( + 'categorize_transaction', + 'create_customer', + 'create_invoice', + 'mark_invoice_paid', + 'send_invoice', + 'mark_invoice_sent', + 'match_transaction_invoice', + 'close_period', + 'lock_period', + 'unlock_period', + 'set_opening_balances', + 'run_year_end', + 'post_kontantmetod_cutoff', + 'run_currency_revaluation', + 'import_sie', + 'explain_voucher_gap', + 'uncategorize_transaction', + 'approve_supplier_invoice', + 'credit_supplier_invoice', + 'credit_invoice', + 'convert_invoice', + 'create_transaction', + 'attach_document_to_transaction', + 'create_voucher', + 'correct_entry', + 'reverse_entry', + 'create_supplier', + 'create_supplier_invoice_from_inbox', + 'post_annual_depreciation', + 'link_invoice_voucher', + 'undo_sie_import', + 'match_batch_allocate', + 'bulk_book_transactions', + 'create_salary_run', + 'generate_agi', + 'link_transaction_journal_entry', + 'link_supplier_invoice_voucher', + 'submit_vat_declaration', + 'submit_agi', + 'create_article', + 'update_article', + 'bulk_book_inbox_items', + 'create_dimension_value', + 'retag_line_dimensions', + 'link_document_to_voucher', + 'update_payslip_line', + 'register_absence', + 'create_employee', + 'update_employee', + 'set_employee_opening_balances', + 'vacation_year_close', + 'create_account', + 'update_account', + 'set_voucher_note', + 'book_salary_run', + 'delete_absence', + 'update_company_settings', + 'update_customer', + 'update_invoice', + 'create_recurring_schedule', + 'update_recurring_schedule', + 'log_mileage_trip', + 'book_mileage_period', + 'link_documents_to_vouchers', + 'reconciliation_match', + 'reconciliation_unmatch' + )) NOT VALID; diff --git a/supabase/migrations/20260823130001_validate_pending_operations_reconciliation_ops.sql b/supabase/migrations/20260823130001_validate_pending_operations_reconciliation_ops.sql new file mode 100644 index 00000000..7a848dbb --- /dev/null +++ b/supabase/migrations/20260823130001_validate_pending_operations_reconciliation_ops.sql @@ -0,0 +1,6 @@ +-- Validate the operation type CHECK re-added in 20260823130000. +-- This separate transaction avoids a full-table scan while the preceding +-- migration holds its stronger table lock. + +ALTER TABLE public.pending_operations + VALIDATE CONSTRAINT pending_operations_operation_type_check; diff --git a/types/index.ts b/types/index.ts index e74cc5e5..81c411cc 100644 --- a/types/index.ts +++ b/types/index.ts @@ -2488,6 +2488,10 @@ export type PendingOperationType = | 'bulk_book_inbox_items' // PR #614: link a single bank tx to an already-posted verifikat (no new JE) | 'link_transaction_journal_entry' + // Account-keyed reconciliation (bank accounts + skattekonto): link outside + // rows to existing verifikat / clear such a link. No ledger writes. + | 'reconciliation_match' + | 'reconciliation_unmatch' // PR5: Skatteverket filing via MCP. Commit = "send for BankID signing" // (returns a signing link); the user's signature in the browser files it. | 'submit_vat_declaration'