Compare commits
No commits in common. "b52da79ec8a6ec073f9570030d5677bc9c46e6da" and "13b5f2bbcb5b879736897367ed1c75759572d544" have entirely different histories.
b52da79ec8
...
13b5f2bbcb
18 changed files with 36 additions and 1117 deletions
|
|
@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb,
|
|||
app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
||||
├── src/
|
||||
│ ├── lib/
|
||||
│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers, slots/ bulk modals)
|
||||
│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers)
|
||||
│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared)
|
||||
│ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia
|
||||
│ │ ├── types.ts # Re-exports from $shared
|
||||
|
|
@ -22,14 +22,14 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
|||
│ │ ├── scrollReveal.ts # Re-exports from $shared
|
||||
│ │ ├── stripe-client.ts # Re-exports from $shared
|
||||
│ │ ├── basket.svelte.ts # Re-exports from $shared
|
||||
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts)
|
||||
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts)
|
||||
│ ├── routes/
|
||||
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
|
||||
│ │ ├── login/ # Admin login
|
||||
│ │ ├── pages/ # Page CRUD + block editor
|
||||
│ │ ├── calendar/ # Event CRUD (menu label: Events)
|
||||
│ │ ├── items/ # Service/product CRUD (menu label: Services & products)
|
||||
│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
|
||||
│ │ ├── slots/ # Bookable time slot CRUD
|
||||
│ │ ├── orders/ # Order list + booking-email status/resend
|
||||
│ │ ├── emails/ # Block-based booking email editor (live preview, test send)
|
||||
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
|
||||
|
|
@ -118,7 +118,6 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
|
|||
### Shared Code
|
||||
- `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/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 `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work
|
||||
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
||||
- `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
|
||||
- `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
|
||||
- `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
|
||||
- `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)
|
||||
- `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). 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.
|
||||
> **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.
|
||||
|
||||
## 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
|
||||
- `/calendar` — events shown by Upcoming Calendar blocks
|
||||
- `/items` — services and products shown in Shop blocks
|
||||
- `/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.
|
||||
- `/slots` — manually created bookable time slots for services
|
||||
- `/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)
|
||||
- `/globals` — header/footer/colors editor
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
<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>
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
<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>
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
<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>
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
<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>
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
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>;
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
// 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 +0,0 @@
|
|||
export * from '$shared/slots';
|
||||
|
|
@ -8,10 +8,8 @@ function itemPayload(data: FormData) {
|
|||
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
|
||||
const rawStock = String(data.get('stock') ?? '').trim();
|
||||
const rawDuration = String(data.get('duration') ?? '').trim();
|
||||
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
|
||||
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
|
||||
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
|
||||
const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
|
||||
|
||||
return {
|
||||
name: String(data.get('name') || '').trim(),
|
||||
|
|
@ -21,7 +19,6 @@ function itemPayload(data: FormData) {
|
|||
type,
|
||||
stock: Number.isNaN(stock) ? null : stock,
|
||||
duration: Number.isNaN(duration) ? null : duration,
|
||||
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
|
||||
active: String(data.get('active')) === 'true'
|
||||
};
|
||||
}
|
||||
|
|
@ -38,7 +35,6 @@ function normalizeItem(record: Record<string, any>): ItemRecord {
|
|||
type: record.type === 'item_with_time' ? 'item_with_time' : 'item',
|
||||
stock: record.stock ?? null,
|
||||
duration: record.duration ?? null,
|
||||
bufferMinutes: record.bufferMinutes ?? null,
|
||||
active: record.active !== false
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@
|
|||
type: ItemType;
|
||||
stock: string;
|
||||
duration: string;
|
||||
bufferMinutes: string;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
|
|
@ -31,7 +30,7 @@
|
|||
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
|
||||
|
||||
function emptyDraft(): ItemDraft {
|
||||
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', active: true };
|
||||
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true };
|
||||
}
|
||||
|
||||
function createItem() {
|
||||
|
|
@ -51,7 +50,6 @@
|
|||
type: item.type,
|
||||
stock: item.stock == null ? '' : String(item.stock),
|
||||
duration: item.duration == null ? '' : String(item.duration),
|
||||
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
|
||||
active: item.active
|
||||
};
|
||||
uploadError = '';
|
||||
|
|
@ -109,7 +107,7 @@
|
|||
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
|
||||
<td>{money.format(item.price)}</td>
|
||||
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
|
||||
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}` : '—'}</td>
|
||||
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td>
|
||||
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||
</tr>
|
||||
|
|
@ -158,17 +156,10 @@
|
|||
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
|
||||
</label>
|
||||
{:else}
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Duration (minutes)</span>
|
||||
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Get-ready time (minutes)</span>
|
||||
<input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} />
|
||||
<span class="label">Gap left after each appointment when generating slots</span>
|
||||
</label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="fieldset">
|
||||
|
|
|
|||
|
|
@ -1,25 +1,8 @@
|
|||
import { env } from '$env/dynamic/private';
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import { toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
|
||||
import { zonedInputToIso } from '$lib/calendar';
|
||||
import type { createPocketBase } from '$lib/pb';
|
||||
import { attempt } from '$lib/server/actions';
|
||||
import { isHoldActive, loadSlotsBetween, runInBatches, type ExistingSlot } from '$lib/server/slots';
|
||||
import {
|
||||
MAX_BULK_SLOTS,
|
||||
addDaysToKey,
|
||||
dateKeysBetween,
|
||||
instantMs,
|
||||
isDateKey,
|
||||
mondayOfKey,
|
||||
monthGridKeys,
|
||||
overlapsAny,
|
||||
planGeneratedSlots,
|
||||
shiftByDays,
|
||||
timeToMinutes,
|
||||
type BulkResult,
|
||||
type PlannedSlot,
|
||||
type TimeWindow
|
||||
} from '$lib/slots';
|
||||
import type { SlotStatus } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
|
|
@ -30,12 +13,13 @@ type SlotPayload =
|
|||
| { error: string };
|
||||
|
||||
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
|
||||
const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10);
|
||||
/** Midnight at the start of `key` in the site timezone, as an ISO instant. */
|
||||
const dayStartIso = (key: string) => zonedInputToIso(`${key}T00:00`, siteTimezone());
|
||||
|
||||
const MAX_RANGE_DAYS = 366;
|
||||
const MAX_COPY_WEEKS = 12;
|
||||
/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */
|
||||
function isHoldActive(slot: Record<string, any> | null) {
|
||||
if (slot?.status !== 'held') return false;
|
||||
const until = Date.parse(String(slot.heldUntil || '').replace(' ', 'T'));
|
||||
return Number.isNaN(until) || until > Date.now();
|
||||
}
|
||||
|
||||
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
|
||||
const itemId = String(data.get('item') || '').trim();
|
||||
|
|
@ -65,89 +49,7 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
|
|||
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } };
|
||||
}
|
||||
|
||||
/** Validated `from`/`to` date keys from a bulk form, or an error message. */
|
||||
function dateRange(data: FormData): { fromDate: string; toDate: string } | { error: string } {
|
||||
const fromDate = String(data.get('fromDate') || '');
|
||||
const toDate = String(data.get('toDate') || '');
|
||||
if (!isDateKey(fromDate) || !isDateKey(toDate)) return { error: 'Choose a start and end date.' };
|
||||
if (toDate < fromDate) return { error: 'The end date is before the start date.' };
|
||||
if (dateKeysBetween(fromDate, toDate).length > MAX_RANGE_DAYS) return { error: 'Choose a range of at most one year.' };
|
||||
return { fromDate, toDate };
|
||||
}
|
||||
|
||||
async function bookableService(pb: Pb, itemId: string) {
|
||||
if (!itemId) return null;
|
||||
const item = await pb.collection('items').getOne(itemId).catch(() => null);
|
||||
return item && item.type === 'item_with_time' ? item : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop candidates that start in the past or overlap a slot of the same
|
||||
* service (existing, or accepted earlier in this run). Different services
|
||||
* may overlap freely — there is no cross-service collision detection.
|
||||
*/
|
||||
function filterCandidates(candidates: (PlannedSlot & { item: string })[], existing: ExistingSlot[]) {
|
||||
const now = Date.now();
|
||||
const taken = new Map<string, PlannedSlot[]>();
|
||||
for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]);
|
||||
|
||||
const accepted: typeof candidates = [];
|
||||
let skippedPast = 0;
|
||||
let skippedOverlap = 0;
|
||||
for (const candidate of candidates) {
|
||||
if (instantMs(candidate.start) <= now) {
|
||||
skippedPast++;
|
||||
continue;
|
||||
}
|
||||
const ranges = taken.get(candidate.item) ?? [];
|
||||
if (overlapsAny(candidate, ranges)) {
|
||||
skippedOverlap++;
|
||||
continue;
|
||||
}
|
||||
ranges.push(candidate);
|
||||
taken.set(candidate.item, ranges);
|
||||
accepted.push(candidate);
|
||||
}
|
||||
accepted.sort((a, b) => instantMs(a.start) - instantMs(b.start));
|
||||
return { accepted, skippedPast, skippedOverlap };
|
||||
}
|
||||
|
||||
function bulkResult(fields: Partial<BulkResult> & Pick<BulkResult, 'action' | 'intent' | 'count'>): { bulk: BulkResult } {
|
||||
return { bulk: { skippedOverlap: 0, skippedPast: 0, kept: 0, firstStart: '', lastStart: '', failed: 0, ...fields } };
|
||||
}
|
||||
|
||||
/** Preview, or create, the accepted candidates. */
|
||||
async function previewOrCreate(
|
||||
pb: Pb,
|
||||
action: 'generate' | 'copy',
|
||||
intent: string,
|
||||
result: ReturnType<typeof filterCandidates>,
|
||||
notesFor: (slot: PlannedSlot & { item: string }) => string
|
||||
) {
|
||||
const { accepted, skippedPast, skippedOverlap } = result;
|
||||
if (accepted.length > MAX_BULK_SLOTS) {
|
||||
return fail(400, { message: `That would create ${accepted.length} slots — at most ${MAX_BULK_SLOTS} at once. Choose a shorter range.` });
|
||||
}
|
||||
const summary = {
|
||||
action,
|
||||
skippedPast,
|
||||
skippedOverlap,
|
||||
firstStart: accepted[0]?.start ?? '',
|
||||
lastStart: accepted.at(-1)?.start ?? ''
|
||||
};
|
||||
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: accepted.length });
|
||||
|
||||
const created = await runInBatches(accepted, 'create', (slot) =>
|
||||
pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, notes: notesFor(slot), status: 'available' })
|
||||
);
|
||||
return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created });
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals, url }) => {
|
||||
const today = todayKey();
|
||||
const monthParam = url.searchParams.get('month') || '';
|
||||
const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7);
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const itemRecords = await locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' })
|
||||
|
|
@ -155,22 +57,12 @@ export const load: PageServerLoad = async ({ locals, url }) => {
|
|||
const items = itemRecords.map((record) => ({
|
||||
id: record.id,
|
||||
name: String(record.name || ''),
|
||||
duration: Number(record.duration) || 0,
|
||||
bufferMinutes: Number(record.bufferMinutes) || 0
|
||||
duration: record.duration ?? 0
|
||||
}));
|
||||
|
||||
// Only the slots shown in the month grid (which spans whole weeks).
|
||||
const grid = monthGridKeys(month);
|
||||
const slotRecords = await locals.pb
|
||||
.collection('slots')
|
||||
.getFullList({
|
||||
filter: locals.pb.filter('start >= {:from} && start < {:to}', {
|
||||
from: new Date(dayStartIso(grid[0])),
|
||||
to: new Date(dayStartIso(addDaysToKey(grid[grid.length - 1], 1)))
|
||||
}),
|
||||
sort: 'start',
|
||||
expand: 'item'
|
||||
})
|
||||
.getFullList({ sort: 'start', expand: 'item' })
|
||||
.catch(() => []);
|
||||
const slots = slotRecords.map((record) => ({
|
||||
id: record.id,
|
||||
|
|
@ -185,7 +77,7 @@ export const load: PageServerLoad = async ({ locals, url }) => {
|
|||
notes: String(record.notes || '')
|
||||
}));
|
||||
|
||||
return { items, slots, month, today };
|
||||
return { items, slots };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
|
|
@ -232,117 +124,5 @@ export const actions: Actions = {
|
|||
const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
|
||||
if (!deleted.ok) return deleted.failure;
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
/** Fill a date range with slots: chosen weekdays, time windows, get-ready gap. */
|
||||
generate: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const intent = String(data.get('intent') || 'preview');
|
||||
const range = dateRange(data);
|
||||
if ('error' in range) return fail(400, { message: range.error });
|
||||
|
||||
const item = await bookableService(locals.pb, String(data.get('item') || ''));
|
||||
if (!item) return fail(400, { message: 'Choose a bookable service.' });
|
||||
const duration = Number(item.duration) || 0;
|
||||
if (duration <= 0) return fail(400, { message: `“${item.name}” has no duration — set one under Services & products.` });
|
||||
|
||||
const weekdays = data.getAll('weekday').map(Number).filter((day) => day >= 0 && day <= 6);
|
||||
if (!weekdays.length) return fail(400, { message: 'Choose at least one weekday.' });
|
||||
|
||||
const froms = data.getAll('windowFrom').map(String);
|
||||
const tos = data.getAll('windowTo').map(String);
|
||||
const windows: TimeWindow[] = froms.map((from, i) => ({ from, to: tos[i] ?? '' }));
|
||||
if (!windows.length) return fail(400, { message: 'Add at least one time window.' });
|
||||
for (const window of windows) {
|
||||
const from = timeToMinutes(window.from);
|
||||
const to = timeToMinutes(window.to);
|
||||
if (from === null || to === null) return fail(400, { message: 'Every time window needs a start and an end time.' });
|
||||
if (to - from < duration) return fail(400, { message: `The window ${window.from}–${window.to} is shorter than one ${duration}-minute appointment.` });
|
||||
}
|
||||
|
||||
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
|
||||
const bufferMinutes = rawBuffer === '' ? Number(item.bufferMinutes) || 0 : parseInt(rawBuffer, 10);
|
||||
if (Number.isNaN(bufferMinutes) || bufferMinutes < 0) return fail(400, { message: 'Get-ready time must be 0 or more minutes.' });
|
||||
|
||||
const planned = planGeneratedSlots({ ...range, weekdays, windows, durationMinutes: duration, bufferMinutes, timeZone: siteTimezone() });
|
||||
if (!planned.length) return fail(400, { message: 'No slots fit those days and times.' });
|
||||
|
||||
const existing = await loadSlotsBetween(
|
||||
locals.pb,
|
||||
dayStartIso(range.fromDate),
|
||||
dayStartIso(addDaysToKey(range.toDate, 1)),
|
||||
item.id
|
||||
).catch(() => null);
|
||||
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
|
||||
|
||||
const notes = String(data.get('notes') || '').trim();
|
||||
const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id })), existing);
|
||||
return previewOrCreate(locals.pb, 'generate', intent, result, () => notes);
|
||||
},
|
||||
|
||||
/** Repeat one week's slots (all services, or one) for the following weeks. */
|
||||
copy: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const intent = String(data.get('intent') || 'preview');
|
||||
const sourceWeek = mondayOfKey(String(data.get('sourceDate') || ''));
|
||||
if (!sourceWeek) return fail(400, { message: 'Choose the week to copy.' });
|
||||
const weeks = parseInt(String(data.get('weeks') || ''), 10);
|
||||
if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` });
|
||||
const itemId = String(data.get('item') || '');
|
||||
|
||||
const source = await loadSlotsBetween(locals.pb, dayStartIso(sourceWeek), dayStartIso(addDaysToKey(sourceWeek, 7)), itemId).catch(() => null);
|
||||
const existing = await loadSlotsBetween(
|
||||
locals.pb,
|
||||
dayStartIso(addDaysToKey(sourceWeek, 7)),
|
||||
dayStartIso(addDaysToKey(sourceWeek, 7 * (weeks + 1))),
|
||||
itemId
|
||||
).catch(() => null);
|
||||
if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' });
|
||||
if (!source.length) return fail(400, { message: 'That week has no slots to copy.' });
|
||||
|
||||
const notesByStart = new Map<string, string>();
|
||||
const candidates: (PlannedSlot & { item: string })[] = [];
|
||||
for (let week = 1; week <= weeks; week++) {
|
||||
for (const slot of source) {
|
||||
const start = shiftByDays(slot.start, 7 * week, siteTimezone());
|
||||
if (!start) continue;
|
||||
const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString();
|
||||
candidates.push({ item: slot.item, start, end });
|
||||
notesByStart.set(`${slot.item}|${start}`, slot.notes);
|
||||
}
|
||||
}
|
||||
|
||||
const result = filterCandidates(candidates, existing);
|
||||
return previewOrCreate(locals.pb, 'copy', intent, result, (slot) => notesByStart.get(`${slot.item}|${slot.start}`) ?? '');
|
||||
},
|
||||
|
||||
/** Delete the free slots in a date range. Booked and currently-held slots stay. */
|
||||
clear: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const intent = String(data.get('intent') || 'preview');
|
||||
const range = dateRange(data);
|
||||
if ('error' in range) return fail(400, { message: range.error });
|
||||
const itemId = String(data.get('item') || '');
|
||||
|
||||
const slots = await loadSlotsBetween(locals.pb, dayStartIso(range.fromDate), dayStartIso(addDaysToKey(range.toDate, 1)), itemId).catch(() => null);
|
||||
if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' });
|
||||
|
||||
const removable = slots.filter((slot) => slot.status !== 'booked' && !isHoldActive(slot));
|
||||
const summary = {
|
||||
action: 'clear' as const,
|
||||
kept: slots.length - removable.length,
|
||||
firstStart: removable[0]?.start ?? '',
|
||||
lastStart: removable.at(-1)?.start ?? ''
|
||||
};
|
||||
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length });
|
||||
|
||||
// Re-check each slot just before deleting it: a customer may have put
|
||||
// it in their basket since the list was read.
|
||||
const deleted = await runInBatches(removable, 'delete', async (slot) => {
|
||||
const fresh = await locals.pb.collection('slots').getOne(slot.id);
|
||||
if (fresh.status === 'booked' || isHoldActive(fresh)) throw new Error('taken since the preview');
|
||||
await locals.pb.collection('slots').delete(slot.id);
|
||||
});
|
||||
return bulkResult({ ...summary, intent: 'done', count: deleted, failed: removable.length - deleted });
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,80 +1,13 @@
|
|||
<script lang="ts">
|
||||
import type { SubmitFunction } from '@sveltejs/kit';
|
||||
import { enhance } from '$app/forms';
|
||||
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
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 items = $derived(data.items || []);
|
||||
let serviceFilter = $state('');
|
||||
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 slots = $derived(data.slots || []);
|
||||
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 = {
|
||||
id: string;
|
||||
item: string;
|
||||
|
|
@ -85,7 +18,6 @@
|
|||
};
|
||||
|
||||
let draft = $state<SlotDraft>(emptyDraft());
|
||||
let editorError = $state('');
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let isHeld = $derived(draft.status === 'held');
|
||||
let selectedItem = $derived(items.find((item) => item.id === draft.item));
|
||||
|
|
@ -97,34 +29,16 @@
|
|||
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
|
||||
});
|
||||
|
||||
function emptyDraft(day = ''): SlotDraft {
|
||||
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
|
||||
return { id: '', item: serviceFilter, start, status: 'available', heldUntil: '', notes: '' };
|
||||
function emptyDraft(): SlotDraft {
|
||||
return { id: '', item: '', start: toZonedDatetimeInput(new Date().toISOString(), data.timezone), status: 'available', heldUntil: '', notes: '' };
|
||||
}
|
||||
|
||||
// Enhanced so the page keeps its ?month= after saving (a plain POST to
|
||||
// ?/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;
|
||||
function createSlot() {
|
||||
draft = emptyDraft();
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editSlot(slot: Slot) {
|
||||
editorError = '';
|
||||
function editSlot(slot: (typeof slots)[number]) {
|
||||
draft = {
|
||||
id: slot.id,
|
||||
item: slot.item,
|
||||
|
|
@ -133,7 +47,6 @@
|
|||
heldUntil: slot.heldUntil,
|
||||
notes: slot.notes
|
||||
};
|
||||
showDay = false;
|
||||
showEditor = true;
|
||||
}
|
||||
</script>
|
||||
|
|
@ -144,79 +57,19 @@
|
|||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Slots</h1>
|
||||
<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>
|
||||
<p class="text-base-content/60">Create bookable time slots for your services. Times are in {data.timezone}.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
|
||||
</div>
|
||||
|
||||
{#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="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">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each monthSlots as slot (slot.id)}
|
||||
{#each slots as slot (slot.id)}
|
||||
<tr>
|
||||
<td><span class="font-semibold">{slot.itemName}</span></td>
|
||||
<td>{formatDateTime(slot.start, data.timezone)}</td>
|
||||
|
|
@ -234,56 +87,18 @@
|
|||
</td>
|
||||
</tr>
|
||||
{:else}
|
||||
<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>
|
||||
<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>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</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'}>
|
||||
<form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
|
||||
<form method="POST" action={action} class="space-y-1">
|
||||
<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}
|
||||
<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.
|
||||
|
|
|
|||
|
|
@ -31,7 +31,6 @@ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[
|
|||
type: record.type,
|
||||
stock: record.stock ?? null,
|
||||
duration: record.duration ?? null,
|
||||
bufferMinutes: record.bufferMinutes ?? null,
|
||||
active: record.active
|
||||
};
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,189 +0,0 @@
|
|||
// Bulk slot planning — pure functions shared by the admin's generate/copy
|
||||
// forms (client hints) and their server actions (what actually gets created).
|
||||
//
|
||||
// Dates are calendar keys (`YYYY-MM-DD`) and times are wall-clock `HH:MM` in
|
||||
// the site's timezone; they become UTC instants only at the very end, via
|
||||
// zonedInputToIso, so a run across a DST change still starts at 09:00.
|
||||
|
||||
import { toZonedDatetimeInput, zonedInputToIso } from './calendar';
|
||||
|
||||
/** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */
|
||||
export type TimeWindow = { from: string; to: string };
|
||||
|
||||
export type PlannedSlot = { start: string; end: string };
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const DATE_KEY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const TIME_RE = /^(\d{2}):(\d{2})$/;
|
||||
|
||||
/** Weekday labels Monday-first, with their `Date.getUTCDay()` number. */
|
||||
export const WEEKDAYS = [
|
||||
{ day: 1, label: 'Mon' },
|
||||
{ day: 2, label: 'Tue' },
|
||||
{ day: 3, label: 'Wed' },
|
||||
{ day: 4, label: 'Thu' },
|
||||
{ day: 5, label: 'Fri' },
|
||||
{ day: 6, label: 'Sat' },
|
||||
{ day: 0, label: 'Sun' }
|
||||
];
|
||||
|
||||
/** What a bulk action reports back: a preview to confirm, or the outcome. */
|
||||
export type BulkResult = {
|
||||
action: 'generate' | 'copy' | 'clear';
|
||||
intent: 'preview' | 'done';
|
||||
/** Slots that will be (preview) or were (done) created/deleted. */
|
||||
count: number;
|
||||
skippedOverlap: number;
|
||||
skippedPast: number;
|
||||
/** clear only: booked or currently-held slots that are left alone. */
|
||||
kept: number;
|
||||
firstStart: string;
|
||||
lastStart: string;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
/** One generate/copy run may create at most this many slots. */
|
||||
export const MAX_BULK_SLOTS = 1000;
|
||||
|
||||
function keyToUtcMs(key: string) {
|
||||
const m = DATE_KEY_RE.exec(key);
|
||||
if (!m) return null;
|
||||
const ms = Date.UTC(+m[1], +m[2] - 1, +m[3]);
|
||||
return Number.isNaN(ms) ? null : ms;
|
||||
}
|
||||
|
||||
function utcMsToKey(ms: number) {
|
||||
return new Date(ms).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function isDateKey(value: string) {
|
||||
return keyToUtcMs(value) !== null;
|
||||
}
|
||||
|
||||
/** `2026-11-03` + 7 → `2026-11-10` (pure calendar arithmetic, no timezone). */
|
||||
export function addDaysToKey(key: string, days: number) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? '' : utcMsToKey(ms + days * DAY_MS);
|
||||
}
|
||||
|
||||
/** 0 = Sunday … 6 = Saturday, for a calendar date key. */
|
||||
export function weekdayOfKey(key: string) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? -1 : new Date(ms).getUTCDay();
|
||||
}
|
||||
|
||||
/** The Monday on or before `key`. */
|
||||
export function mondayOfKey(key: string) {
|
||||
const weekday = weekdayOfKey(key);
|
||||
return weekday < 0 ? '' : addDaysToKey(key, -((weekday + 6) % 7));
|
||||
}
|
||||
|
||||
/** Calendar date keys from `fromKey` to `toKey`, inclusive. */
|
||||
export function dateKeysBetween(fromKey: string, toKey: string) {
|
||||
const from = keyToUtcMs(fromKey);
|
||||
const to = keyToUtcMs(toKey);
|
||||
if (from === null || to === null) return [];
|
||||
const keys: string[] = [];
|
||||
for (let ms = from; ms <= to; ms += DAY_MS) keys.push(utcMsToKey(ms));
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** `2026-11` → the Monday-first grid of date keys covering that month (whole weeks). */
|
||||
export function monthGridKeys(month: string) {
|
||||
const first = `${month}-01`;
|
||||
if (!isDateKey(first)) return [];
|
||||
const [year, monthNumber] = month.split('-').map(Number);
|
||||
const nextFirst = monthNumber === 12 ? `${year + 1}-01-01` : `${year}-${String(monthNumber + 1).padStart(2, '0')}-01`;
|
||||
const gridStart = mondayOfKey(first);
|
||||
const gridEnd = addDaysToKey(mondayOfKey(addDaysToKey(nextFirst, -1)), 6);
|
||||
return dateKeysBetween(gridStart, gridEnd);
|
||||
}
|
||||
|
||||
/** `2026-11` + 1 → `2026-12`. */
|
||||
export function addMonthsToKey(month: string, months: number) {
|
||||
const [year, monthNumber] = month.split('-').map(Number);
|
||||
const index = year * 12 + (monthNumber - 1) + months;
|
||||
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Format a date key with fixed locale (SSR and browser agree), e.g. "Tuesday 3 November". */
|
||||
export function formatDateKey(key: string, options: Intl.DateTimeFormatOptions) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? '' : new Intl.DateTimeFormat('en-GB', { ...options, timeZone: 'UTC' }).format(ms);
|
||||
}
|
||||
|
||||
/** `09:30` → 570, or null. */
|
||||
export function timeToMinutes(value: string) {
|
||||
const m = TIME_RE.exec(value);
|
||||
if (!m || +m[1] > 23 || +m[2] > 59) return null;
|
||||
return +m[1] * 60 + +m[2];
|
||||
}
|
||||
|
||||
export function minutesToTime(minutes: number) {
|
||||
return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start times within the windows: a new appointment starts every
|
||||
* `duration + buffer` minutes and must end by the window's end (the
|
||||
* get-ready time after the last one may run past it).
|
||||
*/
|
||||
export function startTimesInWindows(windows: TimeWindow[], durationMinutes: number, bufferMinutes: number) {
|
||||
const step = durationMinutes + Math.max(0, bufferMinutes);
|
||||
if (durationMinutes <= 0) return [];
|
||||
const times = new Set<number>();
|
||||
for (const window of windows) {
|
||||
const from = timeToMinutes(window.from);
|
||||
const to = timeToMinutes(window.to);
|
||||
if (from === null || to === null) continue;
|
||||
for (let t = from; t + durationMinutes <= to; t += step) times.add(t);
|
||||
}
|
||||
return [...times].sort((a, b) => a - b).map(minutesToTime);
|
||||
}
|
||||
|
||||
export type GeneratePlanInput = {
|
||||
fromDate: string;
|
||||
toDate: string;
|
||||
/** `Date.getUTCDay()` numbers (0 = Sunday) of the days to fill. */
|
||||
weekdays: number[];
|
||||
windows: TimeWindow[];
|
||||
durationMinutes: number;
|
||||
bufferMinutes: number;
|
||||
timeZone: string;
|
||||
};
|
||||
|
||||
/** Every slot the generator would create, before skipping overlaps/past ones. */
|
||||
export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] {
|
||||
const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes);
|
||||
const days = new Set(input.weekdays);
|
||||
const slots: PlannedSlot[] = [];
|
||||
for (const key of dateKeysBetween(input.fromDate, input.toDate)) {
|
||||
if (!days.has(weekdayOfKey(key))) continue;
|
||||
for (const time of times) {
|
||||
const start = zonedInputToIso(`${key}T${time}`, input.timeZone);
|
||||
if (!start) continue;
|
||||
slots.push({ start, end: new Date(Date.parse(start) + input.durationMinutes * 60_000).toISOString() });
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
/** The same wall-clock time `days` later in `timeZone` (so 09:00 stays 09:00 across DST). */
|
||||
export function shiftByDays(iso: string, days: number, timeZone: string) {
|
||||
const local = toZonedDatetimeInput(iso, timeZone);
|
||||
if (!local) return '';
|
||||
const key = addDaysToKey(local.slice(0, 10), days);
|
||||
return key ? zonedInputToIso(`${key}${local.slice(10)}`, timeZone) : '';
|
||||
}
|
||||
|
||||
/** PocketBase dates look like `2026-11-03 08:00:00.000Z`; this parses them and ISO strings. */
|
||||
export function instantMs(value: string) {
|
||||
return Date.parse(String(value || '').replace(' ', 'T'));
|
||||
}
|
||||
|
||||
/** Whether `[start, end)` overlaps any of `ranges` (touching ends don't count). */
|
||||
export function overlapsAny(slot: PlannedSlot, ranges: PlannedSlot[]) {
|
||||
const start = instantMs(slot.start);
|
||||
const end = instantMs(slot.end);
|
||||
return ranges.some((range) => start < instantMs(range.end) && end > instantMs(range.start));
|
||||
}
|
||||
|
|
@ -110,7 +110,6 @@ export type ItemRecord = {
|
|||
type: ItemType;
|
||||
stock: number | null;
|
||||
duration: number | null; // minutes, for item_with_time
|
||||
bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -331,7 +331,6 @@
|
|||
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] },
|
||||
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||
{ "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
|
||||
{ "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true },
|
||||
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
|
||||
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
|
||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// items.bufferMinutes: the get-ready time a service needs after each
|
||||
// appointment (tidying the room, changing linen). The admin's slot generator
|
||||
// uses it as the default gap between generated slots. Empty = no gap.
|
||||
|
||||
function find(app, name) {
|
||||
try {
|
||||
return app.findCollectionByNameOrId(name);
|
||||
} catch (e) {
|
||||
return null; // fresh install: pb_schema.json (already has the field) is imported later
|
||||
}
|
||||
}
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const collection = find(app, 'items');
|
||||
if (!collection || collection.fields.getByName('bufferMinutes')) return;
|
||||
collection.fields.add(new NumberField({ id: 'num_itembuffer1', name: 'bufferMinutes', min: 0, onlyInt: true }));
|
||||
app.save(collection);
|
||||
},
|
||||
(app) => {
|
||||
const collection = find(app, 'items');
|
||||
if (!collection || !collection.fields.getByName('bufferMinutes')) return;
|
||||
collection.fields.removeByName('bufferMinutes');
|
||||
app.save(collection);
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue