ferst-core 0.13.0 → 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 +15 -1
- package/components/recipes/Book.astro +326 -30
- package/content/blocks.ts +20 -6
- package/lib/book.ts +93 -11
- 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';
|
|
@@ -87,6 +87,20 @@ export function formatModules(data) {
|
|
|
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
88
|
out.push(` ${b.name}: ${minutesText(b.minutes)}${how ? `, ${how}` : ''}${b.price ? `, ${b.price}` : ''}`);
|
|
89
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
|
+
}
|
|
90
104
|
}
|
|
91
105
|
out.push('');
|
|
92
106
|
}
|
|
@@ -15,41 +15,111 @@
|
|
|
15
15
|
* The offer's name, length, price and who gives it are read from the platform at build time
|
|
16
16
|
* (lib/book); its free times and places in the browser, since they change by the minute. Needs
|
|
17
17
|
* JavaScript: choosing among live times can't be a plain form. Without it, the block says so.
|
|
18
|
+
*
|
|
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.
|
|
18
28
|
*/
|
|
19
29
|
import ContactForm from './ContactForm.astro';
|
|
20
30
|
import Heading from '../blocks/Heading.astro';
|
|
21
|
-
import { loadBookService, metaLine, whereText } from '../../lib/book';
|
|
31
|
+
import { bookTarget, loadBookResource, loadBookService, metaLine, whereText, type BookService, type BookWho } from '../../lib/book';
|
|
22
32
|
import { resolveGitBase, resolveSiteId } from '../../lib/git-base.mjs';
|
|
23
33
|
|
|
24
34
|
interface Props {
|
|
25
|
-
service
|
|
35
|
+
service?: string;
|
|
36
|
+
resource?: string;
|
|
26
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 }>;
|
|
27
43
|
title?: string;
|
|
28
44
|
intro?: string;
|
|
29
45
|
note?: string;
|
|
30
46
|
buttonLabel?: string;
|
|
31
47
|
}
|
|
32
|
-
const {
|
|
33
|
-
const
|
|
34
|
-
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}` : ''}`}`;
|
|
35
77
|
const { align: blockAlign, headingAlign } = Astro.props as { align?: 'start' | 'center' | 'end'; headingAlign?: 'start' | 'center' | 'end' };
|
|
36
78
|
const headAlign = headingAlign ?? blockAlign ?? 'center';
|
|
37
|
-
|
|
38
|
-
const
|
|
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 ?? '';
|
|
39
87
|
---
|
|
40
88
|
|
|
41
|
-
<section class="b-book" id={anchor} data-book
|
|
42
|
-
|
|
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>}
|
|
43
91
|
<div class="b-book__head" data-recipe-head data-content-align={headAlign}>
|
|
44
|
-
<Heading text={
|
|
45
|
-
<p class="b-book__meta" data-book-meta>{
|
|
46
|
-
{
|
|
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>}
|
|
47
95
|
</div>
|
|
48
96
|
|
|
49
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>}
|
|
50
120
|
<div class="b-book__notice" role="alert" data-book-error hidden></div>
|
|
51
121
|
|
|
52
|
-
|
|
122
|
+
{/* Step 1: what to book */}
|
|
53
123
|
<div class="b-book__pick" data-book-pick hidden>
|
|
54
124
|
{picksWho && (
|
|
55
125
|
<label class="b-book__who">
|
|
@@ -60,7 +130,7 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
60
130
|
</select>
|
|
61
131
|
</label>
|
|
62
132
|
)}
|
|
63
|
-
<div class="b-book__days-bar">
|
|
133
|
+
<div class="b-book__days-bar" hidden={one}>
|
|
64
134
|
<button type="button" class="b-book__nav" data-book-earlier aria-label="Earlier dates" disabled>‹</button>
|
|
65
135
|
<div class="b-book__days" role="group" aria-label="Choose a day" data-book-days></div>
|
|
66
136
|
<button type="button" class="b-book__nav" data-book-later aria-label="Later dates">›</button>
|
|
@@ -80,12 +150,12 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
80
150
|
<p class="b-book__chosen" data-book-chosen></p>
|
|
81
151
|
<label class="b-book__who"><span>How many places</span><input type="number" min="1" value="1" inputmode="numeric" data-book-count /></label>
|
|
82
152
|
<p class="b-book__quote" data-book-quote aria-live="polite"></p>
|
|
83
|
-
<button type="button" class="b-book__go" data-book-hold>Hold these places</button>
|
|
153
|
+
<button type="button" class="b-book__go" data-book-hold>{one ? 'Book now' : 'Hold these places'}</button>
|
|
84
154
|
</div>
|
|
85
155
|
)}
|
|
86
156
|
</div>
|
|
87
157
|
|
|
88
|
-
|
|
158
|
+
{/* Step 2: who they are */}
|
|
89
159
|
<div class="b-book__details" data-book-details hidden>
|
|
90
160
|
<p class="b-book__held" data-book-held></p>
|
|
91
161
|
<ContactForm
|
|
@@ -100,32 +170,53 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
100
170
|
{ name: 'notes', label: 'Anything we should know? (optional)', type: 'textarea' },
|
|
101
171
|
]}
|
|
102
172
|
honeypot
|
|
103
|
-
idPrefix={anchor}
|
|
173
|
+
idPrefix={many ? `${anchor}-${def.id}` : anchor}
|
|
104
174
|
/>
|
|
105
175
|
<button type="button" class="b-book__link" data-book-again>{def.mode === 'places' ? 'Choose another date' : 'Choose another time'}</button>
|
|
106
176
|
</div>
|
|
107
177
|
|
|
108
|
-
|
|
178
|
+
{/* Step 3: booked, and "Add to calendar" */}
|
|
109
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>
|
|
110
193
|
</section>
|
|
111
194
|
|
|
112
195
|
<script>
|
|
113
|
-
import { addDays, bookingMessage, calendarFile, dayChip, endChoices, googleCalendarLink, londonDay, whenText, type EventDate, type TimesAnswer } from '../../lib/book';
|
|
196
|
+
import { addDays, bookingMessage, calendarFile, dayChip, endChoices, googleCalendarLink, londonDay, whenText, whichFree, type EventDate, type TimesAnswer } from '../../lib/book';
|
|
114
197
|
|
|
115
198
|
const SPAN = 14; // days shown at once (dates for a class: four weeks)
|
|
116
199
|
const AHEAD = 60; // how far ahead the platform takes bookings
|
|
117
200
|
|
|
118
201
|
type Hold = { id: string; start: string; end: string; places?: number; title?: string; resource: { name: string }; price: { label: string; note?: string | null } | null };
|
|
119
202
|
|
|
203
|
+
/** One offer's way to book, in its panel. Returns how to start it (once shown) and to leave it. */
|
|
120
204
|
function setUp(block: HTMLElement) {
|
|
121
205
|
const src = block.dataset.book!;
|
|
122
206
|
const holds = block.dataset.holds!;
|
|
123
207
|
const mode = (block.dataset.mode ?? 'times') as 'times' | 'chosen' | 'places';
|
|
124
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
|
|
125
211
|
const minutes = Number(block.dataset.minutes ?? '30');
|
|
126
212
|
const step = Number(block.dataset.step ?? '30');
|
|
127
213
|
const where = block.dataset.where ?? '';
|
|
128
|
-
const
|
|
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;
|
|
129
220
|
const $ = <T extends HTMLElement>(sel: string) => block.querySelector<T>(sel)!;
|
|
130
221
|
const pick = $('[data-book-pick]');
|
|
131
222
|
const details = $('[data-book-details]');
|
|
@@ -190,8 +281,19 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
190
281
|
const times = day ? free(day) : [];
|
|
191
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; }
|
|
192
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 ?? [];
|
|
193
287
|
timesEl.replaceChildren(...times.map((t) => {
|
|
194
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
|
+
}
|
|
195
297
|
if (mode === 'chosen') b.setAttribute('aria-pressed', String(t.time === start));
|
|
196
298
|
return b;
|
|
197
299
|
}));
|
|
@@ -210,6 +312,23 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
210
312
|
// ── A class or a concert: its coming dates, then how many places ──────────
|
|
211
313
|
function drawDates() {
|
|
212
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
|
+
}
|
|
213
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; }
|
|
214
333
|
timesEl.replaceChildren(...dates.map((d) => {
|
|
215
334
|
const chip = dayChip(d.start.slice(0, 10));
|
|
@@ -242,18 +361,29 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
242
361
|
q = `start=${date.start}&end=${date.end}&places=${Math.max(1, Number(count!.value) || 1)}&event=${encodeURIComponent(date.event_id)}`;
|
|
243
362
|
}
|
|
244
363
|
if (!q) return;
|
|
245
|
-
const res = await fetch(`${
|
|
364
|
+
const res = await fetch(`${srcOf(date)}/quote?${q}`, { headers: { Accept: 'application/json' } }).catch(() => null);
|
|
246
365
|
const body = res?.ok ? await res.json().catch(() => null) : null;
|
|
247
366
|
if (!body) return;
|
|
248
367
|
quoteEl.textContent = body.price ? `${body.price.label} · ${body.price.lines.join('; ')} · paid on the day` : 'Free';
|
|
249
|
-
if (holdBtn && mode === 'places') { const n = Math.max(1, Number(count!.value) || 1); holdBtn.textContent = `Hold ${n === 1 ? 'this place' : `${n} places`}`; }
|
|
368
|
+
if (holdBtn && mode === 'places' && !one) { const n = Math.max(1, Number(count!.value) || 1); holdBtn.textContent = `Hold ${n === 1 ? 'this place' : `${n} places`}`; }
|
|
250
369
|
}
|
|
251
370
|
|
|
252
371
|
async function load() {
|
|
253
372
|
say(null);
|
|
254
373
|
timesEl.innerHTML = `<p class="b-book__empty">${mode === 'places' ? 'Loading dates…' : 'Loading free times…'}</p>`;
|
|
255
374
|
try {
|
|
256
|
-
|
|
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' } });
|
|
257
387
|
if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error ?? String(res.status)); }
|
|
258
388
|
answer = (await res.json()) as TimesAnswer;
|
|
259
389
|
day = answer.days.find((d) => free(d.day).length)?.day ?? null;
|
|
@@ -265,12 +395,24 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
265
395
|
}
|
|
266
396
|
}
|
|
267
397
|
|
|
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
|
+
|
|
268
409
|
/** Hold what was picked: a time (and an end), or places at a date. */
|
|
269
410
|
async function take(body: Record<string, unknown>) {
|
|
270
411
|
say(null);
|
|
271
|
-
|
|
412
|
+
if (demo) { pretend(body); return; }
|
|
413
|
+
const res = await fetch(`${mode === 'places' ? srcOf(date) : src}/hold`, {
|
|
272
414
|
method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
273
|
-
body: JSON.stringify({ ...body, ...(who?.value ? { resource_id: who
|
|
415
|
+
body: JSON.stringify({ ...body, ...(who?.value || onlyWith ? { resource_id: who?.value || onlyWith } : {}) }),
|
|
274
416
|
}).catch(() => null);
|
|
275
417
|
const answerBody = res ? await res.json().catch(() => ({})) : {};
|
|
276
418
|
if (!res || res.status !== 201) { say(bookingMessage(answerBody.error ?? '')); await load(); return; }
|
|
@@ -297,6 +439,16 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
297
439
|
ev.preventDefault();
|
|
298
440
|
if (!hold) return;
|
|
299
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
|
+
}
|
|
300
452
|
const data = Object.fromEntries(new FormData(form).entries());
|
|
301
453
|
if (submit) submit.disabled = true;
|
|
302
454
|
const res = await fetch(`${holds}/${hold.id}`, {
|
|
@@ -309,10 +461,19 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
309
461
|
if (body.error === 'hold_expired' || body.error === 'already_booked') { hold = null; show('pick'); await load(); }
|
|
310
462
|
return;
|
|
311
463
|
}
|
|
312
|
-
const b = body.booking as { id: string; start: string; end: string; starts_at?: string; ends_at?: string; service: string; resource: string; places?: number };
|
|
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 };
|
|
313
465
|
done.innerHTML = '';
|
|
314
466
|
const strong = document.createElement('strong');
|
|
315
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
|
+
}
|
|
316
477
|
strong.textContent = `Booked: ${b.service}, ${whenText(b.start)}${b.places ? `, ${b.places} ${b.places === 1 ? 'place' : 'places'}` : ''}${withWhom}.`;
|
|
317
478
|
done.append(strong, ' We’ve emailed you the booking, with an invitation for your calendar.');
|
|
318
479
|
if (b.starts_at && b.ends_at) {
|
|
@@ -332,7 +493,7 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
332
493
|
});
|
|
333
494
|
|
|
334
495
|
$('[data-book-again]').addEventListener('click', async () => {
|
|
335
|
-
if (hold) await fetch(`${holds}/${hold.id}`, { method: 'DELETE' }).catch(() => null);
|
|
496
|
+
if (hold?.id) await fetch(`${holds}/${hold.id}`, { method: 'DELETE' }).catch(() => null);
|
|
336
497
|
hold = null;
|
|
337
498
|
show('pick');
|
|
338
499
|
await load();
|
|
@@ -342,11 +503,49 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
342
503
|
who?.addEventListener('change', () => { day = answer?.days.find((d) => free(d.day).length)?.day ?? null; start = null; drawDays(); drawTimes(); });
|
|
343
504
|
done.tabIndex = -1;
|
|
344
505
|
|
|
345
|
-
|
|
346
|
-
|
|
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
|
+
};
|
|
347
517
|
}
|
|
348
518
|
|
|
349
|
-
|
|
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
|
+
});
|
|
350
549
|
</script>
|
|
351
550
|
|
|
352
551
|
<style>
|
|
@@ -584,6 +783,103 @@ const picksWho = def.mode !== 'places' && def.resources.length > 1;
|
|
|
584
783
|
.b-book__add {
|
|
585
784
|
margin: 0.6rem 0 0;
|
|
586
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
|
+
}
|
|
587
883
|
.b-book__add a {
|
|
588
884
|
color: var(--fg);
|
|
589
885
|
font-weight: 600;
|
package/content/blocks.ts
CHANGED
|
@@ -262,19 +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),
|
|
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(),
|
|
274
278
|
/** One event of it (e.g. `eve_…`, the Christmas concert): only that event's dates. Left out: all of them. */
|
|
275
279
|
event: z.string().min(1).optional(),
|
|
276
|
-
/**
|
|
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). */
|
|
277
290
|
title: z.string().optional(),
|
|
291
|
+
/** Defaults to its description. */
|
|
278
292
|
intro: z.string().optional(),
|
|
279
293
|
/** Small print under the form (e.g. how to cancel). */
|
|
280
294
|
note: z.string().optional(),
|
package/lib/book.ts
CHANGED
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
* how it's booked (`mode`): `times`, a time of its length (a haircut); `chosen`, a start and an end
|
|
14
14
|
* (hall hire), its price worked out as the visitor chooses; `places`, places at one of its coming
|
|
15
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.
|
|
16
20
|
*/
|
|
17
21
|
export type BookMode = 'times' | 'chosen' | 'places';
|
|
18
22
|
export interface BookResource { id: string; name: string; kind: 'place' | 'person' | null }
|
|
@@ -29,6 +33,8 @@ export interface BookService {
|
|
|
29
33
|
step: number;
|
|
30
34
|
/** One event of the offer the block books (a class's or concert's), or null for all its dates. */
|
|
31
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;
|
|
32
38
|
/** Who or what gives it (a visitor may choose, or take anyone available); a place is "at", a person "with". */
|
|
33
39
|
resources: BookResource[];
|
|
34
40
|
/** Where the browser reads free times (`?from&to`) and holds a time (`/hold`). */
|
|
@@ -108,6 +114,16 @@ export function whereText(resources: BookResource[]): string {
|
|
|
108
114
|
return [people.length ? `with ${join(people)}` : '', places.length ? `at ${join(places)}` : ''].filter(Boolean).join(', ');
|
|
109
115
|
}
|
|
110
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
|
+
|
|
111
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". */
|
|
112
128
|
export function metaLine(d: Pick<BookService, 'mode' | 'minutes' | 'price' | 'resources'>): string {
|
|
113
129
|
const length = d.mode === 'chosen' ? `From ${lengthText(d.minutes)}` : lengthText(d.minutes);
|
|
@@ -159,26 +175,39 @@ export function calendarFile(b: Booked, stamp = new Date()): string {
|
|
|
159
175
|
].join('\r\n');
|
|
160
176
|
}
|
|
161
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 }
|
|
190
|
+
|
|
162
191
|
const cache = new Map<string, Promise<BookService>>();
|
|
163
192
|
|
|
164
|
-
export function loadBookService(service: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn; now?: Date; event?: string | null }): Promise<BookService> {
|
|
165
|
-
const key = `${opts.base}|${opts.siteId ?? ''}|${service}|${opts.event ?? ''}`;
|
|
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 ?? ''}`;
|
|
166
195
|
let hit = cache.get(key);
|
|
167
196
|
if (!hit) {
|
|
168
|
-
hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date(), opts.event ?? null);
|
|
197
|
+
hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date(), opts.event ?? null, opts.resource ?? null);
|
|
169
198
|
cache.set(key, hit);
|
|
170
199
|
hit.catch(() => cache.delete(key)); // a failure is retried by the next caller
|
|
171
200
|
}
|
|
172
201
|
return hit;
|
|
173
202
|
}
|
|
174
203
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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();
|
|
179
208
|
const definition = `${base}/sites/${encodeURIComponent(siteId)}/book/${encodeURIComponent(service)}`;
|
|
180
209
|
const today = londonDay(now);
|
|
181
|
-
const url = `${definition}?from=${today}&to=${addDays(today, 1)}${event ? `&event=${encodeURIComponent(event)}` : ''}`;
|
|
210
|
+
const url = `${definition}?from=${today}&to=${addDays(today, 1)}${event ? `&event=${encodeURIComponent(event)}` : ''}${resource ? `&resource=${encodeURIComponent(resource)}` : ''}`;
|
|
182
211
|
let res: Response;
|
|
183
212
|
try {
|
|
184
213
|
res = await fetchFn(url, { headers: { Accept: 'application/json' } });
|
|
@@ -193,11 +222,64 @@ async function fetchService(service: string, base: string, siteId: string | null
|
|
|
193
222
|
}
|
|
194
223
|
if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for offer "${service}" (${url}).`);
|
|
195
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
|
+
}
|
|
196
229
|
return {
|
|
197
230
|
id: d.service.id, name: d.service.name, description: d.service.description ?? '', minutes: d.service.minutes,
|
|
198
231
|
// A platform from before slice 6c says no mode: it books times, at no price it says.
|
|
199
|
-
mode: d.service.mode ?? 'times', price: d.service.price ?? 'Free', lasts: d.service.lasts ?? 'fixed', step: d.service.step_minutes ?? 30, event,
|
|
200
|
-
resources
|
|
201
|
-
|
|
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
|
+
})),
|
|
202
284
|
};
|
|
203
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",
|