feat: wire slot reservation into all booking flows

Customer flow: reservation fires on Date/Time → Details transition with
re-validation on time slot tap and on 'Next' click to prevent simultaneous
bookings. 5-step flow: Service → Date/Time → Reserve → Details (countdown)
→ Payment & Review → Confirm. Guest users redirected to home on success.

Admin call-in: reserve slot before final submission (60min TTL).
Admin walk-in: reserve slot on modal open (5min TTL).

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-04-30 11:45:20 +01:00
co-authored by Sisyphus
parent 52ca9b425b
commit c5b7d9a078
4 changed files with 607 additions and 31 deletions
@@ -91,6 +91,12 @@
let submitting = $state(false);
// =============== Reservation State ===============
let reservationId = $state<string | null>(null);
let reservationExpiresAt = $state<Date | null>(null);
let reservationCountdown = $state<string>('');
let isReserving = $state(false);
// =============== Cache ===============
const workingHoursCache = new SvelteMap<string, Record<string, any>>();
const availableHoursCache = new SvelteMap<string, Record<string, any>>();
@@ -240,6 +246,13 @@
availableHoursCache.clear();
workingHours = null;
availableHours = null;
// Clear reservation state
reservationId = null;
reservationExpiresAt = null;
reservationCountdown = '';
if ((window as any).__bookingCreateCountdownInterval) {
clearInterval((window as any).__bookingCreateCountdownInterval);
}
}
// =============== Data Fetching ===============
@@ -346,6 +359,113 @@
}
}
// =============== Reservation ===============
async function reserveSlot(): Promise<boolean> {
if (!selectedUserId || !selectedDate || !selectedTime) {
return false;
}
isReserving = true;
try {
const localDate = selectedDate.toDate(getLocalTimeZone());
const [hours, minutes] = selectedTime.split(':').map(Number);
localDate.setHours(hours, minutes, 0, 0);
const startTimeISO = localDate.toISOString();
const serviceIds = selectedServices.map((s) => s.id);
// Build service overrides payload
const overrides = [];
for (const [serviceId, data] of Object.entries(serviceOverrides)) {
const durationChanged = parseInt(data.duration) !== data.originalDuration;
if (durationChanged) {
overrides.push({
service_id: serviceId,
override_duration_minutes: parseInt(data.duration)
});
}
}
const response = await fetch('/api/admin/bookings/reserve', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify({
user_id: selectedUserId,
start_time: startTimeISO,
service_ids: serviceIds,
service_overrides: overrides.length > 0 ? overrides : [],
ttl_minutes: 60
})
});
if (response.ok) {
const data = await response.json();
reservationId = data.id;
reservationExpiresAt = new Date(data.expires_at);
startCountdown();
return true;
} else if (response.status === 409) {
toast.error('Slot no longer available, refreshing...');
// Refresh available hours
if (selectedDate) {
fetchHoursForMonth(selectedDate);
}
reservationId = null;
reservationExpiresAt = null;
reservationCountdown = '';
return false;
} else {
const errorText = await response.text();
toast.error(`Failed to reserve slot: ${errorText}`);
return false;
}
} catch (err) {
console.error('Reservation error:', err);
toast.error('Failed to reserve slot');
return false;
} finally {
isReserving = false;
}
}
function startCountdown() {
// Clear any existing interval
if ((window as any).__bookingCreateCountdownInterval) {
clearInterval((window as any).__bookingCreateCountdownInterval);
}
const updateCountdown = () => {
if (!reservationExpiresAt) {
reservationCountdown = '';
return;
}
const now = new Date();
const diff = reservationExpiresAt.getTime() - now.getTime();
if (diff <= 0) {
reservationCountdown = 'Expired';
reservationId = null;
reservationExpiresAt = null;
if ((window as any).__bookingCreateCountdownInterval) {
clearInterval((window as any).__bookingCreateCountdownInterval);
}
return;
}
const minutes = Math.floor(diff / 60000);
const seconds = Math.floor((diff % 60000) / 1000);
reservationCountdown = `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
updateCountdown();
(window as any).__bookingCreateCountdownInterval = setInterval(updateCountdown, 1000);
}
// =============== Logic ===============
function toggleService(service: Service) {
const index = selectedServices.findIndex((s) => s.id === service.id);
@@ -600,6 +720,13 @@
// =============== Submission ===============
async function submitBooking() {
// First, reserve the slot
const reserved = await reserveSlot();
if (!reserved) {
submitting = false;
return;
}
submitting = true;
try {
@@ -1074,6 +1201,24 @@
</Card.Description>
</Card.Header>
<Card.Content class="space-y-4 p-0">
<!-- Reservation Countdown Banner -->
{#if reservationId && reservationExpiresAt}
<div class="mx-6 mt-4 rounded-lg bg-green-50 border border-green-200 p-3">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<svg class="h-5 w-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
<span class="text-sm font-medium text-green-800">
Slot reserved until {reservationExpiresAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</span>
</div>
<span class="text-sm font-mono font-semibold text-green-700">
({reservationCountdown} remaining)
</span>
</div>
</div>
{/if}
{#if loadingWorkingHours}
<div class="flex items-center justify-center p-6">
<p>Loading available dates...</p>
@@ -1184,11 +1329,11 @@
<Card.Footer class="flex justify-between">
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
<Button
disabled={!canProceedStep4 || submitting}
disabled={!canProceedStep4 || submitting || isReserving}
onclick={submitBooking}
class="bg-primary text-primary-foreground"
>
{submitting ? 'Creating Booking...' : 'Create Booking'}
{isReserving ? 'Reserving Slot...' : submitting ? 'Creating Booking...' : 'Create Booking'}
</Button>
</Card.Footer>
</Card.Root>
@@ -5,6 +5,7 @@
import { CalendarDate } from '@internationalized/date';
import { SvelteDate } from 'svelte/reactivity';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import type { AvailableHoursDay } from '$lib/types/booking';
@@ -14,12 +15,18 @@
waitMinutes?: number;
durationMinutes: number;
startTime?: string;
slotEndMinutes?: number; // Store for live countdown
slotEndMinutes?: number;
} | null>(null);
let loading = $state(true);
let noSlotsToday = $state(false);
let currentTime = $state(new Date());
// Reservation state for walk-in
let reservationId = $state<string | null>(null);
let reservationExpiresAt = $state<Date | null>(null);
let reservationCountdown = $state<string>('');
let isReserving = $state(false);
onMount(() => {
calculateSlotAvailability();
@@ -153,6 +160,119 @@
const displayHours = hours % 12 || 12;
return `${displayHours}:${minutes.toString().padStart(2, '0')} ${period}`;
}
async function reserveWalkInSlot(startTime: string): Promise<boolean> {
isReserving = true;
try {
const now = new SvelteDate();
const [hours, minutes] = startTime.split(':').map(Number);
const start = new SvelteDate(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes,
0,
0
);
const startTimeISO = start.toISOString();
const response = await fetch('/api/admin/bookings/reserve', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify({
user_id: null,
start_time: startTimeISO,
service_ids: [],
service_overrides: [],
ttl_minutes: 5
})
});
if (response.ok) {
const data = await response.json();
reservationId = data.id;
reservationExpiresAt = new Date(data.expires_at);
startWalkInCountdown();
return true;
} else if (response.status === 409) {
toast.error('Slot no longer available, please try again');
calculateSlotAvailability();
return false;
} else {
const errorText = await response.text();
toast.error(`Failed to reserve slot: ${errorText}`);
return false;
}
} catch (err) {
console.error('Reservation error:', err);
toast.error('Failed to reserve slot');
return false;
} finally {
isReserving = false;
}
}
function startWalkInCountdown() {
if ((window as any).__walkInCountdownInterval) {
clearInterval((window as any).__walkInCountdownInterval);
}
const updateCountdown = () => {
if (!reservationExpiresAt) {
reservationCountdown = '';
return;
}
const now = new Date();
const diff = reservationExpiresAt.getTime() - now.getTime();
if (diff <= 0) {
reservationCountdown = 'Expired';
reservationId = null;
reservationExpiresAt = null;
toast.error('Slot released — please re-check availability');
if ((window as any).__walkInCountdownInterval) {
clearInterval((window as any).__walkInCountdownInterval);
}
showCreateModal = false;
return;
}
const minutes = Math.floor(diff / 60000);
const seconds = Math.floor((diff % 60000) / 1000);
reservationCountdown = `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
updateCountdown();
(window as any).__walkInCountdownInterval = setInterval(updateCountdown, 1000);
}
function handleStartWalkIn() {
if (slotInfo?.isAvailableNow) {
showCreateModal = true;
} else if (slotInfo?.startTime) {
reserveWalkInSlot(slotInfo.startTime).then((reserved) => {
if (reserved) {
showCreateModal = true;
}
});
}
}
function handleModalClose() {
showCreateModal = false;
reservationId = null;
reservationExpiresAt = null;
reservationCountdown = '';
if ((window as any).__walkInCountdownInterval) {
clearInterval((window as any).__walkInCountdownInterval);
}
}
</script>
<div class="rounded-lg border border-gray-200 bg-white p-4">
@@ -194,10 +314,10 @@
<div class="flex items-center gap-3">
<Button
onclick={() => (showCreateModal = true)}
disabled={noSlotsToday || (slotInfo?.isAvailableNow && (getLiveRemainingMinutes() ?? 0) <= 0)}
onclick={handleStartWalkIn}
disabled={noSlotsToday || isReserving || (slotInfo?.isAvailableNow && (getLiveRemainingMinutes() ?? 0) <= 0)}
>
Start Walk-In Session
{isReserving ? 'Reserving...' : 'Start Walk-In Session'}
</Button>
</div>
</div>
@@ -207,5 +327,7 @@
bind:open={showCreateModal}
maxSlotDuration={slotInfo?.durationMinutes ?? 0}
availableStartTime={slotInfo?.isAvailableNow ? undefined : slotInfo?.startTime}
reservationExpiresAt={reservationExpiresAt}
onclose={handleModalClose}
/>
{/if}
@@ -23,15 +23,19 @@
interface Props {
open: boolean;
maxSlotDuration?: number;
availableStartTime?: string; // "HH:MM" or "HH:MM:SS" format from the available slot
availableStartTime?: string;
reservationExpiresAt?: Date | null;
onBookingCreated?: () => void;
onclose?: () => void;
}
let {
open = $bindable(),
maxSlotDuration = 0,
availableStartTime,
onBookingCreated
reservationExpiresAt,
onBookingCreated,
onclose
}: Props = $props();
// =============== State ===============
@@ -64,6 +68,10 @@
let submitting = $state(false);
// Countdown state
let reservationCountdown = $state<string>('');
let isReservationExpired = $state(false);
// =============== Derived Helpers ===============
function getTotalDuration() {
return selectedServices.reduce((total, service) => {
@@ -123,6 +131,48 @@
}
});
// Handle reservation countdown
$effect(() => {
if (open && reservationExpiresAt) {
startCountdown();
} else {
reservationCountdown = '';
isReservationExpired = false;
}
});
function startCountdown() {
if ((window as any).__walkInModalCountdownInterval) {
clearInterval((window as any).__walkInModalCountdownInterval);
}
const updateCountdown = () => {
if (!reservationExpiresAt) {
reservationCountdown = '';
return;
}
const now = new Date();
const diff = reservationExpiresAt.getTime() - now.getTime();
if (diff <= 0) {
reservationCountdown = 'Expired';
isReservationExpired = true;
if ((window as any).__walkInModalCountdownInterval) {
clearInterval((window as any).__walkInModalCountdownInterval);
}
return;
}
const minutes = Math.floor(diff / 60000);
const seconds = Math.floor((diff % 60000) / 1000);
reservationCountdown = `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
updateCountdown();
(window as any).__walkInModalCountdownInterval = setInterval(updateCountdown, 1000);
}
function resetState() {
currentStep = 1;
userType = 'member';
@@ -305,6 +355,8 @@
notes: notes.trim() || null
};
// TODO: When guest booking is fully implemented, ensure walk-in guest reservations properly transition to real bookings.
const res = await fetch('/api/admin/bookings', {
method: 'POST',
headers: {
@@ -366,6 +418,35 @@
</Modal.Header>
<div class="px-6 pb-4">
<!-- Reservation Countdown Banner -->
{#if reservationExpiresAt && !isReservationExpired}
<div class="mx-6 mt-4 rounded-lg bg-green-50 border border-green-200 p-3">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<svg class="h-5 w-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
<span class="text-sm font-medium text-green-800">
Slot held for
</span>
</div>
<span class="text-sm font-mono font-semibold text-green-700">
{reservationCountdown}
</span>
</div>
</div>
{:else if isReservationExpired}
<div class="mx-6 mt-4 rounded-lg bg-red-50 border border-red-200 p-3">
<div class="flex items-center gap-2">
<svg class="h-5 w-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span class="text-sm font-medium text-red-800">
Slot released — please re-check availability
</span>
</div>
</div>
{/if}
<!-- Step 1: Customer Selection -->
{#if currentStep === 1}
<Card.Root>
@@ -717,7 +798,7 @@
<Card.Footer class="flex justify-between">
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
<Button
disabled={submitting}
disabled={submitting || isReservationExpired}
onclick={submitBooking}
class="bg-primary text-primary-foreground"
>