fix(enable-banking): release ledger claims on disconnect so reconnect lands on the original account (#916) (#955)

Disconnecting a bank left its cash_accounts rows pointing at the revoked
connection, so the BAS slot (e.g. 1930) looked taken forever: reconnecting
the same bank was shunted to 1939 and the picker save was rejected with a
400 the user never saw. Four coordinated fixes:

- DELETE /disconnect now demotes the connection's cash_accounts rows to
  manual (bank_connection_id = null) after marking the connection revoked.
  Rows are never deleted: transactions.cash_account_id and ledger history
  reference them, and upsertFromPsd2 promotes manual holders in place on
  reconnect.
- findFreeLedgerAccount and the PATCH /accounts collision guard no longer
  count claims held by revoked connections (new getRevokedConnectionIds
  helper). This is the self-heal path for rows orphaned before this fix:
  no manual data repair needed.
- upsertFromPsd2 promotes a holder row owned by a revoked connection in
  place (same as the manual seed row), keeping the row id stable so the
  ledger's transaction history stays attached. A duplicate row for the
  same connection+uid on an overflow slot (mirrored there by the callback
  while the slot was wrongly blocked) is merged: deleted when it has no
  linked transactions, demoted to manual otherwise. Either way a primary
  duplicate hands the flag to the promoted row, so the __PRIMARY_SEK__
  sentinel never resolves to a deleted or stale manual row. The
  linked-transactions probe is company-scoped (defense in depth on the
  service-role client).
- AccountPickerDialog surfaces rejected saves inline in the picker with
  the picks intact instead of routing them into the sync-progress modal.
  It also stops signaling the parent to close before the request resolves:
  the parent unmounts the whole component on close, which tore down the
  progress modal mid-flight and made every save outcome (including the
  400) invisible.

Tests: allocator revoked-exclusion + promote/merge unit tests in
lib/cash-accounts, PATCH self-heal case in accounts-route.test.ts, and a
new disconnect-route.test.ts covering claim release and its failure mode.

Fixes #916

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-09 21:10:37 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 15e5dc1a01
commit 2c5e1ce317
7 changed files with 944 additions and 37 deletions
+396 -7
View File
@@ -14,16 +14,46 @@ import {
findFreeLedgerAccount,
allocatePsd2LedgerAccount,
defaultLedgerForCurrency,
getRevokedConnectionIds,
upsertFromPsd2,
} from '../service'
type CashRow = { ledger_account: string; bank_connection_id: string | null }
type ConnRow = { id: string; status: string }
function makeSupabase(rows: CashRow[], error: { message: string } | null = null) {
interface MakeSupabaseOpts {
error?: { message: string } | null
/** bank_connections rows for the status lookup. Missing ids = not revoked. */
connections?: ConnRow[]
connectionsError?: { message: string } | null
}
function makeSupabase(rows: CashRow[], opts: MakeSupabaseOpts = {}) {
return {
from: vi.fn(() => ({
select: vi.fn().mockReturnThis(),
eq: vi.fn(() => Promise.resolve({ data: error ? null : rows, error })),
})),
from: vi.fn((table: string) => {
if (table === 'bank_connections') {
return {
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
in: vi.fn((_col: string, ids: string[]) =>
Promise.resolve(
opts.connectionsError
? { data: null, error: opts.connectionsError }
: {
data: (opts.connections ?? []).filter(c => ids.includes(c.id)),
error: null,
},
),
),
}
}
return {
select: vi.fn().mockReturnThis(),
eq: vi.fn(() =>
Promise.resolve({ data: opts.error ? null : rows, error: opts.error ?? null }),
),
}
}),
} as unknown as SupabaseClient
}
@@ -48,6 +78,32 @@ describe('defaultLedgerForCurrency', () => {
})
})
describe('getRevokedConnectionIds', () => {
it('returns only the ids whose connection is revoked', async () => {
const supabase = makeSupabase([], {
connections: [
{ id: 'conn-a', status: 'revoked' },
{ id: 'conn-b', status: 'active' },
],
})
const revoked = await getRevokedConnectionIds(supabase, 'c1', ['conn-a', 'conn-b'])
expect(revoked).toEqual(new Set(['conn-a']))
})
it('returns an empty set without querying when no ids are given', async () => {
const supabase = makeSupabase([])
const revoked = await getRevokedConnectionIds(supabase, 'c1', [])
expect(revoked.size).toBe(0)
expect((supabase as unknown as { from: ReturnType<typeof vi.fn> }).from).not.toHaveBeenCalled()
})
it('treats every connection as active when the lookup fails (conservative)', async () => {
const supabase = makeSupabase([], { connectionsError: { message: 'boom' } })
const revoked = await getRevokedConnectionIds(supabase, 'c1', ['conn-a'])
expect(revoked.size).toBe(0)
})
})
describe('findFreeLedgerAccount', () => {
it('returns the currency default when nothing holds it', async () => {
const supabase = makeSupabase([])
@@ -62,11 +118,50 @@ describe('findFreeLedgerAccount', () => {
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBe('1930')
})
it('returns the default when it is held only by a REVOKED connection (issue #916)', async () => {
// Disconnecting a bank releases its ledger claims. Rows orphaned before
// that fix still point at the revoked connection; they must count as
// manual holders so a reconnect lands back on 1930, not 1939.
const supabase = makeSupabase(
[{ ledger_account: '1930', bank_connection_id: 'conn-revoked' }],
{ connections: [{ id: 'conn-revoked', status: 'revoked' }] },
)
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBe('1930')
})
it('overflows to 1931 when a CONNECTED row holds the default', async () => {
const supabase = makeSupabase([{ ledger_account: '1930', bank_connection_id: 'conn-1' }])
const supabase = makeSupabase([{ ledger_account: '1930', bank_connection_id: 'conn-1' }], {
connections: [{ id: 'conn-1', status: 'active' }],
})
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBe('1931')
})
it('still overflows when the revoked-status lookup fails (conservative)', async () => {
const supabase = makeSupabase(
[{ ledger_account: '1930', bank_connection_id: 'conn-revoked' }],
{ connectionsError: { message: 'boom' } },
)
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBe('1931')
})
it('keeps revoked-held rows blocking OVERFLOW slots (like manual rows)', async () => {
// The revoked-held row on 1931 keeps its history on that slot; handing the
// slot to a different account would steal it via promote-in-place.
const supabase = makeSupabase(
[
{ ledger_account: '1930', bank_connection_id: 'conn-active' },
{ ledger_account: '1931', bank_connection_id: 'conn-revoked' },
],
{
connections: [
{ id: 'conn-active', status: 'active' },
{ id: 'conn-revoked', status: 'revoked' },
],
},
)
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBe('1935')
})
it('never hands out another currency default as an overflow slot', async () => {
const supabase = makeSupabase([
{ ledger_account: '1930', bank_connection_id: 'conn-1' },
@@ -102,7 +197,7 @@ describe('findFreeLedgerAccount', () => {
})
it('returns null when the lookup fails', async () => {
const supabase = makeSupabase([], { message: 'boom' })
const supabase = makeSupabase([], { error: { message: 'boom' } })
expect(await findFreeLedgerAccount(supabase, 'c1', 'SEK')).toBeNull()
})
})
@@ -167,3 +262,297 @@ describe('allocatePsd2LedgerAccount', () => {
expect(mockSyncMappedAccounts).not.toHaveBeenCalled()
})
})
// ---------------------------------------------------------------------------
// upsertFromPsd2: promote-in-place + duplicate merge (issue #916)
// ---------------------------------------------------------------------------
interface UpsertStub {
/** Row currently holding (company_id, ledger_account), if any. */
holder?: { id: string; bank_connection_id: string | null } | null
/** bank_connections rows for the revoked-status lookup. */
connections?: ConnRow[]
/** Existing row for (company_id, bank_connection_id, external_uid) on another ledger. */
ownRow?: { id: string; is_primary: boolean } | null
/** Whether the duplicate ownRow has linked transactions. */
ownHasTransactions?: boolean
upsertError?: { message: string } | null
// Captured writes:
updates: Array<{ payload: Record<string, unknown>; id: unknown }>
deletes: unknown[]
upserts: Array<Record<string, unknown>>
rpcCalls: Array<{ fn: string; args: Record<string, unknown> }>
/** .eq() filters applied to the linked-transactions probe. */
transactionFilters: Array<{ col: string; value: unknown }>
}
function makeUpsertStub(partial: Partial<UpsertStub> = {}): UpsertStub {
return {
updates: [],
deletes: [],
upserts: [],
rpcCalls: [],
transactionFilters: [],
...partial,
}
}
function makeUpsertSupabase(stub: UpsertStub) {
return {
rpc: vi.fn((fn: string, args: Record<string, unknown>) => {
stub.rpcCalls.push({ fn, args })
return Promise.resolve({ error: null })
}),
from: vi.fn((table: string) => {
if (table === 'bank_connections') {
return {
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
in: vi.fn((_col: string, ids: string[]) =>
Promise.resolve({
data: (stub.connections ?? []).filter(c => ids.includes(c.id)),
error: null,
}),
),
}
}
if (table === 'transactions') {
const chain = {
select: vi.fn(() => chain),
eq: vi.fn((col: string, value: unknown) => {
stub.transactionFilters.push({ col, value })
return chain
}),
limit: vi.fn(() =>
Promise.resolve({
data: stub.ownHasTransactions ? [{ id: 'tx-1' }] : [],
error: null,
}),
),
}
return chain
}
// cash_accounts
return {
select: vi.fn((cols: string) => {
const chain = {
eq: vi.fn(() => chain),
neq: vi.fn(() => chain),
maybeSingle: vi.fn(() => {
// Holder lookup selects bank_connection_id; duplicate lookup
// selects is_primary. Route by the requested columns.
if (cols.includes('bank_connection_id')) {
return Promise.resolve({ data: stub.holder ?? null, error: null })
}
return Promise.resolve({ data: stub.ownRow ?? null, error: null })
}),
}
return chain
}),
update: vi.fn((payload: Record<string, unknown>) => ({
eq: vi.fn((_col: string, id: unknown) => {
stub.updates.push({ payload, id })
const result = Promise.resolve({ data: null, error: null })
return {
select: vi.fn(() => Promise.resolve({ data: [{ id }], error: null })),
then: result.then.bind(result),
catch: result.catch.bind(result),
}
}),
})),
delete: vi.fn(() => ({
eq: vi.fn((_col: string, id: unknown) => {
stub.deletes.push(id)
return Promise.resolve({ error: null })
}),
})),
upsert: vi.fn((payload: Record<string, unknown>) => {
stub.upserts.push(payload)
return Promise.resolve({ error: stub.upsertError ?? null })
}),
}
}),
} as unknown as SupabaseClient
}
const UPSERT_INPUT = {
bank_connection_id: 'conn-new',
external_uid: 'uid-1',
currency: 'SEK',
ledger_account: '1930',
}
describe('upsertFromPsd2', () => {
it('plain-upserts when no row holds the target ledger', async () => {
const stub = makeUpsertStub({ holder: null })
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.upserts).toHaveLength(1)
expect(stub.upserts[0]).toMatchObject({
company_id: 'c1',
bank_connection_id: 'conn-new',
external_uid: 'uid-1',
ledger_account: '1930',
})
expect(stub.updates).toHaveLength(0)
})
it('promotes a MANUAL holder row in place (seed row or demoted-on-disconnect row)', async () => {
const stub = makeUpsertStub({ holder: { id: 'row-manual', bank_connection_id: null } })
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.updates).toHaveLength(1)
expect(stub.updates[0].id).toBe('row-manual')
expect(stub.updates[0].payload).toMatchObject({
bank_connection_id: 'conn-new',
external_uid: 'uid-1',
ledger_account: '1930',
})
expect(stub.upserts).toHaveLength(0)
})
it('promotes a holder owned by a REVOKED connection (orphan self-heal, issue #916)', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
// The orphaned row keeps its id (transaction links survive) and is
// re-bound to the new connection on its original ledger account.
expect(stub.updates).toHaveLength(1)
expect(stub.updates[0].id).toBe('row-old')
expect(stub.updates[0].payload).toMatchObject({
bank_connection_id: 'conn-new',
external_uid: 'uid-1',
ledger_account: '1930',
})
expect(stub.upserts).toHaveLength(0)
expect(stub.deletes).toHaveLength(0)
})
it('does NOT promote a holder owned by an ACTIVE foreign connection', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-other', bank_connection_id: 'conn-other' },
connections: [{ id: 'conn-other', status: 'active' }],
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
// Falls through to the plain upsert; the DB unique constraint is the
// final arbiter for a genuine conflict.
expect(stub.updates).toHaveLength(0)
expect(stub.upserts).toHaveLength(1)
})
it('routes a holder owned by the SAME connection through the plain upsert', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-self', bank_connection_id: 'conn-new' },
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.updates).toHaveLength(0)
expect(stub.upserts).toHaveLength(1)
})
it('deletes an empty duplicate row for the same connection+uid before promoting', async () => {
// Stuck-user recovery: the reconnect callback mirrored uid-1 onto 1939
// while 1930 was wrongly blocked. On remap to 1930 the empty 1939
// duplicate is removed and the orphaned holder is promoted, freeing 1939.
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
ownRow: { id: 'row-dup', is_primary: false },
ownHasTransactions: false,
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.deletes).toEqual(['row-dup'])
expect(stub.updates).toHaveLength(1)
expect(stub.updates[0].id).toBe('row-old')
expect(stub.rpcCalls).toHaveLength(0)
})
it('demotes (not deletes) a duplicate that has linked transactions', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
ownRow: { id: 'row-dup', is_primary: false },
ownHasTransactions: true,
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.deletes).toHaveLength(0)
expect(stub.updates).toHaveLength(2)
// First write releases the duplicate's PSD2 binding, preserving the row
// (and its transactions.cash_account_id links) as a manual account.
expect(stub.updates[0].id).toBe('row-dup')
expect(stub.updates[0].payload).toEqual({ bank_connection_id: null, external_uid: null })
// Second write promotes the holder.
expect(stub.updates[1].id).toBe('row-old')
expect(stub.updates[1].payload).toMatchObject({ bank_connection_id: 'conn-new' })
})
it('scopes the duplicate linked-transactions probe by company (service-role defense in depth)', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
ownRow: { id: 'row-dup', is_primary: false },
ownHasTransactions: false,
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.transactionFilters).toEqual(
expect.arrayContaining([
{ col: 'company_id', value: 'c1' },
{ col: 'cash_account_id', value: 'row-dup' },
]),
)
})
it('transfers the primary flag when the deleted duplicate was primary', async () => {
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
ownRow: { id: 'row-dup', is_primary: true },
ownHasTransactions: false,
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.deletes).toEqual(['row-dup'])
expect(stub.rpcCalls).toEqual([
{
fn: 'set_cash_account_primary',
args: { p_company_id: 'c1', p_cash_account_id: 'row-old' },
},
])
})
it('transfers the primary flag when the DEMOTED duplicate was primary', async () => {
// Otherwise the stale manual row keeps is_primary=true and the
// __PRIMARY_SEK__ sentinel resolves to the wrong row.
const stub = makeUpsertStub({
holder: { id: 'row-old', bank_connection_id: 'conn-old' },
connections: [{ id: 'conn-old', status: 'revoked' }],
ownRow: { id: 'row-dup', is_primary: true },
ownHasTransactions: true,
})
await upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT)
expect(stub.deletes).toHaveLength(0)
expect(stub.updates[0].id).toBe('row-dup')
expect(stub.updates[0].payload).toEqual({ bank_connection_id: null, external_uid: null })
expect(stub.rpcCalls).toEqual([
{
fn: 'set_cash_account_primary',
args: { p_company_id: 'c1', p_cash_account_id: 'row-old' },
},
])
})
it('throws when the plain upsert fails', async () => {
const stub = makeUpsertStub({ holder: null, upsertError: { message: 'duplicate key' } })
await expect(
upsertFromPsd2(makeUpsertSupabase(stub), 'c1', UPSERT_INPUT),
).rejects.toThrow(/duplicate key/)
})
})
+175 -18
View File
@@ -131,6 +131,41 @@ export async function findByIban(
return (data as CashAccount | null) ?? null
}
/**
* Of the given bank_connection ids, return the subset whose connection row has
* status 'revoked'. A revoked connection no longer holds a live claim on its
* cash_accounts rows: the allocator, the picker-save collision guard, and
* upsertFromPsd2's promote-in-place path all treat those rows like manual
* holders so a reconnect can land back on its original ledger account.
*
* On lookup failure this returns an empty set (treat every connection as
* active): the conservative pre-fix behavior.
*/
export async function getRevokedConnectionIds(
supabase: SupabaseClient,
companyId: string,
connectionIds: readonly string[],
): Promise<Set<string>> {
if (connectionIds.length === 0) return new Set()
const { data, error } = await supabase
.from('bank_connections')
.select('id, status')
.eq('company_id', companyId)
.in('id', [...connectionIds])
if (error) {
log.warn('getRevokedConnectionIds lookup failed', { companyId, error: error.message })
return new Set()
}
return new Set(
((data ?? []) as Array<{ id: string; status: string }>)
.filter(c => c.status === 'revoked')
.map(c => c.id),
)
}
/**
* Find a free BAS class-19 slot for a new PSD2 cash account, respecting the
* UNIQUE (company_id, ledger_account) constraint. A bank returning N
@@ -141,6 +176,9 @@ export async function findByIban(
* - The currency default (1930/1932/1933/1934) is available when no
* PSD2-backed row holds it. A manual holder (the seeded 1930 row) does
* not block it — upsertFromPsd2 promotes that row in place.
* Rows held by a REVOKED connection count as manual too: disconnecting a
* bank releases its ledger claims, so reconnecting the same bank gets its
* original slot back instead of overflowing to 1939.
* - Overflow walks the free-use 1931–1959 sub-account slots, skipping the
* four currency defaults (reserved as suggestions for their currencies)
* and any slot held by ANY existing row — promoting an unrelated manual
@@ -169,11 +207,20 @@ export async function findFreeLedgerAccount(
return null
}
const typedRows = (rows ?? []) as Array<{ ledger_account: string; bank_connection_id: string | null }>
const revokedConnectionIds = await getRevokedConnectionIds(
supabase,
companyId,
[...new Set(typedRows.map(r => r.bank_connection_id).filter((id): id is string => id !== null))],
)
const anyTaken = new Set<string>()
const connectedTaken = new Set<string>()
for (const row of (rows ?? []) as Array<{ ledger_account: string; bank_connection_id: string | null }>) {
for (const row of typedRows) {
anyTaken.add(row.ledger_account)
if (row.bank_connection_id !== null) connectedTaken.add(row.ledger_account)
if (row.bank_connection_id !== null && !revokedConnectionIds.has(row.bank_connection_id)) {
connectedTaken.add(row.ledger_account)
}
}
if (!exclude.has(preferred) && !connectedTaken.has(preferred)) return preferred
@@ -265,30 +312,127 @@ export async function upsertFromPsd2(
// create_company_with_owner and the seed_default_cash_account migration plant
// a manual (bank_connection_id IS NULL) row on the same ledger_account so
// reconciliation routes work before any PSD2 connection exists. The first
// PSD2 sync for that BAS slot has to promote that row in place: a plain
// upsert on (company_id, bank_connection_id, external_uid) wouldn't match it
// (NULL ≠ NULL) and the INSERT path then trips the (company_id,
// ledger_account) UNIQUE constraint.
const { data: seedRow, error: seedLookupError } = await supabase
// reconciliation routes work before any PSD2 connection exists, and the
// disconnect handler demotes a revoked connection's rows to manual the same
// way. Rows still pointing at a REVOKED connection (orphans from before the
// disconnect handler released claims) no longer hold a live claim either.
// In all three cases the PSD2 sync claiming that BAS slot has to promote the
// holder row in place: a plain upsert on (company_id, bank_connection_id,
// external_uid) wouldn't match it and the INSERT path then trips the
// (company_id, ledger_account) UNIQUE constraint. Promoting (instead of
// inserting) keeps the row id stable so transactions.cash_account_id links
// and the ledger's history stay attached.
const { data: holderRow, error: holderLookupError } = await supabase
.from('cash_accounts')
.select('id')
.select('id, bank_connection_id')
.eq('company_id', companyId)
.eq('ledger_account', input.ledger_account)
.is('bank_connection_id', null)
.maybeSingle()
if (seedLookupError) {
log.error('upsertFromPsd2 seed lookup failed', {
if (holderLookupError) {
log.error('upsertFromPsd2 holder lookup failed', {
companyId,
bankConnectionId: input.bank_connection_id,
externalUid: input.external_uid,
error: seedLookupError.message,
error: holderLookupError.message,
})
throw new Error(`cash_accounts upsert failed: ${seedLookupError.message}`)
throw new Error(`cash_accounts upsert failed: ${holderLookupError.message}`)
}
if (seedRow) {
const typedHolder = holderRow as { id: string; bank_connection_id: string | null } | null
let promotableRowId: string | null = null
if (typedHolder) {
if (typedHolder.bank_connection_id === null) {
promotableRowId = typedHolder.id
} else if (typedHolder.bank_connection_id !== input.bank_connection_id) {
const revoked = await getRevokedConnectionIds(supabase, companyId, [
typedHolder.bank_connection_id,
])
if (revoked.has(typedHolder.bank_connection_id)) {
promotableRowId = typedHolder.id
}
}
// Holder owned by the input connection itself (or by another ACTIVE
// connection): fall through to the plain upsert. For the former the upsert
// matches on (company_id, bank_connection_id, external_uid) and updates in
// place; for the latter the UNIQUE constraint rejects the write and the
// error surfaces to the caller (the picker-save collision guard should
// have caught it earlier).
}
if (promotableRowId) {
// Promoting the holder makes it THE row for this (bank_connection_id,
// external_uid). If this connection + uid already has a row on another
// ledger (the reconnect callback mirrored it onto an overflow slot while
// the target slot was still wrongly blocked by a revoked connection), that
// duplicate must be resolved first or the promote trips the UNIQUE
// (company_id, bank_connection_id, external_uid) constraint.
const { data: ownRow, error: ownLookupError } = await supabase
.from('cash_accounts')
.select('id, is_primary')
.eq('company_id', companyId)
.eq('bank_connection_id', input.bank_connection_id)
.eq('external_uid', input.external_uid)
.neq('id', promotableRowId)
.maybeSingle()
if (ownLookupError) {
log.error('upsertFromPsd2 duplicate lookup failed', {
companyId,
bankConnectionId: input.bank_connection_id,
externalUid: input.external_uid,
error: ownLookupError.message,
})
throw new Error(`cash_accounts upsert failed: ${ownLookupError.message}`)
}
const typedOwn = ownRow as { id: string; is_primary: boolean } | null
let transferPrimary = false
if (typedOwn) {
// With linked transactions the duplicate is demoted to a plain manual
// row (deleting it would SET NULL those transactions' cash_account_id
// links). Without any, it is a leftover mirror from the broken reconnect
// and is deleted outright so its overflow slot frees up.
const { data: linkedTx, error: linkedTxError } = await supabase
.from('transactions')
.select('id')
.eq('company_id', companyId)
.eq('cash_account_id', typedOwn.id)
.limit(1)
if (linkedTxError) {
log.error('upsertFromPsd2 duplicate transaction check failed', {
companyId,
bankConnectionId: input.bank_connection_id,
externalUid: input.external_uid,
error: linkedTxError.message,
})
throw new Error(`cash_accounts upsert failed: ${linkedTxError.message}`)
}
if ((linkedTx ?? []).length > 0) {
const { error: demoteError } = await supabase
.from('cash_accounts')
.update({ bank_connection_id: null, external_uid: null })
.eq('id', typedOwn.id)
if (demoteError) {
throw new Error(`cash_accounts upsert failed: ${demoteError.message}`)
}
} else {
const { error: deleteError } = await supabase
.from('cash_accounts')
.delete()
.eq('id', typedOwn.id)
if (deleteError) {
throw new Error(`cash_accounts upsert failed: ${deleteError.message}`)
}
}
// A primary duplicate must hand the flag to the promoted row either way:
// deleted, it would leave the __PRIMARY_SEK__ sentinel unresolvable;
// demoted, the sentinel would keep resolving to the stale manual row.
transferPrimary = typedOwn.is_primary
}
// .select() so we can detect a 0-row UPDATE: Supabase's update().eq() returns
// { error: null, data: [] } if the row was deleted between the SELECT above
// and this UPDATE (rare but theoretically possible under concurrent ops).
@@ -297,10 +441,10 @@ export async function upsertFromPsd2(
const { data: promoted, error: promoteError } = await supabase
.from('cash_accounts')
.update(payload)
.eq('id', seedRow.id)
.eq('id', promotableRowId)
.select('id')
if (promoteError) {
log.error('upsertFromPsd2 promote-seed failed', {
log.error('upsertFromPsd2 promote-holder failed', {
companyId,
bankConnectionId: input.bank_connection_id,
externalUid: input.external_uid,
@@ -309,9 +453,22 @@ export async function upsertFromPsd2(
throw new Error(`cash_accounts upsert failed: ${promoteError.message}`)
}
if (promoted && promoted.length > 0) {
if (transferPrimary) {
try {
await setPrimary(supabase, companyId, promotableRowId)
} catch (primaryError) {
// The promote itself succeeded; losing the primary flag is
// recoverable via the AccountPicker, so log instead of unwinding.
log.error('upsertFromPsd2 primary transfer failed', {
companyId,
cashAccountId: promotableRowId,
error: primaryError instanceof Error ? primaryError.message : String(primaryError),
})
}
}
return
}
// Seed row vanished between SELECT and UPDATE: fall through to upsert.
// Holder row vanished between SELECT and UPDATE: fall through to upsert.
}
const { error } = await supabase