fix(bookkeeping): storno of a residual booking's main verifikat releases the bank row whole (#2348)
* fix(bookkeeping): storno of a residual booking's main verifikat releases the bank row whole A residual booking anchors a bank row twice: the pointer column holds the main verifikat and one transaction_voucher_links row of role 'other' holds the small residual verifikat. reverseEntry reset the pointer unconditionally and left the 'other' row behind, so the row split across surfaces: the worklist showed it as att bokfora (is_business IS NULL) while every reader that counts junction rows (the unmatched list behind BookDirectlyDialog, the bulk_book_transactions RPC, is_transaction_booked(), the reconciliation bridge) went on calling it booked. Bulk-book refused it with BULK_BOOK_TX_ALREADY_BOOKED on a row displayed as unbooked. reverseEntry now reads the rows whose pointer it is about to reset and drops their junction rows to any other verifikat right after the reset, before the existing cleanup of the reversed entry's own junction rows. No anchor survives, so every reader agrees without a role fork or a migration; the residual verifikat stays posted and surfaces as unmatched, which is honest because its main sibling is gone. This mirrors what koppla-bort and the 1:N partial-split path already do. Tests: engine.test.ts gains the residual case and the no-pointer case and pins the pointer read before the reset; the opening-balance mock learns the read. The bank_line-only re-booking guards from #2029 stay as defense for rows left behind before this change (prod holds zero such rows). Fixes #2061 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016xry8E1FuYbbedbwvZAxLv * fix(bookkeeping): release reversed-entry transactions and drop their supplementary links in one RPC statement Review finding on #2348 (CodeRabbit, Swedish review note): the pointer read, the pointer reset and the supplementary-link delete were three PostgREST statements. A failed read left the links behind with the pointer already reset, the exact half-anchored row #2061 describes, and a link created between the reset and the delete would have been removed from a stale id set. release_reversed_entry_transactions(p_company_id, p_entry_id) does both in a single data-modifying CTE under the UPDATE's row locks and one snapshot: the DELETE only sees links that existed when the statement started and only for the rows the UPDATE actually released. SECURITY INVOKER, so RLS and the writer-role trigger apply exactly as they did to the direct statements. Links to the reversed entry itself are still left to the engine's junction cleanup (bulk-book N=1 writes a pointer and a bank_line row to the same entry). Migration 20260906172540 applied to staging and covered by tests/pg/release-reversed-entry-transactions.pg.test.ts (main storno releases whole, residual storno touches nothing, bank_line-to-self left for the junction cleanup, tenant scope, viewer refused). Engine unit tests pin the RPC call and the best-effort fallthrough on RPC error. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016xry8E1FuYbbedbwvZAxLv --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
7448490fb7
commit
3c033e466f
@@ -922,9 +922,18 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
* the delete (a row anchored to some other verifikat too), as ids (one
|
||||
* bank_line row each, no amount) or as full rows. `txRows` is what the
|
||||
* partial-split read returns for the rows that still have anchors.
|
||||
* `release` is what the release_reversed_entry_transactions RPC answers
|
||||
* (the pointer reset and the supplementary-link drop live in that RPC since
|
||||
* #2061; its semantics are pinned in tests/pg/release-reversed-entry-
|
||||
* transactions.pg.test.ts, here only the call and the fallthrough are).
|
||||
*/
|
||||
function setup(
|
||||
opts: { voucherLinks?: string[]; remainingLinks?: Array<string | RemainingRow>; txRows?: TxRow[] } = {},
|
||||
opts: {
|
||||
voucherLinks?: string[]
|
||||
remainingLinks?: Array<string | RemainingRow>
|
||||
txRows?: TxRow[]
|
||||
release?: { data: unknown; error: unknown }
|
||||
} = {},
|
||||
) {
|
||||
let jeCall = 0
|
||||
const jeResults = [
|
||||
@@ -968,12 +977,17 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
b.eq = filter('eq')
|
||||
b.in = filter('in')
|
||||
b.is = filter('is')
|
||||
b.neq = filter('neq')
|
||||
b.then = (resolve: (v: unknown) => void) => resolve(resolveWith(current))
|
||||
return b
|
||||
}
|
||||
|
||||
const supabase = {
|
||||
rpc: vi.fn().mockResolvedValue({ data: 8, error: null }),
|
||||
rpc: vi.fn().mockImplementation(async (name: string) =>
|
||||
name === 'release_reversed_entry_transactions'
|
||||
? (opts.release ?? { data: { released: 0, dropped: 0 }, error: null })
|
||||
: { data: 8, error: null },
|
||||
),
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'journal_entries') return jeBuilder()
|
||||
if (table === 'chart_of_accounts') {
|
||||
@@ -1017,23 +1031,23 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
}
|
||||
|
||||
it('resets journal_entry_id, is_business and category so the row returns to Att bokföra (#1950)', async () => {
|
||||
const { supabase, txWrites, linkOps } = setup()
|
||||
const { supabase, txWrites, linkOps } = setup({
|
||||
release: { data: { released: 1, dropped: 1 }, error: null },
|
||||
})
|
||||
|
||||
const result = await reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
|
||||
|
||||
expect(result.id).toBe('reversal-1')
|
||||
expect(txWrites).toHaveLength(1)
|
||||
expect(txWrites[0].payload).toEqual({
|
||||
journal_entry_id: null,
|
||||
is_business: null,
|
||||
category: null,
|
||||
reconciliation_method: null,
|
||||
// The pointer reset (journal_entry_id, is_business, category,
|
||||
// reconciliation_method to null) and the drop of the released rows'
|
||||
// supplementary junction links run inside one RPC statement (#2061),
|
||||
// scoped to this company and this entry: never a company-wide reset.
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('release_reversed_entry_transactions', {
|
||||
p_company_id: 'company-1',
|
||||
p_entry_id: 'entry-1',
|
||||
})
|
||||
// Scoped to rows linked to the reversed entry only: never a company-wide reset.
|
||||
expect(txWrites[0].filters).toEqual([
|
||||
['eq', 'company_id', 'company-1'],
|
||||
['eq', 'journal_entry_id', 'entry-1'],
|
||||
])
|
||||
// No direct write to transactions is left on this path.
|
||||
expect(txWrites).toHaveLength(0)
|
||||
// The junction is consulted for this entry only; nothing to delete or
|
||||
// release when it holds no rows.
|
||||
expect(linkOps).toEqual([
|
||||
@@ -1086,10 +1100,10 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
},
|
||||
])
|
||||
|
||||
// [0] unlink, [1] the partial-split read for the row still anchored
|
||||
// (tx-c), [2] the release of the rows with no anchor left.
|
||||
expect(txWrites).toHaveLength(3)
|
||||
expect(txWrites[1]).toEqual({
|
||||
// [0] the partial-split read for the row still anchored (tx-c), [1] the
|
||||
// release of the rows with no anchor left.
|
||||
expect(txWrites).toHaveLength(2)
|
||||
expect(txWrites[0]).toEqual({
|
||||
op: 'select',
|
||||
payload: 'id, amount, journal_entry_id',
|
||||
filters: [
|
||||
@@ -1097,10 +1111,10 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
['in', 'id', ['tx-c']],
|
||||
],
|
||||
})
|
||||
expect(txWrites[2].payload).toEqual({ is_business: null, category: null, reconciliation_method: null })
|
||||
expect(txWrites[1].payload).toEqual({ is_business: null, category: null, reconciliation_method: null })
|
||||
// Only rows with no anchor left, and never a row whose journal_entry_id
|
||||
// still points at another verifikat (residual booking).
|
||||
expect(txWrites[2].filters).toEqual([
|
||||
expect(txWrites[1].filters).toEqual([
|
||||
['eq', 'company_id', 'company-1'],
|
||||
['in', 'id', ['tx-a', 'tx-b']],
|
||||
['is', 'journal_entry_id', null],
|
||||
@@ -1116,8 +1130,8 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
await reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
|
||||
|
||||
expect(linkOps.map((o) => o.op)).toEqual(['select', 'delete', 'select'])
|
||||
// The unlink plus the partial-split read; no release.
|
||||
expect(txWrites.map((w) => w.op)).toEqual(['update', 'select'])
|
||||
// Only the partial-split read; no release.
|
||||
expect(txWrites.map((w) => w.op)).toEqual(['select'])
|
||||
})
|
||||
|
||||
it('releases a 1:N split whole when one of its verifikat is reversed (#1553): surviving slices dropped', async () => {
|
||||
@@ -1149,9 +1163,10 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
|
||||
it('keeps a row whose surviving slices still sum to its amount, or that carries a non-bank_line anchor', async () => {
|
||||
// tx-full: a bulk-booked-style anchor on another verifikat covering the
|
||||
// whole amount. tx-res: a residual booking's 'other' row (its main
|
||||
// verifikat pointer is null here because the storno of THAT verifikat is
|
||||
// what left it; the residual row is not a slice and is never judged).
|
||||
// whole amount. tx-res: a residual booking's 'other' row whose main
|
||||
// verifikat pointer is already null (a row left behind before the main
|
||||
// storno started dropping such links, #2061); the residual row is not a
|
||||
// slice and the partial-split judgement never touches it.
|
||||
const { supabase, txWrites, linkOps } = setup({
|
||||
voucherLinks: ['tx-full', 'tx-res'],
|
||||
remainingLinks: [
|
||||
@@ -1167,7 +1182,24 @@ describe('reverseEntry: bank transaction unlink', () => {
|
||||
await reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
|
||||
|
||||
expect(linkOps.map((o) => o.op)).toEqual(['select', 'delete', 'select'])
|
||||
expect(txWrites.map((w) => w.op)).toEqual(['update', 'select'])
|
||||
expect(txWrites.map((w) => w.op)).toEqual(['select'])
|
||||
})
|
||||
|
||||
it('runs the release RPC before the junction cleanup, and the storno still completes when the RPC fails', async () => {
|
||||
// The release is best effort like the junction cleanup below it: the
|
||||
// storno is already posted by then, so an RPC error is logged and the
|
||||
// entry-scoped junction cleanup still runs.
|
||||
const { supabase, txWrites, linkOps } = setup({
|
||||
release: { data: null, error: { message: 'boom' } },
|
||||
})
|
||||
|
||||
const result = await reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
|
||||
|
||||
expect(result.id).toBe('reversal-1')
|
||||
const rpcNames = (supabase.rpc as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
|
||||
expect(rpcNames).toContain('release_reversed_entry_transactions')
|
||||
expect(linkOps.map((o) => o.op)).toEqual(['select'])
|
||||
expect(txWrites).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+30
-10
@@ -1252,18 +1252,38 @@ export async function reverseEntry(
|
||||
// (is_business, category, journal_entry_id), plus reconciliation_method:
|
||||
// it describes how the link was made, and the link is gone (the koppla-bort
|
||||
// path in lib/reconciliation/bank-reconciliation.ts resets it the same way).
|
||||
const { error: unlinkError } = await supabase
|
||||
.from('transactions')
|
||||
.update({
|
||||
journal_entry_id: null,
|
||||
is_business: null,
|
||||
category: null,
|
||||
reconciliation_method: null,
|
||||
})
|
||||
.eq('company_id', companyId)
|
||||
.eq('journal_entry_id', entryId)
|
||||
//
|
||||
// A released row must have no anchor left. A residual booking
|
||||
// (lib/reconciliation/residual.ts) keeps the main verifikat in the pointer
|
||||
// column and anchors the small residual verifikat through a junction row of
|
||||
// role 'other'. With the pointer gone that row would be the only thing left,
|
||||
// and it explains a few kronor of fee, not the bank amount: every reader
|
||||
// that counts junction rows (fetchJunctionLinkedTxIds, the bulk_book RPC,
|
||||
// is_transaction_booked()) would go on calling the row booked while the
|
||||
// worklist shows it as att bokföra (#2061). The release_reversed_entry_
|
||||
// transactions RPC therefore resets the pointer AND drops the released
|
||||
// rows' links to other verifikat in one statement (one snapshot, the
|
||||
// UPDATE's row locks): no read-then-write window in which a failed read or
|
||||
// a concurrent booking leaves the half-anchored row behind. That mirrors
|
||||
// what koppla-bort removes and what the 1:N partial-split path below drops;
|
||||
// the residual verifikat stays posted and surfaces as unmatched again,
|
||||
// which is honest: its main sibling is gone. Links to the reversed entry
|
||||
// itself are left to the junction cleanup below, which owns them.
|
||||
const { data: releaseData, error: unlinkError } = await supabase.rpc(
|
||||
'release_reversed_entry_transactions',
|
||||
{ p_company_id: companyId, p_entry_id: entryId },
|
||||
)
|
||||
if (unlinkError) {
|
||||
log.error('failed to unlink transactions from reversed entry', unlinkError, { entryId })
|
||||
} else {
|
||||
const counts = (releaseData ?? {}) as { released?: number; dropped?: number }
|
||||
if ((counts.dropped ?? 0) > 0) {
|
||||
log.info('dropped supplementary voucher links of released transactions', {
|
||||
entryId,
|
||||
released: counts.released ?? 0,
|
||||
dropped: counts.dropped,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Same promise, second anchor. Bulk-booked rows (bulk_book_transactions RPC)
|
||||
|
||||
@@ -93,10 +93,12 @@ export function getPrimaryJournalEntryId(
|
||||
* split of issue #1553), so its presence means the row is booked and a
|
||||
* second booking (manualLink, categorize, link-journal-entry) must refuse.
|
||||
* Rows with role 'other' (a residual booking, lib/reconciliation/residual.ts)
|
||||
* or 'clearing' are supplementary anchors: after a storno of the main
|
||||
* verifikat nulls the pointer, that leftover row must not strand the
|
||||
* transaction with no way to re-book it. The list readers (fetchJunction-
|
||||
* LinkedTxIds, is_transaction_booked()) keep counting every role.
|
||||
* or 'clearing' are supplementary anchors. Since #2061 the engine drops them
|
||||
* together with the pointer when the main verifikat is reversed, so a row
|
||||
* with only a supplementary anchor is a leftover from before that change;
|
||||
* such a row must still not be stranded with no way to re-book it. The list
|
||||
* readers (fetchJunctionLinkedTxIds, is_transaction_booked()) keep counting
|
||||
* every role, and agree with the worklist because no released row keeps one.
|
||||
*/
|
||||
export function hasBankLineJunctionRow(
|
||||
rows: Array<{ role?: string | null }> | null | undefined,
|
||||
|
||||
Reference in New Issue
Block a user