refactor: booking flow wizard with step indicator improvements

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-05-29 16:07:02 +01:00
co-authored by Sisyphus
parent aa75217898
commit 0b3d26914b
2 changed files with 102 additions and 39 deletions
@@ -12,6 +12,7 @@
// Cloudflare geo-blocking prevents non-UK access. BST/GMT transitions are handled manually by // Cloudflare geo-blocking prevents non-UK access. BST/GMT transitions are handled manually by
// staff adjusting working hours; the app does not need timezone-aware scheduling logic. // staff adjusting working hours; the app does not need timezone-aware scheduling logic.
import { CalendarDate, getLocalTimeZone, type DateValue } from '@internationalized/date'; import { CalendarDate, getLocalTimeZone, type DateValue } from '@internationalized/date';
import { goto } from '$app/navigation';
import { authStore } from '$lib/stores/auth.svelte'; import { authStore } from '$lib/stores/auth.svelte';
import { toast } from 'svelte-sonner'; import { toast } from 'svelte-sonner';
import { SvelteDate } from 'svelte/reactivity'; import { SvelteDate } from 'svelte/reactivity';
@@ -40,7 +41,7 @@
} from '$lib/types/booking'; } from '$lib/types/booking';
// =============== State Management =============== // =============== State Management ===============
let currentStep = $state<number>(1); let currentStep = $state<number>(authStore.isAuthenticated ? 1 : 0);
let selectedServices = $state<Service[]>([]); let selectedServices = $state<Service[]>([]);
let selectedDate = $state<CalendarDate | undefined>(undefined); let selectedDate = $state<CalendarDate | undefined>(undefined);
let selectedTime = $state<string | null>(null); let selectedTime = $state<string | null>(null);
@@ -78,7 +79,10 @@
let depositCardFormValid = $derived( let depositCardFormValid = $derived(
selectedPaymentMethod !== null || selectedPaymentMethod !== null ||
(showNewCardForm && newCardNumber.replace(/\s/g, '').length >= 13 && /^\d{2}\/\d{2}$/.test(newCardExpiry) && newCardCVC.length >= 3) (showNewCardForm &&
newCardNumber.replace(/\s/g, '').length >= 13 &&
/^\d{2}\/\d{2}$/.test(newCardExpiry) &&
newCardCVC.length >= 3)
); );
// Confirmation state // Confirmation state
@@ -188,7 +192,7 @@
const appointmentDate = selectedDate.toDate(getLocalTimeZone()); const appointmentDate = selectedDate.toDate(getLocalTimeZone());
appointmentDate.setHours(hours, minutes, 0, 0); appointmentDate.setHours(hours, minutes, 0, 0);
const now = new Date(); const now = new SvelteDate();
const hoursUntilAppointment = (appointmentDate.getTime() - now.getTime()) / (1000 * 60 * 60); const hoursUntilAppointment = (appointmentDate.getTime() - now.getTime()) / (1000 * 60 * 60);
return userDepositsRequired > 0 && hoursUntilAppointment <= 24; return userDepositsRequired > 0 && hoursUntilAppointment <= 24;
@@ -464,8 +468,14 @@
} }
const key = `${mYear}-${String(mMonth).padStart(2, '0')}`; const key = `${mYear}-${String(mMonth).padStart(2, '0')}`;
if (!(key in workingHoursCache)) { if (!(key in workingHoursCache)) {
workingHoursCache[key] = null as unknown as Record<string, { isOpen: boolean; startTime: string; endTime: string }>; workingHoursCache[key] = null as unknown as Record<
availableHoursCache[key] = null as unknown as Record<string, { isOpen: boolean; slots: Array<{ startTime: string; endTime: string }> }>; string,
{ isOpen: boolean; startTime: string; endTime: string }
>;
availableHoursCache[key] = null as unknown as Record<
string,
{ isOpen: boolean; slots: Array<{ startTime: string; endTime: string }> }
>;
loadingMonths[key] = true; loadingMonths[key] = true;
} }
} }
@@ -485,7 +495,14 @@
// Data-driven auto-selection: auto-select the first available date when data loads // Data-driven auto-selection: auto-select the first available date when data loads
$effect(() => { $effect(() => {
if (workingHours && availableHours && !selectedDate && selectedServices.length > 0 && !userNavigatedCalendar && !bookingFlowAutoSelectDone) { if (
workingHours &&
availableHours &&
!selectedDate &&
selectedServices.length > 0 &&
!userNavigatedCalendar &&
!bookingFlowAutoSelectDone
) {
bookingFlowAutoSelectDone = true; bookingFlowAutoSelectDone = true;
const currentDate = new SvelteDate(); const currentDate = new SvelteDate();
@@ -514,11 +531,7 @@
if (!isDateUnavailable(calDate)) { if (!isDateUnavailable(calDate)) {
selectedDate = calDate; selectedDate = calDate;
if (!userNavigatedCalendar) { if (!userNavigatedCalendar) {
placeholder = new CalendarDate( placeholder = new CalendarDate(nextDate.getFullYear(), nextDate.getMonth() + 1, 1);
nextDate.getFullYear(),
nextDate.getMonth() + 1,
1
);
} }
return; return;
} }
@@ -572,7 +585,10 @@
whMap[d.date] = { isOpen: d.isOpen, startTime: d.startTime, endTime: d.endTime }; whMap[d.date] = { isOpen: d.isOpen, startTime: d.startTime, endTime: d.endTime };
}); });
const ahMap: Record<string, { isOpen: boolean; slots: Array<{ startTime: string; endTime: string }> }> = {}; const ahMap: Record<
string,
{ isOpen: boolean; slots: Array<{ startTime: string; endTime: string }> }
> = {};
ahData.forEach((d) => { ahData.forEach((d) => {
ahMap[d.date] = { isOpen: d.isOpen, slots: d.slots }; ahMap[d.date] = { isOpen: d.isOpen, slots: d.slots };
}); });
@@ -789,7 +805,10 @@
function generateGroupedTimeSlots( function generateGroupedTimeSlots(
duration: number, duration: number,
date: CalendarDate | undefined, date: CalendarDate | undefined,
lunchProtectionMap: Map<string, { isBlocked: boolean; showWarning: boolean; warningMessage?: string }> = new Map() lunchProtectionMap: Map<
string,
{ isBlocked: boolean; showWarning: boolean; warningMessage?: string }
> = new Map()
): Array<{ ): Array<{
type: 'available' | 'unavailable'; type: 'available' | 'unavailable';
startTime: string; startTime: string;
@@ -1107,13 +1126,23 @@
let depositRequired = $derived(calculateDepositRequired()); let depositRequired = $derived(calculateDepositRequired());
let totalSteps = $derived(depositRequired ? 5 : 4); let totalSteps = $derived(depositRequired ? 5 : 4);
let stepLabels = $derived( let stepLabels = $derived(
depositRequired authStore.isAuthenticated
? depositRequired
? ['Service', 'Date & Time', 'Details', 'Payment', 'Confirmation'] ? ['Service', 'Date & Time', 'Details', 'Payment', 'Confirmation']
: ['Service', 'Date & Time', 'Details', 'Confirmation'] : ['Service', 'Date & Time', 'Details', 'Confirmation']
: ['Welcome', 'Service', 'Date & Time', 'Details', 'Payment', 'Confirmation']
); );
// =============== Navigation =============== // =============== Navigation ===============
async function nextStep() { async function nextStep() {
if (currentStep === 0) {
currentStep = 1;
setTimeout(() => {
window.scrollTo({ top: 0, behavior: 'smooth' });
}, 50);
return;
}
// Step 2 -> Step 3: Re-validate slot, then reserve // Step 2 -> Step 3: Re-validate slot, then reserve
if (currentStep === 2) { if (currentStep === 2) {
const slotStillFree = await refreshAndValidateSlot(); const slotStillFree = await refreshAndValidateSlot();
@@ -1329,10 +1358,29 @@
<p class="text-gray-600">Professional beauty treatments in a calm and friendly environment</p> <p class="text-gray-600">Professional beauty treatments in a calm and friendly environment</p>
</div> </div>
<StepIndicator <StepIndicator {currentStep} steps={stepLabels} startAt={authStore.isAuthenticated ? 1 : 0} className="{currentStep === 0 ? 'md:hidden' : ''}" />
{currentStep}
steps={stepLabels} {#if currentStep === 0}
/> <Card.Root class="border-fuchsia-200 bg-fuchsia-50">
<Card.Header class="text-center">
<Card.Title>Welcome</Card.Title>
<Card.Description>Log in for the best booking experience</Card.Description>
</Card.Header>
<Card.Content class="p-6 text-center">
<p class="mb-4 text-sm text-muted-foreground">
Guest checkout does not receive loyalty stamps or seasonal discounts.
</p>
<div class="flex flex-col gap-3 sm:flex-row sm:justify-center sm:gap-4">
<Button onclick={() => goto('/login')} variant="outline" class="border-fuchsia-200 hover:bg-fuchsia-100">
Log In
</Button>
<Button onclick={nextStep}>
Continue as Guest
</Button>
</div>
</Card.Content>
</Card.Root>
{/if}
<!-- Step 1: Service Selection --> <!-- Step 1: Service Selection -->
{#if currentStep === 1} {#if currentStep === 1}
@@ -1419,7 +1467,7 @@
</Card.Content> </Card.Content>
<Card.Footer class="flex justify-end"> <Card.Footer class="flex justify-end">
<BookingActions <BookingActions
canBack={false} canBack={!authStore.isAuthenticated}
canNext={canProceedStep1} canNext={canProceedStep1}
nextLabel="Next: Select Date & Time" nextLabel="Next: Select Date & Time"
on:next={nextStep} on:next={nextStep}
@@ -1554,8 +1602,8 @@
{#if !authStore.isAuthenticated} {#if !authStore.isAuthenticated}
<p class="mb-4 text-center text-sm text-yellow-600"> <p class="mb-4 text-center text-sm text-yellow-600">
You are checking out as a guest, so you will miss out on a loyalty stamp. Please login You are checking out as a guest, so you will miss out on a loyalty stamp and any
for full membership benefits. possible seasonal discounts. Please login for full membership benefits.
</p> </p>
<div class="grid gap-4 md:grid-cols-2"> <div class="grid gap-4 md:grid-cols-2">
@@ -1756,7 +1804,10 @@
type="text" type="text"
inputmode="numeric" inputmode="numeric"
value={newCardNumber} value={newCardNumber}
oninput={(e) => (newCardNumber = formatDepositCardNumber((e.target as HTMLInputElement).value))} oninput={(e) =>
(newCardNumber = formatDepositCardNumber(
(e.target as HTMLInputElement).value
))}
placeholder="1234 5678 9012 3456" placeholder="1234 5678 9012 3456"
maxlength={19} maxlength={19}
/> />
@@ -1769,14 +1820,24 @@
type="text" type="text"
inputmode="numeric" inputmode="numeric"
value={newCardExpiry} value={newCardExpiry}
oninput={(e) => (newCardExpiry = formatDepositExpiry((e.target as HTMLInputElement).value))} oninput={(e) =>
(newCardExpiry = formatDepositExpiry(
(e.target as HTMLInputElement).value
))}
placeholder="MM/YY" placeholder="MM/YY"
maxlength={5} maxlength={5}
/> />
</div> </div>
<div class="space-y-2"> <div class="space-y-2">
<Label for="cardCVC">CVC</Label> <Label for="cardCVC">CVC</Label>
<Input id="cardCVC" type="text" inputmode="numeric" bind:value={newCardCVC} placeholder="123" maxlength={4} /> <Input
id="cardCVC"
type="text"
inputmode="numeric"
bind:value={newCardCVC}
placeholder="123"
maxlength={4}
/>
</div> </div>
</div> </div>
{#if authStore.isAuthenticated} {#if authStore.isAuthenticated}
@@ -1996,14 +2057,15 @@
deposit_paid: true, deposit_paid: true,
payments: [], payments: [],
duration_minutes: getTotalDuration(), duration_minutes: getTotalDuration(),
created_at: new Date().toISOString(), created_at: new SvelteDate().toISOString(),
updated_at: new Date().toISOString() updated_at: new SvelteDate().toISOString()
}} }}
onClose={() => (showPayEarlyModal = false)} onClose={() => (showPayEarlyModal = false)}
onComplete={() => { onComplete={() => {
showPayEarlyModal = false; showPayEarlyModal = false;
}} }}
canSaveCards={authStore.currentUser?.role === 'verified_email' || authStore.currentUser?.role === 'affiliate'} canSaveCards={authStore.currentUser?.role === 'verified_email' ||
authStore.currentUser?.role === 'affiliate'}
/> />
{/if} {/if}
</div> </div>
@@ -1,14 +1,16 @@
<script lang="ts"> <script lang="ts">
export let currentStep: number; export let currentStep: number;
export let steps: string[] = ['Service', 'Date & Time', 'Details', 'Payment']; export let steps: string[] = ['Service', 'Date & Time', 'Details', 'Payment'];
export let startAt: number = 0;
export let className: string = '';
const totalSteps = steps.length; const totalSteps = steps.length;
</script> </script>
<div class="mb-8 grid grid-cols-2 gap-4 md:flex md:items-center md:justify-center md:space-x-4"> <div class="mb-8 grid grid-cols-2 gap-4 md:grid-cols-3 md:gap-6 lg:flex lg:items-center lg:justify-center lg:space-x-4 {className}">
{#each steps as step, index (step)} {#each steps as step, index (step)}
{@const stepNumber = index + 1} {@const displayNumber = startAt + index}
{@const isActive = stepNumber <= currentStep} {@const isActive = displayNumber <= currentStep}
{@const isLastStep = index === totalSteps - 1} {@const isLastStep = index === totalSteps - 1}
<div class="flex items-center justify-start md:justify-center"> <div class="flex items-center justify-start md:justify-center">
@@ -18,7 +20,7 @@
? 'bg-primary text-primary-foreground' ? 'bg-primary text-primary-foreground'
: 'bg-gray-200 text-gray-600'}" : 'bg-gray-200 text-gray-600'}"
> >
{stepNumber} {displayNumber}
</div> </div>
<!-- Step label --> <!-- Step label -->
@@ -26,10 +28,9 @@
{step} {step}
</span> </span>
<!-- Connector line (desktop only, not after last step) -->
{#if !isLastStep} {#if !isLastStep}
<div <div
class="mx-4 hidden h-0.5 w-8 md:block {stepNumber < currentStep class="mx-4 hidden h-0.5 w-8 md:hidden lg:block {displayNumber < currentStep
? 'bg-primary' ? 'bg-primary'
: 'bg-gray-200'}" : 'bg-gray-200'}"
></div> ></div>