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>
This commit is contained in:
Mattsson
2026-09-02 00:29:22 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 4f33184a9a
commit 4c76fb10d7
11 changed files with 447 additions and 8 deletions
@@ -25,6 +25,9 @@ interface TransactionAttachDocumentDialogProps {
onOpenChange: (open: boolean) => void
transaction: TransactionWithInvoice | null
onAttached: (transactionId: string, documentId: string) => void
/** Detach the current pin (#2132). The page owns confirm + DELETE; the
* dialog only offers the entry point next to the already-attached hint. */
onDetach?: (transaction: TransactionWithInvoice) => void
}
/**
@@ -40,8 +43,10 @@ export default function TransactionAttachDocumentDialog({
onOpenChange,
transaction,
onAttached,
onDetach,
}: TransactionAttachDocumentDialogProps) {
const t = useTranslations('tx_attach_dialog')
const tDetach = useTranslations('tx_detach')
const { toast } = useToast()
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
const [pickedDoc, setPickedDoc] = useState<AvailableInboxDoc | null>(null)
@@ -144,7 +149,24 @@ export default function TransactionAttachDocumentDialog({
</div>
{transaction.document_id && (
<p className="text-xs text-muted-foreground">{t('already_attached_hint')}</p>
<p className="text-xs text-muted-foreground">
{t('already_attached_hint')}
{onDetach && !transaction.journal_entry_id && (
<>
{' '}
<Button
type="button"
variant="link"
size="sm"
className="h-auto p-0 text-xs"
disabled={isAttaching}
onClick={() => onDetach(transaction)}
>
{tDetach('menu_item')}
</Button>
</>
)}
</p>
)}
<div className="space-y-2">
@@ -28,10 +28,12 @@ import {
MoreHorizontal,
Paperclip,
Trash2,
Unlink,
} from 'lucide-react'
import { TransactionAttachmentIndicator } from './TransactionAttachmentIndicator'
import CorrectionAffordance from '@/components/bookkeeping/CorrectionAffordance'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { canDetachDocument } from './detach-underlag'
import type { JeUnderlagStatus } from '@/lib/transactions/underlag-status'
import type { TransactionWithInvoice, HistoryFilter, SourceFilter } from './transaction-types'
import type {
@@ -60,6 +62,8 @@ interface TransactionHistoryListProps {
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
/** Open the attach-underlag dialog (pin an inbox doc / fresh upload). */
onOpenAttachDocument?: (transaction: TransactionWithInvoice) => void
/** Detach the pinned underlag. Unbooked rows only (see canDetachDocument). */
onDetachDocument?: (transaction: TransactionWithInvoice) => void
/** Open the match-against-existing-voucher dialog. Unbooked rows can end up
* here (not in the inbox) when is_business is already set, e.g. after a
* voucher was removed without a full uncategorize; without this item such
@@ -88,6 +92,7 @@ export default function TransactionHistoryList({
onOpenMatchDialog,
onOpenCategoryDialog,
onOpenAttachDocument,
onDetachDocument,
onOpenMatchVoucher,
onDelete,
onSkvBokfor,
@@ -191,6 +196,7 @@ export default function TransactionHistoryList({
onOpenMatchDialog={onOpenMatchDialog}
onOpenCategoryDialog={onOpenCategoryDialog}
onOpenAttachDocument={onOpenAttachDocument}
onDetachDocument={onDetachDocument}
onOpenMatchVoucher={onOpenMatchVoucher}
onDelete={onDelete}
/>
@@ -238,6 +244,7 @@ function BankHistoryRow({
onOpenMatchDialog,
onOpenCategoryDialog,
onOpenAttachDocument,
onDetachDocument,
onOpenMatchVoucher,
onDelete,
}: {
@@ -247,10 +254,12 @@ function BankHistoryRow({
onOpenMatchDialog: (transaction: TransactionWithInvoice) => void
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
onOpenAttachDocument?: (transaction: TransactionWithInvoice) => void
onDetachDocument?: (transaction: TransactionWithInvoice) => void
onOpenMatchVoucher?: (transaction: TransactionWithInvoice) => void
onDelete?: (id: string) => void
}) {
const t = useTranslations('tx_history')
const tDetach = useTranslations('tx_detach')
// Viewers must not see write affordances. CorrectionAffordance opens a
// dialog that stages a storno + correction journal entry; the API path
// already 403s for viewers but rendering the trigger creates a confusing
@@ -273,11 +282,18 @@ function BankHistoryRow({
const hasJeDoc = jeStatus === 'has'
const missingUnderlag = isBooked && !transaction.document_id && jeStatus === 'missing'
const showAttachItem = canWrite && !!onOpenAttachDocument
// Detach is narrower than attach: only unbooked rows, and only with a pin.
const showDetachItem = canDetachDocument({
isBooked,
canWrite,
documentId: transaction.document_id,
hasHandler: !!onDetachDocument,
})
// Same affordance as the inbox card: an unbooked row may need to be linked
// to an already-booked voucher (e.g. the other leg of a transfer).
const showMatchVoucherItem = canWrite && !isBooked && !!onOpenMatchVoucher
const showOverflowMenu =
hasInvoiceMatch || (canDelete && !!onDelete) || (isBooked && canWrite) || showAttachItem || showMatchVoucherItem
hasInvoiceMatch || (canDelete && !!onDelete) || (isBooked && canWrite) || showAttachItem || showDetachItem || showMatchVoucherItem
const isPrivate = transaction.is_business === false
const categoryLabel =
@@ -418,6 +434,12 @@ function BankHistoryRow({
{t('attach_document')}
</DropdownMenuItem>
)}
{showDetachItem && (
<DropdownMenuItem onSelect={() => onDetachDocument!(transaction)}>
<Unlink className="h-3.5 w-3.5" />
{tDetach('menu_item')}
</DropdownMenuItem>
)}
{isBooked && canWrite && transaction.journal_entry_id && (
<CorrectionAffordance journalEntryId={transaction.journal_entry_id}>
{({ open, isLoading }) => (
@@ -429,7 +451,7 @@ function BankHistoryRow({
)}
{canDelete && onDelete && (
<>
{(hasInvoiceMatch || showAttachItem || showMatchVoucherItem) && <DropdownMenuSeparator />}
{(hasInvoiceMatch || showAttachItem || showDetachItem || showMatchVoucherItem) && <DropdownMenuSeparator />}
<DropdownMenuItem
onSelect={() => onDelete(transaction.id)}
className="text-destructive focus:text-destructive"
@@ -23,6 +23,7 @@ import {
Pencil,
Split,
Trash2,
Unlink,
} from 'lucide-react'
import {
DropdownMenu,
@@ -39,6 +40,7 @@ import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-exten
const HAS_AI_EXTRACTION = ENABLED_EXTENSION_IDS.has('document-extraction')
import { TransactionAttachmentIndicator } from './TransactionAttachmentIndicator'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { canDetachDocument } from './detach-underlag'
import type { TransactionWithInvoice, CategorizeHandler } from './transaction-types'
import type { CashAccount } from '@/types'
@@ -73,6 +75,9 @@ interface TransactionInboxCardProps {
/** Open the attach-underlag dialog: pin an inbox document or a fresh upload
* to the transaction (the tx→doc mirror of the Documents view's matcher). */
onOpenAttachDocument?: (transaction: TransactionWithInvoice) => void
/** Detach the pinned underlag (DELETE attach-document). Unbooked rows only:
* once the doc has propagated onto a verifikation the route answers 409. */
onDetachDocument?: (transaction: TransactionWithInvoice) => void
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
onDelete?: (id: string) => void
/** Mark the transaction as ignored so it leaves the inbox without a journal entry. */
@@ -112,6 +117,7 @@ export default function TransactionInboxCard({
onOpenSplitMatch,
onOpenMatchVoucher,
onOpenAttachDocument,
onDetachDocument,
onOpenCategoryDialog,
onDelete,
onIgnore,
@@ -122,6 +128,7 @@ export default function TransactionInboxCard({
preMigrationCutoff = null,
}: TransactionInboxCardProps) {
const t = useTranslations('tx_inbox_card')
const tDetach = useTranslations('tx_detach')
const tMethod = useTranslations('tx_method')
// Radix' onCheckedChange carries no mouse event, so the shift state is
// captured from the click that precedes it (Radix composes our onClick
@@ -146,8 +153,19 @@ export default function TransactionInboxCard({
if (!detail || detail.transaction_id !== transaction.id || !detail.document_id) return
setOptimisticDocumentId(detail.document_id)
}
// Detach (page handler) drops the override too, or the indicator would
// keep showing a doc the row no longer carries.
function onUnlinked(e: Event) {
const detail = (e as CustomEvent<{ transaction_id?: string }>).detail
if (!detail || detail.transaction_id !== transaction.id) return
setOptimisticDocumentId(null)
}
window.addEventListener('Accounted:transaction-document-linked', onLinked)
return () => window.removeEventListener('Accounted:transaction-document-linked', onLinked)
window.addEventListener('Accounted:transaction-document-unlinked', onUnlinked)
return () => {
window.removeEventListener('Accounted:transaction-document-linked', onLinked)
window.removeEventListener('Accounted:transaction-document-unlinked', onUnlinked)
}
}, [transaction.id])
const attachedDocumentId =
optimisticDocumentId ?? (transaction as { document_id?: string | null }).document_id ?? null
@@ -218,6 +236,15 @@ export default function TransactionInboxCard({
// "Matcha mot underlag": pin an inbox doc / fresh upload to the tx. The
// tx→doc mirror of the Documents view's "Matcha mot transaktion".
const showAttachDocumentItem = isUnbooked && canWrite && !!onOpenAttachDocument
// Same gate as attach, plus an actual pin to remove.
const showDetachDocumentItem =
showAttachDocumentItem &&
canDetachDocument({
isBooked: !isUnbooked,
canWrite,
documentId: attachedDocumentId,
hasHandler: !!onDetachDocument,
})
const showSplitItem = showInvoiceMatchButton && !!onOpenSplitMatch
const showEditItem = isTitleEditable && !!onEditTitle
// Moving between cash accounts only makes sense with somewhere to move TO,
@@ -423,6 +450,17 @@ export default function TransactionInboxCard({
{t('attach_document_btn')}
</DropdownMenuItem>
)}
{showDetachDocumentItem && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
onDetachDocument!(transaction)
}}
>
<Unlink className="h-4 w-4" />
{tDetach('menu_item')}
</DropdownMenuItem>
)}
{showSplitItem && (
<DropdownMenuItem
onClick={(e) => {
@@ -0,0 +1,117 @@
import { describe, it, expect } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
import { canDetachDocument, resolveDetachErrorMessage } from '../detach-underlag'
/**
* "Ta bort underlag" on a transaction (#2132).
*
* Vitest runs in the `node` environment here and never renders components,
* so the menu-item gate and the error mapping live in a pure helper both
* row components and the page call. The rendering side is pinned with
* file-level assertions, like the sibling dialog tests: the components must
* route through the helper, and the strings must exist in both locales.
*/
const ROOT = path.resolve(__dirname, '../../..')
const read = (rel: string) => fs.readFileSync(path.resolve(ROOT, rel), 'utf8')
const readMessages = (locale: 'sv' | 'en', namespace: string) =>
(JSON.parse(read(`messages/${locale}.json`)) as Record<string, Record<string, string>>)[
namespace
]
const ROUTE_409_MESSAGE =
'Bilagan är kopplad till en bokförd verifikation och kan inte tas bort. Storno verifikationen först.'
describe('canDetachDocument', () => {
const base = { isBooked: false, canWrite: true, documentId: 'doc-1', hasHandler: true }
it('shows the item on an unbooked, writable row that carries a pin', () => {
expect(canDetachDocument(base)).toBe(true)
})
it('hides the item once the row is booked (the route would answer 409)', () => {
expect(canDetachDocument({ ...base, isBooked: true })).toBe(false)
})
it('hides the item for read-only members', () => {
expect(canDetachDocument({ ...base, canWrite: false })).toBe(false)
})
it('hides the item when there is nothing to detach', () => {
expect(canDetachDocument({ ...base, documentId: null })).toBe(false)
expect(canDetachDocument({ ...base, documentId: undefined })).toBe(false)
expect(canDetachDocument({ ...base, documentId: '' })).toBe(false)
})
it('hides the item when no handler is wired', () => {
expect(canDetachDocument({ ...base, hasHandler: false })).toBe(false)
})
})
describe('resolveDetachErrorMessage', () => {
it('renders the 409 server message unchanged', () => {
expect(resolveDetachErrorMessage(409, { error: ROUTE_409_MESSAGE })).toBe(ROUTE_409_MESSAGE)
})
it('does not treat a 409 without a message as verbatim', () => {
const msg = resolveDetachErrorMessage(409, { error: '' })
expect(typeof msg).toBe('string')
expect(msg.length).toBeGreaterThan(0)
})
it('maps other statuses through the shared translator to a Swedish message', () => {
const msg = resolveDetachErrorMessage(500, { error: 'Failed to detach document' })
expect(msg).not.toBe('Failed to detach document')
expect(msg.length).toBeGreaterThan(0)
expect(resolveDetachErrorMessage(404, null).length).toBeGreaterThan(0)
})
})
describe('detach affordance wiring', () => {
const inboxCard = read('components/transactions/TransactionInboxCard.tsx')
const historyList = read('components/transactions/TransactionHistoryList.tsx')
const attachDialog = read('components/transactions/TransactionAttachDocumentDialog.tsx')
const page = read('app/(dashboard)/transactions/page.tsx')
it('both row components gate the item through canDetachDocument', () => {
expect(inboxCard).toContain('canDetachDocument({')
expect(historyList).toContain('canDetachDocument({')
expect(inboxCard).toContain("tDetach('menu_item')")
expect(historyList).toContain("tDetach('menu_item')")
})
it('the inbox card only offers detach under the attach gate (unbooked and canWrite)', () => {
expect(inboxCard).toMatch(/showDetachDocumentItem =\s*showAttachDocumentItem &&/)
})
it('the attach dialog offers detach only for unbooked rows', () => {
expect(attachDialog).toContain('onDetach && !transaction.journal_entry_id')
})
it('the page confirms before DELETE and renders 409 through the verbatim path', () => {
expect(page).toContain("variant: 'warning'")
expect(page).toContain("/attach-document`, { method: 'DELETE' }")
expect(page).toContain('resolveDetachErrorMessage(res.status, result)')
})
it('strings exist in both locales with the same keys', () => {
const sv = readMessages('sv', 'tx_detach')
const en = readMessages('en', 'tx_detach')
const required = [
'menu_item',
'confirm_title',
'confirm_body',
'confirm_label',
'cancel_label',
'toast_done',
'toast_failed',
]
for (const key of required) {
expect(sv[key], `sv.tx_detach.${key}`).toBeTruthy()
expect(en[key], `en.tx_detach.${key}`).toBeTruthy()
}
expect(Object.keys(sv).sort()).toEqual(Object.keys(en).sort())
expect(sv.menu_item).toBe('Ta bort underlag')
})
})
@@ -0,0 +1,28 @@
import { getErrorMessage } from '@/lib/errors/get-error-message'
/**
* Gate for the "Ta bort underlag" affordance on a transaction row (#2132).
*
* Mirrors DELETE /api/transactions/[id]/attach-document: once the document has
* propagated onto a verifikation the route answers 409 (BFL 5 kap 6 §), so the
* UI only offers the action to writers, on unbooked rows that carry a pin.
*/
export function canDetachDocument(input: {
isBooked: boolean
canWrite: boolean
documentId: string | null | undefined
hasHandler: boolean
}): boolean {
return !input.isBooked && input.canWrite && !!input.documentId && input.hasHandler
}
/**
* Toast description for a failed detach. A 409 carries the route's own
* Swedish explanation (the doc is already räkenskapsinformation): surface it
* verbatim. Everything else maps through the shared error translator.
*/
export function resolveDetachErrorMessage(status: number, body: unknown): string {
const error = (body as { error?: unknown } | null | undefined)?.error
if (status === 409 && typeof error === 'string' && error.trim()) return error
return getErrorMessage(body, { context: 'transaction', statusCode: status })
}