feat: Square payment integration, booking flow redesign, and timezone/weekday fixes

- Add Square payment integration (mock + handlers + UI): terminal/online payments,
  refunds, tips, saved cards, webhooks. Build-tagged dev/prod clients.
- Redesign booking flow: Step 4 conditional (deposit only), Step 5 confirmation
  screen with booking ID, auto-submit on transition.
- Redesign schedule modal: 2x3 button grid with Pay Deposit/Pay Early logic.
- Add deposit warning banner at Step 1 for users with outstanding deposits.
- Fix weekday conversion bug: Go 0=Sunday vs DB 0=Monday mismatch in 6 locations.
- Fix timezone bug: UTC vs London time in closing hours validation.
- Fix frontend error parsing: plain text backend errors now displayed correctly.
- Fix crypto.randomUUID fallback for environments without Web Crypto.
- Add 7 new regression tests: closing hours, advance check, active booking limit,
  weekday conversion, UTC/London, deposit snapshot, exceptional hours.
- Fix 3 flaky tests: dynamic dates instead of fixed, no-show timing.
This commit is contained in:
2026-05-23 11:29:34 +01:00
parent bcd5ed2bd9
commit 2e1ab9d745
31 changed files with 6155 additions and 229 deletions
+49
View File
@@ -0,0 +1,49 @@
//go:build !dev
// +build !dev
package square
import (
"context"
"errors"
)
var Client SquareClient
type ProdClient struct{}
func NewClient() SquareClient {
return NewProdClient()
}
func NewProdClient() SquareClient {
return &ProdClient{}
}
func (p *ProdClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
return nil, errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (p *ProdClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
return errors.New("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
+252
View File
@@ -0,0 +1,252 @@
//go:build dev
// +build dev
package square
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
)
var Client SquareClient
type MockClient struct {
mu sync.RWMutex
cards map[string]map[string]*CardOnFile
checkouts map[string]*CheckoutResult
payments map[string]*PaymentResult
refunds map[string]*RefundResult
completed map[string]*PaymentResult
}
type devProdClient struct{}
func (d *devProdClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error) {
return nil, fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func (d *devProdClient) DeleteCardOnFile(ctx context.Context, cardID string) error {
return fmt.Errorf("square payments not yet configured — set SQUARE_ACCESS_TOKEN and SQUARE_LOCATION_ID in .env")
}
func NewClient() SquareClient {
return NewDevClient()
}
func NewDevClient() SquareClient {
env := os.Getenv("SQUARE_ENVIRONMENT")
if env == "sandbox" || env == "production" {
log.Printf("[SQUARE-MOCK] SQUARE_ENVIRONMENT=%s — real client TODO stub", 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),
refunds: make(map[string]*RefundResult),
completed: make(map[string]*PaymentResult),
}
}
func (m *MockClient) CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error) {
log.Printf("[SQUARE-MOCK] CreatePayment: amount=%d, reference=%s", req.Amount, req.ReferenceID)
time.Sleep(1 * time.Second)
m.mu.Lock()
defer m.mu.Unlock()
paymentID := fmt.Sprintf("pay_mock_%d", time.Now().UnixNano())
fees := req.Amount*14/1000 + 25 // online rate: 1.4% + 25p
result := &PaymentResult{
ID: paymentID,
Status: "COMPLETED",
Amount: req.Amount,
CardBrand: "VISA",
CardLast4: "4242",
TipAmount: 0,
ReceiptURL: "https://squareup.com/receipt/" + paymentID,
SquarePayID: "sqp_" + paymentID,
Fees: fees,
}
m.payments[paymentID] = result
log.Printf("[SQUARE-MOCK] Payment completed: id=%s, fees=%d", paymentID, 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)
checkoutID := fmt.Sprintf("chk_mock_%d", time.Now().UnixNano())
result := &CheckoutResult{
ID: checkoutID,
Status: "PENDING",
}
m.mu.Lock()
m.checkouts[checkoutID] = result
m.mu.Unlock()
go func() {
time.Sleep(3 * time.Second)
m.mu.Lock()
defer m.mu.Unlock()
paymentID := fmt.Sprintf("pay_%d", time.Now().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",
TipAmount: tipAmount,
ReceiptURL: "https://squareup.com/receipt/" + paymentID,
SquarePayID: "sqp_" + paymentID,
Fees: fees,
}
m.completed[checkoutID] = paymentResult
m.checkouts[checkoutID].Status = "COMPLETED"
log.Printf("[SQUARE-MOCK] Checkout completed: id=%s, amount=%d, tip=%d", checkoutID, amount, tipAmount)
}()
return result, nil
}
func (m *MockClient) GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error) {
log.Printf("[SQUARE-MOCK] GetCheckout: id=%s", checkoutID)
m.mu.RLock()
checkout, ok := m.checkouts[checkoutID]
m.mu.RUnlock()
if !ok {
return nil, fmt.Errorf("checkout not found: %s", checkoutID)
}
if checkout.Status == "PENDING" {
return nil, fmt.Errorf("checkout pending")
}
m.mu.RLock()
result, ok := m.completed[checkoutID]
m.mu.RUnlock()
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) {
log.Printf("[SQUARE-MOCK] RefundPayment: payment=%s, amount=%d", req.PaymentID, req.Amount)
time.Sleep(1 * time.Second)
m.mu.Lock()
defer m.mu.Unlock()
refundID := fmt.Sprintf("ref_mock_%d", time.Now().UnixNano())
amount := req.Amount
if amount == 0 {
if payment, ok := m.payments[req.PaymentID]; ok {
amount = payment.Amount
}
}
result := &RefundResult{
ID: refundID,
Status: "COMPLETED",
Amount: amount,
}
m.refunds[refundID] = result
log.Printf("[SQUARE-MOCK] Refund completed: id=%s, amount=%d", refundID, amount)
return result, nil
}
func (m *MockClient) CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error) {
log.Printf("[SQUARE-MOCK] CreateCardOnFile: user=%s", userID)
m.mu.Lock()
defer m.mu.Unlock()
if m.cards[userID] == nil {
m.cards[userID] = make(map[string]*CardOnFile)
}
cardID := fmt.Sprintf("mock_card_%d", time.Now().UnixNano())
card := &CardOnFile{
ID: cardID,
CardID: "cfa_" + cardID,
Brand: "VISA",
Last4: "4242",
ExpMonth: 12,
ExpYear: 2030,
Fingerprint: fmt.Sprintf("fp_%d", time.Now().UnixNano()),
IsDefault: len(m.cards[userID]) == 0,
}
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 _, ok := cards[cardID]; ok {
delete(m.cards[userID], cardID)
log.Printf("[SQUARE-MOCK] Card deleted: id=%s (user=%s)", cardID, userID)
return nil
}
}
return fmt.Errorf("card not found: %s", cardID)
}
+353
View File
@@ -0,0 +1,353 @@
//go:build test && dev
// +build test,dev
package square
import (
"context"
"sync"
"testing"
"time"
)
func TestDevClient_CreatePayment_ReturnsCompleted(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
req := CreatePaymentReq{
Amount: 5000,
Currency: "GBP",
SourceID: "cnon:test-card",
IdempotencyKey: "test-key-1",
ReferenceID: "booking-123",
Note: "full",
}
result, err := client.CreatePayment(ctx, req)
if err != nil {
t.Fatalf("CreatePayment failed: %v", err)
}
if result.Status != "COMPLETED" {
t.Errorf("expected status COMPLETED, got %s", result.Status)
}
if result.Amount != 5000 {
t.Errorf("expected amount 5000, got %d", result.Amount)
}
if result.CardBrand != "VISA" {
t.Errorf("expected card brand VISA, got %s", result.CardBrand)
}
if result.CardLast4 != "4242" {
t.Errorf("expected last4 4242, got %s", result.CardLast4)
}
if result.Fees == 0 {
t.Error("expected fees to be calculated")
}
}
func TestDevClient_CreateCheckout_PendingThenCompleted(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
req := CreateCheckoutReq{
Amount: 7500,
Currency: "GBP",
IdempotencyKey: "checkout-key-1",
ReferenceID: "booking-456",
TipEnabled: true,
}
result, err := client.CreateCheckout(ctx, req)
if err != nil {
t.Fatalf("CreateCheckout failed: %v", err)
}
if result.Status != "PENDING" {
t.Errorf("expected status PENDING, got %s", result.Status)
}
if result.ID == "" {
t.Error("expected checkout ID to be set")
}
time.Sleep(4 * time.Second)
completed, err := client.GetCheckout(ctx, result.ID)
if err != nil {
t.Fatalf("GetCheckout failed: %v", err)
}
if completed.Status != "COMPLETED" {
t.Errorf("expected status COMPLETED after wait, got %s", completed.Status)
}
if completed.Amount != 8000 {
t.Errorf("expected amount 8000 (7500 + 500 tip), got %d", completed.Amount)
}
if completed.TipAmount != 500 {
t.Errorf("expected tip 500, got %d", completed.TipAmount)
}
}
func TestDevClient_CreateCheckout_NoTip(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
req := CreateCheckoutReq{
Amount: 5000,
Currency: "GBP",
IdempotencyKey: "checkout-key-notip",
ReferenceID: "booking-789",
TipEnabled: false,
}
result, err := client.CreateCheckout(ctx, req)
if err != nil {
t.Fatalf("CreateCheckout failed: %v", err)
}
if result.Status != "PENDING" {
t.Errorf("expected status PENDING, got %s", result.Status)
}
time.Sleep(4 * time.Second)
completed, err := client.GetCheckout(ctx, result.ID)
if err != nil {
t.Fatalf("GetCheckout failed: %v", err)
}
if completed.Amount != 5000 {
t.Errorf("expected amount 5000 (no tip), got %d", completed.Amount)
}
if completed.TipAmount != 0 {
t.Errorf("expected tip 0, got %d", completed.TipAmount)
}
}
func TestDevClient_RefundPayment_ReturnsCompleted(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
paymentReq := CreatePaymentReq{
Amount: 10000,
Currency: "GBP",
SourceID: "cnon:test-card",
IdempotencyKey: "payment-for-refund",
ReferenceID: "booking-refund",
Note: "full",
}
paymentResult, err := client.CreatePayment(ctx, paymentReq)
if err != nil {
t.Fatalf("CreatePayment failed: %v", err)
}
refundReq := RefundPaymentReq{
PaymentID: paymentResult.ID,
Amount: 5000,
IdempotencyKey: "refund-key-1",
Reason: "customer request",
}
refundResult, err := client.RefundPayment(ctx, refundReq)
if err != nil {
t.Fatalf("RefundPayment failed: %v", err)
}
if refundResult.Status != "COMPLETED" {
t.Errorf("expected status COMPLETED, got %s", refundResult.Status)
}
if refundResult.Amount != 5000 {
t.Errorf("expected amount 5000, got %d", refundResult.Amount)
}
}
func TestDevClient_CardOnFile_CreateAndGet(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
userID := "user-test-123"
card, err := client.CreateCardOnFile(ctx, userID, "cnon:test-token")
if err != nil {
t.Fatalf("CreateCardOnFile failed: %v", err)
}
if card.ID == "" {
t.Error("expected card ID to be set")
}
if card.Brand != "VISA" {
t.Errorf("expected brand VISA, got %s", card.Brand)
}
if card.Last4 != "4242" {
t.Errorf("expected last4 4242, got %s", card.Last4)
}
if !card.IsDefault {
t.Error("expected first card to be default")
}
cards, err := client.GetCardsOnFile(ctx, userID)
if err != nil {
t.Fatalf("GetCardsOnFile failed: %v", err)
}
if len(cards) != 1 {
t.Errorf("expected 1 card, got %d", len(cards))
}
if cards[0].ID != card.ID {
t.Errorf("expected card ID %s, got %s", card.ID, cards[0].ID)
}
}
func TestDevClient_CardOnFile_MultipleCards(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
userID := "user-test-multiple"
card1, err := client.CreateCardOnFile(ctx, userID, "cnon:token-1")
if err != nil {
t.Fatalf("CreateCardOnFile failed: %v", err)
}
card2, err := client.CreateCardOnFile(ctx, userID, "cnon:token-2")
if err != nil {
t.Fatalf("CreateCardOnFile failed: %v", err)
}
cards, err := client.GetCardsOnFile(ctx, userID)
if err != nil {
t.Fatalf("GetCardsOnFile failed: %v", err)
}
if len(cards) != 2 {
t.Errorf("expected 2 cards, got %d", len(cards))
}
if !card1.IsDefault {
t.Error("first card should be default")
}
if card2.IsDefault {
t.Error("second card should not be default")
}
}
func TestDevClient_CardOnFile_Delete(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
userID := "user-test-delete"
card, err := client.CreateCardOnFile(ctx, userID, "cnon:token-delete")
if err != nil {
t.Fatalf("CreateCardOnFile failed: %v", err)
}
err = client.DeleteCardOnFile(ctx, card.ID)
if err != nil {
t.Fatalf("DeleteCardOnFile failed: %v", err)
}
cards, err := client.GetCardsOnFile(ctx, userID)
if err != nil {
t.Fatalf("GetCardsOnFile failed: %v", err)
}
if len(cards) != 0 {
t.Errorf("expected 0 cards after delete, got %d", len(cards))
}
}
func TestDevClient_CardOnFile_DeleteNotFound(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
err := client.DeleteCardOnFile(ctx, "non-existent-card")
if err == nil {
t.Error("expected error when deleting non-existent card")
}
}
func TestDevClient_GetCheckout_NotFound(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
_, err := client.GetCheckout(ctx, "non-existent-checkout")
if err == nil {
t.Error("expected error when checkout not found")
}
}
func TestDevClient_ConcurrentPayments(t *testing.T) {
client := NewDevClient().(*MockClient)
ctx := context.Background()
var wg sync.WaitGroup
results := make(chan *PaymentResult, 10)
errors := make(chan error, 10)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
req := CreatePaymentReq{
Amount: int64(1000 + idx*100),
Currency: "GBP",
SourceID: "cnon:test-card",
IdempotencyKey: "concurrent-key-" + string(rune('0'+idx)),
ReferenceID: "booking-concurrent",
Note: "full",
}
result, err := client.CreatePayment(ctx, req)
if err != nil {
errors <- err
return
}
results <- result
}(i)
}
wg.Wait()
close(results)
close(errors)
errorCount := 0
for err := range errors {
t.Logf("Concurrent payment error: %v", err)
errorCount++
}
if errorCount > 0 {
t.Errorf("expected no errors, got %d", errorCount)
}
resultCount := 0
for result := range results {
if result.Status != "COMPLETED" {
t.Errorf("expected status COMPLETED, got %s", result.Status)
}
resultCount++
}
if resultCount != 10 {
t.Errorf("expected 10 results, got %d", resultCount)
}
}
+71
View File
@@ -0,0 +1,71 @@
package square
import "context"
type CreatePaymentReq struct {
Amount int64 // in pence (GBP cents)
Currency string // "GBP"
SourceID string // card token or "cnon:xxx" nonce
IdempotencyKey string
ReferenceID string // booking ID
Note string
}
type CreateCheckoutReq struct {
Amount int64
Currency string
IdempotencyKey string
ReferenceID string
TipEnabled bool
}
type RefundPaymentReq struct {
PaymentID string
Amount int64 // in pence, 0 = full refund
IdempotencyKey string
Reason string
}
type PaymentResult struct {
ID string
Status string // "COMPLETED", "FAILED", "PENDING"
Amount int64
CardBrand string
CardLast4 string
TipAmount int64
ReceiptURL string
SquarePayID string // Square's payment ID
Fees int64 // processing fee in pence
}
type CheckoutResult struct {
ID string
Status string // "PENDING", "COMPLETED", "FAILED"
}
type CardOnFile struct {
ID string
CardID string // Square's card-on-file token
Brand string
Last4 string
ExpMonth int
ExpYear int
Fingerprint string
IsDefault bool
}
type RefundResult struct {
ID string
Status string
Amount int64
}
type SquareClient interface {
CreatePayment(ctx context.Context, req CreatePaymentReq) (*PaymentResult, error)
CreateCheckout(ctx context.Context, req CreateCheckoutReq) (*CheckoutResult, error)
GetCheckout(ctx context.Context, checkoutID string) (*PaymentResult, error)
RefundPayment(ctx context.Context, req RefundPaymentReq) (*RefundResult, error)
CreateCardOnFile(ctx context.Context, userID, cardToken string) (*CardOnFile, error)
GetCardsOnFile(ctx context.Context, userID string) ([]CardOnFile, error)
DeleteCardOnFile(ctx context.Context, cardID string) error
}