Files
accounted/app/api/transactions/[id]/attach-document/route.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

351 lines
15 KiB
TypeScript

import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { AttachDocumentSchema } from '@/lib/api/schemas'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { errorCauseTag } from '@/lib/errors/db-error'
import {
completeInboxItemsForBookedTransaction,
resolveVoucherLinkedEntryIds,
} from '@/lib/transactions/inbox-underlag'
ensureInitialized()
/**
* POST /api/transactions/[id]/attach-document
*
* Pin an unmatched document_attachments row to a bank transaction. Lets users
* (or AI agents via MCP) bind a forwarded/uploaded invoice or receipt before
* the transaction is categorized. When the transaction is later categorized,
* the categorize route propagates the link to document_attachments.journal_entry_id.
* If the transaction is ALREADY booked, the propagation happens here instead
* (mirroring commitAttachDocumentToTransaction in lib/pending-operations/commit.ts).
*
* Idempotent: overwrites any existing link.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'transaction.attach_document',
async (request, { supabase, user, companyId }, { params }) => {
const { id: transactionId } = await params
const validation = await validateBody(request, AttachDocumentSchema)
if (!validation.success) return validation.response
const { document_id } = validation.data
const { data: transaction, error: txError } = await supabase
.from('transactions')
.select('id, document_id, journal_entry_id')
.eq('id', transactionId)
.eq('company_id', companyId)
.maybeSingle()
if (txError || !transaction) {
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
}
const previousDocumentId = (transaction.document_id as string | null) ?? null
const { data: document, error: docError } = await supabase
.from('document_attachments')
.select('id, journal_entry_id')
.eq('id', document_id)
.eq('company_id', companyId)
.maybeSingle()
if (docError || !document) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// A document that already serves as underlag for a DIFFERENT verifikation
// cannot be pinned here: propagating would either corrupt that link or be
// blocked by the document-metadata immutability trigger. Same verifikation
// is fine (idempotent re-attach; propagation below becomes a no-op). A
// bulk-booked tx keeps journal_entry_id null and is anchored through
// transaction_voucher_links, so that anchoring counts as "same" too.
const docJournalEntryId = (document.journal_entry_id as string | null) ?? null
if (docJournalEntryId && docJournalEntryId !== transaction.journal_entry_id) {
const voucherLinked = await resolveVoucherLinkedEntryIds(supabase, companyId, [
transactionId,
])
if (docJournalEntryId !== voucherLinked.get(transactionId)) {
return NextResponse.json(
{ error: 'Underlaget är redan kopplat till en annan verifikation.' },
{ status: 409 },
)
}
}
// Race-free read of journal_entry_id: UPDATE ... RETURNING so the value we
// propagate against reflects any concurrent categorize that committed before
// our UPDATE acquired the row lock. Mirrors commitAttachDocumentToTransaction
// in lib/pending-operations/commit.ts so REST and MCP attaches converge.
const { data: postUpdate, error: updateError } = await supabase
.from('transactions')
.update({ document_id })
.eq('id', transactionId)
.eq('company_id', companyId)
.select('journal_entry_id')
.maybeSingle()
if (updateError) {
const errMsg = (updateError as { message?: string }).message ?? ''
if (errMsg.includes('BFL_DOCUMENT_IMMUTABILITY')) {
return NextResponse.json(
{
error:
'Bilagan är kopplad till en bokförd verifikation och kan inte ersättas. Storno verifikationen först.',
},
{ status: 409 },
)
}
console.error('[attach-document] Failed to attach:', updateError)
return NextResponse.json({ error: 'Failed to attach document' }, { status: 500 })
}
if (!postUpdate) {
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
}
// If this document came from an invoice_inbox_items row, mark that row
// as matched so the inbox UI can show it as "Kopplad" + link back to the
// transaction. Best-effort: a failure here must not roll back the
// (compliant) document attach.
//
// The Supabase client resolves with { error } rather than rejecting on
// RLS/DB errors, so we destructure rather than try/catch.
const { error: inboxLinkErr } = await supabase
.from('invoice_inbox_items')
.update({ matched_transaction_id: transactionId })
.eq('document_id', document_id)
.eq('company_id', companyId)
.is('matched_transaction_id', null)
.is('created_supplier_invoice_id', null)
if (inboxLinkErr) {
console.error('[attach-document] Failed to link inbox item:', inboxLinkErr)
}
// If the transaction is already booked, propagate the link onto the
// verifikation immediately (BFL 5 kap 6 §: the verifikation must reference
// its underlag). Skipped when the doc already points at this verifikation
// (idempotent re-attach). Mirrors commitAttachDocumentToTransaction.
const journalEntryId = (postUpdate.journal_entry_id as string | null) ?? null
if (journalEntryId && docJournalEntryId !== journalEntryId) {
const { error: linkErr } = await supabase
.from('document_attachments')
.update({ journal_entry_id: journalEntryId })
.eq('id', document_id)
.eq('company_id', companyId)
if (linkErr) {
// The enforce_period_lock trigger blocks journal_entry_id writes when
// the target entry sits in a closed/locked period.
const linkMsg = (linkErr as { message?: string }).message ?? ''
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(linkMsg)) {
// Honest about the partial write: the pin on the transaction (and the
// inbox back-link) persisted; only the verifikat link was blocked.
return NextResponse.json(
{
error:
'Bilagan kopplades till transaktionen men verifikationens period är låst: den kunde inte länkas till verifikationen.',
},
{ status: 409 },
)
}
// Surface the propagation failure rather than logging-and-continuing:
// a "succeeded" attach that left document_attachments.journal_entry_id
// null would be a silent compliance gap. A retry is idempotent.
console.error('[attach-document] Failed to propagate to journal entry:', linkErr)
return NextResponse.json(
{
error:
'Bilagan kopplades till transaktionen men kunde inte länkas till verifikationen. Försök igen: operationen är idempotent.',
},
{ status: 500 },
)
}
}
// The transaction may already be booked, directly or via a bulk-book
// samlingsverifikat (journal_entry_id null, anchored through
// transaction_voucher_links): complete the matched inbox items against
// the anchoring verifikat so an after-the-fact attach resolves them
// instead of stranding them as "linked" forever. Best-effort, logged
// inside. Returns the anchoring verifikat (the direct id when there is
// one), so the response and audit trail can report the voucher-linked
// case too.
const effectiveJournalEntryId = await completeInboxItemsForBookedTransaction(
supabase,
companyId,
transactionId,
{ directJournalEntryId: journalEntryId },
)
// Rättelse audit trail (BFL 5 kap 5 §): record swaps where a non-null doc
// was replaced. Best-effort: a logging failure must not roll back the
// (compliant) attach.
if (previousDocumentId && previousDocumentId !== document_id) {
try {
await appendProcessingHistory({
companyId,
correlationId: transactionId,
aggregateType: 'BankTransaction',
aggregateId: transactionId,
eventType: 'TransactionDocumentReplaced',
payload: {
transaction_id: transactionId,
previous_document_id: previousDocumentId,
new_document_id: document_id,
journal_entry_id: effectiveJournalEntryId,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (logErr) {
console.error('[attach-document] Failed to append rättelse event:', logErr)
}
}
return NextResponse.json({
data: {
transaction_id: transactionId,
document_id,
previous_document_id: previousDocumentId,
journal_entry_id: effectiveJournalEntryId,
},
})
},
{ requireWrite: true },
)
/**
* DELETE /api/transactions/[id]/attach-document
*
* Detach a document from a transaction.
*
* Also undoes the invoice_inbox_items back-link written by POST, so the next
* booking does not re-anchor the detached doc (see propagateUnderlag...).
*
* Blocked once the document has propagated into a journal entry (BFL 5 kap 6 §
* räkenskapsinformation immutability): at that point the doc is the
* verifikation's underlag and can only be undone by reversing the entry.
*/
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'transaction.detach_document',
async (_request, { supabase, companyId }, { params }) => {
const { id: transactionId } = await params
const { data: tx, error: fetchError } = await supabase
.from('transactions')
.select('id, document_id')
.eq('id', transactionId)
.eq('company_id', companyId)
.maybeSingle()
if (fetchError || !tx) {
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
}
if (tx.document_id) {
const { data: doc } = await supabase
.from('document_attachments')
.select('journal_entry_id')
.eq('id', tx.document_id)
.eq('company_id', companyId)
.maybeSingle()
if (doc?.journal_entry_id) {
return NextResponse.json(
{
error:
'Bilagan är kopplad till en bokförd verifikation och kan inte tas bort. Storno verifikationen först.',
},
{ status: 409 },
)
}
}
// Step 1: release the inbox back-link the POST path wrote, BEFORE the pin.
// Without this the item still says matched_transaction_id = this tx, and
// the next categorize / book / bulk-book runs
// propagateUnderlagForBookedTransaction, which anchors the DETACHED
// document onto the new verifikation as immutable underlag (BFL 5 kap 7 §:
// the verifikat would cite a receipt the user rejected). Scoped by
// transaction, not by the pinned doc: the unique index on
// matched_transaction_id means at most one item points here, and a stale
// item whose doc differs from the pin (replace path) would re-anchor just
// the same. Items already consumed by a verifikat are left alone.
//
// Ordering: unlink first, then compare-and-set the pin (step 2). A POST
// that lands in between re-pins a new doc and its back-link, and the CAS
// below then refuses to clobber it (409), so the two writes cannot end up
// as "new doc pinned, its inbox item unlinked". A failed unlink returns
// before anything changed, so a retry is trivially idempotent.
const { error: inboxUnlinkErr } = await supabase
.from('invoice_inbox_items')
.update({ matched_transaction_id: null })
.eq('company_id', companyId)
.eq('matched_transaction_id', transactionId)
.is('created_journal_entry_id', null)
if (inboxUnlinkErr) {
// Not best-effort: a stale back-link is the exact defect this detach
// exists to prevent, so a "succeeded" response would hide a compliance
// hazard. Coded cause only: raw driver messages can quote row values.
console.error('[attach-document] Failed to unlink inbox item:', {
cause: errorCauseTag(inboxUnlinkErr),
})
return NextResponse.json(
{
error:
'Inkorgsposten kunde inte släppas, så underlaget är fortfarande kopplat. Försök igen.',
},
{ status: 500 },
)
}
// Step 2: clear the pin, but only if it is still the doc we read above
// (or still empty). A concurrent POST that re-pinned in the meantime wins:
// we must not detach a document the user just attached, nor report
// success for a detach that did not happen.
let clearPin = supabase
.from('transactions')
.update({ document_id: null })
.eq('id', transactionId)
.eq('company_id', companyId)
clearPin = tx.document_id
? clearPin.eq('document_id', tx.document_id)
: clearPin.is('document_id', null)
const { data: cleared, error: updateError } = await clearPin.select('id').maybeSingle()
if (updateError) {
// The enforce_transactions_document_immutability trigger raises a
// P0001 exception with a stable BFL_DOCUMENT_IMMUTABILITY: prefix when the
// previously-attached doc has already become räkenskapsinformation.
// Match on the prefix (not on the generic SQLSTATE) so unrelated future
// exceptions don't get translated into the Swedish underlag message.
const errMsg = (updateError as { message?: string }).message ?? ''
if (errMsg.includes('BFL_DOCUMENT_IMMUTABILITY')) {
return NextResponse.json(
{
error:
'Bilagan är kopplad till en bokförd verifikation och kan inte tas bort. Storno verifikationen först.',
},
{ status: 409 },
)
}
console.error('[attach-document] Failed to detach:', updateError)
return NextResponse.json({ error: 'Failed to detach document' }, { status: 500 })
}
if (!cleared) {
// Zero rows: the pin changed under us (concurrent attach) or the row
// vanished. Either way this detach did not happen; say so instead of
// reporting success for someone else's state.
return NextResponse.json(
{ error: 'Transaktionen ändrades samtidigt. Ladda om sidan och försök igen.' },
{ status: 409 },
)
}
return NextResponse.json({ data: { transaction_id: transactionId, document_id: null } })
},
{ requireWrite: true },
)