feat: enriched edit request system with side-by-side snapshots, calendar preloading, and admin review UI

Backend:
- Add enriched response types (EditSnapshot, EnrichedEditRequest) with original vs proposed snapshots
- Add 4 new GET endpoints for viewing edit requests (user and admin scoped)
- Remove github.com/lib/pq dependency — use native PostgreSQL array scanning
- Clean up edit requests, time blockers, and notifications on booking cancellation
- Validate exceptional closed hours on admin approve (409 Conflict)
- Notification upsert on edit request replace (no duplicate admin notifications)

Frontend:
- New user EditRequestModal with time/services/both modes and lunch protection
- New admin EditRequestModal with side-by-side diff (date/time, services, notes)
- Integrate edit requests into PendingApprovals card and notifications page
- Preload 3 months of availability to prevent calendar snap-back
- Apply lunch protection to isDateUnavailable in BookingFlow and BookingCreateModal
- Fix accessibility: card list items use <button> instead of <div>

Dev & Docs:
- Seed edit requests in local-dev-2.sh
- Update all Obsidian manuals with enriched edit request documentation
- 42 new tests (438/441 passing)
This commit is contained in:
2026-05-26 11:59:07 +01:00
parent 3ccc017716
commit 8574bf2221
19 changed files with 5270 additions and 599 deletions
@@ -197,6 +197,7 @@
// =============== Effects ===============
let wasOpen = false;
let bookingCreateInitialLoadDone = $state(false);
$effect(() => {
if (open && !wasOpen) {
@@ -215,16 +216,21 @@
}
});
// Preload 3 months when entering step 4 to prevent snap-back
$effect(() => {
if (open && currentStep === 4) {
const dateToCheck = selectedDate || placeholder;
fetchHoursForMonth(dateToCheck);
if (open && currentStep === 4 && !bookingCreateInitialLoadDone) {
fetchHoursRange(placeholder, 3);
bookingCreateInitialLoadDone = true;
}
});
// Fetch additional months when navigating beyond preloaded range
$effect(() => {
if (open && currentStep === 4 && placeholder) {
fetchHoursForMonth(placeholder);
if (open && currentStep === 4 && bookingCreateInitialLoadDone && placeholder) {
const monthKey = `${placeholder.year}-${String(placeholder.month).padStart(2, '0')}`;
if (!workingHoursCache.has(monthKey)) {
fetchHoursForMonth(placeholder);
}
}
});
@@ -246,6 +252,7 @@
availableHoursCache.clear();
workingHours = null;
availableHours = null;
bookingCreateInitialLoadDone = false;
// Clear reservation state
reservationId = null;
reservationExpiresAt = null;
@@ -304,6 +311,68 @@
}
}
async function fetchHoursRange(startDate: CalendarDate, months: number) {
// Calculate end month manually (CalendarDate is immutable)
let endYear = startDate.year;
let endMonth = startDate.month + months - 1;
while (endMonth > 12) {
endMonth -= 12;
endYear++;
}
const endMonthDate = new CalendarDate(endYear, endMonth, 1);
const daysInEndMonth = endMonthDate.calendar.getDaysInMonth(endMonthDate);
const startStr = startDate.toString();
const endStr = `${endYear}-${String(endMonth).padStart(2, '0')}-${String(daysInEndMonth).padStart(2, '0')}`;
loadingWorkingHours = true;
loadingAvailableHours = true;
try {
const [whRes, ahRes] = await Promise.all([
fetch(`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`, {
headers: { Authorization: `Bearer ${authStore.currentToken}` }
}),
fetch(`/api/scheduling/available-hours?start=${startStr}&end=${endStr}`, {
headers: { Authorization: `Bearer ${authStore.currentToken}` }
})
]);
if (whRes.ok && ahRes.ok) {
const whData: WorkingHoursDay[] = await whRes.json();
const ahData: AvailableHoursDay[] = await ahRes.json();
const whMap: Record<string, any> = {};
const ahMap: Record<string, any> = {};
whData.forEach((d) => (whMap[d.date] = { isOpen: d.isOpen, startTime: d.startTime, endTime: d.endTime }));
ahData.forEach((d) => (ahMap[d.date] = { isOpen: d.isOpen, slots: d.slots }));
// Cache by month key
for (let i = 0; i < months; i++) {
let mYear = startDate.year;
let mMonth = startDate.month + i;
while (mMonth > 12) {
mMonth -= 12;
mYear++;
}
const key = `${mYear}-${String(mMonth).padStart(2, '0')}`;
workingHoursCache.set(key, whMap);
availableHoursCache.set(key, ahMap);
}
workingHours = whMap;
availableHours = ahMap;
}
} catch (err) {
console.error('Failed to fetch hours', err);
toast.error('Failed to load availability');
} finally {
loadingWorkingHours = false;
loadingAvailableHours = false;
}
}
async function fetchHoursForMonth(date: CalendarDate) {
const monthKey = `${date.year}-${String(date.month).padStart(2, '0')}`;
@@ -712,12 +781,32 @@
if (!workingHours) return true;
const dateStr = date.toString();
if (!workingHours[dateStr]?.isOpen) return true;
const dayHours = workingHours[dateStr];
if (!dayHours?.isOpen) return true;
if (selectedServices.length > 0) {
const duration = getTotalDuration();
const slots = generateAvailableTimeSlots(duration, date);
return slots.length === 0;
if (slots.length === 0) return true;
const dayAvailableHours = availableHours?.[dateStr];
if (dayAvailableHours?.slots) {
const existingBookings = extractBookedSlots(
dayHours.startTime,
dayHours.endTime,
dayAvailableHours.slots
);
const lunchProtection = getLunchProtectionForSlots(
dayHours.startTime,
dayHours.endTime,
existingBookings,
duration,
15,
true
);
const validSlots = slots.filter((t) => !lunchProtection.get(t)?.isBlocked);
if (validSlots.length === 0) return true;
}
}
return false;
@@ -1244,9 +1333,10 @@
selectedDate = newDate;
selectedTime = null;
}}
onPlaceholderChange={(newPlaceholder) => {
placeholder = newPlaceholder;
}}
onPlaceholderChange={(newPlaceholder) => {
placeholder = newPlaceholder;
fetchHoursForMonth(newPlaceholder);
}}
/>
</div>
{/if}
@@ -0,0 +1,377 @@
<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 * as AlertDialog from '$lib/components/ui/alert-dialog';
interface ServiceItem {
id: string;
name: string;
price: number;
duration_minutes: number;
}
interface EditRequest {
id: string;
booking_id: string;
requested_by: string;
requested_at: string;
notes: string | null;
original: {
start_time: string;
end_time: string;
services: ServiceItem[];
notes: string;
};
proposed: {
start_time: string | null;
end_time: string | null;
services: ServiceItem[];
notes: string | null;
};
user: {
id: string;
full_name: string;
email: string;
phone: string;
};
}
interface Props {
open: boolean;
editRequest: EditRequest;
onApproved: () => void;
onDenied: () => void;
}
let { open = $bindable(), editRequest, onApproved, onDenied }: Props = $props();
let submitting = $state(false);
let showDenyConfirm = $state(false);
function formatDateLine1(dateTimeString: string): string {
const d = new Date(dateTimeString);
const dateStr = d.toLocaleDateString('en-GB', {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric'
});
const startTime = d.toLocaleTimeString('en-GB', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
return `${dateStr} at ${startTime}`;
}
function formatDateLine2(dateTimeString: string, durationMinutes: number): string {
const d = new Date(dateTimeString);
const endMinutes = d.getHours() * 60 + d.getMinutes() + durationMinutes;
const endH = Math.floor(endMinutes / 60);
const endM = endMinutes % 60;
const endPeriod = endH >= 12 ? 'pm' : 'am';
const endDisplayH = endH % 12 || 12;
const endTime = `${endDisplayH}:${String(endM).padStart(2, '0')} ${endPeriod}`;
return `${endTime}, ${durationMinutes} minutes`;
}
function getDuration(services: ServiceItem[]): number {
return services.reduce((sum, s) => sum + s.duration_minutes, 0);
}
function isTimeChanged(): boolean {
if (!editRequest.proposed.start_time) return false;
return editRequest.proposed.start_time !== editRequest.original.start_time;
}
function areServicesChanged(): boolean {
const origIds = new Set(editRequest.original.services.map((s) => s.id));
const propIds = new Set(editRequest.proposed.services.map((s) => s.id));
if (origIds.size !== propIds.size) return true;
for (const id of origIds) {
if (!propIds.has(id)) return true;
}
return false;
}
let serviceDiff = $derived.by(() => {
const orig = editRequest.original.services;
const prop = editRequest.proposed.services;
const origIds = new Set(orig.map((s) => s.id));
const propIds = new Set(prop.map((s) => s.id));
return {
removed: orig.filter((s) => !propIds.has(s.id)),
added: prop.filter((s) => !origIds.has(s.id)),
same: orig.filter((s) => propIds.has(s.id))
};
});
async function handleApprove() {
submitting = true;
const loadingToast = toast.loading('Approving change request...');
try {
const response = await fetch(
`/api/admin/bookings/${editRequest.booking_id}/edit-requests/${editRequest.id}/approve`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
}
);
if (response.ok) {
toast.success('Change request approved!', { id: loadingToast });
open = false;
onApproved();
} else {
const text = await response.text();
toast.error('Failed to approve: ' + text, { id: loadingToast });
}
} catch (err) {
console.error('Error approving edit request:', err);
toast.error('Network error approving change request', { id: loadingToast });
} finally {
submitting = false;
}
}
async function handleDeny() {
submitting = true;
const loadingToast = toast.loading('Denying change request...');
try {
const response = await fetch(
`/api/admin/bookings/${editRequest.booking_id}/edit-requests/${editRequest.id}/deny`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
}
);
if (response.ok) {
toast.success('Change request denied', { id: loadingToast });
showDenyConfirm = false;
open = false;
onDenied();
} else {
const text = await response.text();
toast.error('Failed to deny: ' + text, { id: loadingToast });
}
} catch (err) {
console.error('Error denying edit request:', err);
toast.error('Network error denying change request', { id: loadingToast });
} finally {
submitting = false;
showDenyConfirm = 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">Booking Change Request</Modal.Title>
<Modal.Description>
Review the requested changes to {editRequest.user.full_name}'s booking.
</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">{editRequest.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">{editRequest.user.phone || '—'}</div>
</div>
<div>
<div class="text-xs text-gray-500">Email</div>
<div class="font-medium break-all">{editRequest.user.email || '—'}</div>
</div>
</div>
</div>
</div>
<!-- Date & Time Change -->
<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">
Date & Time Change
</h3>
<div class="space-y-3">
<div>
<div class="mb-1 text-xs text-gray-500">Before</div>
<div class="font-medium">
{formatDateLine1(editRequest.original.start_time)}
</div>
<div class="text-sm text-gray-600">
{formatDateLine2(editRequest.original.start_time, getDuration(editRequest.original.services))}
</div>
</div>
{#if isTimeChanged()}
<div>
<div class="mb-1 text-xs text-gray-500">After</div>
<div class="font-medium text-emerald-700">
{formatDateLine1(editRequest.proposed.start_time!)}
</div>
<div class="text-sm text-gray-600">
{formatDateLine2(editRequest.proposed.start_time!, getDuration(editRequest.proposed.services))}
</div>
</div>
{:else}
<div class="text-sm italic text-gray-500">No change</div>
{/if}
</div>
</div>
<!-- Services Change -->
<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">
Services Change
</h3>
<div class="grid gap-4 md:grid-cols-2">
<div>
<div class="mb-1 text-xs text-gray-500">Original</div>
<div class="space-y-2">
{#each editRequest.original.services as service}
{#if serviceDiff.removed.some((s) => s.id === service.id)}
<div class="flex items-start gap-2 rounded border border-red-200 bg-red-50 p-2">
<span class="mt-0.5 text-red-600 font-mono text-sm"></span>
<div class="flex-1">
<div class="text-sm font-medium text-red-700 line-through">
{service.name}
</div>
<div class="text-xs text-red-600">
£{service.price.toFixed(2)} &middot; {service.duration_minutes} min
</div>
</div>
</div>
{:else}
<div class="flex items-start gap-2 rounded border border-gray-200 bg-white p-2">
<span class="mt-0.5 text-gray-400 font-mono text-sm"> </span>
<div class="flex-1">
<div class="text-sm font-medium">{service.name}</div>
<div class="text-xs text-gray-600">
£{service.price.toFixed(2)} &middot; {service.duration_minutes} min
</div>
</div>
</div>
{/if}
{/each}
</div>
</div>
<div>
<div class="mb-1 text-xs text-gray-500">Proposed</div>
<div class="space-y-2">
{#each editRequest.proposed.services as service}
{#if serviceDiff.added.some((s) => s.id === service.id)}
<div class="flex items-start gap-2 rounded border border-emerald-200 bg-emerald-50 p-2">
<span class="mt-0.5 text-emerald-600 font-mono text-sm">+</span>
<div class="flex-1">
<div class="text-sm font-medium text-emerald-700">{service.name}</div>
<div class="text-xs text-emerald-600">
£{service.price.toFixed(2)} &middot; {service.duration_minutes} min
</div>
</div>
</div>
{:else}
<div class="flex items-start gap-2 rounded border border-gray-200 bg-white p-2">
<span class="mt-0.5 text-gray-400 font-mono text-sm"> </span>
<div class="flex-1">
<div class="text-sm font-medium">{service.name}</div>
<div class="text-xs text-gray-600">
£{service.price.toFixed(2)} &middot; {service.duration_minutes} min
</div>
</div>
</div>
{/if}
{/each}
</div>
</div>
</div>
</div>
<!-- Notes Change -->
<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">
Booking Notes Change
</h3>
<div class="grid gap-4 md:grid-cols-2">
<div>
<div class="mb-1 text-xs text-gray-500">Original</div>
<div class="text-sm">{editRequest.original.notes || '—'}</div>
</div>
<div>
<div class="mb-1 text-xs text-gray-500">Proposed</div>
{#if editRequest.proposed.notes && editRequest.proposed.notes !== editRequest.original.notes}
<div class="text-sm">{editRequest.proposed.notes}</div>
{:else}
<div class="text-sm italic text-gray-500">No change</div>
{/if}
</div>
</div>
</div>
<!-- Request Notes -->
{#if editRequest.notes}
<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">
Reason for Change
</h3>
<p class="text-sm text-gray-700">{editRequest.notes}</p>
</div>
{/if}
</div>
<Modal.Footer class="flex items-center justify-end gap-2">
<Button
variant="destructive"
onclick={() => (showDenyConfirm = true)}
disabled={submitting}
>
Deny
</Button>
<Button
onclick={handleApprove}
disabled={submitting}
class="bg-emerald-600 hover:bg-emerald-700"
>
{submitting ? 'Approving...' : 'Approve'}
</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>
<!-- Deny Confirmation Dialog -->
<AlertDialog.Root bind:open={showDenyConfirm}>
<AlertDialog.Content class="z-[60]">
<AlertDialog.Header>
<AlertDialog.Title>Deny this change request?</AlertDialog.Title>
<AlertDialog.Description>
This will reject the requested changes and notify the customer. This action cannot be
undone.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<AlertDialog.Action onclick={handleDeny} class="bg-red-600 hover:bg-red-700">
Deny Request
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>