added booking approvals

This commit is contained in:
2026-01-19 22:32:35 +00:00
parent 1dd37a8d22
commit 3a8ea4c98f
10 changed files with 5793 additions and 0 deletions
@@ -0,0 +1,443 @@
<script lang="ts">
import { authStore } from '$lib/stores/auth.svelte';
import { toast } from 'svelte-sonner';
import * as Modal from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Textarea } from '$lib/components/ui/textarea';
import * as AlertDialog from '$lib/components/ui/alert-dialog';
interface Props {
open: boolean;
booking: {
id: string;
notes?: string;
user?: {
full_name: string;
email?: string;
phone?: string;
};
services: Array<{
service_id: string;
service_name?: string;
price?: number;
duration_minutes?: number;
}>;
};
onApproved: () => void;
}
let { open = $bindable(), booking, onApproved }: Props = $props();
type ServiceOverride = {
serviceId: string;
overridePrice?: number;
overrideDurationMinutes?: number;
};
let notes = $state(booking.notes || '');
let serviceOverrides = $state<
Record<
string,
{
price: string;
duration: string;
originalPrice: number;
originalDuration: number;
}
>
>({});
let submitting = $state(false);
let showDeclineConfirm = $state(false);
// Initialize overrides with original values
$effect(() => {
if (!booking?.services?.length) return;
const overrides: Record<
string,
{
price: string;
duration: string;
originalPrice: number;
originalDuration: number;
}
> = {};
booking.services.forEach((service) => {
if (!service?.service_id) return;
const originalPrice = service.price || 0;
const originalDuration = service.duration_minutes || 60;
overrides[service.service_id] = {
price: originalPrice.toFixed(2),
duration: originalDuration.toString(),
originalPrice,
originalDuration
};
});
serviceOverrides = overrides;
});
// Validate and format price input - FIXED VERSION
function handlePriceInput(serviceId: string, value: string) {
const override = serviceOverrides[serviceId];
if (!override) return;
// Allow only numbers and one decimal point
let cleaned = value;
// Remove any characters that aren't digits or decimal point
cleaned = cleaned.replace(/[^\d.]/g, '');
// Ensure only one decimal point
const parts = cleaned.split('.');
if (parts.length > 2) {
cleaned = parts[0] + '.' + parts.slice(1).join('');
}
// If there's a decimal point, ensure max 2 decimal places
if (cleaned.includes('.')) {
const [integer, decimal] = cleaned.split('.');
if (decimal.length > 2) {
cleaned = integer + '.' + decimal.substring(0, 2);
}
}
serviceOverrides = {
...serviceOverrides,
[serviceId]: {
...override,
price: cleaned
}
};
}
// Validate and format duration input
function handleDurationInput(serviceId: string, value: string) {
const override = serviceOverrides[serviceId];
if (!override) return;
// Remove any non-numeric characters
const cleaned = value.replace(/\D/g, '');
serviceOverrides = {
...serviceOverrides,
[serviceId]: {
...override,
duration: cleaned
}
};
}
// Check if a value has changed from original
function hasPriceChanged(serviceId: string): boolean {
const override = serviceOverrides[serviceId];
if (!override) return false;
const currentPrice = parseFloat(override.price) || 0;
return Math.abs(currentPrice - override.originalPrice) > 0.001; // Account for floating point precision
}
function hasDurationChanged(serviceId: string): boolean {
const override = serviceOverrides[serviceId];
if (!override) return false;
const currentDuration = parseInt(override.duration) || 0;
return currentDuration !== override.originalDuration;
}
async function handleApprove() {
submitting = true;
const loadingToast = toast.loading('Confirming booking...');
try {
// Only include notes if different from original
const notesToSend =
notes.trim() !== (booking.notes || '') ? notes.trim() || undefined : undefined;
// Build service overrides array (only include if values are different)
const overrides: ServiceOverride[] = [];
for (const [serviceId, override] of Object.entries(serviceOverrides)) {
const priceChanged = hasPriceChanged(serviceId);
const durationChanged = hasDurationChanged(serviceId);
if (!priceChanged && !durationChanged) continue;
const overrideObj: ServiceOverride = { serviceId };
if (priceChanged) {
const overridePrice = parseFloat(override.price);
if (!isNaN(overridePrice)) {
overrideObj.overridePrice = overridePrice;
}
}
if (durationChanged) {
const overrideDuration = parseInt(override.duration);
if (!isNaN(overrideDuration)) {
overrideObj.overrideDurationMinutes = overrideDuration;
}
}
overrides.push(overrideObj);
}
const payload = {
notes: notesToSend,
serviceOverrides: overrides.length > 0 ? overrides : undefined
};
const response = await fetch(`/api/admin/bookings/${booking.id}/confirm`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify(payload)
});
if (response.ok) {
toast.success('Booking confirmed successfully!', { id: loadingToast });
open = false;
onApproved();
} else {
const text = await response.text();
toast.error('Failed to confirm: ' + text, { id: loadingToast });
}
} catch (err) {
console.error('Error confirming booking:', err);
toast.error('Network error confirming booking', { id: loadingToast });
} finally {
submitting = false;
}
}
async function handleDecline() {
// TODO: Implement decline/cancel endpoint
toast.info('Decline booking - Coming soon');
showDeclineConfirm = false;
open = false;
}
</script>
<Modal.Root bind:open>
<Modal.Content class="max-h-[90vh] max-w-2xl overflow-y-auto">
<Modal.Header>
<Modal.Title class="text-lg font-semibold">Approve Booking</Modal.Title>
<Modal.Description>
Review and confirm this booking. Adjust pricing or duration if needed.
</Modal.Description>
</Modal.Header>
<div class="space-y-6 px-4 pb-4">
<!-- Customer Contact Info -->
<div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
Customer Contact
</h3>
<div class="space-y-2">
<div>
<div class="text-xs text-gray-500">Name</div>
<div class="font-medium">{booking.user?.full_name || '—'}</div>
</div>
<div class="grid gap-3 md:grid-cols-2">
<div>
<div class="text-xs text-gray-500">Phone</div>
<div class="font-medium">{booking.user?.phone || '—'}</div>
</div>
<div>
<div class="text-xs text-gray-500">Email</div>
<div class="font-medium break-all">{booking.user?.email || '—'}</div>
</div>
</div>
</div>
</div>
<!-- Booking Notes -->
<div>
<label for="booking-notes" class="mb-2 block text-sm font-medium"> Booking Notes </label>
<Textarea
id="booking-notes"
bind:value={notes}
placeholder="Add any notes about this booking... (client will see this)"
rows={3}
class="w-full"
/>
{#if notes.trim() !== (booking.notes || '')}
<div class="mt-1 text-xs text-emerald-600">
✓ Notes will be saved (different from original)
</div>
{:else if booking.notes}
<div class="mt-1 text-xs text-gray-500">Notes unchanged from original</div>
{/if}
</div>
<!-- Service Overrides -->
<div>
<h3 class="mb-3 text-sm font-semibold tracking-wide text-gray-600 uppercase">
Services & Pricing
</h3>
<div class="space-y-3">
{#each booking.services ?? [] as service, i (i)}
{#if service && serviceOverrides[service.service_id]}
<div class="rounded-lg border border-gray-200 bg-white p-4">
<div class="font-medium">{service.service_name || 'Unknown Service'}</div>
<div class="grid gap-3 md:grid-cols-2">
<div>
<label for="price-{service.service_id}" class="mb-1 block text-xs text-gray-600"
>Price Override</label
>
<div class="relative">
<div
class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"
>
<span class="text-gray-500">£</span>
</div>
<!-- Changed to type="text" for better decimal handling -->
<Input
id="price-{service.service_id}"
type="text"
inputmode="decimal"
value={serviceOverrides[service.service_id].price}
oninput={(e) => handlePriceInput(service.service_id, e.target.value)}
onblur={() => {
// Format to 2 decimal places on blur if needed
const val = serviceOverrides[service.service_id].price;
if (val) {
// If there's no decimal point, add .00
if (!val.includes('.')) {
const num = parseFloat(val);
if (!isNaN(num)) {
serviceOverrides[service.service_id].price = num.toFixed(2);
serviceOverrides = serviceOverrides;
}
}
// If there's a decimal point with less than 2 decimal places, pad with zeros
else if (val.includes('.')) {
const parts = val.split('.');
if (parts[1].length === 0) {
serviceOverrides[service.service_id].price = parts[0] + '.00';
serviceOverrides = serviceOverrides;
} else if (parts[1].length === 1) {
serviceOverrides[service.service_id].price =
parts[0] + '.' + parts[1] + '0';
serviceOverrides = serviceOverrides;
}
}
}
}}
class="no-spin w-full pl-7"
placeholder={service.price?.toFixed(2) || '0.00'}
/>
</div>
<div class="mt-1 flex items-center justify-between">
<div class="text-xs text-gray-500">
Default: £{service.price?.toFixed(2) || '0.00'}
</div>
{#if hasPriceChanged(service.service_id)}
<div class="text-xs font-medium text-emerald-600">✓ Changed</div>
{/if}
</div>
</div>
<div>
<label
for="duration-{service.service_id}"
class="mb-1 block text-xs text-gray-600">Duration Override (min)</label
>
<div class="relative">
<Input
id="duration-{service.service_id}"
type="number"
min="1"
step="1"
value={serviceOverrides[service.service_id].duration}
oninput={(e) => handleDurationInput(service.service_id, e.target.value)}
class="no-spin w-full"
placeholder={service.duration_minutes?.toString() || '60'}
/>
</div>
<div class="mt-1 flex items-center justify-between">
<div class="text-xs text-gray-500">
Default: {service.duration_minutes || 60} min
</div>
{#if hasDurationChanged(service.service_id)}
<div class="text-xs font-medium text-emerald-600">✓ Changed</div>
{/if}
</div>
</div>
</div>
</div>
{/if}
{/each}
</div>
</div>
</div>
<Modal.Footer class="flex items-center justify-between gap-2">
<Button
variant="destructive"
onclick={() => (showDeclineConfirm = true)}
disabled={submitting}
>
Decline Booking
</Button>
<div class="flex gap-2">
<Button
onclick={handleApprove}
disabled={submitting}
class="bg-emerald-600 hover:bg-emerald-700"
>
{submitting ? 'Confirming...' : 'Confirm Booking'}
</Button>
</div>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
<!-- Decline Confirmation Dialog -->
<AlertDialog.Root bind:open={showDeclineConfirm}>
<AlertDialog.Content class="z-[60]">
<AlertDialog.Header>
<AlertDialog.Title>Decline this booking?</AlertDialog.Title>
<AlertDialog.Description>
This will cancel the booking and notify the customer. This action cannot be undone.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<AlertDialog.Action onclick={handleDecline} class="bg-red-600 hover:bg-red-700">
Decline Booking
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>
<style>
/* Hide number input arrows for Chrome, Safari, Edge */
input.no-spin::-webkit-outer-spin-button,
input.no-spin::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Hide number input arrows for Firefox */
input.no-spin[type='number'] {
-moz-appearance: textfield;
appearance: textfield;
}
/* Remove arrows from all number inputs in the component */
input[type='number'] {
-moz-appearance: textfield;
appearance: textfield;
}
input[type='number']::-webkit-outer-spin-button,
input[type='number']::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
</style>
@@ -0,0 +1,407 @@
<script lang="ts">
import { authStore } from '$lib/stores/auth.svelte';
import { SvelteDate } from 'svelte/reactivity';
import { toast } from 'svelte-sonner';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Skeleton } from '$lib/components/ui/skeleton';
interface Props {
openBookingModal: (bookingId: string) => void;
openUserModal: (userId: string) => void;
}
let { openBookingModal, openUserModal }: Props = $props();
type Booking = {
id: string;
start_time: string;
status: string;
notes?: string;
user?: {
id: string;
full_name: string;
phone?: string;
profile_pic_url?: string;
};
services: Array<{
service_name?: string;
service_description?: string;
price?: number;
duration_minutes?: number;
}>;
duration_minutes: number;
total_amount: number;
};
let currentAppointment = $state<Booking | null>(null);
let nextAppointment = $state<Booking | null>(null);
let freeTimeAfter = $state(0); // minutes of free time after current/next appointment
let loading = $state(true);
let timeRemaining = $state(0); // minutes remaining in current appointment
let isInProgress = $state(false);
// Calculate time remaining and free time
let interval: ReturnType<typeof setInterval> | null = null;
function calculateTimes() {
const now = new SvelteDate();
if (currentAppointment) {
isInProgress = currentAppointment.status === 'in_progress';
const startTime = new SvelteDate(currentAppointment.start_time);
if (isInProgress) {
// Appointment is in progress - show time remaining until end
const endTime = new SvelteDate(
startTime.getTime() + currentAppointment.duration_minutes * 60 * 1000
);
// If current time is before start time, show time until start
if (now.getTime() < startTime.getTime()) {
const timeUntilMs = startTime.getTime() - now.getTime();
timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
} else {
// Otherwise show time until end
const remainingMs = endTime.getTime() - now.getTime();
timeRemaining = Math.max(0, Math.floor(remainingMs / 60000));
}
// Calculate free time until next appointment
if (nextAppointment) {
const endTime = new SvelteDate(
startTime.getTime() + currentAppointment.duration_minutes * 60 * 1000
);
const nextStart = new SvelteDate(nextAppointment.start_time);
const gapMs = nextStart.getTime() - endTime.getTime();
freeTimeAfter = Math.max(0, Math.floor(gapMs / 60000));
} else {
freeTimeAfter = 0;
}
} else {
// Appointment is upcoming - show time until start
const timeUntilMs = startTime.getTime() - now.getTime();
timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
freeTimeAfter = 0;
// If there's a next appointment, calculate free time after this one ends
if (nextAppointment) {
const endTime = new SvelteDate(
startTime.getTime() + currentAppointment.duration_minutes * 60 * 1000
);
const nextStart = new SvelteDate(nextAppointment.start_time);
const gapMs = nextStart.getTime() - endTime.getTime();
freeTimeAfter = Math.max(0, Math.floor(gapMs / 60000));
}
}
}
}
async function fetchCurrentAndNext() {
loading = true;
try {
const response = await fetch('/api/admin/today/current-next', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
const data = await response.json();
currentAppointment = data.current || null;
nextAppointment = data.next || null;
calculateTimes();
} else {
toast.error('Failed to load current appointment');
}
} catch (err) {
console.error('Error fetching current appointment:', err);
toast.error('Network error loading appointment');
} finally {
loading = false;
}
}
// Start interval for real-time countdown
$effect(() => {
fetchCurrentAndNext();
interval = setInterval(() => {
calculateTimes();
}, 60000); // Update every minute
return () => {
if (interval) clearInterval(interval);
};
});
// WIP Demo actions
function handleBegin() {
toast.info('Begin appointment - Coming soon');
}
function handleEdit() {
if (currentAppointment) {
openBookingModal(currentAppointment.id);
}
}
function handleExtend() {
toast.info('Extend appointment - Coming soon');
}
function handleTakePayment() {
toast.info('Take payment - Coming soon');
}
function handleCancel() {
toast.info('Cancel appointment - Coming soon');
}
const activeAppointment = $derived(currentAppointment || nextAppointment);
</script>
<Card.Root class="border-2 border-blue-200 bg-blue-50">
<Card.Header>
<div class="flex items-start justify-between">
<div>
<Card.Title class="text-2xl">
{isInProgress ? 'Current Appointment' : 'Next Appointment'}
</Card.Title>
{#if activeAppointment}
<Card.Description class="text-base">
{new SvelteDate(activeAppointment.start_time).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
})}
-
{new SvelteDate(
new SvelteDate(activeAppointment.start_time).getTime() +
activeAppointment.duration_minutes * 60 * 1000
).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
})}
</Card.Description>
{/if}
</div>
{#if activeAppointment}
{#if isInProgress}
<Badge class="bg-blue-100 px-3 py-1 text-sm text-blue-800">
<span class="relative mr-2 flex h-2 w-2">
<span
class="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75"
></span>
<span class="relative inline-flex h-2 w-2 rounded-full bg-blue-600"></span>
</span>
In Progress • {timeRemaining} min remaining
{#if freeTimeAfter > 0}
{freeTimeAfter} min free
{/if}
</Badge>
{:else}
<Badge class="bg-amber-100 px-3 py-1 text-sm text-amber-800">
Starts in {timeRemaining} min
</Badge>
{/if}
{/if}
</div>
</Card.Header>
{#if loading}
<Card.Content class="space-y-4">
<div class="flex gap-4">
<Skeleton class="h-20 w-20 rounded-full" />
<div class="flex-1 space-y-2">
<Skeleton class="h-6 w-48" />
<Skeleton class="h-4 w-32" />
<Skeleton class="h-4 w-40" />
</div>
</div>
<Skeleton class="h-32 w-full" />
</Card.Content>
{:else if !activeAppointment}
<Card.Content>
<div class="py-12 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mx-auto mb-4 h-16 w-16 text-gray-300"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
<p class="text-lg font-medium text-gray-600">No appointments right now</p>
<p class="text-sm text-gray-500">Enjoy the break or check tomorrow's schedule</p>
</div>
</Card.Content>
{:else}
<Card.Content>
<div class="grid gap-6 md:grid-cols-3">
<!-- Customer Info -->
<div class="flex items-center gap-4">
{#if activeAppointment.user?.profile_pic_url}
<img
src={activeAppointment.user.profile_pic_url}
alt={activeAppointment.user.full_name}
class="h-20 w-20 rounded-full object-cover ring-4 ring-blue-200"
/>
{:else}
<div
class="flex h-20 w-20 items-center justify-center rounded-full bg-gray-200 text-2xl font-bold text-gray-600 ring-4 ring-blue-200"
>
{activeAppointment.user?.full_name?.charAt(0) || '?'}
</div>
{/if}
<div>
<div class="text-lg font-semibold">{activeAppointment.user?.full_name || 'Guest'}</div>
<div class="text-sm text-gray-600">{activeAppointment.user?.phone || '—'}</div>
{#if activeAppointment.user}
<button
type="button"
class="mt-1 text-xs text-blue-600 hover:underline"
onclick={() => openUserModal(activeAppointment.user!.id)}
>
View customer details →
</button>
{/if}
</div>
</div>
<!-- Services List -->
<div>
<div class="mb-2 text-sm font-semibold text-gray-700">Services</div>
<div class="space-y-2">
{#each activeAppointment.services as service, index (index)}
<div class="rounded-md border border-gray-200 bg-white p-2 text-sm">
<div class="font-medium">{service.service_name || 'Unknown Service'}</div>
{#if service.service_description}
<div class="text-xs text-gray-600">{service.service_description}</div>
{/if}
<div class="mt-1 flex items-center justify-between text-xs text-gray-500">
<span>{service.duration_minutes} mins</span>
</div>
</div>
{/each}
</div>
</div>
<!-- Notes & Actions -->
<div class="space-y-3">
{#if activeAppointment.notes}
<div class="rounded-md border border-amber-200 bg-amber-50 p-3">
<div class="mb-1 flex items-center gap-2 text-xs font-semibold text-amber-800">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clip-rule="evenodd"
/>
</svg>
Notes
</div>
<div class="text-sm text-amber-900">{activeAppointment.notes}</div>
</div>
{/if}
<div class="grid grid-cols-2 gap-2">
{#if !isInProgress}
<Button size="sm" onclick={handleBegin} class="col-span-2">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"
clip-rule="evenodd"
/>
</svg>
Begin
</Button>
{/if}
<Button size="sm" variant="outline" onclick={handleEdit}>
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"
/>
</svg>
Edit
</Button>
<Button size="sm" onclick={handleTakePayment} class="bg-green-600 hover:bg-green-700">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z" />
<path
fill-rule="evenodd"
d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z"
clip-rule="evenodd"
/>
</svg>
Payment
</Button>
{#if isInProgress}
<Button size="sm" variant="outline" onclick={handleExtend}>
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
clip-rule="evenodd"
/>
</svg>
Extend
</Button>
{/if}
<Button size="sm" variant="destructive" onclick={handleCancel} class="col-span-2">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
Cancel
</Button>
</div>
</div>
</div>
</Card.Content>
{/if}
</Card.Root>
@@ -0,0 +1,248 @@
<script lang="ts">
import { authStore } from '$lib/stores/auth.svelte';
import { SvelteDate } from 'svelte/reactivity';
import { toast } from 'svelte-sonner';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Skeleton } from '$lib/components/ui/skeleton';
import ApprovalModal from '$lib/components/admin/ApprovalModal.svelte';
interface Props {
openBookingModal?: (bookingId: string) => void;
}
let { openBookingModal }: Props = $props();
// Match the backend structure
type PendingApproval = {
id: string;
start_time: string;
user_id: string;
user_name: string; // This is a string, not an object
services: string[]; // Array of service names
duration_minutes: number;
created_at: string;
};
type PendingBooking = {
id: string;
start_time: string;
notes?: string;
user?: {
id: string;
full_name: string;
email?: string;
phone?: string;
};
services: Array<{
service_id: string;
service_name?: string;
price?: number;
duration_minutes?: number;
}>;
duration_minutes: number;
created_at: string;
};
let pendingApprovals = $state<PendingApproval[]>([]);
let visibleApprovals = $derived(pendingApprovals.slice(0, 3));
let loading = $state(true);
let showApprovalModal = $state(false);
let selectedBooking = $state<PendingBooking | null>(null);
// Helper function to format date nicely
function formatDateTime(dateTimeString: string): string {
const date = new SvelteDate(dateTimeString);
const dateStr = date.toLocaleDateString('en-US', {
weekday: 'long',
day: 'numeric',
month: 'short'
});
const timeStr = date.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
return `${dateStr} at ${timeStr}`;
}
async function fetchPendingApprovals() {
loading = true;
try {
const response = await fetch('/api/admin/today/pending-approvals', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
const data = await response.json();
pendingApprovals = (data.approvals || []).sort(
(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
} else {
toast.error('Failed to load pending approvals');
}
} catch (err) {
console.error('Error fetching pending approvals:', err);
toast.error('Network error loading pending approvals');
} finally {
loading = false;
}
}
async function openApprovalModal(bookingId: string) {
try {
const response = await fetch(`/api/admin/bookings/${bookingId}`, {
headers: {
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (!response.ok) throw new Error(await response.text());
const data = await response.json();
selectedBooking = data; // now has full services with price/duration
showApprovalModal = true;
} catch (err) {
console.error('Failed to load booking details:', err);
toast.error('Failed to load booking details');
}
}
$effect(() => {
fetchPendingApprovals();
const intervalId = setInterval(() => {
fetchPendingApprovals();
}, 60_000);
return () => {
clearInterval(intervalId);
};
});
</script>
<Card.Root>
<Card.Header>
<div class="flex items-start justify-between">
<div>
<Card.Title class="flex items-center gap-2">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5 text-amber-600"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
clip-rule="evenodd"
/>
</svg>
Pending Approvals
</Card.Title>
<Card.Description>New bookings awaiting confirmation</Card.Description>
</div>
{#if !loading}
<Badge class="bg-amber-100 text-amber-800 hover:bg-amber-100">
{pendingApprovals.length}
</Badge>
{/if}
</div>
</Card.Header>
<Card.Content>
{#if loading}
<div class="space-y-3">
{#each Array(3) as _, i (i)}
<div class="rounded-lg border p-3">
<div class="flex items-start justify-between">
<div class="flex-1 space-y-2">
<Skeleton class="h-4 w-32" />
<Skeleton class="h-3 w-48" />
<Skeleton class="h-3 w-24" />
</div>
<Skeleton class="h-8 w-20" />
</div>
</div>
{/each}
</div>
{:else if pendingApprovals.length === 0}
<div class="py-8 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mx-auto mb-3 h-12 w-12 text-gray-300"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
<p class="text-sm font-medium text-gray-600">All caught up!</p>
<p class="text-xs text-gray-500">No pending bookings to review</p>
</div>
{:else}
<div class="space-y-3">
{#each visibleApprovals as approval (approval.id)}
<div
class="rounded-lg border border-amber-200 bg-amber-50/30 p-3 transition-all hover:shadow-md"
>
<div class="flex items-start justify-between gap-3">
<div class="flex-1">
<div class="font-medium">{approval.user_name || 'Guest'}</div>
<div class="mt-1 text-sm text-gray-600">
{approval.services.join(', ')}
</div>
<div class="mt-1 text-xs text-gray-500">
<div class="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
<span>
{formatDateTime(approval.start_time)}
</span>
<span class="hidden sm:inline"></span>
<span>
{approval.duration_minutes} mins
</span>
</div>
</div>
</div>
<div class="flex flex-col gap-2">
<Button
size="sm"
onclick={() => openApprovalModal(approval.id)}
class="bg-emerald-600 hover:bg-emerald-700"
>
Approve
</Button>
{#if openBookingModal}
<Button size="sm" variant="outline" onclick={() => openBookingModal(approval.id)}>
Details
</Button>
{/if}
</div>
</div>
</div>
{/each}
</div>
{/if}
</Card.Content>
</Card.Root>
<!-- Approval Modal -->
{#if selectedBooking && showApprovalModal}
<ApprovalModal
bind:open={showApprovalModal}
booking={selectedBooking}
onApproved={() => {
showApprovalModal = false;
fetchPendingApprovals();
window.dispatchEvent(new CustomEvent('bookingApproved'));
}}
/>
{/if}
@@ -0,0 +1,212 @@
<script lang="ts">
import { authStore } from '$lib/stores/auth.svelte';
import { SvelteDate } from 'svelte/reactivity';
import { toast } from 'svelte-sonner';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Skeleton } from '$lib/components/ui/skeleton';
interface Props {
openBookingModal: (bookingId: string) => void;
openUserModal: (userId: string) => void;
}
let { openBookingModal, openUserModal }: Props = $props();
type TodayAppointment = {
id: string;
start_time: string;
status: string;
user_name: string;
user_id: string;
services: string[];
duration_minutes: number;
};
let appointments = $state<TodayAppointment[]>([]);
let loading = $state(true);
async function fetchTodayAppointments() {
loading = true;
try {
const response = await fetch('/api/admin/today/appointments', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
const data = await response.json();
appointments = data.appointments || [];
} else {
toast.error("Failed to load today's appointments");
}
} catch (err) {
console.error("Error fetching today's appointments:", err);
toast.error('Network error loading appointments');
} finally {
loading = false;
}
}
// 🔁 Refetch on mount, every minute, and on approval
$effect(() => {
// Initial fetch
fetchTodayAppointments();
// Timer: refetch every 60 seconds
const intervalId = setInterval(() => {
fetchTodayAppointments();
}, 60_000);
// Listener for approval events
function handleApproval() {
fetchTodayAppointments();
}
window.addEventListener('bookingApproved', handleApproval);
// Cleanup
return () => {
clearInterval(intervalId);
window.removeEventListener('bookingApproved', handleApproval);
};
});
// Fetch on mount
$effect(() => {
fetchTodayAppointments();
});
function getStatusColor(status: string): string {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800 hover:bg-green-100';
case 'in_progress':
return 'bg-blue-100 text-blue-800 hover:bg-blue-100';
case 'confirmed':
return 'bg-emerald-100 text-emerald-800 hover:bg-emerald-100';
case 'pending':
return 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100';
case 'client_cancelled':
case 'we_cancelled':
return 'bg-red-100 text-red-800 hover:bg-red-100';
case 'no_show':
return 'bg-gray-100 text-gray-800 hover:bg-gray-100';
default:
return 'bg-gray-100 text-gray-800 hover:bg-gray-100';
}
}
function getStatusBarColor(status: string): string {
switch (status) {
case 'completed':
return 'bg-green-500';
case 'in_progress':
return 'bg-blue-500';
case 'confirmed':
return 'bg-emerald-500';
case 'pending':
return 'bg-yellow-500';
case 'client_cancelled':
case 'we_cancelled':
return 'bg-red-500';
case 'no_show':
return 'bg-gray-500';
default:
return 'bg-gray-500';
}
}
function formatTime(dateString: string): string {
const date = new SvelteDate(dateString);
return date.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
}
function formatStatus(status: string): string {
return status.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
}
</script>
<div class="lg:col-span-2">
<Card.Root>
<Card.Header>
<Card.Title>Today's Appointments</Card.Title>
<Card.Description>Timeline view of all bookings</Card.Description>
</Card.Header>
<Card.Content>
{#if loading}
<div class="space-y-3">
{#each Array(5) as _, i (i)}
<div class="flex items-center gap-4 rounded-lg border p-3">
<Skeleton class="h-4 w-20" />
<Skeleton class="h-10 w-1" />
<div class="flex-1 space-y-2">
<Skeleton class="h-4 w-32" />
<Skeleton class="h-3 w-48" />
</div>
<Skeleton class="h-6 w-20" />
<Skeleton class="h-8 w-16" />
</div>
{/each}
</div>
{:else if appointments.length === 0}
<div class="py-12 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mx-auto mb-4 h-16 w-16 text-gray-300"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
<p class="text-lg font-medium text-gray-600">No appointments today</p>
<p class="text-sm text-gray-500">Looks like you have a quiet day</p>
</div>
{:else}
<div class="space-y-3">
{#each appointments as apt (apt.id)}
<div
class="flex items-center gap-4 rounded-lg border p-3 transition-all hover:shadow-md"
>
<div class="min-w-[80px] text-sm font-semibold text-gray-700">
{formatTime(apt.start_time)}
</div>
<div class="h-10 w-1 rounded {getStatusBarColor(apt.status)}"></div>
<div class="flex-1">
<button
type="button"
class="font-medium hover:text-blue-600 hover:underline"
onclick={() => openUserModal(apt.user_id)}
>
{apt.user_name}
</button>
<div class="text-sm text-gray-600">
{apt.services.join(', ')}{apt.duration_minutes} min
</div>
</div>
<Badge class={getStatusColor(apt.status)}>
{formatStatus(apt.status)}
</Badge>
<Button size="sm" variant="outline" onclick={() => openBookingModal(apt.id)}>
View
</Button>
</div>
{/each}
</div>
{/if}
</Card.Content>
</Card.Root>
</div>
@@ -0,0 +1,50 @@
<script lang="ts" module>
import { type VariantProps, tv } from "tailwind-variants";
export const badgeVariants = tv({
base: "focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] [&>svg]:pointer-events-none [&>svg]:size-3",
variants: {
variant: {
default:
"bg-primary text-primary-foreground [a&]:hover:bg-primary/90 border-transparent",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90 border-transparent",
destructive:
"bg-destructive [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/70 border-transparent text-white",
outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
});
export type BadgeVariant = VariantProps<typeof badgeVariants>["variant"];
</script>
<script lang="ts">
import type { HTMLAnchorAttributes } from "svelte/elements";
import { cn, type WithElementRef } from "$lib/utils.js";
let {
ref = $bindable(null),
href,
class: className,
variant = "default",
children,
...restProps
}: WithElementRef<HTMLAnchorAttributes> & {
variant?: BadgeVariant;
} = $props();
</script>
<svelte:element
this={href ? "a" : "span"}
bind:this={ref}
data-slot="badge"
{href}
class={cn(badgeVariants({ variant }), className)}
{...restProps}
>
{@render children?.()}
</svelte:element>
@@ -0,0 +1,2 @@
export { default as Badge } from "./badge.svelte";
export { badgeVariants, type BadgeVariant } from "./badge.svelte";