feat(reconciliation): three doors over one engine: dashboard routes, v1 API and MCP tools (#1833)
* feat(reconciliation): skattekonto bridge engine, sync-time twin proposals, account-keyed facade The engine half of the reconciliation page (design: Avstämningsmotorn). - lib/reconciliation/skattekonto-reconciliation.ts: getSkattekontoReconciliationStatus anchors at the saldo snapshot and returns the bridge (saldo hos Skatteverket, händelser som saknas, 1630-rader utan händelse, ignorerade, ingående skillnad, bokfört), the item buckets the page shows (proposed, unmatched external, unmatched ledger, matched, ignored, upcoming), opening_difference, unexplained_difference (0,00 by construction when data is consistent), dead-link handling (a link to a reversed/draft entry counts as unlinked and is flagged), awaiting_external for ledger lines within 5 days of the snapshot, staleness, and a window that scopes item lists without hiding older rows. Core reads skattekonto_transactions and the extension's snapshot row directly; no @/extensions import. - lib/reconciliation/gl-balance.ts: one ledger-balance helper with the trial-balance predicate status IN (posted, reversed). The drift check summed posted only, which misstated 1630 for any company with a storno on the account; skattekonto-drift.ts now delegates to the helper. - Proposals at sync: migration 20260823120000 adds suggested_journal_entry_id / suggested_at (ON DELETE SET NULL, partial index on open rows); the sync calls refreshSkattekontoProposals after the upsert. findMatchSuggestionsBulk now assigns one-to-one across rows (AGI period first, then nearest date) and falls back to an entry whose 1630 lines net to the amount (split lines); a proposal is never a link. - lib/reconciliation/service.ts + schemas.ts: the account-keyed facade (bank:<cash_account_id> | skattekonto | manual:NNNN) with listReconciliationAccounts (enabled cash accounts folded per IBAN, skattekonto when configured) and getAccountStatus dispatching to the bank engine or the new one; shared Zod shapes for the v1 registry, MCP schemas and the UI (PR 2). Tests: identity on a mixed fixture, storno pair, stale snapshot, awaiting window, window scoping, failed ledger read, live-linked entries never proposed; matcher one-to-one and split-line cases; proposal refresh writes/clears; service dedupe and dispatch. No UI in this PR. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): roundOre instead of inline öre rounding (guard ratchet) The antipattern ratchet counts Math.round(x*100)/100; the new engine used it in five places. Switch to roundOre from @/lib/money and ratchet the baseline down by the three occurrences this removes net of the matcher rewrite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(reconciliation): three doors over one engine: dashboard routes, v1 API and MCP tools for account-keyed reconciliation PR 2 of the Avstämning build (design: Avstämning via API och MCP). Every door calls lib/reconciliation/{service,items,actions}.ts; none re-implements a link. - lib/reconciliation/items.ts: listAccountItems per account_key, the page's buckets (proposed, unmatched_external, unmatched_ledger, matched, ignored, upcoming), limit/offset; skattekonto from the engine, bank from the scoped transactions + unlinked GL lines (netted per entry). - lib/reconciliation/actions.ts: matchPairs (pairs or use_proposals, dry run, partial success with codes), unmatchLink, setItemIgnored; emits reconciliation.matched / reconciliation.unmatched. - lib/skatteverket/skattekonto-link.ts: canonical core link semantics for a skattekonto row (single line or entry net on 1630, live-link guard, race-safe update, unlink, ignore); the extension keeps its own matchSkattekontoToEntry until its tests are ported. - Dashboard routes /api/reconciliation/accounts[...]: list, status, items, links (POST), links/{linkId} (DELETE), items/{itemId}/ignore (POST); apply directly (a human clicked). - v1 routes /api/v1/companies/{id}/reconciliation/accounts[...]: same six, withApiV1, new scopes reconciliation:read / reconciliation:write (write is a staging scope for SoD), Idempotency-Key + dry_run on writes, registered for OpenAPI, load-routes, skills/accounted-api regenerated. Legacy bank routes and their transactions:* scopes unchanged. - MCP: gnubok_get_reconciliation_status takes account_key (legacy bank path untouched), new gnubok_list_reconciliation_items (default catalog), gnubok_reconcile_match (stages reconciliation_match, preflight = status) and gnubok_reconcile_unmatch (stages reconciliation_unmatch), both search-only to stay under the tools/list payload ceiling; gnubok_link_transaction_to_journal_entry moved to search. Executors in commit.ts; risk tiers medium/low; migration pair 20260823130000/130001 adds the two op types to the CHECK constraint (value list = live prod as of 2026-08-23 + the two); close_period loadout updated. Tests: service/actions/items/link unit tests, v1 route tests (401/403/400/404/ happy, idempotency, dry run), dashboard route tests, MCP tool tests + the guard suite (payload ceiling, descriptions, staging meta, qualified ids). Guards and apiskill:check green; no type errors in changed files. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): refresh the v1 spec snapshot and keep the ignore update readable by the phantom-column guard The six new v1 reconciliation endpoints and the two new scopes were not recorded in the spec snapshot, and setSkattekontoRowIgnored updated through one conditional payload, which the phantom-column scanner cannot read (ceiling 380 -> 381). Two literal payloads instead; snapshot updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
0a8544e0cb
commit
3a62c5419e
@@ -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 },
|
||||
)
|
||||
@@ -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 })
|
||||
},
|
||||
)
|
||||
@@ -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 },
|
||||
)
|
||||
@@ -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 },
|
||||
)
|
||||
@@ -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 })
|
||||
},
|
||||
)
|
||||
@@ -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<typeof import('@/lib/reconciliation/items')>('@/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<string, string>) => ({ 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)
|
||||
})
|
||||
})
|
||||
@@ -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 } })
|
||||
},
|
||||
)
|
||||
+98
@@ -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 },
|
||||
)
|
||||
@@ -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 })
|
||||
}
|
||||
},
|
||||
)
|
||||
+78
@@ -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 },
|
||||
)
|
||||
@@ -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 },
|
||||
)
|
||||
@@ -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 })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -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<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@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<typeof import('@/lib/reconciliation/items')>('@/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<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
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<string, string> = {
|
||||
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<string, string> = {}) =>
|
||||
({ 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)
|
||||
})
|
||||
})
|
||||
@@ -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:<cash_account_id> 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:<cash_account_id> 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 })
|
||||
}
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user