P0 — float truncation: applied math.Round to all remaining int64(x*100) sites (till penceAmount, refund over-refund guard, GetAlreadyRefundedAmount, payment summary conversions). A £1.14 till sale previously charged 113p. P0 — raw PAN stopped at the API edge: - Deleted CardNumber/CardExpMonth/CardExpYear/CardCVC from TillSaleRequest and CardNumber/Expiry/CVC from CreatePaymentMethodRequest. Both now accept card_token (Square nonce) and return 400 when absent. PAN+CVV no longer transit the application server (PCI-DSS SAQ-A scope). - Deleted CreateCardOnFileRaw from the SquareClient interface and all implementations (MockClient, ProdClient, devProdClient). - Added idempotency_key column to refunds table (UNIQUE). P0 — RefundPayment hardened: advisory lock on payment ID (prevents two concurrent refunds passing the over-refund guard), pending-refund-record- then-Square pattern (scheduler reprocesses on failure), same-key dedup. P1 — till sale pending-retry now re-attempts the Square charge instead of returning the stale 'pending' status (gift card was already funded in the committed tx — silent money loss otherwise). Sale row reused, not duplicated. P1 — idempotency key caching in frontend: BuyGiftCard and UserPaymentModal/BookingFlow now cache the key per amount+card, regenerated on change and cleared on success — matches the tip-flow pattern so a lost-response retry dedups instead of double-charging. P1 — CreateTerminalPayment cash/giftcard INSERTs now persist idempotency_key. Key is unique per payment (booking+type+amount would wrongly dedup two legitimate identical payments, e.g. two £50 cash receipts). P1 — gift-card codes no longer logged (spendable credential; value+recipient only). Tests: till pending-retry re-attempt, refund same-key dedup, mock CreatePayment idempotency dedup, CreatePaymentMethod nonce happy path + raw-PAN rejection, till online_square card_token required/valid.
419 lines
12 KiB
Go
419 lines
12 KiB
Go
//go:build dev
|
|
|
|
package square
|
|
|
|
import (
|
|
"context"
|
|
"crussell/clock"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var Client SquareClient
|
|
|
|
var isTesting = os.Getenv("GO_TESTING") == "1"
|
|
|
|
func mockSleep(d time.Duration) {
|
|
if !isTesting {
|
|
time.Sleep(d)
|
|
}
|
|
}
|
|
|
|
type MockClient struct {
|
|
mu sync.RWMutex
|
|
cards map[string]map[string]*CardOnFile
|
|
checkouts map[string]*CheckoutResult
|
|
payments map[string]*PaymentResult
|
|
paymentByKey map[string]*PaymentResult
|
|
refunds map[string]*RefundResult
|
|
completed map[string]*PaymentResult
|
|
HoldCheckouts bool
|
|
ShouldFail bool // if true, CreatePayment/RefundPayment return errors for testing error paths
|
|
}
|
|
|
|
type devProdClient struct{}
|
|
|
|
func (d *devProdClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
|
|
return createPaymentHTTP(ctx, req)
|
|
}
|
|
func (d *devProdClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
|
|
return createCheckoutHTTP(ctx, req)
|
|
}
|
|
func (d *devProdClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
|
|
return getCheckoutHTTP(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) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
|
|
return getCardsOnFileHTTP(ctx, userID)
|
|
}
|
|
func (d *devProdClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
|
|
return deleteCardOnFileHTTP(ctx, cardID)
|
|
}
|
|
|
|
func NewClient() SquareClient {
|
|
return NewDevClient()
|
|
}
|
|
|
|
func NewDevClient() SquareClient {
|
|
env := os.Getenv("SQUARE_ENVIRONMENT")
|
|
if env == "sandbox" || env == "production" {
|
|
log.Printf("[SQUARE-PROD] SQUARE_ENVIRONMENT=%s — making real API calls to %s", env, realBaseURL(env))
|
|
return &devProdClient{}
|
|
}
|
|
log.Println("[SQUARE-MOCK] Using in-memory mock client")
|
|
return &MockClient{
|
|
cards: make(map[string]map[string]*CardOnFile),
|
|
checkouts: make(map[string]*CheckoutResult),
|
|
payments: make(map[string]*PaymentResult),
|
|
paymentByKey: make(map[string]*PaymentResult),
|
|
refunds: make(map[string]*RefundResult),
|
|
completed: make(map[string]*PaymentResult),
|
|
}
|
|
}
|
|
|
|
func detectCardInfo(sourceID string) (brand, last4 string) {
|
|
switch sourceID {
|
|
case "cnon:test-card":
|
|
return "VISA", "4242"
|
|
case "cnon:visa":
|
|
return "VISA", "1111"
|
|
case "cnon:mastercard":
|
|
return "MASTERCARD", "4444"
|
|
case "cnon:amex":
|
|
return "AMERICAN_EXPRESS", "0005"
|
|
default:
|
|
return "VISA", "4242"
|
|
}
|
|
}
|
|
|
|
func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
|
|
if m.ShouldFail {
|
|
return nil, fmt.Errorf("mock: payment declined (simulated failure)")
|
|
}
|
|
log.Printf("[SQUARE-MOCK] CreatePayment: amount=%d, reference=%s, source=%s", req.Amount, req.ReferenceID, req.SourceID)
|
|
mockSleep(1 * time.Second)
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
// Real Square dedups on idempotency key: a retry with the same key returns
|
|
// the original payment rather than creating a second charge. The mock
|
|
// mirrors this so dev/testing behaves like production (also why the tip
|
|
// retry regression test can rely on the mock).
|
|
if req.IdempotencyKey != "" {
|
|
if existing, ok := m.paymentByKey[req.IdempotencyKey]; ok {
|
|
log.Printf("[SQUARE-MOCK] CreatePayment dedup hit: key=%s → id=%s", req.IdempotencyKey, existing.ID)
|
|
return existing, nil
|
|
}
|
|
}
|
|
|
|
now := clock.Now().UTC()
|
|
|
|
status := "COMPLETED"
|
|
if req.Autocomplete != nil && !*req.Autocomplete {
|
|
status = "APPROVED"
|
|
}
|
|
|
|
amount := req.Amount
|
|
tipAmount := int64(0)
|
|
if req.TipMoney != nil {
|
|
tipAmount = *req.TipMoney
|
|
amount += tipAmount
|
|
}
|
|
|
|
cardBrand, cardLast4 := detectCardInfo(req.SourceID)
|
|
|
|
// Entry method: ON_FILE for card-on-file tokens, KEYED for nonces
|
|
entryMethod := "KEYED"
|
|
if len(req.SourceID) >= 5 && req.SourceID[:5] == "ccof:" {
|
|
entryMethod = "ON_FILE"
|
|
}
|
|
|
|
paymentID := fmt.Sprintf("pay_mock_%d", now.UnixNano())
|
|
fees := amount*14/1000 + 25 // online rate: 1.4% + 25p
|
|
|
|
locationID := req.LocationID
|
|
if locationID == "" {
|
|
locationID = "L_MOCK"
|
|
}
|
|
|
|
result := &PaymentResult{
|
|
ID: paymentID,
|
|
Status: status,
|
|
Amount: amount,
|
|
CardBrand: cardBrand,
|
|
CardLast4: cardLast4,
|
|
CardFingerprint: fmt.Sprintf("sqfp_mock_%d", now.UnixNano()),
|
|
ExpMonth: 12,
|
|
ExpYear: 2030,
|
|
EntryMethod: entryMethod,
|
|
CVVStatus: "CVV_ACCEPTED",
|
|
AVSStatus: "AVS_ACCEPTED",
|
|
TipAmount: tipAmount,
|
|
ReceiptURL: "https://squareup.com/receipt/" + paymentID,
|
|
ReceiptNumber: fmt.Sprintf("RCPT_mock_%d", now.UnixNano()),
|
|
SquarePayID: "sqp_" + paymentID,
|
|
Fees: fees,
|
|
BuyerEmail: req.BuyerEmail,
|
|
CustomerID: req.CustomerID,
|
|
LocationID: locationID,
|
|
CreatedAt: now.Format(time.RFC3339),
|
|
UpdatedAt: now.Format(time.RFC3339),
|
|
ReferenceID: req.ReferenceID,
|
|
}
|
|
m.payments[paymentID] = result
|
|
m.payments[result.SquarePayID] = result
|
|
if req.IdempotencyKey != "" {
|
|
m.paymentByKey[req.IdempotencyKey] = result
|
|
}
|
|
log.Printf("[SQUARE-MOCK] Payment created: id=%s, status=%s, amount=%d, fees=%d", paymentID, status, amount, fees)
|
|
return result, nil
|
|
}
|
|
|
|
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)
|
|
|
|
now := clock.Now().UTC()
|
|
checkoutID := fmt.Sprintf("chk_mock_%d", now.UnixNano())
|
|
|
|
result := &CheckoutResult{
|
|
ID: checkoutID,
|
|
Status: "PENDING",
|
|
AmountMoney: req.Amount,
|
|
Currency: req.Currency,
|
|
DeviceID: req.DeviceID,
|
|
ReferenceID: req.ReferenceID,
|
|
Note: req.Note,
|
|
CreatedAt: now.Format(time.RFC3339),
|
|
UpdatedAt: now.Format(time.RFC3339),
|
|
Deadline: now.Add(5 * time.Minute).Format(time.RFC3339),
|
|
}
|
|
|
|
m.mu.Lock()
|
|
m.checkouts[checkoutID] = result
|
|
m.mu.Unlock()
|
|
|
|
// Copy the result before spawning the goroutine to avoid data races.
|
|
// The caller gets this copy; the goroutine modifies the map-stored original.
|
|
resultCopy := *result
|
|
|
|
if !m.HoldCheckouts {
|
|
go func() {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
log.Printf("Panic recovered in Square mock payment processing: %v", r)
|
|
}
|
|
}()
|
|
mockSleep(3 * time.Second)
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
payNow := clock.Now().UTC()
|
|
paymentID := fmt.Sprintf("pay_mock_%d", payNow.UnixNano())
|
|
amount := req.Amount
|
|
tipAmount := int64(0)
|
|
if req.TipEnabled {
|
|
tipAmount = 500
|
|
amount += tipAmount
|
|
}
|
|
fees := amount * 175 / 10000 // in-person rate: 1.75%
|
|
|
|
paymentResult := &PaymentResult{
|
|
ID: paymentID,
|
|
Status: "COMPLETED",
|
|
Amount: amount,
|
|
CardBrand: "VISA",
|
|
CardLast4: "4242",
|
|
CardFingerprint: fmt.Sprintf("sqfp_mock_%d", payNow.UnixNano()),
|
|
ExpMonth: 12,
|
|
ExpYear: 2030,
|
|
EntryMethod: "EMV",
|
|
CVVStatus: "CVV_ACCEPTED",
|
|
AVSStatus: "AVS_ACCEPTED",
|
|
TipAmount: tipAmount,
|
|
ReceiptURL: "https://squareup.com/receipt/" + paymentID,
|
|
ReceiptNumber: fmt.Sprintf("RCPT_mock_%d", payNow.UnixNano()),
|
|
SquarePayID: "sqp_" + paymentID,
|
|
Fees: fees,
|
|
CustomerID: req.CustomerID,
|
|
LocationID: "L_MOCK",
|
|
CreatedAt: payNow.Format(time.RFC3339),
|
|
UpdatedAt: payNow.Format(time.RFC3339),
|
|
ReferenceID: req.ReferenceID,
|
|
}
|
|
m.completed[checkoutID] = paymentResult
|
|
m.checkouts[checkoutID].Status = "COMPLETED"
|
|
m.checkouts[checkoutID].UpdatedAt = payNow.Format(time.RFC3339)
|
|
m.checkouts[checkoutID].PaymentIDs = []string{paymentID}
|
|
log.Printf("[SQUARE-MOCK] Checkout completed: id=%s, amount=%d, tip=%d", checkoutID, amount, tipAmount)
|
|
}()
|
|
}
|
|
|
|
return &resultCopy, nil
|
|
}
|
|
|
|
func (m *MockClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
|
|
log.Printf("[SQUARE-MOCK] GetCheckout: id=%s", checkoutID)
|
|
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
|
|
checkout, ok := m.checkouts[checkoutID]
|
|
if !ok {
|
|
return nil, fmt.Errorf("checkout not found: %s", checkoutID)
|
|
}
|
|
|
|
if checkout.Status == "PENDING" {
|
|
return nil, ErrCheckoutPending
|
|
}
|
|
|
|
result, ok := m.completed[checkoutID]
|
|
if !ok {
|
|
return nil, fmt.Errorf("checkout result not found: %s", checkoutID)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func (m *MockClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
|
|
if m.ShouldFail {
|
|
return nil, fmt.Errorf("mock: refund declined (simulated failure)")
|
|
}
|
|
log.Printf("[SQUARE-MOCK] RefundPayment: payment=%s, amount=%d", req.PaymentID, req.Amount)
|
|
mockSleep(1 * time.Second)
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
now := clock.Now().UTC()
|
|
refundID := fmt.Sprintf("ref_mock_%d", now.UnixNano())
|
|
|
|
payment, ok := m.payments[req.PaymentID]
|
|
if !ok {
|
|
// 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.
|
|
log.Printf("[SQUARE-MOCK] RefundPayment: payment %s not in mock map — proceeding without full payment data", req.PaymentID)
|
|
}
|
|
|
|
amount := req.Amount
|
|
if amount == 0 && ok {
|
|
amount = payment.Amount
|
|
}
|
|
|
|
locationID := req.LocationID
|
|
if locationID == "" {
|
|
locationID = "L_MOCK"
|
|
}
|
|
|
|
result := &RefundResult{
|
|
ID: refundID,
|
|
Status: "COMPLETED",
|
|
Amount: amount,
|
|
PaymentID: req.PaymentID,
|
|
LocationID: locationID,
|
|
Reason: req.Reason,
|
|
CreatedAt: now.Format(time.RFC3339),
|
|
}
|
|
m.refunds[refundID] = result
|
|
log.Printf("[SQUARE-MOCK] Refund completed: id=%s, payment=%s, amount=%d", refundID, req.PaymentID, amount)
|
|
return result, nil
|
|
}
|
|
|
|
func (m *MockClient) CreateCardOnFile(ctx context.Context, userID, cardToken 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
|
|
// ccof:xxx card ID). Raw PANs are rejected exactly as Square would, so the
|
|
// mock behaves identically to production.
|
|
if !isTokenLike(cardToken) {
|
|
return nil, fmt.Errorf("invalid source_id: %q — use a card nonce (cnon:xxx) or card ID (ccof:xxx)", cardToken)
|
|
}
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.cards[userID] == nil {
|
|
m.cards[userID] = make(map[string]*CardOnFile)
|
|
}
|
|
|
|
now := clock.Now().UTC()
|
|
cardID := fmt.Sprintf("mock_card_%d", now.UnixNano())
|
|
brand, last4 := detectCardInfo(cardToken)
|
|
card := &CardOnFile{
|
|
ID: cardID,
|
|
CardID: fmt.Sprintf("ccof_mock_%d", now.UnixNano()),
|
|
Brand: brand,
|
|
Last4: last4,
|
|
ExpMonth: 12,
|
|
ExpYear: 2030,
|
|
Fingerprint: fmt.Sprintf("sqfp_mock_%d", now.UnixNano()),
|
|
CardholderName: "John Doe",
|
|
CustomerID: userID,
|
|
Enabled: true,
|
|
IsDefault: len(m.cards[userID]) == 0,
|
|
Version: 1,
|
|
CreatedAt: now.Format(time.RFC3339),
|
|
}
|
|
m.cards[userID][cardID] = card
|
|
log.Printf("[SQUARE-MOCK] Card created: id=%s, brand=%s, last4=%s", cardID, card.Brand, card.Last4)
|
|
return card, nil
|
|
}
|
|
|
|
func (m *MockClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
|
|
log.Printf("[SQUARE-MOCK] GetCardsOnFile: user=%s", userID)
|
|
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
|
|
userCards, ok := m.cards[userID]
|
|
if !ok {
|
|
return []CardOnFile{}, nil
|
|
}
|
|
|
|
var cards []CardOnFile
|
|
for _, card := range userCards {
|
|
cards = append(cards, *card)
|
|
}
|
|
return cards, nil
|
|
}
|
|
|
|
func (m *MockClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
|
|
log.Printf("[SQUARE-MOCK] DeleteCardOnFile: id=%s", cardID)
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
for userID, cards := range m.cards {
|
|
if card, ok := cards[cardID]; ok {
|
|
card.Enabled = false
|
|
log.Printf("[SQUARE-MOCK] Card disabled: id=%s (user=%s)", cardID, userID)
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("card not found: %s", cardID)
|
|
}
|
|
|
|
// isTokenLike returns true for Square source_id tokens: cnon:xxx nonces and
|
|
// ccof:xxx card IDs. Raw PANs (all digits) are NOT token-like and are rejected.
|
|
func isTokenLike(s string) bool {
|
|
return strings.HasPrefix(s, "cnon:") || strings.HasPrefix(s, "ccof:")
|
|
}
|
|
|
|
func realBaseURL(env string) string {
|
|
if env == "production" {
|
|
return squareProductionURL
|
|
}
|
|
return squareSandboxURL
|
|
}
|