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:
@@ -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)}`}
|
||||
|
||||
@@ -99,9 +99,56 @@
|
||||
let newCardNumber = $state('');
|
||||
let newCardExpiry = $state('');
|
||||
let newCardCVC = $state('');
|
||||
let cardNumberTouched = $state(false);
|
||||
let cardExpiryTouched = $state(false);
|
||||
let cardCVCTouched = $state(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 };
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const expiryParts = $derived(parseExpiryParts(newCardExpiry));
|
||||
|
||||
// Payment flow state
|
||||
let depositPaid = $state(false);
|
||||
|
||||
const cardError = $derived(
|
||||
cardNumberTouched && !isValidLuhn(newCardNumber) && newCardNumber.length > 0
|
||||
? 'Invalid card number'
|
||||
: cardExpiryTouched && expiryParts !== null && (() => { const d = new SvelteDate(expiryParts.year, expiryParts.month); return d < new SvelteDate(); })()
|
||||
? 'This card has expired'
|
||||
: cardExpiryTouched && !/^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardExpiry.length > 0
|
||||
? 'Enter expiry as MM/YY'
|
||||
: cardCVCTouched && newCardCVC.length < 3 && newCardCVC.length > 0
|
||||
? 'Enter your CVC number'
|
||||
: isValidLuhn(newCardNumber) && /^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardCVC.length >= 3
|
||||
? null
|
||||
: newCardNumber.length === 0 && newCardExpiry.length === 0 && newCardCVC.length === 0
|
||||
? null
|
||||
: 'Please complete all card fields'
|
||||
);
|
||||
|
||||
const depositCardFormValid = $derived(
|
||||
selectedPaymentMethod !== null ||
|
||||
(showNewCardForm &&
|
||||
@@ -269,6 +316,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
function handleFieldBlur(field: string) {
|
||||
if (field === 'cardNumber') cardNumberTouched = true;
|
||||
else if (field === 'cardExpiry') cardExpiryTouched = true;
|
||||
else if (field === 'cardCVC') cardCVCTouched = true;
|
||||
}
|
||||
|
||||
function handleFieldInput(field: string) {
|
||||
if (field === 'cardNumber') cardNumberTouched = false;
|
||||
else if (field === 'cardExpiry') cardExpiryTouched = false;
|
||||
else if (field === 'cardCVC') cardCVCTouched = false;
|
||||
}
|
||||
|
||||
async function processPayment(amount: number) {
|
||||
// Synchronous double-click guard — set BEFORE any await so a rapid second
|
||||
// click is rejected immediately, even before the reactive `disabled` has
|
||||
@@ -2315,7 +2374,12 @@
|
||||
bind:cardExpiry={newCardExpiry}
|
||||
bind:cardCVC={newCardCVC}
|
||||
disabled={isProcessingPayment}
|
||||
onfieldblur={handleFieldBlur}
|
||||
onfieldinput={handleFieldInput}
|
||||
/>
|
||||
{#if cardError}
|
||||
<p class="mt-2 text-sm text-red-600">{cardError}</p>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<div class="flex items-center justify-between border-t pt-4">
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
let { brand = '' }: { brand?: string } = $props();
|
||||
|
||||
const brandSvgs: Record<string, string> = {
|
||||
VISA: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#1A1F71"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="11">VISA</text></svg>`,
|
||||
|
||||
MASTERCARD: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#222"/><circle cx="26" cy="12" r="7" fill="#EB001B" opacity="0.9"/><circle cx="34" cy="12" r="7" fill="#F79E1B" opacity="0.9"/></svg>`,
|
||||
|
||||
AMERICAN_EXPRESS: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#016FD0"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="8">AMEX</text></svg>`,
|
||||
|
||||
DISCOVER: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#000"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="7.5">DISCOVER</text></svg>`,
|
||||
|
||||
DINERS_CLUB: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#004A98"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="9">DC</text></svg>`,
|
||||
|
||||
JCB: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#0D4A2E"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="10">JCB</text></svg>`,
|
||||
|
||||
SQUARE_GIFT_CARD: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#E8F5E9"/><rect x="1" y="1" width="58" height="22" rx="2" stroke="#4CAF50" stroke-width="0.5" stroke-dasharray="2 1"/><text x="30" y="16" text-anchor="middle" fill="#2E7D32" font-family="Arial, sans-serif" font-weight="bold" font-size="7">GIFT</text></svg>`,
|
||||
|
||||
CHINA_UNION_PAY: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#D7001E"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="7.5">UNION</text></svg>`,
|
||||
|
||||
UNIONPAY: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#D7001E"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="7.5">UNION</text></svg>`,
|
||||
|
||||
INTERAC: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#074CA1"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="8">INTERAC</text></svg>`,
|
||||
|
||||
EFTPOS: `<svg viewBox="0 0 60 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="24" rx="3" fill="#1A237E"/><text x="30" y="16" text-anchor="middle" fill="white" font-family="Arial, sans-serif" font-weight="bold" font-size="7.5">EFTPOS</text></svg>`
|
||||
};
|
||||
|
||||
const normalizedBrand = $derived(brand.toUpperCase());
|
||||
const normalizedSvg = $derived(brandSvgs[normalizedBrand] ?? '');
|
||||
const showSvg = $derived(normalizedSvg !== '' && normalizedBrand.length >= 3);
|
||||
</script>
|
||||
|
||||
{#if showSvg}
|
||||
<div class="flex h-8 min-w-12 items-center justify-center rounded" role="img" aria-label={brand}>{@html normalizedSvg}</div>
|
||||
{:else}
|
||||
<div class="flex h-8 min-w-12 items-center justify-center rounded bg-gray-100 px-2 text-xs font-medium text-gray-700 uppercase" role="img" aria-label={brand}>
|
||||
{brand}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -9,7 +9,9 @@
|
||||
cardCVC = $bindable(''),
|
||||
saveCard = $bindable(false),
|
||||
showSaveCard = false,
|
||||
disabled = false
|
||||
disabled = false,
|
||||
onfieldblur = (_field: string) => {},
|
||||
onfieldinput = (_field: string) => {}
|
||||
}: {
|
||||
cardNumber?: string;
|
||||
cardExpiry?: string;
|
||||
@@ -17,6 +19,8 @@
|
||||
saveCard?: boolean;
|
||||
showSaveCard?: boolean;
|
||||
disabled?: boolean;
|
||||
onfieldblur?: (field: string) => void;
|
||||
onfieldinput?: (field: string) => void;
|
||||
} = $props();
|
||||
|
||||
function formatNumber(value: string): string {
|
||||
@@ -44,7 +48,11 @@
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
value={cardNumber}
|
||||
oninput={(e) => (cardNumber = formatNumber((e.target as HTMLInputElement).value))}
|
||||
oninput={(e) => {
|
||||
cardNumber = formatNumber((e.target as HTMLInputElement).value);
|
||||
onfieldinput('cardNumber');
|
||||
}}
|
||||
onblur={() => onfieldblur('cardNumber')}
|
||||
placeholder="1234 5678 9012 3456"
|
||||
maxlength={19}
|
||||
{disabled}
|
||||
@@ -58,7 +66,11 @@
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
value={cardExpiry}
|
||||
oninput={(e) => (cardExpiry = formatExpiry((e.target as HTMLInputElement).value))}
|
||||
oninput={(e) => {
|
||||
cardExpiry = formatExpiry((e.target as HTMLInputElement).value);
|
||||
onfieldinput('cardExpiry');
|
||||
}}
|
||||
onblur={() => onfieldblur('cardExpiry')}
|
||||
placeholder="MM/YY"
|
||||
maxlength={5}
|
||||
{disabled}
|
||||
@@ -71,6 +83,8 @@
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
bind:value={cardCVC}
|
||||
oninput={() => onfieldinput('cardCVC')}
|
||||
onblur={() => onfieldblur('cardCVC')}
|
||||
placeholder="123"
|
||||
maxlength={4}
|
||||
{disabled}
|
||||
|
||||
@@ -61,6 +61,9 @@
|
||||
let newCardExpiry = $state('');
|
||||
let newCardCVC = $state('');
|
||||
let saveCardForFuture = $state(false);
|
||||
let cardNumberTouched = $state(false);
|
||||
let cardExpiryTouched = $state(false);
|
||||
let cardCVCTouched = $state(false);
|
||||
|
||||
function parseExpiryParts(value: string): { month: number; year: number } | null {
|
||||
if (!/^\d{2}\/\d{2}$/.test(value)) return null;
|
||||
@@ -99,6 +102,18 @@
|
||||
return sum % 10 === 0 && s.length >= 13 && s.length <= 19;
|
||||
}
|
||||
|
||||
function handleFieldBlur(field: string) {
|
||||
if (field === 'cardNumber') cardNumberTouched = true;
|
||||
else if (field === 'cardExpiry') cardExpiryTouched = true;
|
||||
else if (field === 'cardCVC') cardCVCTouched = true;
|
||||
}
|
||||
|
||||
function handleFieldInput(field: string) {
|
||||
if (field === 'cardNumber') cardNumberTouched = false;
|
||||
else if (field === 'cardExpiry') cardExpiryTouched = false;
|
||||
else if (field === 'cardCVC') cardCVCTouched = false;
|
||||
}
|
||||
|
||||
const cardFormValid = $derived(
|
||||
isValidLuhn(newCardNumber) && expiryParts !== null && newCardCVC.length >= 3 && !isExpiryInPast
|
||||
);
|
||||
@@ -113,19 +128,21 @@
|
||||
!cardSelected
|
||||
? selectedPaymentMethod === null && paymentMethods.length > 0 && !showNewCardForm
|
||||
? 'Please select a card'
|
||||
: !isValidLuhn(newCardNumber) && newCardNumber.length > 0
|
||||
: cardNumberTouched && !isValidLuhn(newCardNumber) && newCardNumber.length > 0
|
||||
? 'Invalid card number'
|
||||
: hasInvalidMonth
|
||||
: cardExpiryTouched && hasInvalidMonth
|
||||
? 'Invalid expiry month'
|
||||
: isExpiryInPast
|
||||
: cardExpiryTouched && isExpiryInPast
|
||||
? 'Expiry date in the past'
|
||||
: !/^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardExpiry.length > 0
|
||||
: cardExpiryTouched && !/^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardExpiry.length > 0
|
||||
? 'Enter expiry as MM/YY'
|
||||
: newCardCVC.length < 3 && newCardCVC.length > 0
|
||||
: cardCVCTouched && newCardCVC.length < 3 && newCardCVC.length > 0
|
||||
? 'Enter your CVC number'
|
||||
: paymentMethods.length === 0 && !showNewCardForm && newCardNumber.length === 0
|
||||
? 'Please enter card details'
|
||||
: 'Please complete all card fields'
|
||||
: isValidLuhn(newCardNumber) && /^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardCVC.length >= 3
|
||||
? null
|
||||
: newCardNumber.length === 0 && newCardExpiry.length === 0 && newCardCVC.length === 0
|
||||
? null
|
||||
: 'Please complete all card fields'
|
||||
: null
|
||||
);
|
||||
|
||||
@@ -842,6 +859,8 @@
|
||||
bind:saveCard={saveCardForFuture}
|
||||
showSaveCard={canSaveCards}
|
||||
disabled={false}
|
||||
onfieldblur={handleFieldBlur}
|
||||
onfieldinput={handleFieldInput}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user