Files
accounted/app/api/transactions/[id]/attach-document/__tests__/route.test.ts
T
MattssonandClaude Fable 5.1 4c76fb10d7 feat(transactions): "Ta bort underlag" detach action on a transaction (#2132) (#2144)
* feat(transactions): "Ta bort underlag" detach action on a transaction (#2132)

Wrong receipt pinned, no way back: the DELETE
/api/transactions/[id]/attach-document route and its tests already existed,
but nothing in the UI called it. This wires it up, frontend only.

- Inbox card and history list: "Ta bort underlag" in the row menu, shown only
  for writers on unbooked rows that carry a pin (canDetachDocument helper).
- Attach dialog: a small "Ta bort underlag" link beside the already-attached
  hint, the one place the app previously admitted a doc was pinned.
- Page: handleDetachDocument confirms (useDestructiveConfirm, warning), then
  DELETEs; 200 clears document_id in local state (list, dialog snapshot, and
  the inbox card's optimistic override via a -unlinked window event) and
  toasts; 409 renders the route's Swedish BFL message verbatim; other errors
  map through get-error-message.
- Strings under tx_detach in sv.json and en.json.
- Tests: gate hidden when booked / read-only / no pin / no handler; 409
  rendered unchanged; wiring and locale assertions.

Out of scope, follow-up: MCP detach tool (new pending-op type + CHECK
migration), detaching from the inbox for non-email docs, and clearing
invoice_inbox_items.matched_transaction_id on detach so the doc is offered
again by inbox-available.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg

* fix(transactions): clear the inbox back-link when detaching underlag (#2132)

Skeptic finding on PR #2144: DELETE attach-document nulled only
transactions.document_id and left invoice_inbox_items.matched_transaction_id
pointing at the transaction. propagateUnderlagForBookedTransaction selects
on exactly that column at categorize / book / bulk-book time, so the
detached receipt would have been re-anchored onto the new verifikation as
immutable underlag (BFL 5 kap 7 §), and the doc never reappeared in
inbox-available for re-matching.

The route now clears the back-link for the detached document, scoped to
items not yet consumed by a verifikat (created_journal_entry_id null),
mirroring the invoice-inbox extension's unmatch. Best-effort like the POST
side: the pin removal is the primary effect. Three DELETE tests cover the
filters, the no-pin case, and a failing unlink. DECISIONS.md and the PR body
record the accepted bulk-booked-row limitation in the history list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg

* fix(transactions): detach reports a failed inbox unlink instead of success (#2132)

Swedish compliance review on PR #2144: the inbox back-link cleanup was
fire-and-forget, so a failed UPDATE returned 200 while leaving exactly the
stale matched_transaction_id that re-anchors a detached document onto the
next verifikation (BFL 5 kap 6-7 §).

The unlink is now scoped by transaction only (the unique index on
matched_transaction_id means at most one item points here, and a stale item
from the replace path would re-anchor just the same), runs even when nothing
was pinned so a retry is idempotent, and a failure answers 500 with an honest
Swedish partial-failure message, mirroring the POST side's propagation
failure. Tests updated accordingly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg

* fix(transactions): release inbox back-link before a compare-and-set pin clear (#2132)

Review findings on PR #2144, one pass:

- CodeRabbit (major): DELETE cleared the pin and then released the inbox
  back-link scoped by transaction, so a POST landing in between could end up
  as "new doc pinned, its inbox item unlinked". The release now runs FIRST,
  and the pin clear is a compare-and-set on the document that was read
  (.eq document_id, or .is null when nothing was pinned). Zero rows answers
  409 "ändrades samtidigt" and keeps the newer pin. A failed release returns
  500 before anything changed, so a retry is trivially idempotent.
- Compliance swarm (A.8.15): the unlink failure log carried the raw driver
  error; it now logs errorCauseTag() only.
- CodeRabbit docstring check: JSDoc on handleDetachDocument.

Tests: order of the two writes, CAS filters for both pinned and empty
states, 409 on concurrent re-attach, coded-cause logging.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 00:29:22 +02:00

420 lines
21 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: 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(),
}))
import { POST, DELETE } from '../route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
function makeReq(body: unknown, method: 'POST' | 'DELETE' = 'POST') {
return new Request('http://localhost/api/transactions/tx-1/attach-document', {
method,
headers: { 'Content-Type': 'application/json' },
body: method === 'POST' ? JSON.stringify(body) : undefined,
})
}
describe('POST /api/transactions/[id]/attach-document', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq({ document_id: 'doc-1' }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 403 when the caller is a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(body).toEqual({ error: 'Forbidden' })
})
it('returns 400 when document_id missing', async () => {
const res = await POST(makeReq({}), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 when transaction not in company', async () => {
enqueue({ data: null, error: null }) // tx fetch
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Transaction not found' })
})
it('returns 404 when document not in company', async () => {
enqueue({ data: { id: 'tx-1' }, error: null }) // tx fetch
enqueue({ data: null, error: null }) // doc fetch
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Document not found' })
})
it('attaches when both rows exist', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { transaction_id: string; document_id: string; journal_entry_id: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.transaction_id).toBe('tx-1')
expect(body.data.document_id).toBe('11111111-1111-4111-8111-111111111111')
expect(body.data.journal_entry_id).toBeNull()
// Unbooked tx: document_attachments is only read (doc fetch), never
// written: no journal entry to propagate to.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(1)
})
it('propagates the link onto the verifikation when the transaction is booked', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: null }) // document_attachments propagation
enqueue({ data: [], error: null }) // completion: matched inbox items (none)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { journal_entry_id: string } }>(res)
expect(status).toBe(200)
expect(body.data.journal_entry_id).toBe('je-1')
// doc fetch + propagation write
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(2)
})
it('skips propagation when the doc already points at the same verifikation (idempotent re-attach)', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1' }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [], error: null }) // completion: matched inbox items (none)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
// No propagation write: only the doc fetch touched document_attachments.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(1)
})
it('returns 409 when the document already belongs to a different verifikation', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-OTHER' }, error: null }) // doc fetch
enqueue({ data: [], error: null }) // voucher-link check: je-OTHER anchors nothing here
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('annan verifikation')
})
it('completes the matched inbox item when the tx is anchored via a bulk-book samlingsverifikat', async () => {
// A bulk-booked tx keeps transactions.journal_entry_id null: the
// verifikat hangs off transaction_voucher_links. Attaching a receipt to
// it must link the underlag to that verifikat and stamp the matched
// inbox item, or the item strands as "linked" (the 2026-08-12 report).
const DOC = '11111111-1111-4111-8111-111111111111'
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: DOC, journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [{ transaction_id: 'tx-1', journal_entry_id: 'je-9' }], error: null }) // voucher links
enqueue({ data: [{ id: 'inbox-1', document_id: DOC }], error: null }) // matched inbox items
enqueue({ data: { journal_entry_id: null }, error: null }) // doc anchor check: free
enqueue({ data: { id: 'je-9' }, error: null }) // linkToJournalEntry: JE ownership check
enqueue({ data: { id: DOC, journal_entry_id: 'je-9' }, error: null }) // linkToJournalEntry: doc update
enqueue({ data: null, error: null }) // created_journal_entry_id stamp
const res = await POST(makeReq({ document_id: DOC }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ data: { journal_entry_id: string } }>(res)
expect(status).toBe(200)
// The response reports the samlingsverifikat the attach completed against.
expect(body.data.journal_entry_id).toBe('je-9')
})
it('returns 409 when the verifikation period is locked during propagation', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: { message: 'cannot link document in a locked/closed fiscal period' } }) // propagation blocked
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('låst')
})
it('returns 500 with the idempotent-retry message when propagation fails', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: { message: 'boom' } }) // propagation fails
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toContain('idempotent')
spy.mockRestore()
})
it('returns 404 when the update matches no row (concurrent delete)', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // transactions update returns no row
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('attempts to update invoice_inbox_items.matched_transaction_id after successful attach', async () => {
// The side effect lets the inbox UI flip an item from "needs action" to
// "Kopplad till transaktion" without an extra round-trip.
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link update
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
// Verify the inbox_items table was touched.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls).toContain('invoice_inbox_items')
})
it('tolerates a failing inbox-link update: the document attach is the primary effect', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: { message: 'rls denied' } }) // inbox-link fails
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { transaction_id: string } }>(res)
// Side-effect failure must not roll back the (compliant) document attach.
expect(status).toBe(200)
expect(body.data.transaction_id).toBe('tx-1')
// The Supabase client resolves with { error } rather than rejecting, so
// we additionally assert that the error was actually inspected and logged
// (not silently dropped by a try/catch that never fires).
expect(spy).toHaveBeenCalledWith(
'[attach-document] Failed to link inbox item:',
expect.objectContaining({ message: 'rls denied' }),
)
spy.mockRestore()
})
})
describe('DELETE /api/transactions/[id]/attach-document', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 403 when the caller is a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(body).toEqual({ error: 'Forbidden' })
})
it('returns 404 when transaction not in company', async () => {
enqueue({ data: null, error: null }) // tx fetch
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Transaction not found' })
})
it('returns 409 when document is already on a journal entry', async () => {
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // doc fetch
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('verifikation')
// Nothing is written on the immutability path.
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
expect(findCalls('transactions', 'update')).toEqual([])
})
it('clears document_id when no journal entry link', async () => {
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // inbox unlink
enqueue({ data: { id: 'tx-1' }, error: null }) // pin CAS (RETURNING id)
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ data: { document_id: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.document_id).toBeNull()
})
it('clears document_id when no doc was attached', async () => {
enqueue({ data: { id: 'tx-1', document_id: null }, error: null }) // tx fetch
enqueue({ data: null, error: null }) // inbox unlink
enqueue({ data: { id: 'tx-1' }, error: null }) // pin CAS
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
// The back-link is released even with nothing pinned (a stale item from
// the replace path would re-anchor just the same), and the CAS then
// requires the pin to still be empty.
expect(findCalls('invoice_inbox_items', 'update')).toEqual([[{ matched_transaction_id: null }]])
expect(findCalls('transactions', 'is')).toContainEqual(['document_id', null])
})
it('releases the inbox back-link BEFORE the pin, scoped by transaction (else booking re-anchors it)', async () => {
// propagateUnderlagForBookedTransaction selects inbox items by
// matched_transaction_id at categorize time; a stale back-link would pin
// the rejected receipt onto the new verifikation as immutable underlag.
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // inbox unlink
enqueue({ data: { id: 'tx-1' }, error: null }) // pin CAS
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(findCalls('invoice_inbox_items', 'update')).toEqual([[{ matched_transaction_id: null }]])
const eqArgs = findCalls('invoice_inbox_items', 'eq')
// Scoped by transaction (unique index: at most one item points here), not
// by the pinned doc, so a stale item from the replace path is cleared too.
expect(eqArgs).toContainEqual(['matched_transaction_id', 'tx-1'])
expect(eqArgs).toContainEqual(['company_id', 'company-1'])
expect(eqArgs).not.toContainEqual(['document_id', 'doc-1'])
// Items already consumed by a verifikat are left alone.
expect(findCalls('invoice_inbox_items', 'is')).toContainEqual(['created_journal_entry_id', null])
// Order: the unlink table is touched before the pin update.
const tables = mockSupabase.from.mock.calls.map((c) => c[0])
expect(tables.indexOf('invoice_inbox_items')).toBeLessThan(tables.lastIndexOf('transactions'))
// Compare-and-set: the pin is cleared only if it is still doc-1.
expect(findCalls('transactions', 'eq')).toContainEqual(['document_id', 'doc-1'])
expect(findCalls('transactions', 'update')).toEqual([[{ document_id: null }]])
})
it('refuses with 409 when the pin changed under us (concurrent re-attach)', async () => {
// Interleaving: we read doc-1, a POST pins doc-2 (and links its inbox
// item) before our CAS runs. Zero rows come back: the new pin is kept and
// the caller is told nothing happened, instead of a success for a state
// that is now "doc-2 pinned, doc-2 inbox item unlinked".
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // inbox unlink
enqueue({ data: null, error: null }) // pin CAS: 0 rows
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('samtidigt')
})
it('reports a failing inbox unlink as 500 with nothing changed, logging a coded cause only', async () => {
// A stale back-link is the exact defect the detach exists to prevent, so
// a 200 here would hide a compliance hazard. Because the unlink runs
// first, the pin is untouched and a retry is trivially idempotent.
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: { code: '42501', message: 'rls denied: row values here' } }) // unlink fails
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toContain('fortfarande kopplat')
expect(findCalls('transactions', 'update')).toEqual([])
// Raw driver messages can quote row values: only the coded cause is logged.
expect(spy).toHaveBeenCalledWith('[attach-document] Failed to unlink inbox item:', {
cause: '42501',
})
spy.mockRestore()
})
})