ferst-core 0.12.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ferst-modules.mjs +17 -2
- package/components/recipes/Book.astro +577 -72
- package/content/blocks.ts +22 -6
- package/lib/book.ts +181 -14
- package/package.json +1 -1
package/bin/ferst-modules.mjs
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// Forms and calendars live in the portal, never in the repo: place a form with a
|
|
11
11
|
// `{ "type": "form", "form": "<its name on this site>" }` block, take a payment with a
|
|
12
12
|
// `{ "type": "pay", "item": "<its id>" }` block, take bookings with a
|
|
13
|
-
// `{ "type": "book", "service": "<its id>" }` block, and show the calendar by setting
|
|
13
|
+
// `{ "type": "book", "service": "<its id>" }` block (or `"resource"`, for a person or a place), and show the calendar by setting
|
|
14
14
|
// calendarSettings.embedUrl to the address printed here.
|
|
15
15
|
import { readFileSync, realpathSync } from 'node:fs';
|
|
16
16
|
import { resolve } from 'node:path';
|
|
@@ -84,8 +84,23 @@ export function formatModules(data) {
|
|
|
84
84
|
out.push('Bookings');
|
|
85
85
|
if (!data.book.length) out.push(' Nothing booked online on this site yet (portal: Events and bookings, "Book online").');
|
|
86
86
|
for (const b of data.book) {
|
|
87
|
-
|
|
87
|
+
const how = { times: 'a time of that length', chosen: 'from that long, a start and an end', places: 'places at its events' }[b.mode];
|
|
88
|
+
out.push(` ${b.name}: ${minutesText(b.minutes)}${how ? `, ${how}` : ''}${b.price ? `, ${b.price}` : ''}`);
|
|
88
89
|
out.push(` place it with: { "type": "book", "service": "${b.id}" }`);
|
|
90
|
+
// Its events (platform 2026-11-24+): "Book now" for one, its next date with places.
|
|
91
|
+
for (const e of b.events ?? []) {
|
|
92
|
+
out.push(` ${e.title}${e.next ? `, next ${e.next.replace('T', ' at ')}` : ''}: { "type": "book", "service": "${b.id}", "event": "${e.id}", "look": "button", "title": "${e.title.replace(/"/g, '\\"')}" }`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// The people and places that provide them (platform 2026-11-24+): a block can name one of them.
|
|
96
|
+
if (data.book_with?.length) {
|
|
97
|
+
const names = new Map(data.book.map((b) => [b.id, b.name]));
|
|
98
|
+
out.push(' Who and where (a block for one books everything they provide online):');
|
|
99
|
+
for (const r of data.book_with) {
|
|
100
|
+
out.push(` ${r.name} (${r.kind === 'place' ? 'a place' : 'a person'}): ${r.offers.map((id) => names.get(id) ?? id).join(', ')}`);
|
|
101
|
+
out.push(` place it with: { "type": "book", "resource": "${r.id}" }`);
|
|
102
|
+
out.push(` or one offer with them: { "type": "book", "service": "<offer>", "resource": "${r.id}" }`);
|
|
103
|
+
}
|
|
89
104
|
}
|
|
90
105
|
out.push('');
|
|
91
106
|
}
|
|
@@ -1,70 +1,161 @@
|
|
|
1
1
|
---
|
|
2
2
|
/**
|
|
3
|
-
* Book — visitors book
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* Book — visitors book one of the organisation's offers, from the Ferst Events and bookings module.
|
|
4
|
+
* One block, shaped by the offer (0.13.0; myai4-webdev docs/EVENTS.md slice 6c, the maintainer
|
|
5
|
+
* 2026-11-23: "a tile that introduces what we are booking … where … and the calendar below it, all
|
|
6
|
+
* in one block"). The head says what it is, how long, with whom or where, and the price; below it
|
|
7
|
+
* is the way to book that offer, as the platform says (`mode`):
|
|
8
|
+
* - times: a day, then a time of its length (a haircut);
|
|
9
|
+
* - chosen: a day, a start, then an end, the price worked out as they choose (hall hire);
|
|
10
|
+
* - places: the coming dates with the places left, then how many (a class, a concert); `event`
|
|
11
|
+
* names one event of the offer (the Christmas concert) to show only its dates.
|
|
12
|
+
* What's picked is held for the visitor at once, for 10 minutes, while they give their details; then
|
|
13
|
+
* it's booked, emailed with an invitation, and the page offers "Add to calendar".
|
|
7
14
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* invitation for their calendar. "Choose another time" lets the held time go.
|
|
15
|
+
* The offer's name, length, price and who gives it are read from the platform at build time
|
|
16
|
+
* (lib/book); its free times and places in the browser, since they change by the minute. Needs
|
|
17
|
+
* JavaScript: choosing among live times can't be a plain form. Without it, the block says so.
|
|
12
18
|
*
|
|
13
|
-
*
|
|
19
|
+
* Or a person or a place (0.14.0; the maintainer 2026-11-24: "we need both and its up to the person
|
|
20
|
+
* configuring the module to pick what is suitable"). `resource` alone: the head introduces them (Sam,
|
|
21
|
+
* the Hall), then the offers they provide online as choices, and below, the chosen one's calendar,
|
|
22
|
+
* booked with them only. `service` and `resource`: that offer, with them only.
|
|
23
|
+
*
|
|
24
|
+
* Shown outside a site (the Ferst portal's preview, the maintainer 2026-11-24: "utilise the core
|
|
25
|
+
* ferst events and bookings module block as it would be applied … to visualise it before someone
|
|
26
|
+
* clicks 'add it to my site'"): the host says which site and platform through `Astro.locals.ferstBook`,
|
|
27
|
+
* and `demo` plays every step with the real free times but never holds or books anything.
|
|
14
28
|
*/
|
|
15
29
|
import ContactForm from './ContactForm.astro';
|
|
16
30
|
import Heading from '../blocks/Heading.astro';
|
|
17
|
-
import {
|
|
31
|
+
import { bookTarget, loadBookResource, loadBookService, metaLine, whereText, type BookService, type BookWho } from '../../lib/book';
|
|
18
32
|
import { resolveGitBase, resolveSiteId } from '../../lib/git-base.mjs';
|
|
19
33
|
|
|
20
34
|
interface Props {
|
|
21
|
-
service
|
|
35
|
+
service?: string;
|
|
36
|
+
resource?: string;
|
|
37
|
+
event?: string;
|
|
38
|
+
/** `button`: "Book now" for one date of a class or an event (its next with places, or `date`). */
|
|
39
|
+
look?: 'button';
|
|
40
|
+
date?: string;
|
|
41
|
+
/** Dates across chosen classes and events, as one list: each an offer booked by places, or one event of it. */
|
|
42
|
+
list?: Array<{ service: string; event?: string }>;
|
|
22
43
|
title?: string;
|
|
23
44
|
intro?: string;
|
|
24
45
|
note?: string;
|
|
25
46
|
buttonLabel?: string;
|
|
26
47
|
}
|
|
27
|
-
const {
|
|
28
|
-
const
|
|
29
|
-
const
|
|
30
|
-
const
|
|
31
|
-
const
|
|
48
|
+
const { event, title, intro, note, buttonLabel = 'Book', look, date } = Astro.props;
|
|
49
|
+
const list = Astro.props.list?.length ? Astro.props.list : null;
|
|
50
|
+
const target = list ? { service: null, resource: null } : bookTarget(Astro.props);
|
|
51
|
+
const host = (Astro.locals as { ferstBook?: { siteId?: string; platform?: string; demo?: boolean } } | undefined)?.ferstBook;
|
|
52
|
+
const base = host?.platform ?? resolveGitBase();
|
|
53
|
+
const siteId = host?.siteId ?? resolveSiteId();
|
|
54
|
+
const demo = !!host?.demo;
|
|
55
|
+
let who: BookWho | null = null;
|
|
56
|
+
let offers: BookService[];
|
|
57
|
+
if (list) {
|
|
58
|
+
// A custom list (the maintainer, 2026-11-24): the dates of each, as one list.
|
|
59
|
+
offers = await Promise.all(list.map((l) => loadBookService(l.service, { base, siteId, event: l.event ?? null })));
|
|
60
|
+
const timed = offers.find((o) => o.mode !== 'places');
|
|
61
|
+
if (timed) throw new Error(`Book block: a list is of classes and events, booked by places; "${timed.name}" is booked by time. Give it a block of its own, or run \`npx ferst-modules\` to list what's booked by places.`);
|
|
62
|
+
} else if (target.service) {
|
|
63
|
+
offers = [await loadBookService(target.service, { base, siteId, event: event ?? null, resource: target.resource })];
|
|
64
|
+
} else {
|
|
65
|
+
const got = await loadBookResource(target.resource!, { base, siteId });
|
|
66
|
+
who = got.resource;
|
|
67
|
+
offers = got.services;
|
|
68
|
+
}
|
|
69
|
+
const lead = offers[0];
|
|
70
|
+
// "Book now" (the maintainer's fourth way, 2026-11-24): one date of a class or an event, nothing to pick
|
|
71
|
+
// but how many places. A haircut or a hire becomes one date only when it's booked, so it has no button.
|
|
72
|
+
const one = look === 'button';
|
|
73
|
+
if (one && (who || lead.mode !== 'places')) {
|
|
74
|
+
throw new Error(`Book block: a "Book now" button is for a class or an event, booked by places; "${lead.name}" is booked by time. Leave out "look" to show its calendar, or run \`npx ferst-modules\` to list what's booked by places.`);
|
|
75
|
+
}
|
|
76
|
+
const anchor = `book-${who ? who.id : `${lead.id}${lead.event ? `-${lead.event}` : ''}${lead.resource ? `-${lead.resource}` : ''}`}`;
|
|
32
77
|
const { align: blockAlign, headingAlign } = Astro.props as { align?: 'start' | 'center' | 'end'; headingAlign?: 'start' | 'center' | 'end' };
|
|
33
78
|
const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
79
|
+
// The head: the offer (its length, with whom or where, its price), or the person or place it names.
|
|
80
|
+
const heading = title ?? (list ? 'Coming up' : who ? who.name : lead.name);
|
|
81
|
+
const meta = list ? '' : who ? (offers.length === 1 ? metaLine({ ...lead, resources: [] }) : '') : metaLine(lead);
|
|
82
|
+
const lines = intro ?? (list ? '' : who ? who.description : lead.description);
|
|
83
|
+
const many = !list && offers.length > 1;
|
|
84
|
+
const panels = list ? [lead] : offers;
|
|
85
|
+
const sources = list ? JSON.stringify(offers.map((o) => ({ book: o.definition, event: o.event ?? '' }))) : undefined;
|
|
86
|
+
const placeOf = (d: BookService) => d.resources.find((r) => r.kind === 'place')?.name ?? '';
|
|
34
87
|
---
|
|
35
88
|
|
|
36
|
-
<section class="b-book" id={anchor} data-book
|
|
89
|
+
<section class="b-book" id={anchor} data-book-block data-demo={demo ? '1' : undefined} data-find={`${base}/sites/${encodeURIComponent(siteId ?? '')}/book/find`}>
|
|
90
|
+
{demo && <p class="b-book__notice" data-book-demo>A preview: try it as a visitor would. The free times are real; nothing is held or booked.</p>}
|
|
37
91
|
<div class="b-book__head" data-recipe-head data-content-align={headAlign}>
|
|
38
|
-
<Heading text={
|
|
39
|
-
<p class="b-book__meta">{
|
|
40
|
-
{
|
|
92
|
+
<Heading text={heading} level={2} />
|
|
93
|
+
{meta && <p class="b-book__meta" data-book-meta>{meta}</p>}
|
|
94
|
+
{lines && <p class="b-book__intro">{lines}</p>}
|
|
41
95
|
</div>
|
|
42
96
|
|
|
43
|
-
<noscript><p class="b-book__notice">Booking
|
|
97
|
+
<noscript><p class="b-book__notice">Booking needs JavaScript switched on in your browser.</p></noscript>
|
|
98
|
+
|
|
99
|
+
{many && (
|
|
100
|
+
<div class="b-book__offers" role="group" aria-label="What would you like to book?" data-book-offers>
|
|
101
|
+
{offers.map((d, i) => (
|
|
102
|
+
<button type="button" class="b-book__offer" data-book-offer={d.id} aria-pressed={String(i === 0)}>
|
|
103
|
+
<strong>{d.name}</strong>
|
|
104
|
+
<span>{metaLine({ ...d, resources: [] })}</span>
|
|
105
|
+
</button>
|
|
106
|
+
))}
|
|
107
|
+
</div>
|
|
108
|
+
)}
|
|
109
|
+
|
|
110
|
+
{panels.map((def, i) => {
|
|
111
|
+
const where = placeOf(def);
|
|
112
|
+
const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
113
|
+
return (
|
|
114
|
+
<div class="b-book__panel" data-book={def.definition} data-holds={def.holds} data-name={def.name} data-label={buttonLabel} data-offer={def.id}
|
|
115
|
+
data-mode={def.mode} data-event={list ? '' : def.event ?? ''} data-resource={def.resource ?? ''} data-minutes={def.minutes} data-step={def.step} data-where={list ? '' : where}
|
|
116
|
+
data-list={sources}
|
|
117
|
+
data-look={one ? 'button' : undefined} data-date={one ? date ?? '' : undefined}
|
|
118
|
+
data-with={whereText(def.resources)} hidden={i > 0}>
|
|
119
|
+
{many && def.description && <p class="b-book__intro">{def.description}</p>}
|
|
44
120
|
<div class="b-book__notice" role="alert" data-book-error hidden></div>
|
|
45
121
|
|
|
46
|
-
|
|
122
|
+
{/* Step 1: what to book */}
|
|
47
123
|
<div class="b-book__pick" data-book-pick hidden>
|
|
48
|
-
{
|
|
124
|
+
{picksWho && (
|
|
49
125
|
<label class="b-book__who">
|
|
50
|
-
<span>Who with</span>
|
|
126
|
+
<span>{def.resources.every((r) => r.kind === 'place') ? 'Where' : 'Who with'}</span>
|
|
51
127
|
<select data-book-who>
|
|
52
|
-
<option value="">Anyone available</option>
|
|
128
|
+
<option value="">{def.resources.every((r) => r.kind === 'place') ? 'Anywhere free' : 'Anyone available'}</option>
|
|
53
129
|
{def.resources.map((r) => <option value={r.id}>{r.name}</option>)}
|
|
54
130
|
</select>
|
|
55
131
|
</label>
|
|
56
132
|
)}
|
|
57
|
-
<div class="b-book__days-bar">
|
|
133
|
+
<div class="b-book__days-bar" hidden={one}>
|
|
58
134
|
<button type="button" class="b-book__nav" data-book-earlier aria-label="Earlier dates" disabled>‹</button>
|
|
59
135
|
<div class="b-book__days" role="group" aria-label="Choose a day" data-book-days></div>
|
|
60
136
|
<button type="button" class="b-book__nav" data-book-later aria-label="Later dates">›</button>
|
|
61
137
|
</div>
|
|
62
|
-
<div class="b-book__times" role="group" aria-label=
|
|
63
|
-
<p class="b-book__empty">Loading free times
|
|
138
|
+
<div class="b-book__times" role="group" aria-label={def.mode === 'places' ? 'Choose a date' : def.mode === 'chosen' ? 'Choose when it starts' : 'Choose a time'} data-book-times aria-live="polite">
|
|
139
|
+
<p class="b-book__empty">{def.mode === 'places' ? 'Loading dates…' : 'Loading free times…'}</p>
|
|
64
140
|
</div>
|
|
141
|
+
{def.mode === 'chosen' && (
|
|
142
|
+
<div class="b-book__more" data-book-end hidden>
|
|
143
|
+
<label class="b-book__who"><span>Until</span><select data-book-end-select></select></label>
|
|
144
|
+
<p class="b-book__quote" data-book-quote aria-live="polite"></p>
|
|
145
|
+
<button type="button" class="b-book__go" data-book-hold>Hold this time</button>
|
|
146
|
+
</div>
|
|
147
|
+
)}
|
|
148
|
+
{def.mode === 'places' && (
|
|
149
|
+
<div class="b-book__more" data-book-places hidden>
|
|
150
|
+
<p class="b-book__chosen" data-book-chosen></p>
|
|
151
|
+
<label class="b-book__who"><span>How many places</span><input type="number" min="1" value="1" inputmode="numeric" data-book-count /></label>
|
|
152
|
+
<p class="b-book__quote" data-book-quote aria-live="polite"></p>
|
|
153
|
+
<button type="button" class="b-book__go" data-book-hold>{one ? 'Book now' : 'Hold these places'}</button>
|
|
154
|
+
</div>
|
|
155
|
+
)}
|
|
65
156
|
</div>
|
|
66
157
|
|
|
67
|
-
|
|
158
|
+
{/* Step 2: who they are */}
|
|
68
159
|
<div class="b-book__details" data-book-details hidden>
|
|
69
160
|
<p class="b-book__held" data-book-held></p>
|
|
70
161
|
<ContactForm
|
|
@@ -79,24 +170,53 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
79
170
|
{ name: 'notes', label: 'Anything we should know? (optional)', type: 'textarea' },
|
|
80
171
|
]}
|
|
81
172
|
honeypot
|
|
82
|
-
idPrefix={anchor}
|
|
173
|
+
idPrefix={many ? `${anchor}-${def.id}` : anchor}
|
|
83
174
|
/>
|
|
84
|
-
<button type="button" class="b-book__link" data-book-again>Choose another time</button>
|
|
175
|
+
<button type="button" class="b-book__link" data-book-again>{def.mode === 'places' ? 'Choose another date' : 'Choose another time'}</button>
|
|
85
176
|
</div>
|
|
86
177
|
|
|
87
|
-
|
|
178
|
+
{/* Step 3: booked, and "Add to calendar" */}
|
|
88
179
|
<div class="b-book__notice b-book__notice--done" role="status" data-book-done hidden></div>
|
|
180
|
+
</div>
|
|
181
|
+
);
|
|
182
|
+
})}
|
|
183
|
+
|
|
184
|
+
{/* Their own bookings: the links, emailed to the address they booked with (2026-11-24). */}
|
|
185
|
+
<details class="b-book__find" data-book-find>
|
|
186
|
+
<summary>Change or cancel a booking</summary>
|
|
187
|
+
<form class="b-book__find-form" data-book-find-form>
|
|
188
|
+
<label class="b-book__who"><span>The email you booked with</span><input type="email" name="email" required autocomplete="email" id={`${anchor}-find-email`} /></label>
|
|
189
|
+
<button type="submit" class="b-book__go">Email me my bookings</button>
|
|
190
|
+
</form>
|
|
191
|
+
<p class="b-book__find-said" role="status" data-book-find-said></p>
|
|
192
|
+
</details>
|
|
89
193
|
</section>
|
|
90
194
|
|
|
91
195
|
<script>
|
|
92
|
-
import { addDays, bookingMessage, dayChip, londonDay, whenText, type TimesAnswer } from '../../lib/book';
|
|
196
|
+
import { addDays, bookingMessage, calendarFile, dayChip, endChoices, googleCalendarLink, londonDay, whenText, whichFree, type EventDate, type TimesAnswer } from '../../lib/book';
|
|
93
197
|
|
|
94
|
-
const SPAN = 14; // days shown at once
|
|
198
|
+
const SPAN = 14; // days shown at once (dates for a class: four weeks)
|
|
95
199
|
const AHEAD = 60; // how far ahead the platform takes bookings
|
|
96
200
|
|
|
201
|
+
type Hold = { id: string; start: string; end: string; places?: number; title?: string; resource: { name: string }; price: { label: string; note?: string | null } | null };
|
|
202
|
+
|
|
203
|
+
/** One offer's way to book, in its panel. Returns how to start it (once shown) and to leave it. */
|
|
97
204
|
function setUp(block: HTMLElement) {
|
|
98
205
|
const src = block.dataset.book!;
|
|
99
206
|
const holds = block.dataset.holds!;
|
|
207
|
+
const mode = (block.dataset.mode ?? 'times') as 'times' | 'chosen' | 'places';
|
|
208
|
+
const onlyEvent = block.dataset.event || '';
|
|
209
|
+
const onlyWith = block.dataset.resource || ''; // the person or place the block names: booked with them only
|
|
210
|
+
const demo = !!block.closest('[data-book-block]')?.hasAttribute('data-demo'); // a preview: nothing is held or booked
|
|
211
|
+
const minutes = Number(block.dataset.minutes ?? '30');
|
|
212
|
+
const step = Number(block.dataset.step ?? '30');
|
|
213
|
+
const where = block.dataset.where ?? '';
|
|
214
|
+
const one = block.dataset.look === 'button'; // "Book now": one date, only how many places left to choose
|
|
215
|
+
// A custom list: each source's dates, as one list; each date booked through its own offer.
|
|
216
|
+
const sources = block.dataset.list ? (JSON.parse(block.dataset.list) as Array<{ book: string; event: string }>) : null;
|
|
217
|
+
const srcOf = (d: EventDate | null) => (d as (EventDate & { src?: string }) | null)?.src ?? src;
|
|
218
|
+
const pinned = block.dataset.date || '';
|
|
219
|
+
const span = one ? 31 : mode === 'places' ? SPAN * 2 : SPAN;
|
|
100
220
|
const $ = <T extends HTMLElement>(sel: string) => block.querySelector<T>(sel)!;
|
|
101
221
|
const pick = $('[data-book-pick]');
|
|
102
222
|
const details = $('[data-book-details]');
|
|
@@ -107,6 +227,12 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
107
227
|
const earlier = $<HTMLButtonElement>('[data-book-earlier]');
|
|
108
228
|
const later = $<HTMLButtonElement>('[data-book-later]');
|
|
109
229
|
const who = block.querySelector<HTMLSelectElement>('[data-book-who]');
|
|
230
|
+
const more = block.querySelector<HTMLElement>('[data-book-end], [data-book-places]');
|
|
231
|
+
const endSel = block.querySelector<HTMLSelectElement>('[data-book-end-select]');
|
|
232
|
+
const count = block.querySelector<HTMLInputElement>('[data-book-count]');
|
|
233
|
+
const quoteEl = block.querySelector<HTMLElement>('[data-book-quote]');
|
|
234
|
+
const holdBtn = block.querySelector<HTMLButtonElement>('[data-book-hold]');
|
|
235
|
+
const chosenEl = block.querySelector<HTMLElement>('[data-book-chosen]');
|
|
110
236
|
const form = details.querySelector<HTMLFormElement>('form')!;
|
|
111
237
|
const submit = form.querySelector<HTMLButtonElement>('button[type="submit"]');
|
|
112
238
|
|
|
@@ -114,51 +240,154 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
114
240
|
let from = today;
|
|
115
241
|
let answer: TimesAnswer | null = null;
|
|
116
242
|
let day: string | null = null;
|
|
117
|
-
let
|
|
243
|
+
let start: string | null = null; // chosen: the start picked (HH:MM)
|
|
244
|
+
let date: EventDate | null = null; // places: the date picked
|
|
245
|
+
let hold: Hold | null = null;
|
|
118
246
|
|
|
119
247
|
const say = (text: string | null) => { error.textContent = text ?? ''; error.hidden = !text; };
|
|
120
|
-
const show = (
|
|
248
|
+
const show = (stepName: 'pick' | 'details' | 'done') => { pick.hidden = stepName !== 'pick'; details.hidden = stepName !== 'details'; done.hidden = stepName !== 'done'; };
|
|
121
249
|
const free = (d: string) => (answer?.days.find((x) => x.day === d)?.times ?? []).filter((t) => !who?.value || t.resources.includes(who.value));
|
|
250
|
+
const button = (cls: string, text: string, onClick: () => void, disabled = false) => {
|
|
251
|
+
const b = document.createElement('button');
|
|
252
|
+
b.type = 'button'; b.className = cls; b.textContent = text; b.disabled = disabled;
|
|
253
|
+
b.addEventListener('click', onClick);
|
|
254
|
+
return b;
|
|
255
|
+
};
|
|
122
256
|
|
|
257
|
+
// ── The days (times and chosen) ────────────────────────────────────────────
|
|
123
258
|
function drawDays() {
|
|
124
|
-
daysEl.
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
259
|
+
daysEl.hidden = mode === 'places';
|
|
260
|
+
if (mode !== 'places') {
|
|
261
|
+
daysEl.replaceChildren(...(answer?.days ?? []).map((d) => {
|
|
262
|
+
const chip = dayChip(d.day);
|
|
263
|
+
const b = document.createElement('button');
|
|
264
|
+
b.type = 'button';
|
|
265
|
+
b.className = 'b-book__day';
|
|
266
|
+
b.disabled = free(d.day).length === 0;
|
|
267
|
+
b.setAttribute('aria-pressed', String(d.day === day));
|
|
268
|
+
b.innerHTML = `<span>${chip.weekday}</span><strong>${chip.date}</strong>`;
|
|
269
|
+
b.setAttribute('aria-label', `${chip.weekday} ${chip.date}${b.disabled ? ', nothing free' : ''}`);
|
|
270
|
+
b.addEventListener('click', () => { day = d.day; start = null; drawDays(); drawTimes(); });
|
|
271
|
+
return b;
|
|
272
|
+
}));
|
|
273
|
+
}
|
|
136
274
|
earlier.disabled = from <= today;
|
|
137
|
-
later.disabled = addDays(from,
|
|
275
|
+
later.disabled = addDays(from, span) > addDays(today, AHEAD);
|
|
138
276
|
}
|
|
139
277
|
|
|
140
278
|
function drawTimes() {
|
|
279
|
+
if (more) more.hidden = true;
|
|
280
|
+
if (mode === 'places') return drawDates();
|
|
141
281
|
const times = day ? free(day) : [];
|
|
142
282
|
if (!day) { timesEl.innerHTML = `<p class="b-book__empty">${answer?.days.some((d) => free(d.day).length) ? 'Choose a day.' : 'Nothing free in these dates. Try later dates.'}</p>`; return; }
|
|
143
283
|
if (!times.length) { timesEl.innerHTML = '<p class="b-book__empty">Nothing free that day.</p>'; return; }
|
|
284
|
+
// Several places, "Anywhere free" (the maintainer's second way, 2026-11-24: "hall hire showing any
|
|
285
|
+
// hall available"): each time says which are free then.
|
|
286
|
+
const places = answer?.resources ?? [];
|
|
144
287
|
timesEl.replaceChildren(...times.map((t) => {
|
|
145
|
-
const b =
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
288
|
+
const b = button('b-book__time', t.time, () => (mode === 'chosen' ? chooseStart(t.time) : void take({ start: t.start })));
|
|
289
|
+
const which = who?.value ? null : whichFree(t.resources, places);
|
|
290
|
+
if (which) {
|
|
291
|
+
b.innerHTML = '<strong></strong><span></span>';
|
|
292
|
+
b.querySelector('strong')!.textContent = t.time;
|
|
293
|
+
b.querySelector('span')!.textContent = which;
|
|
294
|
+
b.setAttribute('aria-label', `${t.time}, free: ${which}`);
|
|
295
|
+
b.classList.add('b-book__time--which');
|
|
296
|
+
}
|
|
297
|
+
if (mode === 'chosen') b.setAttribute('aria-pressed', String(t.time === start));
|
|
298
|
+
return b;
|
|
299
|
+
}));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ── Hall hire: a start, then an end, and what it comes to ─────────────────
|
|
303
|
+
function chooseStart(time: string) {
|
|
304
|
+
start = time;
|
|
305
|
+
drawTimes();
|
|
306
|
+
const ends = endChoices(free(day!).map((t) => t.time), time, minutes, step);
|
|
307
|
+
endSel!.replaceChildren(...ends.map((e) => { const o = document.createElement('option'); o.value = e; o.textContent = e === '24:00' ? 'midnight' : e; return o; }));
|
|
308
|
+
more!.hidden = !ends.length;
|
|
309
|
+
void quote();
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ── A class or a concert: its coming dates, then how many places ──────────
|
|
313
|
+
function drawDates() {
|
|
314
|
+
const dates = answer?.events ?? [];
|
|
315
|
+
if (one) {
|
|
316
|
+
const d = dates.find((x) => (pinned ? x.start === pinned : x.left > 0));
|
|
317
|
+
if (!d || d.left === 0) { timesEl.innerHTML = `<p class="b-book__empty">${d ? 'It’s full.' : 'No dates with places just now.'}</p>`; return; }
|
|
318
|
+
const card = document.createElement('div');
|
|
319
|
+
card.className = 'b-book__one';
|
|
320
|
+
card.innerHTML = '<strong></strong><span></span>';
|
|
321
|
+
card.querySelector('strong')!.textContent = d.title;
|
|
322
|
+
card.querySelector('span')!.textContent = `${whenText(d.start)}${where ? `, at ${where}` : ''} · ${d.left} ${d.left === 1 ? 'place' : 'places'} left · ${d.price}`;
|
|
323
|
+
timesEl.replaceChildren(card);
|
|
324
|
+
date = d;
|
|
325
|
+
chosenEl!.textContent = '';
|
|
326
|
+
count!.max = String(d.left);
|
|
327
|
+
if (Number(count!.value) > d.left) count!.value = String(d.left);
|
|
328
|
+
more!.hidden = false;
|
|
329
|
+
void quote();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (!dates.length) { timesEl.innerHTML = `<p class="b-book__empty">${onlyEvent ? 'No dates to book in these weeks.' : 'Nothing to book in these weeks. Try later dates.'}</p>`; return; }
|
|
333
|
+
timesEl.replaceChildren(...dates.map((d) => {
|
|
334
|
+
const chip = dayChip(d.start.slice(0, 10));
|
|
335
|
+
const left = d.left === 0 ? 'Full' : `${d.left} ${d.left === 1 ? 'place' : 'places'} left`;
|
|
336
|
+
const b = button('b-book__date', '', () => chooseDate(d), d.left === 0);
|
|
337
|
+
b.innerHTML = `<strong>${chip.weekday} ${chip.date}, ${d.start.slice(11)}</strong><span>${onlyEvent ? '' : `${d.title} · `}${left} · ${d.price}</span>`;
|
|
338
|
+
b.setAttribute('aria-pressed', String(date?.event_id === d.event_id && date?.start === d.start));
|
|
150
339
|
return b;
|
|
151
340
|
}));
|
|
152
341
|
}
|
|
342
|
+
function chooseDate(d: EventDate) {
|
|
343
|
+
date = d;
|
|
344
|
+
drawDates();
|
|
345
|
+
chosenEl!.textContent = `${d.title}, ${whenText(d.start)}${where ? `, at ${where}` : ''}.`;
|
|
346
|
+
count!.max = String(d.left);
|
|
347
|
+
if (Number(count!.value) > d.left) count!.value = String(d.left);
|
|
348
|
+
more!.hidden = false;
|
|
349
|
+
void quote();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** What it comes to, from the platform, as they choose. */
|
|
353
|
+
async function quote() {
|
|
354
|
+
if (!quoteEl) return;
|
|
355
|
+
quoteEl.textContent = '';
|
|
356
|
+
let q = '';
|
|
357
|
+
if (mode === 'chosen' && day && start && endSel?.value) {
|
|
358
|
+
const end = endSel.value === '24:00' ? `${addDays(day, 1)}T00:00` : `${day}T${endSel.value}`;
|
|
359
|
+
q = `start=${day}T${start}&end=${end}`;
|
|
360
|
+
} else if (mode === 'places' && date) {
|
|
361
|
+
q = `start=${date.start}&end=${date.end}&places=${Math.max(1, Number(count!.value) || 1)}&event=${encodeURIComponent(date.event_id)}`;
|
|
362
|
+
}
|
|
363
|
+
if (!q) return;
|
|
364
|
+
const res = await fetch(`${srcOf(date)}/quote?${q}`, { headers: { Accept: 'application/json' } }).catch(() => null);
|
|
365
|
+
const body = res?.ok ? await res.json().catch(() => null) : null;
|
|
366
|
+
if (!body) return;
|
|
367
|
+
quoteEl.textContent = body.price ? `${body.price.label} · ${body.price.lines.join('; ')} · paid on the day` : 'Free';
|
|
368
|
+
if (holdBtn && mode === 'places' && !one) { const n = Math.max(1, Number(count!.value) || 1); holdBtn.textContent = `Hold ${n === 1 ? 'this place' : `${n} places`}`; }
|
|
369
|
+
}
|
|
153
370
|
|
|
154
371
|
async function load() {
|
|
155
372
|
say(null);
|
|
156
|
-
timesEl.innerHTML =
|
|
373
|
+
timesEl.innerHTML = `<p class="b-book__empty">${mode === 'places' ? 'Loading dates…' : 'Loading free times…'}</p>`;
|
|
157
374
|
try {
|
|
158
|
-
|
|
375
|
+
if (sources) {
|
|
376
|
+
const all = await Promise.all(sources.map(async (s) => {
|
|
377
|
+
const r = await fetch(`${s.book}?from=${from}&to=${addDays(from, span)}${s.event ? `&event=${encodeURIComponent(s.event)}` : ''}`, { headers: { Accept: 'application/json' } });
|
|
378
|
+
if (!r.ok) { const b = await r.json().catch(() => ({})); throw new Error(b.error ?? String(r.status)); }
|
|
379
|
+
return ((await r.json()) as TimesAnswer).events?.map((e) => ({ ...e, src: s.book })) ?? [];
|
|
380
|
+
}));
|
|
381
|
+
answer = { service: { id: '', name: block.dataset.name ?? '', minutes }, resources: [], days: [], events: all.flat().sort((a, b) => a.start.localeCompare(b.start)) };
|
|
382
|
+
start = null; date = null;
|
|
383
|
+
drawDays(); drawTimes();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const res = await fetch(`${src}?from=${from}&to=${addDays(from, span)}${onlyEvent ? `&event=${encodeURIComponent(onlyEvent)}` : ''}${onlyWith ? `&resource=${encodeURIComponent(onlyWith)}` : ''}`, { headers: { Accept: 'application/json' } });
|
|
159
387
|
if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error ?? String(res.status)); }
|
|
160
388
|
answer = (await res.json()) as TimesAnswer;
|
|
161
389
|
day = answer.days.find((d) => free(d.day).length)?.day ?? null;
|
|
390
|
+
start = null; date = null;
|
|
162
391
|
drawDays(); drawTimes();
|
|
163
392
|
} catch (e) {
|
|
164
393
|
timesEl.innerHTML = '';
|
|
@@ -166,24 +395,60 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
166
395
|
}
|
|
167
396
|
}
|
|
168
397
|
|
|
169
|
-
|
|
398
|
+
/** A preview's hold: what a visitor would see held, with nothing sent. */
|
|
399
|
+
function pretend(body: Record<string, unknown>) {
|
|
400
|
+
const start = String(body.start);
|
|
401
|
+
const plus = (local: string, m: number) => { const t = Number(local.slice(11, 13)) * 60 + Number(local.slice(14, 16)) + m; return `${local.slice(0, 11)}${String(Math.floor(t / 60) % 24).padStart(2, '0')}:${String(t % 60).padStart(2, '0')}`; };
|
|
402
|
+
hold = { id: '', start, end: typeof body.end === 'string' ? body.end : date ? date.end : plus(start, minutes), places: typeof body.places === 'number' ? body.places : undefined, title: date?.title, resource: { name: '' }, price: null };
|
|
403
|
+
const h = hold;
|
|
404
|
+
const what = h.places ? `${h.title ?? block.dataset.name}, ${whenText(h.start)}, ${h.places} ${h.places === 1 ? 'place' : 'places'}` : `${whenText(h.start)} to ${h.end.slice(11)}`;
|
|
405
|
+
$('[data-book-held]').textContent = `${what}. On your website, this is kept for the visitor for 10 minutes while they give their details. In this preview, nothing is kept.`;
|
|
406
|
+
show('details');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Hold what was picked: a time (and an end), or places at a date. */
|
|
410
|
+
async function take(body: Record<string, unknown>) {
|
|
170
411
|
say(null);
|
|
171
|
-
|
|
412
|
+
if (demo) { pretend(body); return; }
|
|
413
|
+
const res = await fetch(`${mode === 'places' ? srcOf(date) : src}/hold`, {
|
|
172
414
|
method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
173
|
-
body: JSON.stringify({
|
|
415
|
+
body: JSON.stringify({ ...body, ...(who?.value || onlyWith ? { resource_id: who?.value || onlyWith } : {}) }),
|
|
174
416
|
}).catch(() => null);
|
|
175
|
-
const
|
|
176
|
-
if (!res || res.status !== 201) { say(bookingMessage(
|
|
177
|
-
hold =
|
|
178
|
-
|
|
417
|
+
const answerBody = res ? await res.json().catch(() => ({})) : {};
|
|
418
|
+
if (!res || res.status !== 201) { say(bookingMessage(answerBody.error ?? '')); await load(); return; }
|
|
419
|
+
hold = answerBody.hold as Hold;
|
|
420
|
+
const h = hold;
|
|
421
|
+
const what = h.places ? `${h.title ?? block.dataset.name}, ${whenText(h.start)}, ${h.places} ${h.places === 1 ? 'place' : 'places'}` : `${whenText(h.start)} to ${h.end.slice(11)}, ${h.resource.name ? `${where ? 'at' : 'with'} ${h.resource.name}` : ''}`;
|
|
422
|
+
const price = h.price ? ` ${h.price.label}, paid on the day.` : '';
|
|
423
|
+
$('[data-book-held]').textContent = `${what}.${price} We’re keeping this for you for 10 minutes while you give your details.`;
|
|
179
424
|
show('details');
|
|
180
425
|
form.querySelector<HTMLInputElement>('input[name="name"]')?.focus();
|
|
181
426
|
}
|
|
182
427
|
|
|
428
|
+
holdBtn?.addEventListener('click', () => {
|
|
429
|
+
if (mode === 'chosen' && day && start && endSel?.value) {
|
|
430
|
+
void take({ start: `${day}T${start}`, end: endSel.value === '24:00' ? `${addDays(day, 1)}T00:00` : `${day}T${endSel.value}` });
|
|
431
|
+
} else if (mode === 'places' && date) {
|
|
432
|
+
void take({ event_id: date.event_id, start: date.start, places: Math.max(1, Number(count!.value) || 1) });
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
endSel?.addEventListener('change', () => void quote());
|
|
436
|
+
count?.addEventListener('input', () => void quote());
|
|
437
|
+
|
|
183
438
|
form.addEventListener('submit', async (ev) => {
|
|
184
439
|
ev.preventDefault();
|
|
185
440
|
if (!hold) return;
|
|
186
441
|
say(null);
|
|
442
|
+
if (demo) {
|
|
443
|
+
done.innerHTML = '';
|
|
444
|
+
const strong = document.createElement('strong');
|
|
445
|
+
strong.textContent = 'This is a preview: nothing was booked.';
|
|
446
|
+
done.append(strong, ' On your website, the visitor would now be booked, emailed the booking with an invitation for their calendar, and offered “Add to calendar”.');
|
|
447
|
+
hold = null;
|
|
448
|
+
show('done');
|
|
449
|
+
done.focus();
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
187
452
|
const data = Object.fromEntries(new FormData(form).entries());
|
|
188
453
|
if (submit) submit.disabled = true;
|
|
189
454
|
const res = await fetch(`${holds}/${hold.id}`, {
|
|
@@ -196,31 +461,91 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
196
461
|
if (body.error === 'hold_expired' || body.error === 'already_booked') { hold = null; show('pick'); await load(); }
|
|
197
462
|
return;
|
|
198
463
|
}
|
|
464
|
+
const b = body.booking as { id: string; status?: string; start: string; end: string; starts_at?: string; ends_at?: string; service: string; resource: string; places?: number };
|
|
199
465
|
done.innerHTML = '';
|
|
200
466
|
const strong = document.createElement('strong');
|
|
201
|
-
|
|
202
|
-
|
|
467
|
+
const withWhom = b.resource ? `, ${where ? 'at' : 'with'} ${b.resource}` : '';
|
|
468
|
+
// On request (platform 2026-11-24): asked for, its time kept, until the organisation confirms it.
|
|
469
|
+
if (b.status === 'requested') {
|
|
470
|
+
strong.textContent = `Requested: ${b.service}, ${whenText(b.start)}${b.places ? `, ${b.places} ${b.places === 1 ? 'place' : 'places'}` : ''}${withWhom}.`;
|
|
471
|
+
done.append(strong, ' The time is kept for you while they answer. We’ve emailed you, and you’ll get the booking, with an invitation for your calendar, once it’s confirmed.');
|
|
472
|
+
hold = null;
|
|
473
|
+
show('done');
|
|
474
|
+
done.focus();
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
strong.textContent = `Booked: ${b.service}, ${whenText(b.start)}${b.places ? `, ${b.places} ${b.places === 1 ? 'place' : 'places'}` : ''}${withWhom}.`;
|
|
478
|
+
done.append(strong, ' We’ve emailed you the booking, with an invitation for your calendar.');
|
|
479
|
+
if (b.starts_at && b.ends_at) {
|
|
480
|
+
const booked = { title: `${b.service}${withWhom.replace(/^, /, ' ')}`, starts_at: b.starts_at, ends_at: b.ends_at, location: where || null, uid: b.id };
|
|
481
|
+
const add = document.createElement('p');
|
|
482
|
+
add.className = 'b-book__add';
|
|
483
|
+
const google = document.createElement('a');
|
|
484
|
+
google.href = googleCalendarLink(booked); google.target = '_blank'; google.rel = 'noopener'; google.textContent = 'Add to Google Calendar';
|
|
485
|
+
const file = document.createElement('a');
|
|
486
|
+
file.href = `data:text/calendar;charset=utf-8,${encodeURIComponent(calendarFile(booked))}`; file.download = 'booking.ics'; file.textContent = 'Add to Apple Calendar or Outlook';
|
|
487
|
+
add.append(google, ' · ', file);
|
|
488
|
+
done.append(add);
|
|
489
|
+
}
|
|
203
490
|
hold = null;
|
|
204
491
|
show('done');
|
|
205
492
|
done.focus();
|
|
206
493
|
});
|
|
207
494
|
|
|
208
495
|
$('[data-book-again]').addEventListener('click', async () => {
|
|
209
|
-
if (hold) await fetch(`${holds}/${hold.id}`, { method: 'DELETE' }).catch(() => null);
|
|
496
|
+
if (hold?.id) await fetch(`${holds}/${hold.id}`, { method: 'DELETE' }).catch(() => null);
|
|
210
497
|
hold = null;
|
|
211
498
|
show('pick');
|
|
212
499
|
await load();
|
|
213
500
|
});
|
|
214
|
-
earlier.addEventListener('click', () => { from = addDays(from, -
|
|
215
|
-
later.addEventListener('click', () => { from = addDays(from,
|
|
216
|
-
who?.addEventListener('change', () => { day = answer?.days.find((d) => free(d.day).length)?.day ?? null; drawDays(); drawTimes(); });
|
|
501
|
+
earlier.addEventListener('click', () => { from = addDays(from, -span) < today ? today : addDays(from, -span); void load(); });
|
|
502
|
+
later.addEventListener('click', () => { from = addDays(from, span); void load(); });
|
|
503
|
+
who?.addEventListener('change', () => { day = answer?.days.find((d) => free(d.day).length)?.day ?? null; start = null; drawDays(); drawTimes(); });
|
|
217
504
|
done.tabIndex = -1;
|
|
218
505
|
|
|
219
|
-
|
|
220
|
-
|
|
506
|
+
let started = false;
|
|
507
|
+
return {
|
|
508
|
+
/** Shown: load its times the first time. */
|
|
509
|
+
start() { if (!started) { started = true; show('pick'); void load(); } },
|
|
510
|
+
/** Another offer chosen: let go of anything held here. */
|
|
511
|
+
async leave() {
|
|
512
|
+
if (hold?.id) await fetch(`${holds}/${hold.id}`, { method: 'DELETE' }).catch(() => null);
|
|
513
|
+
hold = null;
|
|
514
|
+
if (started) { show('pick'); say(null); }
|
|
515
|
+
},
|
|
516
|
+
};
|
|
221
517
|
}
|
|
222
518
|
|
|
223
|
-
|
|
519
|
+
// A block for a person or a place shows each offer they provide as a choice, and the chosen one's panel.
|
|
520
|
+
document.querySelectorAll<HTMLElement>('[data-book-block]').forEach((section) => {
|
|
521
|
+
const panels = [...section.querySelectorAll<HTMLElement>('[data-book]')].map((el) => ({ el, run: setUp(el) }));
|
|
522
|
+
const choices = [...section.querySelectorAll<HTMLButtonElement>('[data-book-offer]')];
|
|
523
|
+
const choose = (offer: string) => {
|
|
524
|
+
for (const p of panels) {
|
|
525
|
+
const on = p.el.dataset.offer === offer;
|
|
526
|
+
if (!on && !p.el.hidden) void p.run.leave();
|
|
527
|
+
p.el.hidden = !on;
|
|
528
|
+
if (on) p.run.start();
|
|
529
|
+
}
|
|
530
|
+
for (const c of choices) c.setAttribute('aria-pressed', String(c.dataset.bookOffer === offer));
|
|
531
|
+
};
|
|
532
|
+
for (const c of choices) c.addEventListener('click', () => choose(c.dataset.bookOffer!));
|
|
533
|
+
if (panels[0]) choose(panels[0].el.dataset.offer!);
|
|
534
|
+
|
|
535
|
+
// "Change or cancel a booking": the same answer whatever the address, from the platform.
|
|
536
|
+
const findForm = section.querySelector<HTMLFormElement>('[data-book-find-form]');
|
|
537
|
+
const said = section.querySelector<HTMLElement>('[data-book-find-said]');
|
|
538
|
+
findForm?.addEventListener('submit', async (ev) => {
|
|
539
|
+
ev.preventDefault();
|
|
540
|
+
if (!said) return;
|
|
541
|
+
const email = String(new FormData(findForm).get('email') ?? '').trim();
|
|
542
|
+
if (section.hasAttribute('data-demo')) { said.textContent = `In this preview, nothing is sent. On your website, ${email || 'they'} would be emailed a link to each of their bookings.`; return; }
|
|
543
|
+
said.textContent = 'One moment…';
|
|
544
|
+
const res = await fetch(section.dataset.find!, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ email }) }).catch(() => null);
|
|
545
|
+
const body = res ? await res.json().catch(() => ({})) : {};
|
|
546
|
+
said.textContent = res?.ok ? (body.message ?? 'If you have bookings with us under that address, we’ve emailed you a link to each.') : bookingMessage(body.error ?? '');
|
|
547
|
+
});
|
|
548
|
+
});
|
|
224
549
|
</script>
|
|
225
550
|
|
|
226
551
|
<style>
|
|
@@ -383,4 +708,184 @@ const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
|
383
708
|
.b-book__details[hidden] {
|
|
384
709
|
display: none;
|
|
385
710
|
}
|
|
711
|
+
.b-book__more {
|
|
712
|
+
display: flex;
|
|
713
|
+
flex-direction: column;
|
|
714
|
+
gap: 0.75rem;
|
|
715
|
+
padding: 1rem;
|
|
716
|
+
border: 1px solid var(--border);
|
|
717
|
+
border-radius: var(--radius-sm);
|
|
718
|
+
background: var(--bg-section);
|
|
719
|
+
}
|
|
720
|
+
.b-book__more input,
|
|
721
|
+
.b-book__more select {
|
|
722
|
+
font: inherit;
|
|
723
|
+
font-weight: 400;
|
|
724
|
+
color: var(--fg);
|
|
725
|
+
background: var(--field-bg, var(--bg-surface));
|
|
726
|
+
border: var(--field-border, 1px solid var(--border));
|
|
727
|
+
border-radius: var(--field-radius, var(--radius-sm));
|
|
728
|
+
padding: 0.6rem 0.75rem;
|
|
729
|
+
max-width: 12rem;
|
|
730
|
+
}
|
|
731
|
+
.b-book__quote,
|
|
732
|
+
.b-book__chosen {
|
|
733
|
+
margin: 0;
|
|
734
|
+
font-weight: 600;
|
|
735
|
+
font-variant-numeric: tabular-nums;
|
|
736
|
+
}
|
|
737
|
+
.b-book__go {
|
|
738
|
+
align-self: flex-start;
|
|
739
|
+
font: inherit;
|
|
740
|
+
font-weight: 700;
|
|
741
|
+
padding: 0.65rem 1.25rem;
|
|
742
|
+
border: 0;
|
|
743
|
+
border-radius: var(--radius-sm);
|
|
744
|
+
background: var(--gold);
|
|
745
|
+
color: var(--on-gold, #fff);
|
|
746
|
+
cursor: pointer;
|
|
747
|
+
}
|
|
748
|
+
.b-book__go:focus-visible,
|
|
749
|
+
.b-book__date:focus-visible {
|
|
750
|
+
outline: 2px solid var(--gold);
|
|
751
|
+
outline-offset: 2px;
|
|
752
|
+
}
|
|
753
|
+
.b-book__times:has(.b-book__date) {
|
|
754
|
+
grid-template-columns: 1fr;
|
|
755
|
+
}
|
|
756
|
+
.b-book__date {
|
|
757
|
+
display: flex;
|
|
758
|
+
flex-direction: column;
|
|
759
|
+
align-items: flex-start;
|
|
760
|
+
gap: 0.15rem;
|
|
761
|
+
padding: 0.7rem 0.9rem;
|
|
762
|
+
font: inherit;
|
|
763
|
+
text-align: start;
|
|
764
|
+
color: var(--fg);
|
|
765
|
+
background: var(--bg-surface);
|
|
766
|
+
border: 1px solid var(--border);
|
|
767
|
+
border-radius: var(--radius-sm);
|
|
768
|
+
cursor: pointer;
|
|
769
|
+
}
|
|
770
|
+
.b-book__date span {
|
|
771
|
+
color: var(--muted);
|
|
772
|
+
font-size: 0.92rem;
|
|
773
|
+
}
|
|
774
|
+
.b-book__date[aria-pressed='true'],
|
|
775
|
+
.b-book__time[aria-pressed='true'] {
|
|
776
|
+
border-color: var(--gold);
|
|
777
|
+
background: var(--gold-light);
|
|
778
|
+
}
|
|
779
|
+
.b-book__date:disabled {
|
|
780
|
+
opacity: 0.5;
|
|
781
|
+
cursor: default;
|
|
782
|
+
}
|
|
783
|
+
.b-book__add {
|
|
784
|
+
margin: 0.6rem 0 0;
|
|
785
|
+
}
|
|
786
|
+
.b-book__find summary {
|
|
787
|
+
cursor: pointer;
|
|
788
|
+
color: var(--fg);
|
|
789
|
+
text-decoration: underline;
|
|
790
|
+
}
|
|
791
|
+
.b-book__find-form {
|
|
792
|
+
display: flex;
|
|
793
|
+
flex-direction: column;
|
|
794
|
+
gap: 0.75rem;
|
|
795
|
+
margin-top: 0.75rem;
|
|
796
|
+
}
|
|
797
|
+
.b-book__find-form input {
|
|
798
|
+
font: inherit;
|
|
799
|
+
color: var(--fg);
|
|
800
|
+
background: var(--field-bg, var(--bg-surface));
|
|
801
|
+
border: var(--field-border, 1px solid var(--border));
|
|
802
|
+
border-radius: var(--field-radius, var(--radius-sm));
|
|
803
|
+
padding: 0.6rem 0.75rem;
|
|
804
|
+
max-width: 20rem;
|
|
805
|
+
}
|
|
806
|
+
.b-book__find-said {
|
|
807
|
+
margin: 0.5rem 0 0;
|
|
808
|
+
color: var(--muted);
|
|
809
|
+
}
|
|
810
|
+
.b-book__time--which {
|
|
811
|
+
display: flex;
|
|
812
|
+
flex-direction: column;
|
|
813
|
+
align-items: center;
|
|
814
|
+
gap: 0.1rem;
|
|
815
|
+
}
|
|
816
|
+
.b-book__time--which span {
|
|
817
|
+
font-size: 0.75rem;
|
|
818
|
+
font-weight: 400;
|
|
819
|
+
color: var(--muted);
|
|
820
|
+
}
|
|
821
|
+
.b-book__times:has(.b-book__time--which) {
|
|
822
|
+
grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
|
|
823
|
+
}
|
|
824
|
+
.b-book__days-bar[hidden] {
|
|
825
|
+
display: none;
|
|
826
|
+
}
|
|
827
|
+
.b-book__one {
|
|
828
|
+
display: flex;
|
|
829
|
+
flex-direction: column;
|
|
830
|
+
gap: 0.15rem;
|
|
831
|
+
padding: 0.85rem 1rem;
|
|
832
|
+
border: 1px solid var(--border);
|
|
833
|
+
border-radius: var(--radius-sm);
|
|
834
|
+
background: var(--bg-surface);
|
|
835
|
+
grid-column: 1 / -1;
|
|
836
|
+
}
|
|
837
|
+
.b-book__one span {
|
|
838
|
+
color: var(--muted);
|
|
839
|
+
}
|
|
840
|
+
.b-book__panel {
|
|
841
|
+
display: flex;
|
|
842
|
+
flex-direction: column;
|
|
843
|
+
gap: 1rem;
|
|
844
|
+
}
|
|
845
|
+
.b-book__panel[hidden] {
|
|
846
|
+
display: none;
|
|
847
|
+
}
|
|
848
|
+
.b-book__offers {
|
|
849
|
+
display: grid;
|
|
850
|
+
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
|
|
851
|
+
gap: 0.5rem;
|
|
852
|
+
}
|
|
853
|
+
.b-book__offer {
|
|
854
|
+
display: flex;
|
|
855
|
+
flex-direction: column;
|
|
856
|
+
align-items: flex-start;
|
|
857
|
+
gap: 0.15rem;
|
|
858
|
+
padding: 0.75rem 0.9rem;
|
|
859
|
+
font: inherit;
|
|
860
|
+
text-align: start;
|
|
861
|
+
color: var(--fg);
|
|
862
|
+
background: var(--bg-surface);
|
|
863
|
+
border: 1px solid var(--border);
|
|
864
|
+
border-radius: var(--radius-sm);
|
|
865
|
+
cursor: pointer;
|
|
866
|
+
transition: border-color 0.15s ease, background 0.15s ease;
|
|
867
|
+
}
|
|
868
|
+
.b-book__offer span {
|
|
869
|
+
color: var(--muted);
|
|
870
|
+
font-size: 0.92rem;
|
|
871
|
+
}
|
|
872
|
+
.b-book__offer:hover {
|
|
873
|
+
border-color: var(--gold);
|
|
874
|
+
}
|
|
875
|
+
.b-book__offer[aria-pressed='true'] {
|
|
876
|
+
border-color: var(--gold);
|
|
877
|
+
background: var(--gold-light);
|
|
878
|
+
}
|
|
879
|
+
.b-book__offer:focus-visible {
|
|
880
|
+
outline: 2px solid var(--gold);
|
|
881
|
+
outline-offset: 2px;
|
|
882
|
+
}
|
|
883
|
+
.b-book__add a {
|
|
884
|
+
color: var(--fg);
|
|
885
|
+
font-weight: 600;
|
|
886
|
+
}
|
|
887
|
+
.b-book__more[hidden],
|
|
888
|
+
.b-book__days[hidden] {
|
|
889
|
+
display: none;
|
|
890
|
+
}
|
|
386
891
|
</style>
|
package/content/blocks.ts
CHANGED
|
@@ -262,17 +262,33 @@ export const payBlock = z.object({
|
|
|
262
262
|
});
|
|
263
263
|
|
|
264
264
|
/** Visitors book a time for one of the organisation's offers, from the Ferst Events and bookings
|
|
265
|
-
* module ("Haircut", 30 minutes). The block names the offer
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
265
|
+
* module ("Haircut", 30 minutes). The block names the offer, a person or a place (everything they
|
|
266
|
+
* provide online, the visitor choosing which), or both (that offer with them only); one of the
|
|
267
|
+
* two is needed. Names, lengths, prices, who gives it and the free times are the organisation's,
|
|
268
|
+
* read from the platform (lib/book), never written here. A picked time is held for the visitor
|
|
269
|
+
* while they give their details, then booked; the visitor is emailed. List what a site takes
|
|
270
|
+
* bookings for, and who provides it, with `npx ferst-modules`. */
|
|
269
271
|
export const bookBlock = z.object({
|
|
270
272
|
type: z.literal('book'),
|
|
271
273
|
enabled: z.boolean().default(true),
|
|
272
274
|
/** The offer's id in the portal (e.g. `evs_8c1d…`). */
|
|
273
|
-
service: z.string().min(1),
|
|
274
|
-
/**
|
|
275
|
+
service: z.string().min(1).optional(),
|
|
276
|
+
/** A person's or a place's id in the portal (e.g. `evr_3f2a…`): what they provide online, booked with them. */
|
|
277
|
+
resource: z.string().min(1).optional(),
|
|
278
|
+
/** One event of it (e.g. `eve_…`, the Christmas concert): only that event's dates. Left out: all of them. */
|
|
279
|
+
event: z.string().min(1).optional(),
|
|
280
|
+
/** `button`: "Book now" for one date of a class or an event, with only the booker's details left
|
|
281
|
+
* (the maintainer, 2026-11-24). Its next date with places, or `date`. Left out: the calendar or list. */
|
|
282
|
+
look: z.enum(['button']).optional(),
|
|
283
|
+
/** With `look: button`: one date of a repeating event ('YYYY-MM-DDTHH:MM', London). Left out: the next with places. */
|
|
284
|
+
date: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/).optional(),
|
|
285
|
+
/** A list of dates across chosen classes and events, in place of `service` (the maintainer, 2026-11-24:
|
|
286
|
+
* "a custom block where we pick what event types we want to group to display as a single list"):
|
|
287
|
+
* each an offer booked by places (all its events), or one event of it. */
|
|
288
|
+
list: z.array(z.object({ service: z.string().min(1), event: z.string().min(1).optional() })).min(1).max(20).optional(),
|
|
289
|
+
/** Defaults to the offer's name (or the person's or place's, when the block names them alone). */
|
|
275
290
|
title: z.string().optional(),
|
|
291
|
+
/** Defaults to its description. */
|
|
276
292
|
intro: z.string().optional(),
|
|
277
293
|
/** Small print under the form (e.g. how to cancel). */
|
|
278
294
|
note: z.string().optional(),
|
package/lib/book.ts
CHANGED
|
@@ -8,14 +8,35 @@
|
|
|
8
8
|
* A booking is always the site's own, so the site must say who it is (`siteId` in
|
|
9
9
|
* ferst-site.json). An offer that isn't booked online, or a platform that can't be reached, fails
|
|
10
10
|
* the build: better the last good deploy stays live than a Book button that can't book.
|
|
11
|
+
*
|
|
12
|
+
* One block, shaped by the offer (0.13.0; myai4-webdev docs/EVENTS.md slice 6c): the platform says
|
|
13
|
+
* how it's booked (`mode`): `times`, a time of its length (a haircut); `chosen`, a start and an end
|
|
14
|
+
* (hall hire), its price worked out as the visitor chooses; `places`, places at one of its coming
|
|
15
|
+
* dates (a class, a concert). The page names the offer, and may name one event of it.
|
|
16
|
+
*
|
|
17
|
+
* Or a person or a place (0.14.0; the maintainer 2026-11-24: "we need both and its up to the person
|
|
18
|
+
* configuring the module to pick what is suitable"): `resource` alone books everything they provide
|
|
19
|
+
* online, the visitor choosing which in the block; with `service`, that offer with them only.
|
|
11
20
|
*/
|
|
21
|
+
export type BookMode = 'times' | 'chosen' | 'places';
|
|
22
|
+
export interface BookResource { id: string; name: string; kind: 'place' | 'person' | null }
|
|
12
23
|
export interface BookService {
|
|
13
24
|
id: string;
|
|
14
25
|
name: string;
|
|
15
26
|
description: string;
|
|
16
27
|
minutes: number;
|
|
17
|
-
/**
|
|
18
|
-
|
|
28
|
+
/** How it's booked; what it costs, as the owner put it ("£25 an hour", "Free"). */
|
|
29
|
+
mode: BookMode;
|
|
30
|
+
price: string;
|
|
31
|
+
/** A fixed length, or chosen when booking (from `minutes`, in steps of `step`). */
|
|
32
|
+
lasts: 'fixed' | 'chosen';
|
|
33
|
+
step: number;
|
|
34
|
+
/** One event of the offer the block books (a class's or concert's), or null for all its dates. */
|
|
35
|
+
event: string | null;
|
|
36
|
+
/** The person or place the block books it with (then `resources` is just them), or null for anyone who gives it. */
|
|
37
|
+
resource: string | null;
|
|
38
|
+
/** Who or what gives it (a visitor may choose, or take anyone available); a place is "at", a person "with". */
|
|
39
|
+
resources: BookResource[];
|
|
19
40
|
/** Where the browser reads free times (`?from&to`) and holds a time (`/hold`). */
|
|
20
41
|
definition: string;
|
|
21
42
|
/** Where the browser books a held time (`/:hold`) or lets it go. */
|
|
@@ -66,37 +87,127 @@ export function bookingMessage(code: string): string {
|
|
|
66
87
|
case 'name_required': return 'Please give your name.';
|
|
67
88
|
case 'invalid_email': return 'Please give an email address we can send your booking to.';
|
|
68
89
|
case 'bookings_not_open': return 'This website isn’t taking bookings just now.';
|
|
90
|
+
case 'not_enough_places': return 'There aren’t that many places left. Please choose fewer, or another date.';
|
|
91
|
+
case 'invalid_date': return 'That date isn’t on offer any more. Please choose another.';
|
|
92
|
+
case 'invalid_length': case 'invalid_end': return 'Please choose when it ends again.';
|
|
93
|
+
case 'one_day': return 'Online, a booking starts and ends on the same day. For longer, please ask us.';
|
|
69
94
|
default: return 'The booking couldn’t be made just now. Please try again.';
|
|
70
95
|
}
|
|
71
96
|
}
|
|
72
97
|
|
|
73
|
-
/**
|
|
98
|
+
/** One coming date of a class or a concert: its places left and its price. */
|
|
99
|
+
export interface EventDate { event_id: string; title: string; description?: string; start: string; end: string; places: number; left: number; price: string }
|
|
100
|
+
|
|
101
|
+
/** The platform's answer for an offer's free times (or, booked by places, its coming dates), as the block reads it. */
|
|
74
102
|
export interface TimesAnswer {
|
|
75
|
-
service: { id: string; name: string; description?: string; minutes: number };
|
|
76
|
-
resources: Array<{ id: string; name: string }>;
|
|
103
|
+
service: { id: string; name: string; description?: string; minutes: number; mode?: BookMode; lasts?: 'fixed' | 'chosen'; step_minutes?: number; price?: string };
|
|
104
|
+
resources: Array<{ id: string; name: string; kind?: 'place' | 'person' }>;
|
|
77
105
|
days: Array<{ day: string; times: Array<{ time: string; start: string; resources: string[] }> }>;
|
|
106
|
+
events?: EventDate[];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const join = (names: string[]) => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}`);
|
|
110
|
+
/** "with Sam or Alex", "at the Hall": a place is somewhere to be, a person someone to see. */
|
|
111
|
+
export function whereText(resources: BookResource[]): string {
|
|
112
|
+
const places = resources.filter((r) => r.kind === 'place').map((r) => r.name);
|
|
113
|
+
const people = resources.filter((r) => r.kind !== 'place').map((r) => r.name);
|
|
114
|
+
return [people.length ? `with ${join(people)}` : '', places.length ? `at ${join(places)}` : ''].filter(Boolean).join(', ');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Which of several places are free at a time, for a calendar of hire across them with "Anywhere free"
|
|
119
|
+
* (2026-11-24): "All free", or their names. Null when it isn't said: one place, or people.
|
|
120
|
+
*/
|
|
121
|
+
export function whichFree(free: string[], places: Array<{ id: string; name: string; kind?: string | null }>): string | null {
|
|
122
|
+
if (places.length < 2 || !places.every((r) => r.kind === 'place')) return null;
|
|
123
|
+
const names = places.filter((r) => free.includes(r.id)).map((r) => r.name);
|
|
124
|
+
return names.length === places.length ? 'All free' : names.join(', ');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The block's line under its name: "30 minutes · with Sam or Alex · £18 a booking", "From 1 hour · at the Hall · £25 an hour". */
|
|
128
|
+
export function metaLine(d: Pick<BookService, 'mode' | 'minutes' | 'price' | 'resources'>): string {
|
|
129
|
+
const length = d.mode === 'chosen' ? `From ${lengthText(d.minutes)}` : lengthText(d.minutes);
|
|
130
|
+
return [length, whereText(d.resources), d.price].filter(Boolean).join(' · ');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const mins = (hhmm: string) => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
|
|
134
|
+
const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
|
|
135
|
+
/**
|
|
136
|
+
* The ends a hall hire starting at `start` can have: at least `minutes`, in steps of `step`, while
|
|
137
|
+
* the time stays free. `free` is the day's free starts for its shortest length (the platform's
|
|
138
|
+
* answer); a longer booking is free while every start under it is. The platform checks again on hold.
|
|
139
|
+
*/
|
|
140
|
+
export function endChoices(free: string[], start: string, minutes: number, step: number): string[] {
|
|
141
|
+
const at = free.map(mins).sort((a, b) => a - b);
|
|
142
|
+
const set = new Set(at);
|
|
143
|
+
const s = mins(start);
|
|
144
|
+
if (!set.has(s)) return [];
|
|
145
|
+
const gaps = at.slice(1).map((m, i) => m - at[i]).filter((g) => g > 0);
|
|
146
|
+
const grid = gaps.length ? Math.min(...gaps) : step;
|
|
147
|
+
const out: string[] = [];
|
|
148
|
+
for (let end = s + minutes; end <= 24 * 60; end += step) {
|
|
149
|
+
let ok = true;
|
|
150
|
+
for (let t = s; t <= end - minutes; t += grid) if (!set.has(t)) { ok = false; break; }
|
|
151
|
+
if (!ok) break;
|
|
152
|
+
out.push(end === 24 * 60 ? '24:00' : hhmm(end));
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** A booking, for "Add to calendar": its title, UTC times, where, and its id. */
|
|
158
|
+
export interface Booked { title: string; starts_at: string; ends_at: string; location?: string | null; uid?: string }
|
|
159
|
+
const utcBasic = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
|
160
|
+
/** Add to Google Calendar. */
|
|
161
|
+
export function googleCalendarLink(b: Booked): string {
|
|
162
|
+
const q = [`action=TEMPLATE`, `text=${encodeURIComponent(b.title)}`, `dates=${encodeURIComponent(`${utcBasic(b.starts_at)}/${utcBasic(b.ends_at)}`)}`];
|
|
163
|
+
if (b.location) q.push(`location=${encodeURIComponent(b.location)}`);
|
|
164
|
+
return `https://calendar.google.com/calendar/render?${q.join('&')}`;
|
|
78
165
|
}
|
|
166
|
+
const icsText = (t: string) => t.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
|
|
167
|
+
/** A calendar file for Apple Calendar, Outlook and the rest. */
|
|
168
|
+
export function calendarFile(b: Booked, stamp = new Date()): string {
|
|
169
|
+
return [
|
|
170
|
+
'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Ferst//Book//EN', 'METHOD:PUBLISH', 'BEGIN:VEVENT',
|
|
171
|
+
`UID:${b.uid ?? `${utcBasic(b.starts_at)}`}@ferst.co.uk`, `DTSTAMP:${utcBasic(stamp.toISOString())}`,
|
|
172
|
+
`DTSTART:${utcBasic(b.starts_at)}`, `DTEND:${utcBasic(b.ends_at)}`, `SUMMARY:${icsText(b.title)}`,
|
|
173
|
+
...(b.location ? [`LOCATION:${icsText(b.location)}`] : []),
|
|
174
|
+
'END:VEVENT', 'END:VCALENDAR', '',
|
|
175
|
+
].join('\r\n');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** What a block names: an offer, a person or place, or both. Naming neither fails the build. */
|
|
179
|
+
export function bookTarget(props: { service?: string | null; resource?: string | null }): { service: string | null; resource: string | null } {
|
|
180
|
+
const service = props.service || null;
|
|
181
|
+
const resource = props.resource || null;
|
|
182
|
+
if (!service && !resource) {
|
|
183
|
+
throw new Error('Book block: name an offer ("service": "<id>"), a person or place ("resource": "<id>"), or both. Run `npx ferst-modules` to list what this site takes bookings for.');
|
|
184
|
+
}
|
|
185
|
+
return { service, resource };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A person or a place, as a block naming them shows them. */
|
|
189
|
+
export interface BookWho extends BookResource { description: string }
|
|
79
190
|
|
|
80
191
|
const cache = new Map<string, Promise<BookService>>();
|
|
81
192
|
|
|
82
|
-
export function loadBookService(service: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn; now?: Date }): Promise<BookService> {
|
|
83
|
-
const key = `${opts.base}|${opts.siteId ?? ''}|${service}`;
|
|
193
|
+
export function loadBookService(service: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn; now?: Date; event?: string | null; resource?: string | null }): Promise<BookService> {
|
|
194
|
+
const key = `${opts.base}|${opts.siteId ?? ''}|${service}|${opts.event ?? ''}|${opts.resource ?? ''}`;
|
|
84
195
|
let hit = cache.get(key);
|
|
85
196
|
if (!hit) {
|
|
86
|
-
hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date());
|
|
197
|
+
hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date(), opts.event ?? null, opts.resource ?? null);
|
|
87
198
|
cache.set(key, hit);
|
|
88
199
|
hit.catch(() => cache.delete(key)); // a failure is retried by the next caller
|
|
89
200
|
}
|
|
90
201
|
return hit;
|
|
91
202
|
}
|
|
92
203
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
204
|
+
const noSiteId = () => new Error(`Book block: this site doesn't say who it is, so it can't take bookings. Add "siteId" to ferst-site.json (or set FERST_SITE_ID).`);
|
|
205
|
+
|
|
206
|
+
async function fetchService(service: string, base: string, siteId: string | null, fetchFn: FetchFn, now: Date, event: string | null, resource: string | null): Promise<BookService> {
|
|
207
|
+
if (!siteId) throw noSiteId();
|
|
97
208
|
const definition = `${base}/sites/${encodeURIComponent(siteId)}/book/${encodeURIComponent(service)}`;
|
|
98
209
|
const today = londonDay(now);
|
|
99
|
-
const url = `${definition}?from=${today}&to=${addDays(today, 1)}`;
|
|
210
|
+
const url = `${definition}?from=${today}&to=${addDays(today, 1)}${event ? `&event=${encodeURIComponent(event)}` : ''}${resource ? `&resource=${encodeURIComponent(resource)}` : ''}`;
|
|
100
211
|
let res: Response;
|
|
101
212
|
try {
|
|
102
213
|
res = await fetchFn(url, { headers: { Accept: 'application/json' } });
|
|
@@ -111,8 +222,64 @@ async function fetchService(service: string, base: string, siteId: string | null
|
|
|
111
222
|
}
|
|
112
223
|
if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for offer "${service}" (${url}).`);
|
|
113
224
|
const d = (await res.json()) as TimesAnswer;
|
|
225
|
+
const resources = d.resources.map((r) => ({ id: r.id, name: r.name, kind: r.kind ?? null })).filter((r) => !resource || r.id === resource);
|
|
226
|
+
if (resource && !resources.length) {
|
|
227
|
+
throw new Error(`Book block: "${resource}" doesn’t provide "${service}" online. Check who provides it in the portal (Events and bookings), or run \`npx ferst-modules\` to list who provides what.`);
|
|
228
|
+
}
|
|
114
229
|
return {
|
|
115
230
|
id: d.service.id, name: d.service.name, description: d.service.description ?? '', minutes: d.service.minutes,
|
|
116
|
-
|
|
231
|
+
// A platform from before slice 6c says no mode: it books times, at no price it says.
|
|
232
|
+
mode: d.service.mode ?? 'times', price: d.service.price ?? 'Free', lasts: d.service.lasts ?? 'fixed', step: d.service.step_minutes ?? 30, event, resource,
|
|
233
|
+
resources, definition, holds: `${base}/sites/${encodeURIComponent(siteId)}/book/holds`,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The platform's answer for a person or a place: who they are, and each offer they provide online. */
|
|
238
|
+
interface WithAnswer {
|
|
239
|
+
resource: { id: string; name: string; kind?: 'place' | 'person'; description?: string };
|
|
240
|
+
offers: Array<{ id: string; name: string; description?: string; minutes: number; lasts?: 'fixed' | 'chosen'; step_minutes?: number; mode: BookMode; price?: string; resources?: Array<{ id: string; name: string; kind?: 'place' | 'person' }> }>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const whoCache = new Map<string, Promise<{ resource: BookWho; services: BookService[] }>>();
|
|
244
|
+
|
|
245
|
+
/** A person or a place, and everything they provide online, each booked with them only (a block naming `resource` alone). */
|
|
246
|
+
export function loadBookResource(resource: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn }): Promise<{ resource: BookWho; services: BookService[] }> {
|
|
247
|
+
const key = `${opts.base}|${opts.siteId ?? ''}|${resource}`;
|
|
248
|
+
let hit = whoCache.get(key);
|
|
249
|
+
if (!hit) {
|
|
250
|
+
hit = fetchResource(resource, opts.base, opts.siteId ?? null, opts.fetch ?? fetch);
|
|
251
|
+
whoCache.set(key, hit);
|
|
252
|
+
hit.catch(() => whoCache.delete(key));
|
|
253
|
+
}
|
|
254
|
+
return hit;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function fetchResource(resource: string, base: string, siteId: string | null, fetchFn: FetchFn): Promise<{ resource: BookWho; services: BookService[] }> {
|
|
258
|
+
if (!siteId) throw noSiteId();
|
|
259
|
+
const site = `${base}/sites/${encodeURIComponent(siteId)}/book`;
|
|
260
|
+
const url = `${site}/with/${encodeURIComponent(resource)}`;
|
|
261
|
+
let res: Response;
|
|
262
|
+
try {
|
|
263
|
+
res = await fetchFn(url, { headers: { Accept: 'application/json' } });
|
|
264
|
+
} catch (e) {
|
|
265
|
+
throw new Error(`Book block: couldn’t reach the Ferst platform for "${resource}" (${url}): ${e instanceof Error ? e.message : String(e)}`);
|
|
266
|
+
}
|
|
267
|
+
if (res.status === 404) {
|
|
268
|
+
throw new Error(`Book block: "${resource}" provides nothing booked online on this site. Check it in the portal (Events and bookings: what they provide, and "Book online"), or run \`npx ferst-modules\` to list who takes bookings.`);
|
|
269
|
+
}
|
|
270
|
+
if (res.status === 403) {
|
|
271
|
+
throw new Error(`Book block: this site isn’t taking bookings ("${resource}"). Check Events and bookings is switched on for the site, and that the organisation takes bookings.`);
|
|
272
|
+
}
|
|
273
|
+
if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for "${resource}" (${url}).`);
|
|
274
|
+
const d = (await res.json()) as WithAnswer;
|
|
275
|
+
const who: BookWho = { id: d.resource.id, name: d.resource.name, kind: d.resource.kind ?? null, description: d.resource.description ?? '' };
|
|
276
|
+
return {
|
|
277
|
+
resource: who,
|
|
278
|
+
services: d.offers.map((o) => ({
|
|
279
|
+
id: o.id, name: o.name, description: o.description ?? '', minutes: o.minutes, mode: o.mode, price: o.price ?? 'Free',
|
|
280
|
+
lasts: o.lasts ?? 'fixed', step: o.step_minutes ?? 30, event: null, resource: who.id,
|
|
281
|
+
resources: [{ id: who.id, name: who.name, kind: who.kind }],
|
|
282
|
+
definition: `${site}/${encodeURIComponent(o.id)}`, holds: `${site}/holds`,
|
|
283
|
+
})),
|
|
117
284
|
};
|
|
118
285
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ferst-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Ferst Core — the shared, brand-agnostic client-site system: Astro components, layouts, content schemas, the layered config resolver, and a neutral styling architecture that every client overrides.",
|
|
6
6
|
"license": "BUSL-1.1",
|