Square payment integration: real HTTP client, tip flow rewrite, card UI/validation overhaul

Backend:
- Create square_http_client.go: real Square REST API client (Payments, Terminal Checkouts, Refunds, Cards, Locations) with proper JSON types, auth, error handling
- Update ProdClient in square.go to delegate to shared HTTP functions
- Wire devProdClient in square_dev.go to also make real HTTP calls for sandbox/prod env
- Rewrite CreateTipPayment handler: accept card_id OR new_card_token (+save_card), advisory lock, idempotency check, max amount validation
- Add ValidateCardInfo, bump ValidateAmount max to £10,000
- Fix mock CreateCardOnFile to detect brand/last4 from raw card numbers
- Fix mock RefundPayment to index by SquarePayID and accept unknown payment IDs
- Remove dead types (ProcessingFee, sqAddress), add Deadline parity
- Fix AMEX brand inconsistency (AMEX -> AMERICAN_EXPRESS)
- Pre-existing fix: remove unused context import in giftcards.go

Frontend:
- CardInput.svelte: add onfieldblur/onfieldinput callbacks for blur-based validation
- CardBrandIcon.svelte: brand SVGs for VISA, MC, AMEX, Discover, Diners, JCB, Square Gift Card, UnionPay, Interac, EFTPOS
- tip/+page, pay-tip/[id], UserBookingModal tip: saved card list + CardInput + Luhn/expiry/CVC validation + blur-based errors + no-saved-cards edge case
- UserPaymentModal, BookingFlow: card validation parity (blur-based, all-valid check)
- account page: replace text brand badges with CardBrandIcon
- Fix handleCustomTip bug (state mutations outside if block)
- Remove dead pageState variable
- Add tip modal scroll (max-h-[90vh] overflow-y-auto)
- Submit button disabled on !isCardValid

Tests:
- 30 square package tests (+new: CreateCardOnFile raw number path, detectCardInfo variants)
- 5 tip handler tests (HappyPath, NoPriorPayment, WrongOwner, MultipleTips, TxFailure)
- All +-race clean, refund tests fixed
This commit is contained in:
2026-08-22 00:34:49 +01:00
parent f6caaab8a3
commit 4abcb324c9
17 changed files with 2171 additions and 358 deletions
@@ -15,6 +15,9 @@
import { computeBalanceDue } from '$lib/utils/booking';
import { parseWallClockDate } from '$lib/utils/timeSlots';
import type { Booking, BookingDiscount, Payment } from '$lib/types/booking';
import CardInput from '$lib/components/payments/CardInput.svelte';
import CardBrandIcon from '$lib/components/payments/CardBrandIcon.svelte';
import { savedCardsStore, type SavedCard } from '$lib/stores/savedCards.svelte';
interface Props {
open: boolean;
bookingId: string;
@@ -135,10 +138,101 @@
let customTipInput = $state('');
let tipProcessing = $state(false);
// Card selection state for tips
let tipSavedCards = $state<SavedCard[]>([]);
let tipLoadingCards = $state(false);
let tipSelectedCardId = $state<string | null>(null);
let tipShowNewCard = $state(false);
// New card form state for tips
let tipNewCardNumber = $state('');
let tipNewCardExpiry = $state('');
let tipNewCardCVC = $state('');
let tipSaveCardFuture = $state(false);
let tipCardNumberTouched = $state(false);
let tipCardExpiryTouched = $state(false);
let tipCVCTouched = $state(false);
const canSaveCards = $derived(
authStore.currentUser?.role === 'verified_email' || authStore.currentUser?.role === 'affiliate'
);
// Card validation (matching UserPaymentModal pattern)
function isValidLuhn(cardNumber: string): boolean {
const s = cardNumber.replace(/\D/g, '');
let sum = 0;
let alternate = false;
for (let i = s.length - 1; i >= 0; i--) {
let n = parseInt(s[i], 10);
if (alternate) {
n *= 2;
if (n > 9) n -= 9;
}
sum += n;
alternate = !alternate;
}
return sum % 10 === 0 && s.length >= 13 && s.length <= 19;
}
function handleTipFieldBlur(field: string) {
if (field === 'cardNumber') tipCardNumberTouched = true;
else if (field === 'cardExpiry') tipCardExpiryTouched = true;
else if (field === 'cardCVC') tipCVCTouched = true;
}
function handleTipFieldInput(field: string) {
if (field === 'cardNumber') tipCardNumberTouched = false;
else if (field === 'cardExpiry') tipCardExpiryTouched = false;
else if (field === 'cardCVC') tipCVCTouched = false;
}
function parseExpiryParts(value: string): { month: number; year: number } | null {
if (!/^\d{2}\/\d{2}$/.test(value)) return null;
const [monthStr, yearStr] = value.split('/');
const month = parseInt(monthStr, 10);
const year = 2000 + parseInt(yearStr, 10);
if (month < 1 || month > 12) return null;
return { month, year };
}
const tipNewCardExpiryParts = $derived(parseExpiryParts(tipNewCardExpiry));
const isTipNewCardExpiryPast = $derived(
tipNewCardExpiryParts !== null &&
(() => {
const expiryDate = new SvelteDate(tipNewCardExpiryParts.year, tipNewCardExpiryParts.month);
return expiryDate < new SvelteDate();
})()
);
const hasTipNewCardInvalidMonth = $derived(/^\d{2}\/\d{2}$/.test(tipNewCardExpiry) && tipNewCardExpiryParts === null);
const tipNewCardError = $derived(
tipShowNewCard || tipSavedCards.length === 0
? tipCardNumberTouched && !isValidLuhn(tipNewCardNumber) && tipNewCardNumber.length > 0
? 'Invalid card number'
: tipCardExpiryTouched && hasTipNewCardInvalidMonth
? 'Invalid expiry month'
: tipCardExpiryTouched && isTipNewCardExpiryPast
? 'This card has expired'
: tipCardExpiryTouched && tipNewCardExpiry.length > 0 && !/^\d{2}\/\d{2}$/.test(tipNewCardExpiry)
? 'Enter expiry as MM/YY'
: tipCVCTouched && tipNewCardCVC.length < 3 && tipNewCardCVC.length > 0
? 'Enter your CVC number'
: isValidLuhn(tipNewCardNumber) && /^\d{2}\/\d{2}$/.test(tipNewCardExpiry) && tipNewCardCVC.length >= 3
? null
: tipNewCardNumber.length === 0 && tipNewCardExpiry.length === 0 && tipNewCardCVC.length === 0
? null
: 'Please complete all card fields'
: null
);
const isTipCardValid = $derived(
tipSelectedCardId !== null ||
(isValidLuhn(tipNewCardNumber) &&
tipNewCardExpiryParts !== null &&
!isTipNewCardExpiryPast &&
tipNewCardCVC.length >= 3)
);
const tipPresets = $derived(
selectedBooking
? [
@@ -169,9 +263,31 @@
}
if (/^\d+(\.\d{0,2})?$/.test(sanitized) || sanitized === '') {
customTipInput = sanitized;
selectedTipPreset = null;
tipAmount = parseFloat(sanitized) || 0;
}
}
async function loadTipSavedCards() {
if (savedCardsStore.loaded) {
tipSavedCards = savedCardsStore.cards;
if (tipSavedCards.length > 0 && !tipSelectedCardId) {
tipSelectedCardId = tipSavedCards.find((c) => c.is_default)?.id || tipSavedCards[0].id;
}
return;
}
tipLoadingCards = true;
try {
await savedCardsStore.fetch();
tipSavedCards = savedCardsStore.cards;
if (tipSavedCards.length > 0 && !tipSelectedCardId) {
tipSelectedCardId = tipSavedCards.find((c) => c.is_default)?.id || tipSavedCards[0].id;
}
} catch {
// ignore
} finally {
tipLoadingCards = false;
}
selectedTipPreset = null;
tipAmount = parseFloat(customTipInput) || 0;
}
async function submitTip() {
@@ -180,15 +296,43 @@
toast.error('Please select a tip amount');
return;
}
if (tipSavedCards.length > 0 && !tipSelectedCardId && !tipShowNewCard) {
toast.error('Please select a payment method');
return;
}
if ((tipShowNewCard || tipSavedCards.length === 0) && !tipNewCardNumber.replace(/\s/g, '')) {
toast.error('Please enter your card number');
return;
}
tipProcessing = true;
// Validate card details for new card payments
if (tipShowNewCard || tipSavedCards.length === 0) {
if (!isValidLuhn(tipNewCardNumber) || !/^\d{2}\/\d{2}$/.test(tipNewCardExpiry) || isTipNewCardExpiryPast || tipNewCardCVC.length < 3) {
tipProcessing = false;
toast.error(tipNewCardError || 'Please enter valid credit card details');
return;
}
}
try {
const body: Record<string, unknown> = { amount: Math.round(tipAmount * 100) };
if (tipShowNewCard || tipSavedCards.length === 0) {
body.new_card_token = tipNewCardNumber.replace(/\s/g, '');
body.card_expiry = tipNewCardExpiry;
body.card_cvc = tipNewCardCVC;
body.save_card = tipSaveCardFuture;
} else {
body.card_id = tipSelectedCardId;
}
const response = await apiFetch(`/api/bookings/${selectedBooking.id}/tip`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: Math.round(tipAmount * 100),
card_token: 'placeholder'
})
body: JSON.stringify(body)
});
if (!response.ok) {
const errorText = await response.text();
@@ -258,6 +402,12 @@
}
});
$effect(() => {
if (showTipModal) {
loadTipSavedCards();
}
});
function printReceipt() {
if (!selectedBooking) {
toast.error('No booking data to print');
@@ -1026,7 +1176,7 @@ ${hasVAT ? `<p class="warning">VAT is included at ${biz?.default_vat_rate ?? 20}
}
}}
>
<Modal.Content class="!z-[70] max-w-[calc(100%-2rem)]">
<Modal.Content class="!z-[70] max-w-[calc(100%-2rem)] max-h-[90vh] overflow-y-auto">
<Modal.Header>
<Modal.Title>Leave a Tip</Modal.Title>
<Modal.Description>Show your appreciation for great service</Modal.Description>
@@ -1068,6 +1218,87 @@ ${hasVAT ? `<p class="warning">VAT is included at ${biz?.default_vat_rate ?? 20}
/>
</div>
</div>
<!-- Card Selection for Tip -->
<div class="space-y-3">
<span class="block text-xs font-semibold tracking-wider text-gray-500 uppercase">Payment Method</span>
{#if tipLoadingCards}
<div class="py-2 text-center text-sm text-gray-500">Loading payment methods...</div>
{:else if tipSavedCards.length > 0}
<div class="space-y-2">
{#each tipSavedCards as card (card.id)}
<button
type="button"
class="flex w-full items-center justify-between rounded-lg border p-3 text-left {tipSelectedCardId === card.id && !tipShowNewCard ? 'border-input bg-accent' : 'border-gray-200 hover:bg-gray-50'}"
onclick={() => { tipSelectedCardId = card.id; tipShowNewCard = false; }}
>
<div class="flex items-center gap-3">
<CardBrandIcon brand={card.brand} />
<div class="text-sm">
<span class="font-mono">**** {card.last_4}</span>
<span class="ml-2 text-xs text-gray-400"
>Exp {String(card.exp_month).padStart(2, '0')}/{card.exp_year}</span
>
</div>
</div>
{#if tipSelectedCardId === card.id && !tipShowNewCard}
<span class="text-xs font-semibold text-primary">Selected</span>
{/if}
</button>
{/each}
<button
type="button"
class="flex w-full items-center justify-between rounded-lg border p-3 text-left {tipShowNewCard ? 'border-input bg-accent' : 'border-gray-200 hover:bg-gray-50'}"
onclick={() => { tipSelectedCardId = null; tipShowNewCard = true; }}
>
<div class="flex items-center gap-3">
<div
class="flex h-8 min-w-12 items-center justify-center rounded border border-dashed border-gray-300 text-xs font-medium text-gray-400"
>
NEW
</div>
<span class="animate-pulse text-sm font-medium text-gray-700">Use a new card</span>
</div>
{#if tipShowNewCard}
<span class="text-xs font-semibold text-primary">Selected</span>
{/if}
</button>
</div>
{#if tipShowNewCard}
<div class="space-y-3 rounded-lg border bg-gray-50 p-3">
<CardInput
bind:cardNumber={tipNewCardNumber}
bind:cardExpiry={tipNewCardExpiry}
bind:cardCVC={tipNewCardCVC}
bind:saveCard={tipSaveCardFuture}
showSaveCard={canSaveCards}
onfieldblur={handleTipFieldBlur}
onfieldinput={handleTipFieldInput}
/>
{#if tipNewCardError}
<div class="mt-1 text-xs font-semibold text-red-500">{tipNewCardError}</div>
{/if}
</div>
{/if}
{:else}
<div class="space-y-3 rounded-lg border bg-gray-50 p-3">
<CardInput
bind:cardNumber={tipNewCardNumber}
bind:cardExpiry={tipNewCardExpiry}
bind:cardCVC={tipNewCardCVC}
bind:saveCard={tipSaveCardFuture}
showSaveCard={canSaveCards}
onfieldblur={handleTipFieldBlur}
onfieldinput={handleTipFieldInput}
/>
{#if tipNewCardError}
<div class="mt-1 text-xs font-semibold text-red-500">{tipNewCardError}</div>
{/if}
</div>
{/if}
</div>
</div>
<Modal.Footer>
@@ -1075,7 +1306,7 @@ ${hasVAT ? `<p class="warning">VAT is included at ${biz?.default_vat_rate ?? 20}
<Button
class="hover:bg-fuchsia-50"
onclick={submitTip}
disabled={tipAmount <= 0 || tipProcessing}
disabled={tipAmount <= 0 || !isTipCardValid || tipProcessing}
loading={tipProcessing}
>
{tipProcessing ? 'Processing...' : `Pay Tip £${tipAmount.toFixed(2)}`}