fix(cash-accounts): never propose or accept an orphaned twin ledger as counter-account; match and re-point across sibling ledgers (#1643) (#2010)

* fix(cash-accounts): never propose or accept an orphaned cash-account ledger as counter-account (#1643)

A broken bank reconnect leaves cash_accounts rows that share the live
account's IBAN (held by a revoked connection, or demoted to manual by the
#916 fix). Three consequences are fixed here:

- Problem 4 (silent mis-booking): the own-account transfer detector paired
  with such an orphan and proposed its ledger as the counter-account, and a
  counterparty template learned from that result replayed as 1940/1931 in
  the booking dialog. The detector now tolerates several rows on one IBAN,
  never pairs with the transaction's own row, a disabled row, or a revoked
  holder; the mapping engine drops a "transfer" whose counter equals the
  settlement account; suggest-categories withholds learned suggestions that
  reference an orphaned ledger; and both commit paths (POST
  /api/transactions/[id]/categorize, categorizeMatchedTransaction) reject
  with the new TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT (400). Orphans are
  only refused in the COUNTER position: a stranded row still settles on its
  own ledger, and a manual account without a live IBAN twin is never
  treated as orphaned, so transfers between two live accounts keep booking.
- Problem 1 (match dialog): the ranked unmatched-entries path also offers
  vouchers booked on sibling ledgers of the same IBAN, and manualLink
  accepts a voucher line on a sibling ledger. When it does, the same locked
  UPDATE re-points transactions.cash_account_id to the live sibling row
  (currency-gated, like PATCH /api/transactions/[id]/cash-account) so the
  account-keyed reconciliation does not count a cross-account link as an
  imbalance on both ledgers.
- Problem 3 (naming): allocatePsd2LedgerAccount names the chart account
  BAS-style (BAS reference name for a standard slot, else "Bankkonto
  <CUR>") instead of the ASPSP-reported holder name.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): address review findings on the orphaned-ledger guards (#1643)

One in-memory topology (cash_accounts rows + bank_connections status) now
defines "live", "orphaned" and "same physical account" for the transfer
detector, the match/link flows and every commit guard, so a proposal is
never made that a guard later rejects.

- Finding 1/4/6 (own IBAN as counterparty): findPairableCashAccountByIban
  treats the transaction's own IBAN as "not a transfer": every same-currency
  row on that IBAN is the same physical account, whichever is live, so
  interest stamped with the own IBAN never pairs with a twin (two active
  rows, a demoted-manual twin, or a live twin of a stranded row). Only a
  pocket in another currency on that IBAN can still pair. guardCounterLegs
  refuses a same-IBAN same-currency twin in the counter position on every
  commit path, even when both rows are active.
- Finding 3: with several surviving candidates (currency pockets with no
  discriminator, or two active twins) the finder returns null instead of
  picking the lowest ledger, which is what the pre-PR lookup did.
- Finding 5: the finder drops every row in the orphaned set, the same
  predicate the commit guards use (demoted-manual twins included).
- Finding 9: "live" means enabled + connection status 'active'; an
  expired/error twin of a live row is orphaned, a lone expired connection
  (re-auth window) is not.
- Finding 2: siblings are keyed on (normalized IBAN, currency) in
  describeCashAccountSiblings and the unmatched-entries route, so a SEK
  transaction can no longer link to a voucher whose only bank leg is on the
  EUR pocket of the same IBAN; manualLink rejects that as before.
- Finding 8: manualLink re-points a row only when the voucher sits on the
  LIVE sibling and the own row is not live; the reverse direction links
  without moving the row.
- Finding 7: the v1 REST categorize route runs the same guardCounterLegs
  check after account_override and returns
  TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT. MCP stages through
  categorizeMatchedTransaction, already covered.
- Finding 10: a learned template whose stale 19xx leg is a twin of the
  settlement row is rewritten to the settlement account (it is the bank
  leg, not the counter) instead of refused; suggest-categories exempts each
  transaction's own settlement ledger before withholding a suggestion. The
  error message now covers both the twin and the disconnected case.

Tests pin each behavior (service, detector, manualLink, unmatched-entries,
dashboard and v1 categorize routes, suggest-categories).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): address round-2 review findings (#1643)

1+3. Orphan derivation keyed on (IBAN, currency): loadCashAccountTopology
   now keys the live twin on normalized IBAN plus currency (the rule every
   other "same physical account" check in the PR already used), so a
   manual or deselected GBP/EUR pocket beside a live SEK pocket of a
   multi-currency account is never orphaned, still pairs in the transfer
   detector and is accepted as counter at commit. Twin computation is
   shared (twinLedgersOf).
2. suggest-categories mirrors guardCounterLegs: a learned 19xx leg that is
   a twin of the transaction's own row is rewritten to the settlement
   ledger in the offered suggestion instead of being withheld; only a true
   counter-position orphan (or a twin that would book the settlement
   ledger against itself) is withheld. One topology load per batch
   (loadCounterLegTopology).
4. The free-form dialog path (POST /api/transactions/[id]/book) gets a
   line-level guard (guardBookedCounterLines): a 19xx line that is a twin
   of the transaction's own row or an orphaned ledger, alongside the
   settlement leg, is refused with TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT.
   Only runs when the lines touch two distinct 19xx ledgers. The twin
   rewrite in suggest-categories (2) covers the both-active shape before
   the dialog is even opened.
5. manualLink re-points the row onto the sibling ledger the voucher was
   booked on whenever the sibling is live or the own row is not (both-live
   twins and both-dead rows included); only a live row whose voucher sits
   on a dead sibling links without moving. unmatched-entries now uses
   describeCashAccountSiblings and does not offer dead-sibling vouchers to
   a live row.

DECISIONS.md: the PR's existing review follow-up line amended.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): address round-3 review findings (#1643)

1. Revoked-held rows are no longer orphaned unconditionally. A row whose
   connection is revoked is orphaned only under the twin rule (not live
   AND a live row shares its normalized IBAN + currency), so a
   disconnected-but-real account (the company's only 1930, or two real
   accounts on one revoked connection) stays pairable by the transfer
   detector and bookable as counter on every guarded path. Tests cover
   the no-twin case for getOrphanedCounterLedgers,
   findPairableCashAccountByIban, detectOwnAccountTransfer,
   guardCounterLegs and guardBookedCounterLines; the existing revoked
   tests now use a twin shape.
2. manualLink / unmatched-entries decide the re-point on the destination:
   a new shouldRepointToSibling moves onto a live sibling, or onto a dead
   one only when the own row's holder is gone (released: bank_connection_id
   null or revoked) and no sibling is live. An expired/error/pending own
   row links without moving. SiblingCashAccount gains `released`. Tests:
   expired own row + demoted twin links without moving and the twin's
   vouchers are not offered.
3. loadCounterLegTopology is exercised directly: settlement ledger and
   twins, other-currency pocket, null/unknown ids, cache, orphan set
   equal to guardCounterLegs' refusals on the same fixture, lookup failure.
4. guardBookedCounterLines docstring and the /book route comment now state
   that only the two-cash-legs shape is inspected; a single hand-typed
   19xx line is not (covering it would cost a cash_accounts lookup on
   every ordinary booking). DECISIONS.md lines amended accordingly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): address round-4 review findings (#1643)

1. Same-connection re-registration twins (the dominant prod shape): two
   enabled rows on one active connection sharing (IBAN, currency) are now
   told apart by balance_updated_at; only the most recently synced row is
   live, the other is a stale twin (orphaned as a counter, never a
   re-point destination, and the transfer detector pairs with the syncing
   row alone). Rows with no stamp or the same stamp both stay live.
2. POST /book: a single 19xx line that is a sibling ledger the row should
   move to (the live twin of a stranded row) re-points cash_account_id in
   the same locked UPDATE that links the voucher, mirroring manualLink.
   guardBookedCounterLines returns { refusedLedger, repointCashAccountId };
   an ordinary booking pays one PK read of the own row.
3. manualLink refuses the link (success:false, Swedish error) when the
   voucher sits only on a dead sibling instead of writing a cross-account
   link with a server-side warn; the REST and MCP link callers reach it
   without the unmatched-entries filter.
4. manualLink judges a voucher touching several sibling ledgers on the
   best of them (a live sibling, else the first the row may move to)
   instead of the first line PostgREST returns.

Tests pinned in lib/cash-accounts, lib/reconciliation and the /book route;
the two DECISIONS.md lines for #1643 amended in place.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): address round-5 review findings (#1643)

1/2/5. Same-connection twin liveness no longer ranks on
   cash_accounts.balance_updated_at (a connect-time snapshot the sync
   never refreshes, inverted on prod in 4 of 5 stamped groups). The live
   row is the one whose external_uid the bank still lists in
   bank_connections.accounts_data (rewritten on every sync); no listing,
   both listed or neither listed keeps both rows live (round-3 behavior).
   getConnectionStatuses selects accounts_data in the same query.
3. guardBookedCounterLines single-19xx-line shape: a twin the row may not
   move to (dead or disabled) is refused with
   TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT instead of posting the only
   bank leg on the dead ledger; an unrelated 19xx line still posts as
   typed. Route test added.
4. Disabled cash_accounts rows are never siblings, so neither manualLink
   nor /book re-points a transaction onto a deselected row; a voucher
   booked only there is refused as a cross-account link.
6. PR body rewritten to the final rules; DECISIONS.md round-4 line
   amended (signal correction, /book refusal, disabled siblings).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): never treat a null external_uid as listed by the bank (#1643)

CashAccount.external_uid is nullable in the shared type; the same-connection
twin rule now skips null uids instead of passing them to Set.has, which
failed the strict type check in CI.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(cash-accounts): drop the same-connection twin liveness rule; both rows stay live (#1643)

Two enabled rows on one active bank connection sharing (IBAN, currency)
are no longer ranked. Round 4 ranked on cash_accounts.balance_updated_at
and round 5 on external_uid presence in bank_connections.accounts_data;
each was verified against prod and each was contradicted by it (ingest
routes by the accounts_data entry's ledger_account, which in two groups
points at the OLD row, so the "stale" row is the one still being fed).

Restores the round-3 behavior: neither twin is orphaned, the transfer
finder returns null when both survive, no guard refuses either, and
shouldRepointToSibling treats both as live siblings. No replacement
signal; how to model the shape is a founder decision (PR #2010 review).
getConnectionStatuses no longer selects accounts_data.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-29 00:26:47 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 1a8fe36bc4
commit 4e1eb3d662
23 changed files with 3270 additions and 83 deletions
@@ -237,6 +237,120 @@ describe('POST /api/transactions/[id]/book', () => {
)
})
it('returns 400 TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT when a line books the settlement row against its active twin (#1643)', async () => {
// The issue's dialog shape: 1930 and 1931 both enabled on one active
// connection; "Ändra rader" pre-filled 1930 debit / 1931 credit from a
// template learned on 1931. Booking it would move money between two
// ledgers of one physical account with nothing reaching the P&L.
const iban = 'SE4550000000058398257466'
const tx = makeTransaction({ id: 'tx-1', amount: 500, journal_entry_id: null, cash_account_id: 'ca-1930' })
enqueue({ data: tx, error: null }) // fetch transaction
enqueue({
data: [
{ id: 'ca-1930', ledger_account: '1930', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
{ id: 'ca-1931', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
],
}) // cash_accounts topology
enqueue({ data: [{ id: 'conn-live', status: 'active' }] }) // bank_connections statuses
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: {
...validBody,
lines: [
{ account_number: '1930', debit_amount: 500, credit_amount: 0 },
{ account_number: '1931', debit_amount: 0, credit_amount: 500 },
],
},
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { accountNumber: string } } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT')
expect(body.error.details.accountNumber).toBe('1931')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
})
it('re-points a stranded row onto the live sibling when its single bank line is that ledger (#1643 round 4)', async () => {
// Nyte-shape: the transaction sits on the demoted 1931, the user books it
// with the bank leg on the live 1940 against a P&L account. The voucher
// posts on 1940 and the row moves there in the same locked UPDATE, so
// neither ledger's reconciliation is left with a half.
const iban = 'SE4550000000058398257466'
const tx = makeTransaction({ id: 'tx-1', amount: 500, journal_entry_id: null, cash_account_id: 'ca-orphan' })
enqueue({ data: tx, error: null }) // fetch transaction
enqueue({ data: { ledger_account: '1931' } }) // own row
enqueue({
data: [
{ id: 'ca-orphan', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: null },
{ id: 'ca-live', ledger_account: '1940', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
],
}) // cash_accounts topology
enqueue({ data: [{ id: 'conn-live', status: 'active' }] }) // bank_connections statuses
mockCreateJournalEntry.mockResolvedValue(makeJournalEntry({ id: 'je-new' }))
enqueue({ data: [{ id: 'tx-1' }], error: null }) // link update
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: {
...validBody,
lines: [
{ account_number: '1940', debit_amount: 500, credit_amount: 0 },
{ account_number: '8311', debit_amount: 0, credit_amount: 500 },
],
},
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
expect(response.status).toBe(200)
expect(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
expect(findCalls('transactions', 'update')).toContainEqual([
expect.objectContaining({ journal_entry_id: 'je-new', cash_account_id: 'ca-live' }),
])
})
it('returns 400 TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT when the single bank line sits on a dead twin of the live own row (#1643 round 5)', async () => {
// Problem 4: the transaction sits on the live 1940, the dialog pre-fills
// [1931, 3011] from a template learned before the reconnect, and 1931 is
// the revoked twin. Posting would strand the only bank leg on 1931 while
// the transaction stays on 1940, so it is refused before the engine runs.
const iban = 'SE4550000000058398257466'
const tx = makeTransaction({ id: 'tx-1', amount: 500, journal_entry_id: null, cash_account_id: 'ca-live' })
enqueue({ data: tx, error: null }) // fetch transaction
enqueue({ data: { ledger_account: '1940' } }) // own row
enqueue({
data: [
{ id: 'ca-live', ledger_account: '1940', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
{ id: 'ca-orphan', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-old' },
],
}) // cash_accounts topology
enqueue({
data: [
{ id: 'conn-live', status: 'active' },
{ id: 'conn-old', status: 'revoked' },
],
}) // bank_connections statuses
const request = createMockRequest('/api/transactions/tx-1/book', {
method: 'POST',
body: {
...validBody,
lines: [
{ account_number: '1931', debit_amount: 500, credit_amount: 0 },
{ account_number: '3011', debit_amount: 0, credit_amount: 500 },
],
},
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { accountNumber: string } } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT')
expect(body.error.details.accountNumber).toBe('1931')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
})
it('atomically unignores an ignored transaction when booking it', async () => {
const tx = makeTransaction({
id: 'tx-1',
+25
View File
@@ -3,6 +3,7 @@ import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { guardBookedCounterLines } from '@/lib/cash-accounts/service'
import { reverseOrphanedJournalEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
import { validateBody } from '@/lib/api/validate'
@@ -143,6 +144,29 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
dupLog.warn('booking-time duplicate detection failed (continuing)', err as Error)
}
// A 19xx counter line that is a twin of the transaction's own cash account
// (same IBAN, same currency: the other ledger of one connection, or a
// stale row left by a broken reconnect) or an orphaned ledger books one
// physical account against itself or onto a junk balance-sheet account.
// The dialog pre-fills such lines from learned templates (issue #1643
// problem 4); this is the same refusal the categorize paths apply. A
// booking whose single 19xx line is a sibling ledger the row should move
// to (the live twin of a stranded row) instead re-points the transaction
// there in the locked UPDATE below, as manualLink does for the same
// voucher (see guardBookedCounterLines).
const { refusedLedger, repointCashAccountId } = await guardBookedCounterLines(
supabase,
companyId,
lines.map((line) => line.account_number),
transaction.cash_account_id ?? null,
)
if (refusedLedger) {
return errorResponseFromCode('TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT', log, {
requestId,
details: { accountNumber: refusedLedger },
})
}
// Create journal entry via the engine
let journalEntry
try {
@@ -174,6 +198,7 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
is_business: true,
is_ignored: false,
category: 'uncategorized',
...(repointCashAccountId ? { cash_account_id: repointCashAccountId } : {}),
})
.eq('id', id)
.eq('company_id', companyId)
@@ -76,7 +76,11 @@ vi.mock('@/lib/bookkeeping/mapping-engine', () => ({
},
}))
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
// Spread the real module so buildMappingResultFromCounterpartyTemplate (pure)
// replays a learned template exactly as production does; only the learning
// write is stubbed.
vi.mock('@/lib/bookkeeping/counterparty-templates', async (importActual) => ({
...(await importActual<typeof import('@/lib/bookkeeping/counterparty-templates')>()),
upsertCounterpartyTemplate: vi.fn().mockResolvedValue(undefined),
}))
@@ -1552,4 +1556,182 @@ describe('POST /api/transactions/[id]/categorize', () => {
expect(body.error.details.accountNumber).toBe('5420')
expect(mockCreateTransactionJournalEntry).not.toHaveBeenCalled()
})
// ----------------------------------------------------------------
// Orphaned counter-account guard (issue #1643 problem 4)
// ----------------------------------------------------------------
it('returns 400 TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT when a learned template credits a ledger held by a revoked connection', async () => {
// The issue's exact shape: +217,04 interest on the live 1940 account, and
// a template learned while the detector paired with the orphan row
// proposes 1940 debit / 1931 credit (revenue onto a junk asset account).
const tx = makeTransaction({
id: 'tx-1',
amount: 217.04,
merchant_name: 'SEB',
journal_entry_id: null,
cash_account_id: 'ca-live',
})
enqueue({ data: tx, error: null })
enqueue({ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }, error: null })
// categorization_templates: the learned counterparty template
enqueue({
data: {
id: '11111111-1111-4111-8111-111111111111',
company_id: 'company-1',
counterparty_name: 'SEB',
counterparty_aliases: [],
debit_account: '1940',
credit_account: '1931',
vat_treatment: null,
vat_account: null,
category: null,
line_pattern: null,
occurrence_count: 3,
confidence: 0.9,
source: 'auto_learned',
is_active: true,
},
error: null,
})
// resolveSettlementAccount: the row's own cash account is the live 1940
enqueue({ data: { ledger_account: '1940' }, error: null })
// Guard: cash_accounts scan + bank_connections status lookup
enqueue({
data: [
{ id: 'ca-live', ledger_account: '1940', bank_connection_id: 'conn-new', iban: 'SE455', enabled: true },
{ id: 'ca-orphan', ledger_account: '1931', bank_connection_id: 'conn-old', iban: 'SE455', enabled: true },
],
error: null,
})
enqueue({
data: [
{ id: 'conn-new', status: 'active' },
{ id: 'conn-old', status: 'revoked' },
],
error: null,
})
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: { is_business: true, counterparty_template_id: '11111111-1111-4111-8111-111111111111' },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { accountNumber?: string } }
}>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT')
expect(body.error.details.accountNumber).toBe('1931')
expect(mockCreateTransactionJournalEntry).not.toHaveBeenCalled()
})
it('rewrites a learned template whose stale BANK leg is a twin of the settlement row instead of refusing (#1643)', async () => {
// Template learned as 5010 / 1931 while the account sat on 1931; the
// transaction now settles on the live 1940 row of the same IBAN. The
// counter (5010) is fine, only the bank side is stale.
const tx = makeTransaction({
id: 'tx-1',
amount: -1200,
merchant_name: 'Hyresvärden',
journal_entry_id: null,
cash_account_id: 'ca-live',
})
enqueue({ data: tx, error: null })
enqueue({ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }, error: null })
enqueue({
data: {
id: '11111111-1111-4111-8111-111111111111',
company_id: 'company-1',
counterparty_name: 'Hyresvärden',
counterparty_aliases: [],
debit_account: '5010',
credit_account: '1931',
vat_treatment: null,
vat_account: null,
category: null,
line_pattern: null,
occurrence_count: 3,
confidence: 0.9,
source: 'auto_learned',
is_active: true,
},
error: null,
})
enqueue({ data: { ledger_account: '1940' }, error: null }) // resolveSettlementAccount
enqueue({
data: [
{ id: 'ca-live', ledger_account: '1940', bank_connection_id: 'conn-new', iban: 'SE455', enabled: true, currency: 'SEK' },
{ id: 'ca-orphan', ledger_account: '1931', bank_connection_id: null, iban: 'SE455', enabled: true, currency: 'SEK' },
],
error: null,
})
enqueue({ data: [{ id: 'conn-new', status: 'active' }], error: null })
// ensureFiscalPeriod: existing period
enqueue({ data: [{ id: 'period-1' }], error: null })
mockCreateTransactionJournalEntry.mockResolvedValue({ id: 'je-1' })
mockSaveUserMappingRule.mockResolvedValue(undefined)
// Update transaction (CAS guard)
enqueue({ data: [{ id: 'tx-1' }], error: null })
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: { is_business: true, counterparty_template_id: '11111111-1111-4111-8111-111111111111' },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<unknown>(response)
expect(status, JSON.stringify(body)).toBe(200)
expect(mockCreateTransactionJournalEntry).toHaveBeenCalledTimes(1)
const mapping = mockCreateTransactionJournalEntry.mock.calls[0][4] as {
debit_account: string
credit_account: string
}
expect(mapping.debit_account).toBe('5010')
expect(mapping.credit_account).toBe('1940')
})
it('still books a transfer whose 19xx counter is a live cash account', async () => {
const tx = makeTransaction({
id: 'tx-1',
amount: -500,
merchant_name: 'Sparkonto',
journal_entry_id: null,
})
enqueue({ data: tx, error: null })
enqueue({ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }, error: null })
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts -> 1930
// account_override chart lookup: 1940 exists and is active
enqueue({ data: { account_number: '1940', account_class: 1 }, error: null })
// Guard: 1940 is held by an ACTIVE connection, so it is a genuine transfer target
enqueue({
data: [{ id: 'ca-live', ledger_account: '1940', bank_connection_id: 'conn-live', iban: 'SE455', enabled: true }],
error: null,
})
enqueue({ data: [{ id: 'conn-live', status: 'active' }], error: null })
// ensureFiscalPeriod: existing period
enqueue({ data: [{ id: 'period-1' }], error: null })
mockCreateTransactionJournalEntry.mockResolvedValue({ id: 'je-1' })
mockSaveUserMappingRule.mockResolvedValue(undefined)
// Update transaction (CAS guard)
enqueue({ data: [{ id: 'tx-1' }], error: null })
const request = createMockRequest('/api/transactions/tx-1/categorize', {
method: 'POST',
body: { is_business: true, category: 'expense_other', account_override: '1940' },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_id).toBe('je-1')
expect(mockCreateTransactionJournalEntry).toHaveBeenCalledTimes(1)
})
})
@@ -12,6 +12,7 @@ import { detectBookingDuplicate } from '@/lib/transactions/booking-duplicate-det
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { saveUserMappingRule, applySettlementAccount } from '@/lib/bookkeeping/mapping-engine'
import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
import { guardCounterLegs } from '@/lib/cash-accounts/service'
import { upsertCounterpartyTemplate, buildMappingResultFromCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode, getStructuredError } from '@/lib/errors/get-structured-error'
@@ -415,6 +416,29 @@ export const POST = withRouteContext(
})
}
// Issue #1643 problem 4: a learned template or transfer proposal must never
// book the COUNTER leg onto an orphaned cash-account ledger, or onto a twin
// ledger of the transaction's own bank account. Confirming such a proposal
// silently drops revenue/expense from the P&L onto a junk balance-sheet
// account. A twin that is merely the stale BANK leg of a learned template
// is rewritten to the settlement account instead (see guardCounterLegs).
{
const guarded = await guardCounterLegs(
supabase,
companyId!,
mappingResult,
settlementAccount,
transaction.cash_account_id,
)
if (guarded.refusedLedger) {
return errorResponseFromCode('TX_CATEGORIZE_ORPHANED_COUNTER_ACCOUNT', txLog, {
requestId,
details: { accountNumber: guarded.refusedLedger },
})
}
mappingResult = guarded.mappingResult
}
// Pre-validate every account the engine will resolve. Templates,
// counterparty templates, and category defaults can all reference accounts
// that aren't activated in this company's kontoplan. Without this check,
@@ -0,0 +1,243 @@
/**
* POST /api/transactions/suggest-categories: counterparty suggestions whose
* learned accounts reference an ORPHANED cash-account ledger are withheld
* (issue #1643 problem 4). A learned template carries the ledger it was
* learned on; replaying it after a broken reconnect would pre-fill a junk
* balance-sheet account as the booking dialog's counter-account.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const findCounterpartyTemplatesBatchMock = vi.fn()
// Spread the real module: category-suggestions also imports pure helpers from
// here (normalizeCounterpartyName), and only the DB-backed batch lookup is stubbed.
vi.mock('@/lib/bookkeeping/counterparty-templates', async (importActual) => ({
...(await importActual<typeof import('@/lib/bookkeeping/counterparty-templates')>()),
findCounterpartyTemplatesBatch: (...args: unknown[]) => findCounterpartyTemplatesBatchMock(...args),
}))
const loadCounterLegTopologyMock = vi.fn()
vi.mock('@/lib/cash-accounts/service', () => ({
loadCounterLegTopology: (...args: unknown[]) => loadCounterLegTopologyMock(...args),
}))
/** Topology stub mirroring lib/cash-accounts/service: orphan set + per-row context. */
function topology(
orphaned: string[],
contexts: Record<string, { settlementLedger: string | null; twins: string[] }> = {},
) {
return {
orphaned: new Set(orphaned),
contextFor: (cashAccountId: string | null | undefined) => {
const ctx = cashAccountId ? contexts[cashAccountId] : undefined
return ctx
? { settlementLedger: ctx.settlementLedger, twins: new Set(ctx.twins) }
: { settlementLedger: null, twins: new Set<string>() }
},
}
}
import { POST } from '../route'
const emptyParams = { params: Promise.resolve({}) }
const TX_ID = '22222222-2222-4222-8222-222222222222'
function makeTemplate(overrides: Record<string, unknown> = {}) {
return {
id: 'cpt-1',
user_id: null,
company_id: 'company-1',
counterparty_name: 'SEB',
counterparty_aliases: [],
debit_account: '1940',
credit_account: '1931',
vat_treatment: null,
vat_account: null,
category: null,
line_pattern: null,
occurrence_count: 3,
confidence: 0.9,
last_seen_date: '2026-07-01',
source: 'auto_learned',
is_active: true,
created_at: '2026-07-01T00:00:00Z',
updated_at: '2026-07-01T00:00:00Z',
...overrides,
}
}
/** Queue the four queries the route always runs, in order. */
function enqueueBaseQueries() {
enqueue({ data: [{ id: TX_ID, amount: 217.04, currency: 'SEK', description: 'Ränta' }] }) // transactions
enqueue({ data: [] }) // mapping_rules
enqueue({ data: [] }) // historical transactions
enqueue({ data: { entity_type: 'aktiebolag' } }) // company_settings
}
function request() {
return createMockRequest('/api/transactions/suggest-categories', {
method: 'POST',
body: { transaction_ids: [TX_ID] },
})
}
type Body = {
template_suggestions: Record<string, Array<{ template_id: string; debit_account: string; credit_account: string }>>
}
describe('POST /api/transactions/suggest-categories', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
loadCounterLegTopologyMock.mockResolvedValue(topology([]))
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(request(), emptyParams)
expect(response.status).toBe(401)
})
it('withholds a counterparty suggestion whose learned accounts hit an orphaned ledger', async () => {
enqueueBaseQueries()
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate(), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(topology(['1931']))
const response = await POST(request(), emptyParams)
const { status, body } = await parseJsonResponse<Body>(response)
expect(status).toBe(200)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.find((s) => s.template_id?.startsWith('cp:'))).toBeUndefined()
})
it('keeps a template whose stale BANK leg is a twin of the live row, shown on the settlement ledger (#1643 round 2)', async () => {
// Transaction on the live 1940 row; the template was learned as 5010 /
// 1931 before the reconnect moved the account. The commit guard rewrites
// 1931 to 1940 and books it, so the suggestion must be offered the same way.
enqueue({ data: [{ id: TX_ID, amount: -1200, currency: 'SEK', description: 'Hyra', cash_account_id: 'ca-live' }] })
enqueue({ data: [] }) // mapping_rules
enqueue({ data: [] }) // historical transactions
enqueue({ data: { entity_type: 'aktiebolag' } }) // company_settings
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '5010', credit_account: '1931' }), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(
topology(['1931'], { 'ca-live': { settlementLedger: '1940', twins: ['1931'] } }),
)
const response = await POST(request(), emptyParams)
const { status, body } = await parseJsonResponse<Body>(response)
expect(status).toBe(200)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.some((s) => s.debit_account === '5010' && s.credit_account === '1940')).toBe(true)
expect(suggestions.some((s) => s.credit_account === '1931')).toBe(false)
})
it('rewrites a both-active twin leg (two ledgers on one connection) to the settlement ledger (#1643 round 2)', async () => {
// Nothing is orphaned: 1930 and 1931 are both enabled on the active
// connection. The template learned on 1931 is still the same account.
enqueue({ data: [{ id: TX_ID, amount: -1200, currency: 'SEK', description: 'Hyra', cash_account_id: 'ca-1930' }] })
enqueue({ data: [] })
enqueue({ data: [] })
enqueue({ data: { entity_type: 'aktiebolag' } })
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '5010', credit_account: '1931' }), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(
topology([], { 'ca-1930': { settlementLedger: '1930', twins: ['1931'] } }),
)
const response = await POST(request(), emptyParams)
const { body } = await parseJsonResponse<Body>(response)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.some((s) => s.debit_account === '5010' && s.credit_account === '1930')).toBe(true)
})
it('withholds a template whose twin leg sits in the COUNTER position (settlement against itself)', async () => {
enqueue({ data: [{ id: TX_ID, amount: 217.04, currency: 'SEK', description: 'Ränta', cash_account_id: 'ca-live' }] })
enqueue({ data: [] })
enqueue({ data: [] })
enqueue({ data: { entity_type: 'aktiebolag' } })
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '1940', credit_account: '1931' }), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(
topology([], { 'ca-live': { settlementLedger: '1940', twins: ['1931'] } }),
)
const response = await POST(request(), emptyParams)
const { body } = await parseJsonResponse<Body>(response)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.find((s) => s.template_id?.startsWith('cp:'))).toBeUndefined()
})
it('keeps a learned suggestion whose only 19xx leg is the transaction\'s OWN (orphaned) settlement ledger', async () => {
// A transaction still stranded on the orphaned 1931 row: the template
// learned as 5010 / 1931 is valid for it, the 1931 leg is its bank side.
enqueue({ data: [{ id: TX_ID, amount: -1200, currency: 'SEK', description: 'Hyra', cash_account_id: 'ca-orphan' }] })
enqueue({ data: [] }) // mapping_rules
enqueue({ data: [] }) // historical transactions
enqueue({ data: { entity_type: 'aktiebolag' } }) // company_settings
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '5010', credit_account: '1931' }), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(
topology(['1931'], { 'ca-orphan': { settlementLedger: '1931', twins: ['1940'] } }),
)
const response = await POST(request(), emptyParams)
const { status, body } = await parseJsonResponse<Body>(response)
expect(status).toBe(200)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.some((s) => s.debit_account === '5010' && s.credit_account === '1931')).toBe(true)
})
it('keeps a counterparty suggestion whose accounts are clean', async () => {
enqueueBaseQueries()
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '1930', credit_account: '8311' }), confidence: 0.9 }]]),
)
loadCounterLegTopologyMock.mockResolvedValue(topology(['1931']))
const response = await POST(request(), emptyParams)
const { status, body } = await parseJsonResponse<Body>(response)
expect(status).toBe(200)
const suggestions = body.template_suggestions[TX_ID] ?? []
expect(suggestions.some((s) => s.debit_account === '1930' && s.credit_account === '8311')).toBe(true)
})
it('does not query the orphan set when no counterparty template references a 19xx account', async () => {
enqueueBaseQueries()
findCounterpartyTemplatesBatchMock.mockResolvedValue(
new Map([[TX_ID, { template: makeTemplate({ debit_account: '6570', credit_account: '2440' }), confidence: 0.9 }]]),
)
const response = await POST(request(), emptyParams)
expect(response.status).toBe(200)
expect(loadCounterLegTopologyMock).not.toHaveBeenCalled()
})
})
@@ -2,7 +2,8 @@ import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getSuggestedCategories, getSuggestedTemplates, buildMerchantHistory, merchantHistoryFor, buildCounterpartySuggestion, type SuggestedCategory, type SuggestedTemplate } from '@/lib/transactions/category-suggestions'
import { findCounterpartyTemplatesBatch } from '@/lib/bookkeeping/counterparty-templates'
import type { Transaction, EntityType } from '@/types'
import { loadCounterLegTopology, type CounterLegTopology } from '@/lib/cash-accounts/service'
import type { Transaction, EntityType, CategorizationTemplate } from '@/types'
/**
* POST /api/transactions/suggest-categories
@@ -82,12 +83,76 @@ export const POST = withRouteContext(
template_suggestions[tx.id] = await getSuggestedTemplates(tx as Transaction, entityType, mappingRules || undefined)
}
// Inject counterparty template matches as top suggestions
// Inject counterparty template matches as top suggestions. A learned
// template can carry the ledger it was learned on. The same rules
// guardCounterLegs applies at commit (issue #1643 problem 4) decide what
// the transactions page is offered, so a suggestion is never shown that
// the commit guard would refuse, and never withheld that it would book:
// - a 19xx leg that is a TWIN of the transaction's own row (same IBAN,
// same currency: the stale bank leg of a template learned before a
// reconnect moved the account, or the other enabled ledger of one
// connection) is rewritten to the settlement ledger; if that leaves
// the settlement ledger against itself the suggestion is withheld,
// - a remaining 19xx leg in the orphaned set (revoked connection, or a
// stale twin of some live account) is a counter-position orphan and
// the suggestion is withheld: it would pre-fill a junk balance-sheet
// account in the booking dialog.
// Static library templates only reference BAS business accounts plus the
// literal 1930 settlement placeholder, so they never need this check.
// The transaction's OWN settlement ledger is exempt: a transaction still
// stranded on the orphaned row settles there.
let counterLegTopology: CounterLegTopology | null | undefined
const guardLearnedTemplate = async (
tmpl: CategorizationTemplate,
tx: Transaction,
): Promise<CategorizationTemplate | null> => {
const isCashLedger = (a: string | null | undefined): a is string => !!a && /^19\d{2}$/.test(a)
const accounts = [
tmpl.debit_account,
tmpl.credit_account,
...(tmpl.line_pattern ?? []).map((entry) => entry.account),
].filter(isCashLedger)
if (accounts.length === 0) return tmpl
if (counterLegTopology === undefined) {
counterLegTopology = await loadCounterLegTopology(supabase, companyId)
}
if (!counterLegTopology) return tmpl
const { settlementLedger, twins } = counterLegTopology.contextFor(tx.cash_account_id)
let guarded = tmpl
if (settlementLedger && accounts.some((a) => twins.has(a))) {
const rewrite = (a: string): string => (twins.has(a) ? settlementLedger : a)
guarded = {
...tmpl,
debit_account: rewrite(tmpl.debit_account),
credit_account: rewrite(tmpl.credit_account),
line_pattern: tmpl.line_pattern
? tmpl.line_pattern.map((entry) => ({ ...entry, account: rewrite(entry.account) }))
: tmpl.line_pattern,
}
if (guarded.debit_account === settlementLedger && guarded.credit_account === settlementLedger) {
return null
}
}
const remaining = [
guarded.debit_account,
guarded.credit_account,
...(guarded.line_pattern ?? []).map((entry) => entry.account),
].filter(isCashLedger)
const orphanHit = remaining.some(
(a) => a !== settlementLedger && counterLegTopology!.orphaned.has(a),
)
return orphanHit ? null : guarded
}
for (const tx of transactions) {
const cpMatch = counterpartyMatches.get(tx.id)
if (!cpMatch) continue
const template = await guardLearnedTemplate(cpMatch.template, tx as Transaction)
if (!template) continue
const cpSuggestion = buildCounterpartySuggestion(cpMatch.template, cpMatch.confidence)
const cpSuggestion = buildCounterpartySuggestion(template, cpMatch.confidence)
const existing = template_suggestions[tx.id] || []
template_suggestions[tx.id] = [cpSuggestion, ...existing]