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:
@@ -91,6 +91,12 @@
|
|||||||
|
|
||||||
let submitting = $state(false);
|
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 ===============
|
// =============== Cache ===============
|
||||||
const workingHoursCache = new SvelteMap<string, Record<string, any>>();
|
const workingHoursCache = new SvelteMap<string, Record<string, any>>();
|
||||||
const availableHoursCache = new SvelteMap<string, Record<string, any>>();
|
const availableHoursCache = new SvelteMap<string, Record<string, any>>();
|
||||||
@@ -240,6 +246,13 @@
|
|||||||
availableHoursCache.clear();
|
availableHoursCache.clear();
|
||||||
workingHours = null;
|
workingHours = null;
|
||||||
availableHours = null;
|
availableHours = null;
|
||||||
|
// Clear reservation state
|
||||||
|
reservationId = null;
|
||||||
|
reservationExpiresAt = null;
|
||||||
|
reservationCountdown = '';
|
||||||
|
if ((window as any).__bookingCreateCountdownInterval) {
|
||||||
|
clearInterval((window as any).__bookingCreateCountdownInterval);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// =============== Data Fetching ===============
|
// =============== 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 ===============
|
// =============== Logic ===============
|
||||||
function toggleService(service: Service) {
|
function toggleService(service: Service) {
|
||||||
const index = selectedServices.findIndex((s) => s.id === service.id);
|
const index = selectedServices.findIndex((s) => s.id === service.id);
|
||||||
@@ -600,6 +720,13 @@
|
|||||||
|
|
||||||
// =============== Submission ===============
|
// =============== Submission ===============
|
||||||
async function submitBooking() {
|
async function submitBooking() {
|
||||||
|
// First, reserve the slot
|
||||||
|
const reserved = await reserveSlot();
|
||||||
|
if (!reserved) {
|
||||||
|
submitting = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
submitting = true;
|
submitting = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1074,6 +1201,24 @@
|
|||||||
</Card.Description>
|
</Card.Description>
|
||||||
</Card.Header>
|
</Card.Header>
|
||||||
<Card.Content class="space-y-4 p-0">
|
<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}
|
{#if loadingWorkingHours}
|
||||||
<div class="flex items-center justify-center p-6">
|
<div class="flex items-center justify-center p-6">
|
||||||
<p>Loading available dates...</p>
|
<p>Loading available dates...</p>
|
||||||
@@ -1184,11 +1329,11 @@
|
|||||||
<Card.Footer class="flex justify-between">
|
<Card.Footer class="flex justify-between">
|
||||||
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
|
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
|
||||||
<Button
|
<Button
|
||||||
disabled={!canProceedStep4 || submitting}
|
disabled={!canProceedStep4 || submitting || isReserving}
|
||||||
onclick={submitBooking}
|
onclick={submitBooking}
|
||||||
class="bg-primary text-primary-foreground"
|
class="bg-primary text-primary-foreground"
|
||||||
>
|
>
|
||||||
{submitting ? 'Creating Booking...' : 'Create Booking'}
|
{isReserving ? 'Reserving Slot...' : submitting ? 'Creating Booking...' : 'Create Booking'}
|
||||||
</Button>
|
</Button>
|
||||||
</Card.Footer>
|
</Card.Footer>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
import { CalendarDate } from '@internationalized/date';
|
import { CalendarDate } from '@internationalized/date';
|
||||||
import { SvelteDate } from 'svelte/reactivity';
|
import { SvelteDate } from 'svelte/reactivity';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
import { toast } from 'svelte-sonner';
|
||||||
|
|
||||||
import type { AvailableHoursDay } from '$lib/types/booking';
|
import type { AvailableHoursDay } from '$lib/types/booking';
|
||||||
|
|
||||||
@@ -14,12 +15,18 @@
|
|||||||
waitMinutes?: number;
|
waitMinutes?: number;
|
||||||
durationMinutes: number;
|
durationMinutes: number;
|
||||||
startTime?: string;
|
startTime?: string;
|
||||||
slotEndMinutes?: number; // Store for live countdown
|
slotEndMinutes?: number;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
let loading = $state(true);
|
let loading = $state(true);
|
||||||
let noSlotsToday = $state(false);
|
let noSlotsToday = $state(false);
|
||||||
let currentTime = $state(new Date());
|
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(() => {
|
onMount(() => {
|
||||||
calculateSlotAvailability();
|
calculateSlotAvailability();
|
||||||
|
|
||||||
@@ -153,6 +160,119 @@
|
|||||||
const displayHours = hours % 12 || 12;
|
const displayHours = hours % 12 || 12;
|
||||||
return `${displayHours}:${minutes.toString().padStart(2, '0')} ${period}`;
|
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>
|
</script>
|
||||||
|
|
||||||
<div class="rounded-lg border border-gray-200 bg-white p-4">
|
<div class="rounded-lg border border-gray-200 bg-white p-4">
|
||||||
@@ -194,10 +314,10 @@
|
|||||||
|
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<Button
|
<Button
|
||||||
onclick={() => (showCreateModal = true)}
|
onclick={handleStartWalkIn}
|
||||||
disabled={noSlotsToday || (slotInfo?.isAvailableNow && (getLiveRemainingMinutes() ?? 0) <= 0)}
|
disabled={noSlotsToday || isReserving || (slotInfo?.isAvailableNow && (getLiveRemainingMinutes() ?? 0) <= 0)}
|
||||||
>
|
>
|
||||||
Start Walk-In Session
|
{isReserving ? 'Reserving...' : 'Start Walk-In Session'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -207,5 +327,7 @@
|
|||||||
bind:open={showCreateModal}
|
bind:open={showCreateModal}
|
||||||
maxSlotDuration={slotInfo?.durationMinutes ?? 0}
|
maxSlotDuration={slotInfo?.durationMinutes ?? 0}
|
||||||
availableStartTime={slotInfo?.isAvailableNow ? undefined : slotInfo?.startTime}
|
availableStartTime={slotInfo?.isAvailableNow ? undefined : slotInfo?.startTime}
|
||||||
|
reservationExpiresAt={reservationExpiresAt}
|
||||||
|
onclose={handleModalClose}
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -23,15 +23,19 @@
|
|||||||
interface Props {
|
interface Props {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
maxSlotDuration?: number;
|
maxSlotDuration?: number;
|
||||||
availableStartTime?: string; // "HH:MM" or "HH:MM:SS" format from the available slot
|
availableStartTime?: string;
|
||||||
|
reservationExpiresAt?: Date | null;
|
||||||
onBookingCreated?: () => void;
|
onBookingCreated?: () => void;
|
||||||
|
onclose?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
let {
|
||||||
open = $bindable(),
|
open = $bindable(),
|
||||||
maxSlotDuration = 0,
|
maxSlotDuration = 0,
|
||||||
availableStartTime,
|
availableStartTime,
|
||||||
onBookingCreated
|
reservationExpiresAt,
|
||||||
|
onBookingCreated,
|
||||||
|
onclose
|
||||||
}: Props = $props();
|
}: Props = $props();
|
||||||
|
|
||||||
// =============== State ===============
|
// =============== State ===============
|
||||||
@@ -64,6 +68,10 @@
|
|||||||
|
|
||||||
let submitting = $state(false);
|
let submitting = $state(false);
|
||||||
|
|
||||||
|
// Countdown state
|
||||||
|
let reservationCountdown = $state<string>('');
|
||||||
|
let isReservationExpired = $state(false);
|
||||||
|
|
||||||
// =============== Derived Helpers ===============
|
// =============== Derived Helpers ===============
|
||||||
function getTotalDuration() {
|
function getTotalDuration() {
|
||||||
return selectedServices.reduce((total, service) => {
|
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() {
|
function resetState() {
|
||||||
currentStep = 1;
|
currentStep = 1;
|
||||||
userType = 'member';
|
userType = 'member';
|
||||||
@@ -305,6 +355,8 @@
|
|||||||
notes: notes.trim() || null
|
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', {
|
const res = await fetch('/api/admin/bookings', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -366,6 +418,35 @@
|
|||||||
</Modal.Header>
|
</Modal.Header>
|
||||||
|
|
||||||
<div class="px-6 pb-4">
|
<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 -->
|
<!-- Step 1: Customer Selection -->
|
||||||
{#if currentStep === 1}
|
{#if currentStep === 1}
|
||||||
<Card.Root>
|
<Card.Root>
|
||||||
@@ -717,7 +798,7 @@
|
|||||||
<Card.Footer class="flex justify-between">
|
<Card.Footer class="flex justify-between">
|
||||||
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
|
<Button variant="outline" onclick={() => currentStep--}>Back</Button>
|
||||||
<Button
|
<Button
|
||||||
disabled={submitting}
|
disabled={submitting || isReservationExpired}
|
||||||
onclick={submitBooking}
|
onclick={submitBooking}
|
||||||
class="bg-primary text-primary-foreground"
|
class="bg-primary text-primary-foreground"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -44,6 +44,105 @@
|
|||||||
});
|
});
|
||||||
let isSubmitting = $state(false);
|
let isSubmitting = $state(false);
|
||||||
|
|
||||||
|
// =============== Slot Reservation System ===============
|
||||||
|
let reservationId = $state<string | null>(null);
|
||||||
|
let reservationExpiresAt = $state<Date | null>(null);
|
||||||
|
let reservationCountdown = $state<string>('');
|
||||||
|
let reservationExpired = $state(false);
|
||||||
|
let isReserving = $state(false);
|
||||||
|
|
||||||
|
// =============== Slot Reservation Functions ===============
|
||||||
|
async function reserveSlot() {
|
||||||
|
isReserving = true;
|
||||||
|
try {
|
||||||
|
if (!selectedDate || !selectedTime) {
|
||||||
|
toast.error('Please select a date and time');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [hours, minutes] = selectedTime.split(':').map(Number);
|
||||||
|
const bookingDate = selectedDate.toDate(getLocalTimeZone());
|
||||||
|
bookingDate.setHours(hours, minutes, 0, 0);
|
||||||
|
const startTimeISO = bookingDate.toISOString();
|
||||||
|
const serviceIds = selectedServices.map((s) => s.id);
|
||||||
|
|
||||||
|
const response = await fetch('/api/bookings/reserve', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ start_time: startTimeISO, service_ids: serviceIds })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
if (response.status === 429) {
|
||||||
|
toast.error('Too many active reservations. Please wait or log in.');
|
||||||
|
} else if (response.status === 409) {
|
||||||
|
toast.error('This time slot is no longer available. Please choose a different time.');
|
||||||
|
await refreshAvailableHours();
|
||||||
|
} else {
|
||||||
|
toast.error('Failed to reserve slot. Please try again.');
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
reservationId = data.id;
|
||||||
|
reservationExpiresAt = new Date(data.expires_at);
|
||||||
|
reservationExpired = false;
|
||||||
|
startCountdown();
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('Network error while reserving slot.');
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
isReserving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCountdown() {
|
||||||
|
if (!reservationExpiresAt) return;
|
||||||
|
|
||||||
|
const updateCountdown = () => {
|
||||||
|
if (!reservationExpiresAt) {
|
||||||
|
reservationCountdown = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const diff = reservationExpiresAt.getTime() - now.getTime();
|
||||||
|
|
||||||
|
if (diff <= 0) {
|
||||||
|
reservationCountdown = '00:00';
|
||||||
|
reservationExpired = true;
|
||||||
|
reservationId = null;
|
||||||
|
reservationExpiresAt = null;
|
||||||
|
toast.error('Your reservation has expired. Please select a new time slot.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const minutes = Math.floor(diff / 60000);
|
||||||
|
const seconds = Math.floor((diff % 60000) / 1000);
|
||||||
|
reservationCountdown = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
updateCountdown();
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
if (reservationExpired) {
|
||||||
|
clearInterval(interval);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateCountdown();
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshAvailableHours() {
|
||||||
|
if (!selectedDate) return;
|
||||||
|
|
||||||
|
const monthKey = `${selectedDate.year}-${String(selectedDate.month).padStart(2, '0')}`;
|
||||||
|
availableHoursCache.delete(monthKey);
|
||||||
|
await fetchHoursForMonth(selectedDate);
|
||||||
|
}
|
||||||
|
|
||||||
// =============== Services Management ===============
|
// =============== Services Management ===============
|
||||||
let services = $state<Service[]>([]);
|
let services = $state<Service[]>([]);
|
||||||
let servicesLoading = $state(true);
|
let servicesLoading = $state(true);
|
||||||
@@ -557,13 +656,55 @@
|
|||||||
// Only clear if we're on the date/time selection step
|
// Only clear if we're on the date/time selection step
|
||||||
if (currentStep === 2 && selectedDate) {
|
if (currentStep === 2 && selectedDate) {
|
||||||
const monthKey = `${selectedDate.year}-${String(selectedDate.month).padStart(2, '0')}`;
|
const monthKey = `${selectedDate.year}-${String(selectedDate.month).padStart(2, '0')}`;
|
||||||
availableHoursCache.delete(monthKey); // Only delete current month
|
availableHoursCache.delete(monthKey);
|
||||||
fetchHoursForMonth(selectedDate);
|
fetchHoursForMonth(selectedDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
selectedTime = null;
|
selectedTime = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Select a time slot with server-side re-validation
|
||||||
|
async function selectTimeWithValidation(time: string) {
|
||||||
|
selectedTime = time;
|
||||||
|
await refreshAndValidateSlot();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-fetch available hours and check if selectedTime is still available
|
||||||
|
async function refreshAndValidateSlot() {
|
||||||
|
if (!selectedDate || !selectedTime) return;
|
||||||
|
|
||||||
|
const monthKey = `${selectedDate.year}-${String(selectedDate.month).padStart(2, '0')}`;
|
||||||
|
availableHoursCache.delete(monthKey);
|
||||||
|
await fetchHoursForMonth(selectedDate);
|
||||||
|
|
||||||
|
const dateStr = selectedDate.toString();
|
||||||
|
const dayAvailable = availableHours?.[dateStr]?.slots;
|
||||||
|
if (!dayAvailable || dayAvailable.length === 0) {
|
||||||
|
toast.error('Sorry, this slot is no longer available. Please choose a different time.');
|
||||||
|
selectedTime = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const duration = getTotalDuration();
|
||||||
|
const [selHour, selMinute] = selectedTime.split(':').map(Number);
|
||||||
|
const selStart = selHour * 60 + selMinute;
|
||||||
|
const selEnd = selStart + duration;
|
||||||
|
|
||||||
|
const stillAvailable = dayAvailable.some(slot => {
|
||||||
|
const [sH, sM] = slot.startTime.split(':').map(Number);
|
||||||
|
const [eH, eM] = slot.endTime.split(':').map(Number);
|
||||||
|
return selStart >= (sH * 60 + sM) && selEnd <= (eH * 60 + eM);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!stillAvailable) {
|
||||||
|
toast.error('Sorry, this slot was just taken. Please choose a different time.');
|
||||||
|
selectedTime = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
function formatDuration(minutes: number): string {
|
function formatDuration(minutes: number): string {
|
||||||
const hours = Math.floor(minutes / 60);
|
const hours = Math.floor(minutes / 60);
|
||||||
const remainingMinutes = minutes % 60;
|
const remainingMinutes = minutes % 60;
|
||||||
@@ -610,8 +751,16 @@
|
|||||||
);
|
);
|
||||||
|
|
||||||
// =============== Navigation ===============
|
// =============== Navigation ===============
|
||||||
function nextStep() {
|
async function nextStep() {
|
||||||
if (currentStep < 4) {
|
// Step 2 -> Step 3: Re-validate slot, then reserve
|
||||||
|
if (currentStep === 2) {
|
||||||
|
const slotStillFree = await refreshAndValidateSlot();
|
||||||
|
if (!slotStillFree) return;
|
||||||
|
const reserved = await reserveSlot();
|
||||||
|
if (!reserved) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentStep < 5) {
|
||||||
currentStep++;
|
currentStep++;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
@@ -632,7 +781,7 @@
|
|||||||
const canProceedStep1 = $derived(selectedServices.length > 0);
|
const canProceedStep1 = $derived(selectedServices.length > 0);
|
||||||
const canProceedStep2 = $derived(!!(selectedDate && selectedTime));
|
const canProceedStep2 = $derived(!!(selectedDate && selectedTime));
|
||||||
const canProceedStep3 = $derived(
|
const canProceedStep3 = $derived(
|
||||||
authStore.isAuthenticated
|
(authStore.isAuthenticated
|
||||||
? !!(
|
? !!(
|
||||||
authStore.currentUser?.firstName &&
|
authStore.currentUser?.firstName &&
|
||||||
authStore.currentUser?.lastName &&
|
authStore.currentUser?.lastName &&
|
||||||
@@ -644,8 +793,9 @@
|
|||||||
customerInfo.lastName &&
|
customerInfo.lastName &&
|
||||||
customerInfo.email &&
|
customerInfo.email &&
|
||||||
customerInfo.phone
|
customerInfo.phone
|
||||||
)
|
)) && !reservationExpired
|
||||||
);
|
);
|
||||||
|
const canProceedStep4 = $derived(true);
|
||||||
|
|
||||||
// =============== Submission ===============
|
// =============== Submission ===============
|
||||||
async function submitBooking() {
|
async function submitBooking() {
|
||||||
@@ -666,21 +816,56 @@
|
|||||||
// Extract service IDs
|
// Extract service IDs
|
||||||
const serviceIds = selectedServices.map((s) => s.id);
|
const serviceIds = selectedServices.map((s) => s.id);
|
||||||
|
|
||||||
|
// For guest users, create a guest account first
|
||||||
|
let guestUserId: string | null = null;
|
||||||
|
if (!authStore.isAuthenticated) {
|
||||||
|
const guestResponse = await fetch('/api/users/guest', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
firstName: customerInfo.firstName,
|
||||||
|
lastName: customerInfo.lastName,
|
||||||
|
email: customerInfo.email,
|
||||||
|
phone: customerInfo.phone
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!guestResponse.ok) {
|
||||||
|
const errorText = await guestResponse.text();
|
||||||
|
if (guestResponse.status === 409) {
|
||||||
|
toast.error('Email already registered — please log in to book.');
|
||||||
|
} else {
|
||||||
|
toast.error('Failed to create guest account. Please try again.');
|
||||||
|
}
|
||||||
|
isSubmitting = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const guestData = await guestResponse.json();
|
||||||
|
guestUserId = guestData.id;
|
||||||
|
}
|
||||||
|
|
||||||
// Build request body
|
// Build request body
|
||||||
const requestBody = {
|
const requestBody: Record<string, unknown> = {
|
||||||
service_ids: serviceIds,
|
service_ids: serviceIds,
|
||||||
start_time: startTimeISO,
|
start_time: startTimeISO,
|
||||||
notes: customerInfo.specialRequests || null
|
notes: customerInfo.specialRequests || null
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (guestUserId) {
|
||||||
|
requestBody.user_id = guestUserId;
|
||||||
|
}
|
||||||
|
|
||||||
console.log('Submitting booking:', requestBody);
|
console.log('Submitting booking:', requestBody);
|
||||||
|
|
||||||
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
|
if (authStore.currentToken) {
|
||||||
|
headers['Authorization'] = `Bearer ${authStore.currentToken}`;
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch('/api/bookings', {
|
const response = await fetch('/api/bookings', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${authStore.currentToken}`
|
|
||||||
},
|
|
||||||
body: JSON.stringify(requestBody)
|
body: JSON.stringify(requestBody)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -701,14 +886,18 @@
|
|||||||
|
|
||||||
toast.success(`Booking confirmed for ${bookingDateStr} at ${bookingTimeStr}!`);
|
toast.success(`Booking confirmed for ${bookingDateStr} at ${bookingTimeStr}!`);
|
||||||
|
|
||||||
// Reset form and redirect to account page
|
// Clear reservation state
|
||||||
|
reservationId = null;
|
||||||
|
reservationExpiresAt = null;
|
||||||
|
|
||||||
|
// Reset form and redirect
|
||||||
selectedServices = [];
|
selectedServices = [];
|
||||||
selectedDate = undefined;
|
selectedDate = undefined;
|
||||||
selectedTime = null;
|
selectedTime = null;
|
||||||
currentStep = 1;
|
currentStep = 1;
|
||||||
|
|
||||||
// Navigate to account page to see bookings
|
// Navigate to account page (logged-in) or home (guest)
|
||||||
window.location.href = '/account';
|
window.location.href = authStore.isAuthenticated ? '/account' : '/';
|
||||||
} else {
|
} else {
|
||||||
// Handle error response
|
// Handle error response
|
||||||
const errorText = await response.text();
|
const errorText = await response.text();
|
||||||
@@ -760,7 +949,7 @@
|
|||||||
<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 {currentStep} />
|
<StepIndicator {currentStep} steps={['Service', 'Date & Time', 'Details', 'Payment & Review', 'Confirm']} />
|
||||||
|
|
||||||
<!-- Step 1: Service Selection -->
|
<!-- Step 1: Service Selection -->
|
||||||
{#if currentStep === 1}
|
{#if currentStep === 1}
|
||||||
@@ -857,7 +1046,7 @@
|
|||||||
{selectedTime}
|
{selectedTime}
|
||||||
formattedDate={formattedSelectedDate}
|
formattedDate={formattedSelectedDate}
|
||||||
onselect={(time) => {
|
onselect={(time) => {
|
||||||
selectedTime = time;
|
selectTimeWithValidation(time);
|
||||||
}}
|
}}
|
||||||
lunchProtectionStatus={lunchProtectionStatus()}
|
lunchProtectionStatus={lunchProtectionStatus()}
|
||||||
/>
|
/>
|
||||||
@@ -916,6 +1105,18 @@
|
|||||||
<Card.Description>Please confirm your contact information</Card.Description>
|
<Card.Description>Please confirm your contact information</Card.Description>
|
||||||
</Card.Header>
|
</Card.Header>
|
||||||
<Card.Content class="space-y-6">
|
<Card.Content class="space-y-6">
|
||||||
|
{#if reservationExpired}
|
||||||
|
<div class="rounded-lg bg-red-50 p-4 text-center">
|
||||||
|
<p class="text-red-600">Reservation expired — please go back and select a new time</p>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="rounded-lg bg-blue-50 p-4 text-center">
|
||||||
|
<p class="text-blue-700">
|
||||||
|
Your slot is reserved for {reservationCountdown} — complete your booking before time expires
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<BookingSummary
|
<BookingSummary
|
||||||
services={selectedServices}
|
services={selectedServices}
|
||||||
date={selectedDate}
|
date={selectedDate}
|
||||||
@@ -994,18 +1195,18 @@
|
|||||||
onclick={nextStep}
|
onclick={nextStep}
|
||||||
class="bg-primary text-primary-foreground"
|
class="bg-primary text-primary-foreground"
|
||||||
>
|
>
|
||||||
Next: Payment
|
{reservationExpired ? 'Reservation Expired' : 'Next: Review & Payment'}
|
||||||
</Button>
|
</Button>
|
||||||
</Card.Footer>
|
</Card.Footer>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<!-- Step 4: Payment (complete) -->
|
<!-- Step 4: Payment & Review -->
|
||||||
{#if currentStep === 4}
|
{#if currentStep === 4}
|
||||||
<Card.Root>
|
<Card.Root>
|
||||||
<Card.Header>
|
<Card.Header>
|
||||||
<Card.Title>Payment Confirmation</Card.Title>
|
<Card.Title>Payment & Review</Card.Title>
|
||||||
<Card.Description>Review and complete your booking</Card.Description>
|
<Card.Description>Review your booking details</Card.Description>
|
||||||
</Card.Header>
|
</Card.Header>
|
||||||
<Card.Content class="space-y-6">
|
<Card.Content class="space-y-6">
|
||||||
<BookingSummary
|
<BookingSummary
|
||||||
@@ -1024,7 +1225,7 @@
|
|||||||
showCustomer={true}
|
showCustomer={true}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- Payment form placeholder -->
|
<!-- TODO: Integrate payment processor (Stripe/Square) here. Current flow: logged-in users go straight to confirmation, guest users show payment step before confirmation. -->
|
||||||
<div class="rounded-lg bg-white p-6">
|
<div class="rounded-lg bg-white p-6">
|
||||||
<h2 class="mb-4 text-2xl font-semibold">Payment</h2>
|
<h2 class="mb-4 text-2xl font-semibold">Payment</h2>
|
||||||
<p class="text-gray-600">Square payment integration will be added here.</p>
|
<p class="text-gray-600">Square payment integration will be added here.</p>
|
||||||
@@ -1033,11 +1234,38 @@
|
|||||||
<Card.Footer class="flex justify-between">
|
<Card.Footer class="flex justify-between">
|
||||||
<Button variant="outline" onclick={prevStep}>Back</Button>
|
<Button variant="outline" onclick={prevStep}>Back</Button>
|
||||||
<Button
|
<Button
|
||||||
disabled={!canProceedStep3 || isSubmitting}
|
disabled={isSubmitting}
|
||||||
|
onclick={nextStep}
|
||||||
|
class="bg-primary text-primary-foreground"
|
||||||
|
>
|
||||||
|
Next: Confirm
|
||||||
|
</Button>
|
||||||
|
</Card.Footer>
|
||||||
|
</Card.Root>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Step 5: Confirm -->
|
||||||
|
{#if currentStep === 5}
|
||||||
|
<Card.Root>
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title>Confirm Your Booking</Card.Title>
|
||||||
|
<Card.Description>Ready to confirm your appointment</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Content class="space-y-6">
|
||||||
|
<div class="rounded-lg bg-gray-50 p-6 text-center">
|
||||||
|
<p class="text-lg">
|
||||||
|
Ready to confirm: {selectedServices.map((s) => s.name).join(', ')} on {selectedDate?.toDate(getLocalTimeZone()).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })} at {selectedTime}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</Card.Content>
|
||||||
|
<Card.Footer class="flex justify-between">
|
||||||
|
<Button variant="outline" onclick={prevStep}>Back</Button>
|
||||||
|
<Button
|
||||||
|
disabled={isSubmitting}
|
||||||
onclick={submitBooking}
|
onclick={submitBooking}
|
||||||
class="bg-primary text-primary-foreground"
|
class="bg-primary text-primary-foreground"
|
||||||
>
|
>
|
||||||
{isSubmitting ? 'Processing...' : 'Complete Booking'}
|
{isSubmitting ? 'Processing...' : 'Confirm Booking'}
|
||||||
</Button>
|
</Button>
|
||||||
</Card.Footer>
|
</Card.Footer>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
|
|||||||
Reference in New Issue
Block a user