fix(workshops): decrement workshop_instances.current_participants on failed payment — was leaking phantom seats

The paid-workshop register flow (commit 815998e7 path) increments
workshop_instances.current_participants when the registration row is
INSERTed — before payment completes. The Payrexx webhook then either
confirms or fails the payment:

  - SUCCESS path: flips registration to CONFIRMED; count stays +1 (correct).
  - FAILURE path (CANCELLED/DECLINED): flipped registration to CANCELLED
    but never decremented the count.

Net: every payment that didn't go through left a phantom +1 on the
instance's seat count. Over time the capacity check at
/api/workshops/[slug]/register-with-payment:102
(current_participants >= max_participants) starts blocking legitimate
sign-ups for workshops that aren't actually full — only fraction of
the counted "participants" ever paid.

current_participants is a real DB column (cms-api migration
003_comprehensive_schema_enhancement.sql) but isn't modeled in the
Drizzle schema in src/db/schema/workshops.ts, so the route had to use
raw SQL to increment it. Mirroring that here for the decrement.

Implementation: SELECT the workshopInstanceId from the registration
before flipping it to cancelled (so we know which instance to
decrement), then a raw-SQL UPDATE with GREATEST(... - 1, 0) so a
duplicate/out-of-band webhook can't drive the count negative. If the
registration is missing entirely (duplicate webhook, manual cleanup),
the decrement is skipped — idempotent.

Added 2 regression tests: one asserts db.execute is called when the
SELECT yields a workshopInstanceId; one asserts it's NOT called when
the registration is missing. 30 tests pass (was 28, +2); tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-25 23:33:46 +02:00
1 parent 83a433fb28
commit 0e33c92893
2 files changed
+61 -1

No files matched your search

@@ -75,10 +75,15 @@ const mockDbUpdate = jest.fn().mockReturnValue({ set: mockUpdateSet })
// Select — configurable per call; default returns empty
const mockDbSelect = jest.fn(() => makeSelectChain([]))
// db.execute — used for raw SQL (e.g. workshop_instances participant
// decrement, which isn't modeled in the Drizzle schema)
const mockDbExecute = jest.fn().mockResolvedValue({ rows: [] })
jest.mock('@/db', () => ({
db: {
select: (...args: unknown[]) => mockDbSelect.apply(null, args),
update: (...args: unknown[]) => mockDbUpdate.apply(null, args),
execute: (...args: unknown[]) => mockDbExecute.apply(null, args),
},
}))
@@ -253,6 +258,7 @@ beforeEach(() => {
mockUpdateSet.mockReturnValue({ where: mockUpdateWhere })
mockDbUpdate.mockReturnValue({ set: mockUpdateSet })
mockDbSelect.mockImplementation(() => makeSelectChain([]))
mockDbExecute.mockResolvedValue({ rows: [] })
})
// ============================================================================
@@ -549,6 +555,33 @@ describe('handleGenericPayment — CANCELLED / DECLINED', () => {
)
})
it('decrements workshop_instances.current_participants on payment failure so phantom count from register-with-payment is undone', async () => {
// The register-with-payment route increments current_participants when
// the registration is INSERTed (before payment completes). Without
// decrementing here on payment failure, the count leaks +1 per failed
// payment and the capacity check eventually blocks legit users.
// (The sql mock in this file collapses template-literals to a
// {__sql:'mocked'} placeholder, so we can only assert that the raw-
// SQL path was taken via db.execute — the inline GREATEST(...) clamp
// is enforced by direct read of the route source.)
mockDbSelect.mockImplementationOnce(() => makeSelectChain([{ workshopInstanceId: 'inst-99' }]))
const tx = makePaymentTx({ workshopRegistrationId: 'reg-99' })
await handleGenericPayment(tx, PAYREXX_TRANSACTION_STATUS.DECLINED, null)
expect(mockDbExecute).toHaveBeenCalledTimes(1)
})
it('skips the participant decrement when the registration row is missing (idempotent on duplicate webhook)', async () => {
// select returns empty (registration already gone / never existed)
mockDbSelect.mockImplementation(() => makeSelectChain([]))
const tx = makePaymentTx({ workshopRegistrationId: 'reg-missing' })
await handleGenericPayment(tx, PAYREXX_TRANSACTION_STATUS.CANCELLED, null)
expect(mockDbExecute).not.toHaveBeenCalled()
})
it('cancels service appointment when serviceAppointmentId is set', async () => {
const tx = makePaymentTx({ serviceAppointmentId: 'appt-2' })
+28 -1
View File
@@ -319,8 +319,24 @@ export async function handleGenericPayment(
})
.where(eq(paymentTransactions.id, paymentTx.id))
// Revert workshop registration to cancelled
// Revert workshop registration to cancelled + decrement the phantom
// participant count. The register-with-payment route at route.ts:140
// increments workshop_instances.current_participants on the initial
// INSERT (before payment completes). Without decrementing here, every
// failed payment leaves a +1 in the count that has no real
// registration backing it — over time the capacity check at
// register-with-payment.ts:102 blocks legitimate users from a
// workshop that's not actually full. GREATEST(...,0) clamps so a
// duplicate webhook can't drive the count negative.
if (paymentTx.workshopRegistrationId) {
// Look up the instanceId first (the registration row will be
// flipped to cancelled below, but we still need to know which
// instance's count to decrement).
const [reg] = await db
.select({ workshopInstanceId: workshopRegistrations.workshopInstanceId })
.from(workshopRegistrations)
.where(eq(workshopRegistrations.id, paymentTx.workshopRegistrationId))
await db
.update(workshopRegistrations)
.set({
@@ -330,6 +346,17 @@ export async function handleGenericPayment(
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.where(eq(workshopRegistrations.id, paymentTx.workshopRegistrationId))
if (reg?.workshopInstanceId) {
// current_participants is a real DB column (cms-api migration 003)
// but isn't modeled in the Drizzle schema — fall back to raw SQL.
// Matches the increment shape in register-with-payment/route.ts:141.
await db.execute(sql`
UPDATE workshop_instances
SET current_participants = GREATEST(current_participants - 1, 0)
WHERE id = ${reg.workshopInstanceId}
`)
}
}
// Revert service appointment