fix: payments review rounds — money-safety, GDPR, security, gift-card cancel, modal stacking

Money-safety:
- Deterministic till idempotency fallback (Square-charging only); cash/on_the_house keep unique keys; £250 till gift-card cap; 45-char key validation
- Gift-card admin caps £250/tx + £5,000/day; user buy £500/day; BuyGiftCard allowlist unchanged
- CancelGiftCard: CCR 2013 14-day right with partial-spend refund of the unspent balance (spend verified via payments.gift_card_id); atomic vs redeem/transfer; refunds stay pending until reversal commits; admin cancel surface (AdminCancelGiftCard)
- Sweep: cancelled-booking charges failed+notified instead of silently completed; source-override replay uses live square_source_id; legacy square-less refund sweep; snapshot refresh on pending reuse
- Refund lock consolidation; recordTerminalPaymentTx shared recorder; structured Square error codes; terminal checkout CustomerID

GDPR / security:
- Notes retained as de-identified medical/safety record at erasure (single field treated as health data; rest of record wiped, no re-identification map) + comments updated per UK GDPR/Art 9/Equality Act 2010
- square_request_snapshot PII scrubbed on all erasure paths; delete_guest_user FK unlinks; verification codes + dispute reasons handled; idle/stale-guest erasure deletes Square cards/customers + CardDAV/R2
- Durable square-erasure outbox job (retry-square-erasures); 2FA dev/prod build split, pepper fail-closed, no prod code-in-log; prod 2FA delivery fail-loud without a channel
- Webhook unknown-type family split (non-money acked, money retried); untracked dispute notifications; rate-limit CF/X-Real-IP trust gating; nginx CSP nonce + api_limit

Frontend:
- Dynamic z-index stack (ui/dialog/zindex.ts) claimed in open order via data-state observer; re-claims on every reopen; removes stale !z-* overrides — nested modals (booking→user→booking) always paint newest-on-top (browser-verified 3-level + reopen)
- Mobile: iOS zoom fixes, bottom-sheet dialogs, 44px touch targets, inputmode decimal, dvh
- Gift-card buy/cancel UI, admin £250 + daily limits, cancellation/privacy/terms policy accuracy

S3:
- Connect() creates buckets before probing; in-memory fallback only on genuine unreachability; health reports degraded; stale S3_PUBLIC_URL documented (host-specific)

Tests/docs:
- 2263 test functions; all 22 backend packages green; round8/9/10 regression suites; NextEditWindowTime removes wall-clock flake; docs reconciled (notes retention, gift-card partial-use, modal T15 future work)
This commit is contained in:
2026-08-22 00:34:50 +01:00
parent 9111258461
commit 78e6d00dc5
89 changed files with 7702 additions and 853 deletions
@@ -106,6 +106,22 @@ func countUnackedCriticalNotificationsForBooking(t *testing.T, bookingID string)
return n
}
// countUntrackedCriticalNotification returns the number of unacknowledged
// NULL-booking critical_payment_log notifications for a dispute's deterministic
// id (disputeNotificationID).
func countUntrackedCriticalNotification(t *testing.T, disputeID string) int {
t.Helper()
var n int
if err := db.Conn.QueryRow(context.Background(), `
SELECT COUNT(*) FROM admin_notifications
WHERE id = $1 AND reason = 'critical_payment_log'
AND booking_id IS NULL AND acknowledged_at IS NULL
`, disputeNotificationID(disputeID)).Scan(&n); err != nil {
t.Fatalf("failed to count critical notifications for dispute %s: %v", disputeID, err)
}
return n
}
// =============================================================================
// (a) handleDisputeStateUpdated — findPaymentByDisputeID fallback
// =============================================================================
@@ -163,14 +179,17 @@ func TestWebhook_DisputeStateUpdated_Lost_EmptyPaymentID_FallsBackToDisputeRow(t
}
}
// TestWebhook_DisputeStateUpdated_EmptyPaymentID_NoDisputeRow_NoMutation
// TestWebhook_DisputeStateUpdated_EmptyPaymentID_NoDisputeRow_RaisesCritical
// covers the fallback's dead end: when neither the payload's (empty) Square
// payment id nor the disputes table yields a payment, the handler returns
// success WITHOUT mutating state — payment untouched, no disputes row, no
// notification — and still commits the dedup row (Square's retry is
// acknowledged 200, not re-dispatched forever).
func TestWebhook_DisputeStateUpdated_EmptyPaymentID_NoDisputeRow_NoMutation(t *testing.T) {
payID, bookingID := createWebhookTestBookingPayment(t)
// payment id nor the disputes table yields a payment, the chargeback is
// UNTRACKED — the handler raises the same critical_payment_log notification as
// dispute.created (booking_id NULL, the deterministic disputeNotificationID) so
// a state.updated arriving without a prior created event is never a silent
// money-loss path. No disputes row is written, the payment row is untouched,
// and the dedup row still commits (Square's retry is acknowledged 200, not
// re-dispatched forever).
func TestWebhook_DisputeStateUpdated_EmptyPaymentID_NoDisputeRow_RaisesCritical(t *testing.T) {
payID, _ := createWebhookTestBookingPayment(t)
event := SquareWebhookEvent{
Type: "dispute.state.updated",
@@ -205,9 +224,12 @@ func TestWebhook_DisputeStateUpdated_EmptyPaymentID_NoDisputeRow_NoMutation(t *t
if got := getPaymentStatus(t, payID); got != "completed" {
t.Errorf("expected payment untouched ('completed') when the fallback finds no dispute, got %q", got)
}
// No critical notification: the handler returns before any insert.
if n := countUnackedCriticalNotificationsForBooking(t, bookingID); n != 0 {
t.Errorf("expected NO critical notification when the fallback finds no dispute, got %d", n)
// The untracked chargeback MUST still surface in-app: exactly one
// unacknowledged NULL-booking critical notification under the dispute's
// deterministic id — the same contract as dispute.created's untracked
// branch.
if got := countUntrackedCriticalNotification(t, "dts_no_dispute_row_1"); got != 1 {
t.Errorf("expected 1 unacknowledged NULL-booking critical notification for the untracked dispute, got %d", got)
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected 1 dedup row (the no-op dispatch still commits), got %d", n)