Slots: bulk tools, get-ready time, group places, and bookings block overlapping slots #3

Merged
reudy merged 11 commits from session/redo-slots-and-add-get-ready-tim into main 2026-10-24 12:15:35 +02:00
3 changed files with 206 additions and 20 deletions
Showing only changes of commit b52da79ec8 - Show all commits

View file

@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb,
app-admin/ # SvelteKit admin app (serves admin.<domain>) app-admin/ # SvelteKit admin app (serves admin.<domain>)
├── src/ ├── src/
│ ├── lib/ │ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers) │ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers, slots/ bulk modals)
│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) │ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared)
│ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia │ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia
│ │ ├── types.ts # Re-exports from $shared │ │ ├── types.ts # Re-exports from $shared
@ -22,14 +22,14 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── scrollReveal.ts # Re-exports from $shared
│ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared
│ │ ├── basket.svelte.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts) │ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts)
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
│ │ ├── login/ # Admin login │ │ ├── login/ # Admin login
│ │ ├── pages/ # Page CRUD + block editor │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── calendar/ # Event CRUD (menu label: Events)
│ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── slots/ # Bookable time slot CRUD │ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── orders/ # Order list + booking-email status/resend
│ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
@ -118,6 +118,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### Shared Code ### Shared Code
- `packages/shared/src/types.ts` — all type definitions - `packages/shared/src/types.ts` — all type definitions
- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) - `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block)
- `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts`
- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` - Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'`
- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work - Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work

View file

@ -112,7 +112,7 @@ If schema import fails because of a PocketBase version mismatch, create these co
Commerce collections (see the Stripe section above for context): Commerce collections (see the Stripe section above for context):
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `active` bool - `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `active` bool
- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text - `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text
- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot` - `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`
@ -120,7 +120,7 @@ Commerce collections (see the Stripe section above for context):
- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot) - `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot)
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool - `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool
> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Relation and select fields carry their config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`) at the field top level, not nested under `options`. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass. > **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Field config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`, number `min`/`max`/`onlyInt`) belongs at the field top level — 0.23 silently ignores anything nested under `options`, so the older number/text fields that still use `options` get no min/max on a fresh install. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass.
## Authentication ## Authentication
@ -138,7 +138,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages/[slug]` — block editor with draft preview - `/pages/[slug]` — block editor with draft preview
- `/calendar` — events shown by Upcoming Calendar blocks - `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services and products shown in Shop blocks - `/items` — services and products shown in Shop blocks
- `/slots` — manually created bookable time slots for services - `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (free slots only). Bulk tools preview first, skip slots in the past or overlapping a slot of the same service, and never touch booked or in-basket slots. Different services may overlap — there is no cross-service collision check.
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons - `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons
- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
- `/globals` — header/footer/colors editor - `/globals` — header/footer/colors editor

View file

@ -1,13 +1,80 @@
<script lang="ts"> <script lang="ts">
import type { SubmitFunction } from '@sveltejs/kit';
import { enhance } from '$app/forms';
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte';
import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte';
import { WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys } from '$lib/slots';
import type { BulkResult } from '$lib/slots';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
let slots = $derived(data.slots || []); let serviceFilter = $state('');
let showEditor = $state(false); let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter));
type Slot = (typeof slots)[number];
// ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4;
let gridKeys = $derived(monthGridKeys(data.month));
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
let slotsByDay = $derived.by(() => {
const byDay = new Map<string, Slot[]>();
for (const slot of slots) {
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
}
return byDay;
});
let monthSlots = $derived(slots.filter((slot) => toZonedDatetimeInput(slot.start, data.timezone).startsWith(data.month)));
// ── Modals ──
let showEditor = $state(false);
let showGenerate = $state(false);
let showCopy = $state(false);
let showClear = $state(false);
let dayKey = $state('');
let showDay = $state(false);
let copyFrom = $state('');
let clearRange = $state({ from: '', to: '' });
let daySlots = $derived(slotsByDay.get(dayKey) ?? []);
let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null);
function bulkMessage(result: BulkResult) {
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
const verb = result.action === 'clear' ? 'Deleted' : 'Created';
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (booked or taken in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`;
}
function statusClass(status: string) {
if (status === 'booked') return 'border-info/40 bg-info/15';
if (status === 'held') return 'border-warning/50 bg-warning/20';
return 'border-success/40 bg-success/10';
}
function openDay(key: string) {
dayKey = key;
showDay = true;
}
function openCopy(key: string) {
copyFrom = mondayOfKey(key);
showDay = false;
showCopy = true;
}
function openClear(from: string, to: string) {
clearRange = { from, to };
showDay = false;
showClear = true;
}
// ── Single slot editor ──
type SlotDraft = { type SlotDraft = {
id: string; id: string;
item: string; item: string;
@ -18,6 +85,7 @@
}; };
let draft = $state<SlotDraft>(emptyDraft()); let draft = $state<SlotDraft>(emptyDraft());
let editorError = $state('');
let action = $derived(draft.id ? '?/update' : '?/create'); let action = $derived(draft.id ? '?/update' : '?/create');
let isHeld = $derived(draft.status === 'held'); let isHeld = $derived(draft.status === 'held');
let selectedItem = $derived(items.find((item) => item.id === draft.item)); let selectedItem = $derived(items.find((item) => item.id === draft.item));
@ -29,16 +97,34 @@
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`; return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
}); });
function emptyDraft(): SlotDraft { function emptyDraft(day = ''): SlotDraft {
return { id: '', item: '', start: toZonedDatetimeInput(new Date().toISOString(), data.timezone), status: 'available', heldUntil: '', notes: '' }; const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
return { id: '', item: serviceFilter, start, status: 'available', heldUntil: '', notes: '' };
} }
function createSlot() { // Enhanced so the page keeps its ?month= after saving (a plain POST to
draft = emptyDraft(); // ?/create would drop it), and errors show inside the open modal.
const submitSlot: SubmitFunction = () => {
editorError = '';
return async ({ result, update }) => {
if (result.type === 'failure') {
editorError = String(result.data?.message || 'Could not save the slot.');
return;
}
if (result.type === 'success') showEditor = false;
await update();
};
};
function createSlot(day = '') {
editorError = '';
draft = emptyDraft(day);
showDay = false;
showEditor = true; showEditor = true;
} }
function editSlot(slot: (typeof slots)[number]) { function editSlot(slot: Slot) {
editorError = '';
draft = { draft = {
id: slot.id, id: slot.id,
item: slot.item, item: slot.item,
@ -47,6 +133,7 @@
heldUntil: slot.heldUntil, heldUntil: slot.heldUntil,
notes: slot.notes notes: slot.notes
}; };
showDay = false;
showEditor = true; showEditor = true;
} }
</script> </script>
@ -57,19 +144,79 @@
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div>
<h1 class="text-3xl font-bold">Slots</h1> <h1 class="text-3xl font-bold">Slots</h1>
<p class="text-base-content/60">Create bookable time slots for your services. Times are in {data.timezone}.</p> <p class="text-base-content/60">Bookable time slots for your services. Times are in {data.timezone}.</p>
</div>
<div class="flex flex-wrap gap-2">
<button class="btn" type="button" onclick={() => createSlot()}>Create slot</button>
<button class="btn" type="button" onclick={() => openCopy(data.today)}>Copy a week</button>
<button class="btn" type="button" onclick={() => openClear(data.today > `${data.month}-01` ? data.today : `${data.month}-01`, monthEnd)}>Clear slots</button>
<button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
</div> </div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
{#if bulkDone}<div class="alert alert-success" role="status">{bulkMessage(bulkDone)}</div>{/if}
{#if !items.length}<div class="alert" role="status">Add a bookable service under Services & products first.</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box bg-base-100 p-5 shadow">
<div class="overflow-x-auto"> <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex gap-2">
<a class="btn btn-outline btn-sm" href="?month={addMonthsToKey(data.month, -1)}" data-sveltekit-noscroll>← Previous</a>
<a class="btn btn-ghost btn-sm" href="?month={data.today.slice(0, 7)}" data-sveltekit-noscroll>Today</a>
<a class="btn btn-outline btn-sm" href="?month={addMonthsToKey(data.month, 1)}" data-sveltekit-noscroll>Next →</a>
</div>
<h2 class="text-2xl font-bold">{monthLabel}</h2>
<select class="select select-sm w-auto" aria-label="Show service" bind:value={serviceFilter}>
<option value="">All services</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</div>
<div class="grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase text-base-content/50 md:gap-2">
{#each WEEKDAYS as weekday (weekday.day)}<div>{weekday.label}</div>{/each}
</div>
<div class="mt-2 grid grid-cols-7 gap-1 md:gap-2">
{#each gridKeys as key (key)}
{@const daySlotList = slotsByDay.get(key) ?? []}
{@const isToday = key === data.today}
<div class="min-h-28 min-w-0 rounded-box border border-base-300 bg-base-200/60 p-1 md:p-2" class:opacity-40={!key.startsWith(data.month)}>
<button
class="btn btn-circle btn-xs mb-1 {isToday ? 'btn-primary' : 'btn-ghost'}"
type="button"
title="Show this day"
aria-current={isToday ? 'date' : undefined}
onclick={() => openDay(key)}>{Number(key.slice(8))}</button
>
<div class="space-y-1">
{#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)}
<button class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {statusClass(slot.status)}" type="button" title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {slot.status}" onclick={() => (slot.status === 'booked' ? openDay(key) : editSlot(slot))}>
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
<span class="hidden lg:inline">{slot.itemName}</span>
</button>
{/each}
{#if daySlotList.length > MAX_CHIPS}
<button class="btn btn-ghost btn-xs w-full" type="button" onclick={() => openDay(key)}>+{daySlotList.length - MAX_CHIPS} more</button>
{/if}
</div>
</div>
{/each}
</div>
<div class="mt-4 flex flex-wrap gap-4 text-xs text-base-content/70">
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {statusClass('available')}"></span> Available</span>
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {statusClass('held')}"></span> In a basket</span>
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {statusClass('booked')}"></span> Booked</span>
</div>
</div>
<!-- Collapsed by default: a generated month is hundreds of rows, and the calendar covers day-to-day use. -->
<details class="collapse collapse-arrow rounded-box bg-base-100 shadow">
<summary class="collapse-title text-2xl font-bold">All slots in {monthLabel} <span class="text-base font-normal text-base-content/60">({monthSlots.length})</span></summary>
<div class="collapse-content overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead> <thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each slots as slot (slot.id)} {#each monthSlots as slot (slot.id)}
<tr> <tr>
<td><span class="font-semibold">{slot.itemName}</span></td> <td><span class="font-semibold">{slot.itemName}</span></td>
<td>{formatDateTime(slot.start, data.timezone)}</td> <td>{formatDateTime(slot.start, data.timezone)}</td>
@ -87,18 +234,56 @@
</td> </td>
</tr> </tr>
{:else} {:else}
<tr><td colspan="5" class="py-10 text-center text-base-content/60">{items.length ? 'No slots yet — create one so customers can book.' : 'Add a bookable service under Services & products first.'}</td></tr> <tr><td colspan="5" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr>
{/each} {/each}
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </details>
</div> </div>
<GenerateSlotsModal bind:open={showGenerate} {items} timezone={data.timezone} today={data.today} />
<CopyWeekModal bind:open={showCopy} {items} timezone={data.timezone} sourceDate={copyFrom} />
<ClearSlotsModal bind:open={showClear} {items} timezone={data.timezone} fromDate={clearRange.from} toDate={clearRange.to} />
<Modal bind:open={showDay} title={formatDateKey(dayKey, { weekday: 'long', day: 'numeric', month: 'long' })} wide>
{#if daySlots.length}
<ul class="divide-y divide-base-300">
{#each daySlots as slot (slot.id)}
<li class="flex items-center gap-3 py-2">
<span class="w-28 shrink-0 font-semibold">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span>
<span class="min-w-0 flex-1">
<span class="block truncate">{slot.itemName}</span>
{#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if}
</span>
<span
class="badge capitalize"
class:badge-success={slot.status === 'available'}
class:badge-warning={slot.status === 'held'}
class:badge-info={slot.status === 'booked'}
>{slot.status}</span>
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} onclick={() => editSlot(slot)}>Edit</button>
</li>
{/each}
</ul>
{:else}
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
{/if}
<div class="modal-action flex-wrap justify-between">
<div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button>
{#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if}
</div>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot(dayKey)}>Add slot</button>
</div>
</Modal>
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}> <Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}>
<form method="POST" action={action} class="space-y-1"> <form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
<input type="hidden" name="id" value={draft.id} /> <input type="hidden" name="id" value={draft.id} />
{#if editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if}
{#if isHeld} {#if isHeld}
<div class="alert alert-warning mb-2 text-sm"> <div class="alert alert-warning mb-2 text-sm">
This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed. This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed.