Files
Crussell/backend/handlers/payments/sweep.go
T
popertots 7439fa86c1 Fix payment review round 3: saved-card idempotency, stale-pending sweep, webhook fail-closed
R1/R4: saved_card branch in CreateTerminalPayment now mirrors CreateTipPayment
- advisory lock (crussell:payment:<bookingID>) serializes concurrent double-clicks
- deterministic key bookingID-sc-type-amount-cardID (<=45 chars) so a lost-response
  retry derives the same key and dedups instead of double-charging
- idempotency switch inside the lock: completed -> dedup, pending -> reuse with
  pence amount-guard, failed -> clean 409
- success response includes card_brand/card_last4 (frontend already reads them)

R2: add 'failed' case to all four retry switches (tip, booking, gift card, till)
- a swept/definitively-rejected record returns 409 instead of 500-ing on the
  idempotency_key UNIQUE constraint

R3: extend SweepStalePendingPayments to till_sales card rows
- sweeps pending till_sales (online_square/in_person_card) past Square's ~24h
  key retention, closing the double-charge window for till sales
- swept rows logged with the same CRITICAL manual-reconciliation marker as the
  refund sweep

Webhook fail-closed: reject 503 when SQUARE_WEBHOOK_SIGNATURE_KEY unset, 403 on
bad signature (was: skip verification in dev)

Refund status resolution: refunds now resolve by Square status
(COMPLETED/PENDING/FAILED/REJECTED) instead of assuming completed; real error
codes (REFUND_AMOUNT_INVALID, PAYMENT_NOT_REFUNDABLE, REFUND_ALREADY_PENDING)
added to the definitive/processed classification

HTTP client: CreateCard key truncated to <=45 chars, device_options always sent
(env SQUARE_TERMINAL_DEVICE_ID fallback), processing_fee reads amount_money,
ListCards cursor loop, refund keys hashed to <=45 chars

Other fixes: payment/till/gift-card advisory-lock + FOR UPDATE asymmetries,
GetPaymentByID NULL scans, loyalty redemption lock, card upsert on conflict,
mock ccof: prefix parity, IsValidSquareCheckoutID for real Square IDs,
isAdminRequest defense-in-depth on all 6 admin payment handlers, webhook
signature docs, M8/L5 debug markers removed

Docs: README/FC/TM/Overview updated (22 jobs, 20 CRITICAL sites, 23-section
GDPR export, sweep jobs, webhook fail-closed); P11 plan marks remaining items
(sandbox smoke test, M-8 customer_id, saved-card key dedup trade-off) as
deferred with rationale; gap backlog pruned of completed items
2026-08-22 00:34:49 +01:00

75 lines
3.0 KiB
Go

package payments
import (
"context"
"log"
"time"
"crussell/clock"
"crussell/db"
)
// SweepStalePendingPayments marks pending payment records that are older than
// Square's idempotency-key retention window (~24h) as 'failed'. A pending
// record means the DB committed but the Square charge outcome is unknown; it
// normally resolves on a same-key client retry. But if the client abandoned
// the attempt, the record stays pending forever — and retrying it after the
// key expires would ISSUE A SECOND CHARGE (Square no longer dedups). Failing
// stale pendings closes that double-charge window: a late retry finds a
// 'failed' record and stops instead of charging again.
//
// Only online/till card payments can be pending — cash/giftcard/on_the_house
// are committed synchronously and never enter this state. Both the payments
// table and till_sales carry pending card-sale rows and are swept here.
//
// A swept row may have been genuinely charged at Square with a lost response —
// it is flagged with a CRITICAL manual-reconciliation log (like the refund
// sweep) so the money is not silently lost in limbo (MINOR-R3).
const stalePendingPaymentAge = 24 * time.Hour
func SweepStalePendingPayments(ctx context.Context) (int, error) {
cutoff := clock.Now().Add(-stalePendingPaymentAge)
tag, err := db.Conn.Exec(ctx, `
UPDATE payments
SET status = 'failed', updated_at = NOW()
WHERE status = 'pending'
AND created_at < $1
`, cutoff)
if err != nil {
return 0, err
}
payCount := int(tag.RowsAffected())
// till_sales rows for card payments (stored as 'online_square' or
// 'in_person_card' in the payment_method enum — saved_card/online_square/
// card_machine requests all persist as one of those) can also be pending.
// Sweep them too — a lost-response till sale would otherwise stay pending
// and a retry after key retention would reuse the stored key → Square sees
// an expired key → second charge (R3). Cash / on_the_house are committed
// synchronously and never pending.
tillTag, err := db.Conn.Exec(ctx, `
UPDATE till_sales
SET status = 'failed', updated_at = NOW()
WHERE status = 'pending'
AND created_at < $1
AND payment_method IN ('online_square', 'in_person_card')
`, cutoff)
if err != nil {
return 0, err
}
tillCount := int(tillTag.RowsAffected())
total := payCount + tillCount
if total > 0 {
log.Printf("[SWEEP] Marked %d stale pending payments (%d payments, %d till sales) as failed (older than %s) — late retries will be rejected, preventing a second Square charge", total, payCount, tillCount, stalePendingPaymentAge)
}
if payCount > 0 {
log.Printf("CRITICAL: %d pending payments swept to failed may have been charged at Square with a lost response — manual reconciliation required before refunding/charging", payCount)
}
if tillCount > 0 {
log.Printf("CRITICAL: %d pending till sales swept to failed may have been charged at Square with a lost response — manual reconciliation required", tillCount)
}
return total, nil
}