Sixth fresh-eyes review pass (5 agents: goal, QA, code-quality, security, context-mining). QA FAILED the deposit-required new-card flow; the P0 root cause was backend + frontend, now fixed. All 20 packages green. P0 money-safety: - Deposit-required bookings now actually charge the deposit on new-card payment. Two-part fix: (1) CreateBookingHandler re-reads the trigger-maintained total_amount/total_duration_minutes from the DB after the booking_services insert (the INSERT..RETURNING row predates the recalc trigger, so TotalAmount serialized as 0 and DepositPaid computed TRUE on an unpaid booking — the frontend gate trusted deposit_paid:true, never charged, and confirmed the booking with zero payment rows); (2) BookingFlow.svelte gates the confirmation view on depositPaid and guards against re-creating a booking on retry. Regression test TestBookings_Create_DepositPaidFalseOnUnpaidBooking. Payments (idempotency + money): - deriveBookingPaymentIdempotencyKey: no-client-key fallback now advances a sequence for repeatable types (partial) and rotates past refunded completed rows, so refund-then-repay and equal-amount partials diverge onto distinct keys; an un-refunded completed row keeps its key (double-charge protection holds). Dedup hits on refunded rows now 409, never stale success. - chargeFailureStatus default is 503 (ambiguous), never 402; table test. - Flaky TestBookingPayment_FullPayment_SplitsIntoDepositAndBalance fixed (ORDER BY payment_type). - resolveChargeSource: orphaned card-on-file disabled via DeleteCardOnFile when SaveCardForUser fails (best-effort, redacted log); retry path preserved. Square client: - Dev builds HARD-FAIL (panic) on SQUARE_ENVIRONMENT=production without SQUARE_ALLOW_REAL_API=1; sandbox routes with a loud banner. - Mock fault-injection FailAfterCommit (commit-then-5xx) exercises the exact lost-response same-key retry; SimulateCardTokenUsed; 45-char idempotency-key cap parity; SquareEnvironment/SquareLocationID shared env helpers used by the sweep (env contract no longer comment-only). - listRefunds truncation now errors (money-sensitive reconcile retries instead of over-refunding); getCardsOnFile truncation loudly logged. Webhooks + 2FA: - square-environment header checked fail-closed (403) when configured env is production/sandbox; dispatch DB work bounded by 30s timeout contexts. - 2FA codes HMAC-SHA256 pepper'd (TWO_FACTOR_PEPPER) with legacy-hash migration + upgrade-on-verify; disable-flow mint cooldown (1/min, 429) caps the brute-force loop; in-lockout records never LRU-evicted. Repo hygiene: - env-docs CI gate green again (FRONTEND_ORIGIN + SQUARE_ALLOW_REAL_API + TWO_FACTOR_PEPPER documented; Vite DEV built-in allowlisted). - Dead square_deposits schema dropped; obsidian/README/legal-page drift fixed (consumeradvice.scot signposting, CORS allowlist, p11 R3/P13, T1). - 2FA disable residual documented; P6 email/SMS delivery and P12 sandbox smoke test remain the pre-go-live gates. Verification: go test -tags test,dev -count=1 -parallel 8 ./... (20/20 ok), go build ./... + -tags dev, go vet clean, svelte-check 0 errors, env-docs gate OK, live deposit-required flow re-verified end-to-end (deposit £11 charged, square_payment_id recorded).
60 lines
2.6 KiB
Go
60 lines
2.6 KiB
Go
package payments
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"crussell/internal/square"
|
|
)
|
|
|
|
// chargeFailureStatus classifies a SquareClient.CreatePayment error into the
|
|
// HTTP status a payment handler should return:
|
|
//
|
|
// - 503 (Service Unavailable) for AMBIGUOUS failures: transport/network
|
|
// errors, Square 5xx responses, context cancellation/deadline, and the
|
|
// retryable 4xx statuses 429 (rate limited), 408 (request timeout), and
|
|
// 425 (too early) — the money state at Square is unknown, so the frontend
|
|
// should treat it as a retry (the pending record is resumed on a same-key
|
|
// retry). Square's own docs treat 429 as "retry later"; mapping it (or a
|
|
// timeout/early request) to 402 would mislabel a retryable condition as a
|
|
// permanent decline.
|
|
// - 402 (Payment Required) for DEFINITIVE declines: a structured Square
|
|
// error (squareAPIError) carrying any OTHER 4xx status (400/402/422 etc.)
|
|
// means Square positively rejected the charge (card declined/expired,
|
|
// AVS/CVV failure) — retrying with the same inputs cannot succeed.
|
|
//
|
|
// A nil error is never expected (callers only invoke this on the error path);
|
|
// it maps to 402 defensively. The dev mock returns plain errors for simulated
|
|
// failures, which classify as 503 (ambiguous) — correct for a mock standing in
|
|
// for an unreachable Square.
|
|
func chargeFailureStatus(err error) int {
|
|
if err == nil {
|
|
return http.StatusPaymentRequired
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
status := square.ErrorStatusCode(err)
|
|
if status == 0 || status >= 500 {
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
// Retryable/ambiguous 4xx carve-outs: 429 (RATE_LIMITED), 408 (request
|
|
// timeout), and 425 (too early) are not definitive declines — Square's
|
|
// docs tell clients to retry later. Classify them as 503 so the pending
|
|
// record stays resumable on a same-key retry instead of being labelled a
|
|
// permanent decline. True declines (400/402/422 etc.) fall through to 402.
|
|
if status == http.StatusTooManyRequests || status == http.StatusRequestTimeout || status == http.StatusTooEarly {
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
if status >= 400 && status < 500 {
|
|
return http.StatusPaymentRequired
|
|
}
|
|
// Anything else (1xx/2xx/3xx — impossible in practice, but defensive) is
|
|
// AMBIGUOUS: the money state at Square is unknown, so the failure must be
|
|
// retryable. The default is deliberately 503, never 402 — a definitive
|
|
// decline classification on an ambiguous outcome would suppress the
|
|
// same-key retry that resumes the pending record.
|
|
return http.StatusServiceUnavailable
|
|
}
|