Implement full Square payment review fixes + frontend polish

Implement every finding from the deep payment review (P0-P2, minors,
nitpicks), then close the post-implementation re-review items, then
align card-form typography and roll out the Square trust badge.

Backend - Square API alignment:
- tip_settings.allow_tipping nested under device_options (was top-level:
  terminal tips were silently lost in prod)
- CreateCardOnFile now accepts customerID and sends card.customer_id;
  saved-card (ccof:) charges forward square_customer_id as CustomerID
- New SquareClient methods GetPayment, CreateCustomer, CancelCheckout
- SCA verification_token accepted + forwarded in all charge paths
- ExpMonth/ExpYear -> *int; URL-path id validation; CancelCheckout
  NOT_FOUND-only no-op (dropped unverified NOOP); exported ErrorCode/
  ErrorDetail helpers; mock rejects raw PANs, RList locks, redacts
  emails, ForceRefundPending hook

Backend - money safety:
- sweepManualPendingSquareRefunds reconciles rows WITH square_refund_id
  instead of stranding them forever
- SweepStalePendingPayments reconciles at Square before failing (tri-state:
  leave pending on transport error, rescue completed, fail definitively)
- GetCheckoutStatus cancellation-recheck; terminal CANCELED resolution;
  SweepStaleTerminalCheckouts covers terminal_checkouts table
- till gift-card clawback on definitive failure incl. retry path +
  INSUFFICIENT_FUNDS/ADDRESS_VERIFICATION_FAILURE/TRANSACTION_LIMIT
- cross-user saved-card collision fixed (UNIQUE(user_id,square_card_id))
- customer provisioning (lazy, save-only); one-off/guest mint no customer
- discount preview/apply unified in discounts.go (global-milestone visible
  in preview, N+1 eliminated, redemption counter preserved on failures)
- webhook event_id dedup; refund loop dedup; stale comment fixes
- test-isolation t.Cleanup on committed sweep tests

Frontend:
- SCA tokenizeWithVerification across all charge flows (amount as
  major-units decimal), 5-min token-expiry re-tokenize, verification_token
  in request bodies
- PaymentModal synchronous double-click + zero/negative-amount guards
- till online-card UI wired to /api/admin/till/sale
- policyPopover generalised; new /privacy-policy route; consent checkbox
  copy + Square privacy link
- Square card iframe styled to app typography (Inter 14px, oklch tokens);
  mock form md:text-sm parity
- 'Secure payment powered by Square' badge on all 8 card-payment flows

Schema/docs: terminal_checkouts + square_customer_id + per-user card
constraint in init-script.sql; README migrations; P14 plan + backlog +
Technical Manual updated.

Includes 39 modified/new test files; full backend suite (25 pkgs),
-race on payments+square, and frontend build are green.
This commit is contained in:
2026-08-22 00:34:49 +01:00
parent fb21538532
commit 54a5b1024e
45 changed files with 6815 additions and 937 deletions
+122 -12
View File
@@ -5,6 +5,7 @@ package square
import (
"context"
"crussell/clock"
"crypto/sha256"
"fmt"
"log"
"os"
@@ -31,6 +32,7 @@ type MockClient struct {
paymentByKey map[string]*PaymentResult
refunds map[string]*RefundResult
refundByKey map[string]*RefundResult
customers map[string]*CustomerResult
completed map[string]*PaymentResult
HoldCheckouts bool
ShouldFail bool // if true, CreatePayment/RefundPayment return errors for testing error paths
@@ -38,6 +40,10 @@ type MockClient struct {
// = normal success; when set (e.g. "PAYMENT_ALREADY_REFUNDED"),
// RefundPayment returns the sentinel-wrapped error for that code.
FailRefundCode string
// ForceRefundPending makes RefundPayment return a PENDING refund so the
// prod-only pending-refund branch (normally only reachable against the
// real Square API) can be exercised in dev/tests.
ForceRefundPending bool
}
type devProdClient struct{}
@@ -51,11 +57,20 @@ func (d *devProdClient) CreateCheckout(ctx context.Context, req CreateCheckoutRe
func (d *devProdClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
return getCheckoutHTTP(ctx, checkoutID)
}
func (d *devProdClient) GetPayment(ctx context.Context, paymentID string) (*PaymentResult, error) {
return getPaymentHTTP(ctx, paymentID)
}
func (d *devProdClient) CreateCustomer(ctx context.Context, name, email string) (*CustomerResult, error) {
return createCustomerHTTP(ctx, name, email)
}
func (d *devProdClient) CancelCheckout(ctx context.Context, checkoutID string) error {
return cancelCheckoutHTTP(ctx, checkoutID)
}
func (d *devProdClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
return refundPaymentHTTP(ctx, req)
}
func (d *devProdClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
return createCardOnFileHTTP(ctx, userID, cardToken)
func (d *devProdClient) CreateCardOnFile(ctx context.Context, userID, cardToken, customerID string) (*CardOnFile, error) {
return createCardOnFileHTTP(ctx, userID, cardToken, customerID)
}
func (d *devProdClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
return getCardsOnFileHTTP(ctx, userID)
@@ -85,6 +100,7 @@ func NewDevClient() SquareClient {
paymentByKey: make(map[string]*PaymentResult),
refunds: make(map[string]*RefundResult),
refundByKey: make(map[string]*RefundResult),
customers: make(map[string]*CustomerResult),
completed: make(map[string]*PaymentResult),
}
}
@@ -108,6 +124,12 @@ func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*
if m.ShouldFail {
return nil, fmt.Errorf("mock: payment declined (simulated failure)")
}
// Match the real Square API: source_id must be a token (cnon:xxx nonce or
// ccof:xxx card ID). Raw PANs are rejected exactly as Square would, so the
// mock behaves identically to production (PCI-DSS parity).
if !isTokenLike(req.SourceID) {
return nil, fmt.Errorf("invalid source_id: %q — use a card nonce (cnon:xxx) or card ID (ccof:xxx)", req.SourceID)
}
// Do NOT log the full source token — it is a single-use nonce (cnon:) or a
// card reference (ccof:) that could be replayed. Log only its prefix and
// length for debugging (S-2).
@@ -164,6 +186,9 @@ func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*
locationID = "L_MOCK"
}
expMonth := 12
expYear := 2030
result := &PaymentResult{
ID: paymentID,
Status: status,
@@ -171,8 +196,8 @@ func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*
CardBrand: cardBrand,
CardLast4: cardLast4,
CardFingerprint: fmt.Sprintf("sqfp_mock_%d", now.UnixNano()),
ExpMonth: 12,
ExpYear: 2030,
ExpMonth: &expMonth,
ExpYear: &expYear,
EntryMethod: entryMethod,
CVVStatus: "CVV_ACCEPTED",
AVSStatus: "AVS_ACCEPTED",
@@ -198,7 +223,7 @@ func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*
}
func (m *MockClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
log.Printf("[SQUARE-MOCK] CreateCheckout: amount=%d, tipEnabled=%v, reference=%s", req.Amount, req.TipEnabled, req.ReferenceID)
log.Printf("[SQUARE-MOCK] CreateCheckout: amount=%d, allowTipping=%v, reference=%s", req.Amount, req.AllowTipping, req.ReferenceID)
now := clock.Now().UTC()
checkoutID := fmt.Sprintf("chk_mock_%d", now.UnixNano())
@@ -239,12 +264,15 @@ func (m *MockClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq)
paymentID := fmt.Sprintf("pay_mock_%d", payNow.UnixNano())
amount := req.Amount
tipAmount := int64(0)
if req.TipEnabled {
if req.AllowTipping {
tipAmount = 500
amount += tipAmount
}
fees := amount * 175 / 10000 // in-person rate: 1.75%
expMonth := 12
expYear := 2030
paymentResult := &PaymentResult{
ID: paymentID,
Status: "COMPLETED",
@@ -252,8 +280,8 @@ func (m *MockClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq)
CardBrand: "VISA",
CardLast4: "4242",
CardFingerprint: fmt.Sprintf("sqfp_mock_%d", payNow.UnixNano()),
ExpMonth: 12,
ExpYear: 2030,
ExpMonth: &expMonth,
ExpYear: &expYear,
EntryMethod: "EMV",
CVVStatus: "CVV_ACCEPTED",
AVSStatus: "AVS_ACCEPTED",
@@ -302,6 +330,19 @@ func (m *MockClient) GetCheckout(ctx context.Context, checkoutID string) (*Payme
return result, nil
}
func (m *MockClient) GetPayment(ctx context.Context, paymentID string) (*PaymentResult, error) {
log.Printf("[SQUARE-MOCK] GetPayment: id=%s", paymentID)
m.mu.RLock()
defer m.mu.RUnlock()
payment, ok := m.payments[paymentID]
if !ok {
return nil, fmt.Errorf("payment not found: %s", paymentID)
}
return payment, nil
}
func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
if m.ShouldFail {
return nil, fmt.Errorf("%w: refund declined (simulated failure)", ErrRefundDeclined)
@@ -336,6 +377,13 @@ func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*
payment, ok := m.payments[req.PaymentID]
if !ok {
if req.Amount == 0 {
// A £0 refund resolves to a full refund only when the payment is
// known; against an unknown payment there is nothing to size it
// from. The real DB has a CHECK (amount > 0), so an empty refund
// must fail rather than silently record £0.
return nil, fmt.Errorf("square: refund amount must be positive (payment %s not found, cannot resolve full refund)", req.PaymentID)
}
// Payment not in mock map — this happens when integration tests
// create payments via DB fixture with a square_payment_id, bypassing
// the mock. Process the refund without full payment data.
@@ -352,9 +400,14 @@ func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*
locationID = "L_MOCK"
}
status := "COMPLETED"
if m.ForceRefundPending {
status = "PENDING"
}
result := &RefundResult{
ID: refundID,
Status: "COMPLETED",
Status: status,
Amount: amount,
PaymentID: req.PaymentID,
LocationID: locationID,
@@ -369,7 +422,7 @@ func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*
return result, nil
}
func (m *MockClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
func (m *MockClient) CreateCardOnFile(ctx context.Context, userID, cardToken, customerID string) (*CardOnFile, error) {
log.Printf("[SQUARE-MOCK] CreateCardOnFile: user=%s", userID)
// Match the real Square API: source_id must be a token (cnon:xxx nonce or
@@ -450,8 +503,8 @@ func (m *MockClient) DeleteCardOnFile(ctx context.Context, cardID string) error
func (m *MockClient) ListPaymentRefunds(ctx context.Context, paymentID string, beginTime time.Time) ([]RefundResult, error) {
log.Printf("[SQUARE-MOCK] ListPaymentRefunds: payment=%s, begin=%s", paymentID, beginTime.UTC().Format(time.RFC3339))
m.mu.Lock()
defer m.mu.Unlock()
m.mu.RLock()
defer m.mu.RUnlock()
out := []RefundResult{}
for _, r := range m.refunds {
@@ -473,6 +526,63 @@ func isTokenLike(s string) bool {
return strings.HasPrefix(s, "cnon:") || strings.HasPrefix(s, "ccof:")
}
// redactedEmail masks a customer email for dev logs (PII, S-2 convention):
// only the first two characters of the local part plus the domain are shown,
// e.g. "ja***@example.com". Malformed addresses fall back to "[redacted]".
func redactedEmail(email string) string {
at := strings.Index(email, "@")
if at < 2 || at+1 >= len(email) {
return "[redacted]"
}
return email[:2] + "***@" + email[at+1:]
}
func (m *MockClient) CreateCustomer(ctx context.Context, name, email string) (*CustomerResult, error) {
log.Printf("[SQUARE-MOCK] CreateCustomer: name=%s, email=%s", name, redactedEmail(email))
if email == "" {
return nil, fmt.Errorf("mock: customer email is required")
}
m.mu.Lock()
defer m.mu.Unlock()
// Real Square dedups on the idempotency key (derived from the email);
// the mock mirrors this by deduping on email so a retry returns the
// original customer rather than creating a duplicate.
if existing, ok := m.customers[email]; ok {
log.Printf("[SQUARE-MOCK] CreateCustomer dedup hit: email=%s → id=%s", redactedEmail(email), existing.ID)
return existing, nil
}
sum := sha256.Sum256([]byte(email))
customer := &CustomerResult{
ID: "cus_mock_" + fmt.Sprintf("%x", sum)[:12],
Email: email,
CreatedAt: clock.Now().UTC().Format(time.RFC3339),
}
m.customers[email] = customer
log.Printf("[SQUARE-MOCK] Customer created: id=%s, email=%s", customer.ID, redactedEmail(email))
return customer, nil
}
func (m *MockClient) CancelCheckout(ctx context.Context, checkoutID string) error {
log.Printf("[SQUARE-MOCK] CancelCheckout: id=%s", checkoutID)
m.mu.Lock()
defer m.mu.Unlock()
// Real Square cancels only pending/in-progress checkouts; a completed or
// missing checkout is a no-op (Square returns 404/NOT_FOUND in prod).
if checkout, ok := m.checkouts[checkoutID]; ok {
if checkout.Status == "PENDING" || checkout.Status == "IN_PROGRESS" {
checkout.Status = "CANCELED"
checkout.UpdatedAt = clock.Now().UTC().Format(time.RFC3339)
}
}
return nil
}
func realBaseURL(env string) string {
if env == "production" {
return squareProductionURL