Slots: bulk generate, copy week and clear, with a preview step
Generate fills a date range (weekdays x opening hours) spaced by the service's duration + get-ready time (overridable). Copy repeats a week into the next 1-12 weeks; Clear deletes free slots in a range. Each previews first, skips past slots and overlaps with the same service, and never touches booked or in-basket slots. Planning is pure and DST-safe in $shared/slots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
This commit is contained in:
parent
1a71c9db73
commit
2052ad5a59
9 changed files with 862 additions and 11 deletions
54
app-admin/src/lib/admin/slots/BulkActions.svelte
Normal file
54
app-admin/src/lib/admin/slots/BulkActions.svelte
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<script lang="ts">
|
||||
// Footer of a bulk slot form: the server's preview, then Preview / confirm
|
||||
// buttons. See bulkForm.svelte.ts for the two-step submit.
|
||||
import { formatDateTime } from '$lib/calendar';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
import type { BulkForm } from './bulkForm.svelte';
|
||||
|
||||
let { bulk, timezone, onCancel }: { bulk: BulkForm; timezone: string; onCancel: () => void } = $props();
|
||||
|
||||
let preview = $derived(bulk.preview);
|
||||
let deleting = $derived(preview?.action === 'clear');
|
||||
let plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
||||
</script>
|
||||
|
||||
{#if bulk.error}<div class="alert alert-error mt-3 text-sm" role="alert">{bulk.error}</div>{/if}
|
||||
|
||||
{#if preview}
|
||||
<div class="mt-3 rounded-box bg-base-200 p-4 text-sm">
|
||||
{#if preview.count}
|
||||
<p class="font-semibold">
|
||||
{plural(preview.count, 'slot')} will be {deleting ? 'deleted' : 'created'}{preview.count > 1
|
||||
? `, from ${formatDateTime(preview.firstStart, timezone)} to ${formatDateTime(preview.lastStart, timezone)}`
|
||||
: `, at ${formatDateTime(preview.firstStart, timezone)}`}.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="font-semibold">Nothing to {deleting ? 'delete' : 'create'}.</p>
|
||||
{/if}
|
||||
<ul class="mt-1 list-inside list-disc text-base-content/70 empty:hidden">
|
||||
{#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.</li>{/if}
|
||||
{#if preview.skippedPast}<li>{plural(preview.skippedPast, 'slot')} skipped — in the past.</li>{/if}
|
||||
{#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.</li>{/if}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="modal-action">
|
||||
<button class="btn" type="button" onclick={onCancel}>Cancel</button>
|
||||
<button class={['btn', !preview?.count && 'btn-primary']} type="submit" name="intent" value="preview" disabled={bulk.busy}>
|
||||
{#if bulk.busy}<span class="loading loading-spinner loading-xs"></span>{/if}
|
||||
{preview ? 'Preview again' : 'Preview'}
|
||||
</button>
|
||||
{#if preview?.count}
|
||||
<button
|
||||
class={['btn', deleting ? 'btn-error' : 'btn-primary']}
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="create"
|
||||
disabled={bulk.busy}
|
||||
onclick={deleting ? confirmSubmit(`Delete ${plural(preview.count, 'slot')}?`) : undefined}
|
||||
>
|
||||
{deleting ? 'Delete' : 'Create'} {plural(preview.count, 'slot')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
59
app-admin/src/lib/admin/slots/ClearSlotsModal.svelte
Normal file
59
app-admin/src/lib/admin/slots/ClearSlotsModal.svelte
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
fromDate,
|
||||
toDate
|
||||
}: { open?: boolean; items: { id: string; name: string }[]; timezone: string; fromDate: string; toDate: string } = $props();
|
||||
|
||||
let draft = $state({ fromDate: '', toDate: '', item: '' });
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
// Each opening starts from the range the admin opened it for (a day or the month).
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
draft.fromDate = fromDate;
|
||||
draft.toDate = toDate;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Clear slots" wide>
|
||||
<form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1">
|
||||
<p class="text-sm text-base-content/70">Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.</p>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">From</span>
|
||||
<input class="input w-full" type="date" name="fromDate" required bind:value={draft.fromDate} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">To</span>
|
||||
<input class="input w-full" type="date" name="toDate" required min={draft.fromDate} bind:value={draft.toDate} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Services</span>
|
||||
<select class="select w-full" name="item" bind:value={draft.item}>
|
||||
<option value="">All services</option>
|
||||
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
68
app-admin/src/lib/admin/slots/CopyWeekModal.svelte
Normal file
68
app-admin/src/lib/admin/slots/CopyWeekModal.svelte
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import { addDaysToKey, formatDateKey, mondayOfKey } from '$lib/slots';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
sourceDate
|
||||
}: { open?: boolean; items: { id: string; name: string }[]; timezone: string; sourceDate: string } = $props();
|
||||
|
||||
let draft = $state({ sourceDate: '', weeks: 1, item: '' });
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
// Each opening copies from the week the admin opened it from.
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
draft.sourceDate = sourceDate;
|
||||
});
|
||||
});
|
||||
|
||||
const shortDate = (key: string) => formatDateKey(key, { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
let monday = $derived(mondayOfKey(draft.sourceDate));
|
||||
let weeks = $derived(Math.max(1, Math.min(12, Number(draft.weeks) || 1)));
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Copy a week" wide>
|
||||
<form method="POST" action="?/copy" use:enhance={bulk.submit} class="space-y-1">
|
||||
<p class="text-sm text-base-content/70">Repeat one week’s slots in the weeks after it — same weekdays and times. Slots already there are left alone.</p>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Copy the week of</span>
|
||||
<input class="input w-full" type="date" name="sourceDate" required bind:value={draft.sourceDate} />
|
||||
{#if monday}<span class="label">{shortDate(monday)} – {shortDate(addDaysToKey(monday, 6))}</span>{/if}
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Into the next</span>
|
||||
<select class="select w-full" name="weeks" bind:value={draft.weeks}>
|
||||
{#each Array.from({ length: 12 }, (_, i) => i + 1) as n}
|
||||
<option value={n}>{n} week{n === 1 ? '' : 's'}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if monday}<span class="label">{shortDate(addDaysToKey(monday, 7))} – {shortDate(addDaysToKey(monday, 7 * (weeks + 1) - 1))}</span>{/if}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Services</span>
|
||||
<select class="select w-full" name="item" bind:value={draft.item}>
|
||||
<option value="">All services</option>
|
||||
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
135
app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
Normal file
135
app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import { WEEKDAYS, addDaysToKey, startTimesInWindows, type TimeWindow } from '$lib/slots';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
type Service = { id: string; name: string; duration: number; bufferMinutes: number };
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
today
|
||||
}: { open?: boolean; items: Service[]; timezone: string; today: string } = $props();
|
||||
|
||||
// Kept between openings, so a second run starts from the last settings.
|
||||
let draft = $state({
|
||||
item: '',
|
||||
fromDate: '',
|
||||
toDate: '',
|
||||
weekdays: [1, 2, 3, 4, 5],
|
||||
windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[],
|
||||
bufferMinutes: '',
|
||||
notes: ''
|
||||
});
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
let service = $derived(items.find((item) => item.id === draft.item));
|
||||
let startTimes = $derived(
|
||||
service ? startTimesInWindows(draft.windows, service.duration, Number(draft.bufferMinutes) || 0) : []
|
||||
);
|
||||
|
||||
// Each opening starts without a stale preview; the first one also fills in dates.
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
if (!draft.fromDate) {
|
||||
draft.fromDate = today;
|
||||
draft.toDate = addDaysToKey(today, 27);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function selectService(id: string) {
|
||||
draft.item = id;
|
||||
// The service's own get-ready time is the default; it can be overridden here.
|
||||
draft.bufferMinutes = String(items.find((item) => item.id === id)?.bufferMinutes ?? 0);
|
||||
}
|
||||
|
||||
function addWindow() {
|
||||
const last = draft.windows.at(-1);
|
||||
draft.windows.push(last ? { from: last.to, to: last.to } : { from: '09:00', to: '17:00' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Generate slots" wide>
|
||||
<form method="POST" action="?/generate" use:enhance={bulk.submit} class="space-y-1">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Service</span>
|
||||
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}>
|
||||
<option value="" disabled>Select a service…</option>
|
||||
{#each items as item (item.id)}
|
||||
<option value={item.id}>{item.name} ({item.duration} min)</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">From</span>
|
||||
<input class="input w-full" type="date" name="fromDate" required bind:value={draft.fromDate} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">To</span>
|
||||
<input class="input w-full" type="date" name="toDate" required min={draft.fromDate} bind:value={draft.toDate} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="fieldset">
|
||||
<span class="fieldset-legend">Days</span>
|
||||
<div class="join grid grid-cols-7">
|
||||
{#each WEEKDAYS as weekday (weekday.day)}
|
||||
<input class="btn join-item btn-sm px-1" type="checkbox" name="weekday" value={weekday.day} aria-label={weekday.label} bind:group={draft.weekdays} />
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fieldset">
|
||||
<span class="fieldset-legend">Opening hours ({timezone})</span>
|
||||
<div class="space-y-2">
|
||||
{#each draft.windows as window, i}
|
||||
<div class="flex items-center gap-2">
|
||||
<input class="input w-32" type="time" name="windowFrom" required aria-label="From" bind:value={window.from} />
|
||||
<span>–</span>
|
||||
<input class="input w-32" type="time" name="windowTo" required aria-label="To" bind:value={window.to} />
|
||||
{#if draft.windows.length > 1}
|
||||
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove these hours" onclick={() => draft.windows.splice(i, 1)}>✕</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addWindow}>+ Add hours (e.g. after a lunch break)</button>
|
||||
</div>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Get-ready time (minutes)</span>
|
||||
<input class="input w-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} />
|
||||
<span class="label">Gap after each appointment. Defaults to the service’s own get-ready time.</span>
|
||||
</label>
|
||||
|
||||
{#if service}
|
||||
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
|
||||
{#if startTimes.length}
|
||||
<span class="font-semibold">{startTimes.length} per day:</span> {startTimes.join(', ')}
|
||||
{:else}
|
||||
No {service.duration}-minute appointment fits in these hours.
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Notes <span class="font-normal text-base-content/50">(optional, added to every slot)</span></span>
|
||||
<input class="input w-full" name="notes" bind:value={draft.notes} />
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
60
app-admin/src/lib/admin/slots/bulkForm.svelte.ts
Normal file
60
app-admin/src/lib/admin/slots/bulkForm.svelte.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { applyAction } from '$app/forms';
|
||||
import type { SubmitFunction } from '@sveltejs/kit';
|
||||
import type { BulkResult } from '$lib/slots';
|
||||
|
||||
/**
|
||||
* State for a /slots bulk form (generate, copy, clear), which is always
|
||||
* submitted twice: first `intent=preview` (the server says what it would
|
||||
* do), then `intent=create` to do it. The preview only counts while the
|
||||
* inputs are unchanged — `inputsKey` is a snapshot of them — so the admin
|
||||
* can't confirm numbers for a form they have since edited.
|
||||
*
|
||||
* Previews and errors stay inside the modal; a finished run closes it and
|
||||
* reloads the page, whose `form.bulk` then shows the outcome.
|
||||
*/
|
||||
export function bulkForm(inputsKey: () => string, close: () => void) {
|
||||
let preview = $state<BulkResult | null>(null);
|
||||
let previewKey = $state('');
|
||||
let error = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
const submit: SubmitFunction = () => {
|
||||
const key = inputsKey();
|
||||
busy = true;
|
||||
error = '';
|
||||
return async ({ result, update }) => {
|
||||
busy = false;
|
||||
if (result.type === 'success' && result.data?.bulk?.intent === 'preview') {
|
||||
preview = result.data.bulk as BulkResult;
|
||||
previewKey = key;
|
||||
} else if (result.type === 'failure') {
|
||||
error = String(result.data?.message || 'Something went wrong.');
|
||||
} else if (result.type === 'success') {
|
||||
preview = null;
|
||||
close();
|
||||
await update({ reset: false });
|
||||
} else {
|
||||
await applyAction(result);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
get preview() {
|
||||
return preview && previewKey === inputsKey() ? preview : null;
|
||||
},
|
||||
get error() {
|
||||
return error;
|
||||
},
|
||||
get busy() {
|
||||
return busy;
|
||||
},
|
||||
reset() {
|
||||
preview = null;
|
||||
error = '';
|
||||
},
|
||||
submit
|
||||
};
|
||||
}
|
||||
|
||||
export type BulkForm = ReturnType<typeof bulkForm>;
|
||||
65
app-admin/src/lib/server/slots.ts
Normal file
65
app-admin/src/lib/server/slots.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// Server helpers for the /slots bulk actions (generate, copy week, clear).
|
||||
// Planning is pure and lives in $shared/slots; this file does the PocketBase
|
||||
// reads/writes around it.
|
||||
|
||||
import { instantMs, type PlannedSlot } from '$lib/slots';
|
||||
import type { createPocketBase } from '$lib/pb';
|
||||
|
||||
type Pb = ReturnType<typeof createPocketBase>;
|
||||
|
||||
export type ExistingSlot = PlannedSlot & {
|
||||
id: string;
|
||||
item: string;
|
||||
status: string;
|
||||
heldUntil: string;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
/** How many PocketBase writes a bulk action runs at once. */
|
||||
const WRITE_CONCURRENCY = 5;
|
||||
|
||||
/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */
|
||||
export function isHoldActive(slot: Record<string, any> | null) {
|
||||
if (slot?.status !== 'held') return false;
|
||||
const until = instantMs(String(slot.heldUntil || ''));
|
||||
return Number.isNaN(until) || until > Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Slots starting in `[fromIso, toIso)`, optionally for one service. A slot
|
||||
* without an end gets one from its service's duration, so overlap checks
|
||||
* always have a real range.
|
||||
*/
|
||||
export async function loadSlotsBetween(pb: Pb, fromIso: string, toIso: string, itemId = ''): Promise<ExistingSlot[]> {
|
||||
const filter = itemId
|
||||
? pb.filter('start >= {:from} && start < {:to} && item = {:item}', { from: new Date(fromIso), to: new Date(toIso), item: itemId })
|
||||
: pb.filter('start >= {:from} && start < {:to}', { from: new Date(fromIso), to: new Date(toIso) });
|
||||
const records = await pb.collection('slots').getFullList({ filter, sort: 'start', expand: 'item' });
|
||||
return records.map((record) => {
|
||||
const start = String(record.start || '');
|
||||
const duration = Number(record.expand?.item?.duration) || 0;
|
||||
const end = record.end ? String(record.end) : new Date(instantMs(start) + duration * 60_000).toISOString();
|
||||
return {
|
||||
id: record.id,
|
||||
item: String(record.item || ''),
|
||||
start,
|
||||
end,
|
||||
status: String(record.status || 'available'),
|
||||
heldUntil: record.heldUntil ? String(record.heldUntil) : '',
|
||||
notes: String(record.notes || '')
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Run `fn` over `values` a few at a time; returns how many succeeded. */
|
||||
export async function runInBatches<T>(values: T[], label: string, fn: (value: T) => Promise<unknown>) {
|
||||
let succeeded = 0;
|
||||
for (let i = 0; i < values.length; i += WRITE_CONCURRENCY) {
|
||||
const results = await Promise.allSettled(values.slice(i, i + WRITE_CONCURRENCY).map(fn));
|
||||
for (const result of results) {
|
||||
if (result.status === 'fulfilled') succeeded++;
|
||||
else console.error(`[slots] ${label} failed`, result.reason);
|
||||
}
|
||||
}
|
||||
return succeeded;
|
||||
}
|
||||
1
app-admin/src/lib/slots.ts
Normal file
1
app-admin/src/lib/slots.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/slots';
|
||||
Loading…
Add table
Add a link
Reference in a new issue