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
+111 -34
View File
@@ -17,14 +17,20 @@ import (
)
type SavedCard struct {
ID string `json:"id"`
SquareCardID string `json:"square_card_id"`
Brand string `json:"brand"`
Last4 string `json:"last_4"`
ExpMonth int `json:"exp_month"`
ExpYear int `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
IsDefault bool `json:"is_default"`
ID string `json:"id"`
// SquareCustomerID is the user's provisioned Square customer profile id
// (P14), persisted on the row the first time the user saves a card. It is
// forwarded to CreatePayment as CustomerID on saved-card (ccof:) charges,
// which Square requires for card-on-file payments. Empty for rows created
// before provisioning was introduced.
SquareCustomerID string `json:"square_customer_id,omitempty"`
SquareCardID string `json:"square_card_id"`
Brand string `json:"brand"`
Last4 string `json:"last_4"`
ExpMonth int `json:"exp_month"`
ExpYear int `json:"exp_year"`
Fingerprint string `json:"fingerprint"`
IsDefault bool `json:"is_default"`
}
type PaymentService struct{}
@@ -472,6 +478,9 @@ func (s *PaymentService) GetBookingRemainingBalanceCents(ctx context.Context, bo
SELECT COALESCE(SUM(amount), 0) AS paid_pounds
FROM payments
WHERE booking_id = $1 AND status = 'completed'
-- A tip is money paid beyond the booking total — it does not
-- reduce the balance owed, so it must not count as "paid".
AND payment_type <> 'tip'
)
SELECT GREATEST(0, ROUND((bt.total_pounds - pt.paid_pounds) * 100))::bigint
FROM booking_total bt, paid_total pt
@@ -484,7 +493,7 @@ func (s *PaymentService) GetBookingRemainingBalanceCents(ctx context.Context, bo
func (s *PaymentService) GetUserPaymentMethods(ctx context.Context, userID string) ([]SavedCard, error) {
rows, err := db.Conn.Query(ctx, `
SELECT id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default
SELECT id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default, COALESCE(square_customer_id, '')
FROM user_saved_cards
WHERE user_id = $1 AND deleted_at IS NULL
ORDER BY is_default DESC, created_at DESC
@@ -498,7 +507,7 @@ func (s *PaymentService) GetUserPaymentMethods(ctx context.Context, userID strin
var cards []SavedCard
for rows.Next() {
var c SavedCard
err := rows.Scan(&c.ID, &c.SquareCardID, &c.Brand, &c.Last4, &c.ExpMonth, &c.ExpYear, &c.Fingerprint, &c.IsDefault)
err := rows.Scan(&c.ID, &c.SquareCardID, &c.Brand, &c.Last4, &c.ExpMonth, &c.ExpYear, &c.Fingerprint, &c.IsDefault, &c.SquareCustomerID)
if err != nil {
return nil, err
}
@@ -546,55 +555,123 @@ func (s *PaymentService) CreatePaymentMethodFromToken(ctx context.Context, userI
// PCI-DSS: raw PANs are never accepted. The client must supply a Square
// Web Payments nonce (cnon:xxx), which the backend tokenizes via the
// Cards API — the full PAN exists only inside Square's vault.
cardOnFile, err := SquareClient.CreateCardOnFile(ctx, userID, cardToken)
//
// P14: this endpoint saves a card, so lazily ensure the user has a Square
// customer profile BEFORE the card is tokenized — if provisioning fails the
// card cannot be saved, so abort with a clear error instead of creating an
// orphan card at Square. One-off (non-save) payments never call this.
squareCustomerID, err := s.ensureSquareCustomer(ctx, userID)
if err != nil {
return nil, err
}
cardOnFile, err := SquareClient.CreateCardOnFile(ctx, userID, cardToken, squareCustomerID)
if err != nil {
return nil, fmt.Errorf("failed to tokenize card: %w", err)
}
var savedCardID string
var isDefault bool
// ON CONFLICT (square_card_id): a response-lost retry re-tokenizes the same
// card (CreateCardOnFile's deterministic key returns the same ccof: id), so
// the UNIQUE constraint would otherwise 500 on the duplicate. Upsert instead
// so the retry returns the existing saved card (N-8).
// ON CONFLICT (user_id, square_card_id): a response-lost retry re-tokenizes
// the same card for the SAME user (CreateCardOnFile's deterministic key
// returns the same ccof: id), so the per-user UNIQUE constraint would
// otherwise 500 on the duplicate. Upsert instead so the retry returns the
// existing saved card (N-8). The conflict target is scoped per user — a
// card tokenized by user B that user A already saved is a brand-new row for
// B, never a mutation of A's row.
err = db.Conn.QueryRow(ctx, `
INSERT INTO user_saved_cards (user_id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default)
SELECT $1, $2, $3, $4, $5, $6, $7,
INSERT INTO user_saved_cards (user_id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, square_customer_id, is_default)
SELECT $1, $2, $3, $4, $5, $6, $7, $8,
NOT EXISTS(SELECT 1 FROM user_saved_cards WHERE user_id = $1 AND deleted_at IS NULL)
ON CONFLICT (square_card_id) DO UPDATE SET
ON CONFLICT (user_id, square_card_id) DO UPDATE SET
brand = EXCLUDED.brand,
last_4 = EXCLUDED.last_4,
exp_month = EXCLUDED.exp_month,
exp_year = EXCLUDED.exp_year,
fingerprint = EXCLUDED.fingerprint,
square_customer_id = EXCLUDED.square_customer_id,
deleted_at = NULL,
retained_until = NULL
WHERE user_saved_cards.user_id = EXCLUDED.user_id
RETURNING id, is_default
`, userID, cardOnFile.CardID, cardOnFile.Brand, cardOnFile.Last4, cardOnFile.ExpMonth, cardOnFile.ExpYear, cardOnFile.Fingerprint).Scan(&savedCardID, &isDefault)
`, userID, cardOnFile.CardID, cardOnFile.Brand, cardOnFile.Last4, cardOnFile.ExpMonth, cardOnFile.ExpYear, cardOnFile.Fingerprint, squareCustomerID).Scan(&savedCardID, &isDefault)
if err != nil {
return nil, fmt.Errorf("failed to save card: %w", err)
}
return &SavedCard{
ID: savedCardID,
SquareCardID: cardOnFile.CardID,
Brand: cardOnFile.Brand,
Last4: cardOnFile.Last4,
ExpMonth: cardOnFile.ExpMonth,
ExpYear: cardOnFile.ExpYear,
Fingerprint: cardOnFile.Fingerprint,
IsDefault: isDefault,
ID: savedCardID,
SquareCustomerID: squareCustomerID,
SquareCardID: cardOnFile.CardID,
Brand: cardOnFile.Brand,
Last4: cardOnFile.Last4,
ExpMonth: cardOnFile.ExpMonth,
ExpYear: cardOnFile.ExpYear,
Fingerprint: cardOnFile.Fingerprint,
IsDefault: isDefault,
}, nil
}
func (s *PaymentService) SaveCardForUser(ctx context.Context, userID, squareCardID, brand, last4 string, expMonth, expYear int, fingerprint string) (string, error) {
var id string
// ensureSquareCustomer lazily provisions a Square customer profile for the
// user (P14). A customer is only ever minted when a card is being SAVED — the
// saved-card row is the persistence point, and the id is reused for every
// subsequent card save by the same user. Square dedups on a deterministic
// idempotency key derived from the email, so a response-lost retry returns the
// same customer instead of minting a duplicate.
func (s *PaymentService) ensureSquareCustomer(ctx context.Context, userID string) (string, error) {
var customerID sql.NullString
err := db.Conn.QueryRow(ctx, `
SELECT square_customer_id FROM user_saved_cards
WHERE user_id = $1 AND square_customer_id IS NOT NULL AND square_customer_id <> ''
ORDER BY created_at DESC
LIMIT 1
`, userID).Scan(&customerID)
if err == nil && customerID.Valid {
return customerID.String, nil
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return "", fmt.Errorf("failed to look up Square customer id: %w", err)
}
var name, email string
if err := db.Conn.QueryRow(ctx, `
SELECT fn, email FROM users WHERE id = $1
`, userID).Scan(&name, &email); err != nil {
return "", fmt.Errorf("failed to load user for Square customer provisioning: %w", err)
}
customer, err := SquareClient.CreateCustomer(ctx, name, email)
if err != nil {
return "", fmt.Errorf("failed to create Square customer for card save: %w", err)
}
return customer.ID, nil
}
// EnsureSquareCustomer lazily provisions (or reuses) the user's Square customer
// profile, persisting its id on the saved-card row for reuse. Exported for
// handlers that must pass the customer id to CreateCardOnFile in save-card
// flows (P14): Square creates the card against that customer, and subsequent
// saved-card (ccof:) charges carry it as CreatePaymentReq.CustomerID.
func (s *PaymentService) EnsureSquareCustomer(ctx context.Context, userID string) (string, error) {
return s.ensureSquareCustomer(ctx, userID)
}
func (s *PaymentService) SaveCardForUser(ctx context.Context, userID, squareCardID, brand, last4 string, expMonth, expYear int, fingerprint string) (string, error) {
// P14: SaveCardForUser is only ever called in save-card flows, so lazily
// ensure the Square customer exists and persist its id on the saved-card
// row for reuse by subsequent card saves from the same user.
squareCustomerID, err := s.ensureSquareCustomer(ctx, userID)
if err != nil {
return "", err
}
var id string
err = db.Conn.QueryRow(ctx, `
INSERT INTO user_saved_cards (
user_id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default, created_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, false, NOW())
user_id, square_card_id, square_customer_id, brand, last_4, exp_month, exp_year, fingerprint, is_default, created_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, false, NOW())
RETURNING id
`, userID, squareCardID, brand, last4, expMonth, expYear, fingerprint).Scan(&id)
`, userID, squareCardID, squareCustomerID, brand, last4, expMonth, expYear, fingerprint).Scan(&id)
if err != nil {
return "", err
@@ -612,10 +689,10 @@ func (s *PaymentService) GetCardByID(ctx context.Context, cardID, userID string)
func (s *PaymentService) GetCardByIDQuerier(ctx context.Context, q db.Querier, cardID, userID string) (*SavedCard, error) {
var c SavedCard
err := q.QueryRow(ctx, `
SELECT id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default
SELECT id, square_card_id, brand, last_4, exp_month, exp_year, fingerprint, is_default, COALESCE(square_customer_id, '')
FROM user_saved_cards
WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL
`, cardID, userID).Scan(&c.ID, &c.SquareCardID, &c.Brand, &c.Last4, &c.ExpMonth, &c.ExpYear, &c.Fingerprint, &c.IsDefault)
`, cardID, userID).Scan(&c.ID, &c.SquareCardID, &c.Brand, &c.Last4, &c.ExpMonth, &c.ExpYear, &c.Fingerprint, &c.IsDefault, &c.SquareCustomerID)
if err != nil {
return nil, err