fix(transactions): allow re-linking a bank tx stranded on a reversed verifikat (#988) (#1009)

* fix(transactions): allow re-linking a bank tx stranded on a reversed verifikat (#988)

A transaction whose journal_entry_id points at a reversed/cancelled entry reads
as "utan koppling" in the UI (the transactions page enriches only status='posted'
links), yet the re-booking guards treated ANY non-null pointer as "already
linked". So a storno'd/corrected transaction could never be linked to another
verifikat or re-categorized: the exact symptom in issue #988.

Add a shared hasLiveJournalEntryLink() predicate used by every re-booking guard
(linkTransactionToJournalEntry, manualLink, categorize-core, and the MCP link
stage-check): a pointer at a non-posted entry is treated as re-linkable, and the
two optimistic-locked writes now lock on the exact previous pointer (null OR the
stale id) instead of always .is(null), so the overwrite goes through race-safely.
hasLiveJournalEntryLink fails closed on a read error so a transient blip can't
detach a genuinely live link.

The source was fixed in #726 (reverseEntry/correctEntry now detach/re-point the
tx); this makes the guards self-heal for the pre-#726 backlog and any future
best-effort miss.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(transactions): detect 0-row CAS before invoice effects; fix categorize commit test

Addresses PR review (CodeRabbit Critical + CI):

- link-journal-entry.ts: the tx UPDATE now .select('id') and treats a 0-row
  result as LINK_TX_TX_ALREADY_LINKED, failing BEFORE any invoice settlement /
  invoice_payments insert. Without this, a concurrent re-link that lost the CAS
  would still mark the invoice paid against a transaction we didn't link (same
  optimistic-lock contract manualLink already enforces).

- pending-operations commit route test: the categorize_transaction "already
  categorized" case now enqueues the hasLiveJournalEntryLink status read (posted
  = live) so it still returns 409. This was the core-only CI failure: the new
  liveness read in categorize-core consumed a queued response.

- Updated the link happy-path / invoice-race test enqueues to return a row for
  the now-selecting tx UPDATE.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-12 22:43:02 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent dcd33997b7
commit f04dc4c4e0
9 changed files with 249 additions and 26 deletions
@@ -181,6 +181,7 @@ describe('POST /api/pending-operations/:id/commit', () => {
{ data: pendingOp }, // fetch pending op
{ data: { id: 'op-1' } }, // CAS claim
{ data: tx }, // fetch transaction (already has JE)
{ data: { status: 'posted' } }, // hasLiveJournalEntryLink: existing JE is live
{ data: null, error: null }, // auto-reject update
])
@@ -71,11 +71,12 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
expect(body.error.code).toBe('TX_CATEGORIZE_TX_NOT_FOUND')
})
it('returns 400 when transaction is already linked', async () => {
it('returns 400 when transaction is already linked to a LIVE (posted) entry', async () => {
enqueue({
data: makeTransaction({ id: TX_UUID, journal_entry_id: 'je-prior' }),
error: null,
})
enqueue({ data: { status: 'posted' }, error: null }) // hasLiveJournalEntryLink: prior link is live
const request = createMockRequest(`/api/transactions/${TX_UUID}/link-journal-entry`, {
method: 'POST',
body: { journal_entry_id: JE_UUID },
@@ -86,6 +87,31 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
expect(body.error.code).toBe('LINK_TX_TX_ALREADY_LINKED')
})
it('re-links a transaction stranded on a reversed entry (#988)', async () => {
// Pointer at a status='reversed' entry reads as "utan koppling" in the UI;
// the link must succeed to another posted verifikat, overwriting the stale id.
enqueue({
data: makeTransaction({ id: TX_UUID, journal_entry_id: 'je-reversed', amount: 1000, date: '2026-05-15' }),
error: null,
})
enqueue({ data: { status: 'reversed' }, error: null }) // hasLiveJournalEntryLink: stale link
enqueue({
data: { id: JE_UUID, status: 'posted', voucher_series: 'A', voucher_number: 7, entry_date: '2026-05-15' },
error: null,
}) // target JE fetch
enqueue({ data: [{ id: TX_UUID }], error: null }) // tx UPDATE
enqueue({ data: null, error: null }) // logMatchEvent insert
const request = createMockRequest(`/api/transactions/${TX_UUID}/link-journal-entry`, {
method: 'POST',
body: { journal_entry_id: JE_UUID },
})
const response = await POST(request, createMockRouteParams({ id: TX_UUID }))
const { status, body } = await parseJsonResponse<{ success: boolean; voucher_label: string }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.voucher_label).toBe('A-7')
})
it('returns 404 when journal entry not found', async () => {
enqueue({
data: makeTransaction({ id: TX_UUID, journal_entry_id: null }),
@@ -145,7 +171,7 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
error: null,
})
// Update transaction
enqueue({ data: null, error: null })
enqueue({ data: [{ id: TX_UUID }], error: null })
// logMatchEvent insert
enqueue({ data: null, error: null })
@@ -199,7 +225,7 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
error: null,
})
// Update transaction
enqueue({ data: null, error: null })
enqueue({ data: [{ id: TX_UUID }], error: null })
// Update invoice (optimistic lock returns updated row)
enqueue({ data: [{ id: INV_UUID }], error: null })
// Insert invoice_payments
@@ -303,7 +329,7 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
error: null,
})
// Update transaction succeeds
enqueue({ data: null, error: null })
enqueue({ data: [{ id: TX_UUID }], error: null })
// Optimistic invoice update returns 0 rows
enqueue({ data: [], error: null })
// Compensating rollback: restore prior tx state
@@ -345,7 +371,7 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
error: null,
})
// Update transaction succeeds
enqueue({ data: null, error: null })
enqueue({ data: [{ id: TX_UUID }], error: null })
// Optimistic invoice update succeeds
enqueue({ data: [{ id: INV_UUID }], error: null })
// invoice_payments insert fails with non-23505 error