Files
accounted/components/transactions/__tests__/detach-underlag.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

118 lines
4.6 KiB
TypeScript

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')
})
})