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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> --------- Co-authored-by: Jakob Wennberg <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
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 },
|
||||
)
|
||||
File diff suppressed because one or more lines are too long
+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 },
|
||||
)
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -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)
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user