domma-cms 1.36.0 → 1.37.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/bin/lib/left-free-tier.js +4 -1
  3. package/bin/update.js +4 -0
  4. package/docs/DommaFeatures.md +8 -6
  5. package/docs/plugin-development.md +2 -2
  6. package/package.json +1 -1
  7. package/plugins/docs/tests/plugin.test.js +2 -0
  8. package/plugins/free-tier.lock.json +2 -50
  9. package/server/services/siteGitignore.js +1 -1
  10. package/plugins/booking/CLAUDE.md +0 -204
  11. package/plugins/booking/admin/css/index.css +0 -192
  12. package/plugins/booking/admin/lib/details.js +0 -58
  13. package/plugins/booking/admin/lib/diary-layout.js +0 -158
  14. package/plugins/booking/admin/lib/drafts.js +0 -139
  15. package/plugins/booking/admin/lib/email.js +0 -191
  16. package/plugins/booking/admin/lib/extension-sections.js +0 -160
  17. package/plugins/booking/admin/lib/kit.js +0 -471
  18. package/plugins/booking/admin/templates/booking.html +0 -1
  19. package/plugins/booking/admin/views/booking.js +0 -216
  20. package/plugins/booking/admin/views/bookings.js +0 -132
  21. package/plugins/booking/admin/views/diary.js +0 -382
  22. package/plugins/booking/admin/views/panels.js +0 -603
  23. package/plugins/booking/admin/views/people.js +0 -318
  24. package/plugins/booking/admin/views/services.js +0 -264
  25. package/plugins/booking/admin/views/settings.js +0 -222
  26. package/plugins/booking/collections/booking-bookables.json +0 -17
  27. package/plugins/booking/collections/booking-bookings.json +0 -18
  28. package/plugins/booking/collections/booking-services.json +0 -17
  29. package/plugins/booking/config.js +0 -36
  30. package/plugins/booking/docs/guide.md +0 -73
  31. package/plugins/booking/inject/body.html +0 -1
  32. package/plugins/booking/lib/call.js +0 -88
  33. package/plugins/booking/lib/extensions.js +0 -169
  34. package/plugins/booking/lib/mail.js +0 -113
  35. package/plugins/booking/lib/store.js +0 -392
  36. package/plugins/booking/plugin.js +0 -905
  37. package/plugins/booking/plugin.json +0 -81
  38. package/plugins/booking/plugin.public.js +0 -175
  39. package/plugins/booking/public/booking.css +0 -159
  40. package/plugins/booking/public/booking.js +0 -808
  41. package/plugins/booking/public/lib/clean.js +0 -141
  42. package/plugins/booking/public/lib/page-format.js +0 -121
  43. package/plugins/booking/public/lib/slots.js +0 -247
  44. package/plugins/booking/public/lib/time.js +0 -131
  45. package/plugins/booking/templates/booking.html +0 -5
  46. package/plugins/booking/tests/admin-diary.test.js +0 -81
  47. package/plugins/booking/tests/admin-drafts.test.js +0 -67
  48. package/plugins/booking/tests/api.test.js +0 -651
  49. package/plugins/booking/tests/email.test.js +0 -69
  50. package/plugins/booking/tests/public.test.js +0 -72
  51. package/plugins/booking/tests/pure.test.js +0 -189
  52. package/plugins/booking/tests/seo.test.js +0 -71
@@ -1,905 +0,0 @@
1
- /**
2
- * Booking - the API (mounted at /api/plugins/booking).
3
- *
4
- * Admin (the `booking` permission; read to look, manage to change):
5
- * GET /bootstrap settings, services, people & rooms, users, what else is here
6
- * GET /count sidebar badge: bookings still to come today
7
- * GET /bookings?from=&to= bookings starting in a range (ISO instants)
8
- * GET /bookings/:id · POST /bookings · PUT /bookings/:id · PUT /bookings/:id/move · DELETE /bookings/:id
9
- * GET /bookings/:id/call-chat an online booking's call chat, read-only (booking.read; 1.5) - saved per
10
- * session (a class's shared call has one) in data/call-chat.json
11
- * GET /slots?service=&from=&to=&with=&ignore= free times (dates in the business zone)
12
- * GET/POST /services · PUT/DELETE /services/:id
13
- * GET/POST /bookables · PUT/DELETE /bookables/:id
14
- * GET /settings · PUT /settings
15
- * GET /contact/:id a contact of the caller's, to fill a new booking
16
- * GET /contact?email= the caller's contact with that email (an email's "Book…")
17
- *
18
- * Customers (no sign-in), under /public:
19
- * GET /public/services what can be booked
20
- * GET /public/slots free times for a service
21
- * POST /public/book make a booking (honeypot, rate limited)
22
- * GET /public/booking/:id?t= the customer's own booking (token-gated)
23
- * POST /public/booking/:id/cancel · POST /public/booking/:id/move (token in the body)
24
- * GET /public/booking/:id/ics?t=
25
- *
26
- * The booking page itself is plugin.public.js.
27
- */
28
-
29
- import path from 'node:path';
30
- import {fileURLToPath} from 'node:url';
31
- import {getConfig} from '../../server/config.js';
32
- import {getPluginStates} from '../../server/services/plugins.js';
33
- import {getPermissionsFor} from '../../server/services/roles.js';
34
- import {getEffectiveRoles} from '../../server/services/userRoles.js';
35
- import {getUserById, listUsers} from '../../server/services/users.js';
36
- import {isToolEnabled} from '../../server/services/tools.js';
37
- import {cleanBookable, cleanCustomer, cleanService, whenLabel} from './public/lib/clean.js';
38
- import {bookingRange, HOLDING, slotsFor} from './public/lib/slots.js';
39
- import {addDays, atWallClock, isDate, wallClock} from './public/lib/time.js';
40
- import {bookingRegistry} from './lib/extensions.js';
41
- import {callWindow, hostPath, invitePath, joinPath, sessionOf, whoIsCalling} from './lib/call.js';
42
- import {compose, icsFor, mailReady, send, siteAddress, siteTitle} from './lib/mail.js';
43
- import {
44
- BOOKABLES, BOOKINGS, NAME, SERVICES, SlotTaken, allBookables, allBookings, allServices, calendarBusy, changeBooking,
45
- cleanSettings, contactByEmail, customerMayChange, ensureCollections, getBookable, getBooking, getService, linkContact, liveSettings,
46
- ownContact, placeBooking, publicBooking, refreshShelf, removeBooking, removeThing, saveSettings, saveThing,
47
- settingsNow, shelfNow, tokenOk, uniqueSlug
48
- } from './lib/store.js';
49
-
50
- /**
51
- * The site's address for links in emails and the admin: `site.baseUrl` (Settings > Site), else '' - a link is then
52
- * left out and the log says so once. Until 1.6.3 a request's Host header stood in when the setting was empty, so a
53
- * booker who could reach the server with a Host of their choosing (default vhost, direct IP, misconfigured proxy)
54
- * got the owner an email whose "Start the call" button went to their domain carrying the host key. A Host header
55
- * is the caller's to choose; it never decides where anyone's link points. `request` is accepted for the registry's
56
- * callers (Pro) and ignored.
57
- */
58
- let warnedNoBase = false;
59
- function siteBase(request = null, log = null) {
60
- let base = '';
61
- try { base = String(getConfig('site')?.baseUrl || ''); } catch { /* no site config */ }
62
- if (/^https?:\/\/[^/\s]+/i.test(base)) return base.replace(/\/+$/, '');
63
- if (log && !warnedNoBase) {
64
- warnedNoBase = true;
65
- log.warn?.('[booking] Site URL is not set (Settings > Site): booking emails go out without links until it is.');
66
- }
67
- return '';
68
- }
69
-
70
- const manageUrl = (s, b, base) => `${base}${s.bookingPath}/manage/${b.id}?t=${b.token}`;
71
- const fail = (reply, status, error, extra = {}) => reply.code(status).send({error, ...extra});
72
- const uidOf = (request) => request.user?.id ?? request.user?.sub ?? '';
73
- const contactsOn = () => { try { return isToolEnabled('contacts'); } catch { return false; } };
74
-
75
- /** Extension data sent by the admin: {owner: {...}} objects only. */
76
- const extOf = (v) => (v && typeof v === 'object' && !Array.isArray(v)
77
- ? Object.fromEntries(Object.entries(v).filter(([k, x]) => /^[a-z0-9-]{1,64}$/.test(k) && x && typeof x === 'object' && !Array.isArray(x)))
78
- : {});
79
-
80
- /** Extra booking-form questions as the page may see them. */
81
- const publicFields = (list) => list.map(f => ({
82
- id: String(f.id).slice(0, 64), label: String(f.label).slice(0, 200), kind: String(f.kind || 'text'), required: f.required === true,
83
- help: String(f.help || '').slice(0, 300), options: Array.isArray(f.options) ? f.options.map(o => String(o).slice(0, 100)).slice(0, 50) : []
84
- }));
85
-
86
- /**
87
- * What the admin sees of a booking: everything but the customer's link token.
88
- * An online booking carries the host's call address instead of the raw key.
89
- */
90
- const adminBooking = (b) => {
91
- if (!b) return b;
92
- const {token, hostKey, callExtraKey, ...rest} = b;
93
- return b.online === true && hostKey ? {...rest, hostUrl: hostPath(settingsNow(), b)} : rest;
94
- };
95
-
96
- /** A service as the booking page sees it. */
97
- function publicService(svc, bookables) {
98
- const mine = bookables.filter(b => b.active !== false && svc.bookables.includes(b.id));
99
- return {
100
- id: svc.id, slug: svc.slug, name: svc.name, description: svc.description, duration: svc.duration, colour: svc.colour,
101
- chooseBookable: svc.chooseBookable !== false && mine.length > 1,
102
- bookables: mine.map(b => ({id: b.id, name: b.name, kind: b.kind, description: b.description}))
103
- };
104
- }
105
-
106
- /**
107
- * The booking page, anywhere:
108
- * [booking /] the whole flow, every service
109
- * [booking service="hair-cut" /] straight to one service
110
- * [booking service="hair-cut" with="<bookable id>" /]
111
- * Self-closing: a bare [booking] is left as text. The page's script
112
- * (public/booking.js, on every page via inject/body.html - the sanitiser strips
113
- * a shortcode's own <script>) mounts on [data-booking] and adds its stylesheet.
114
- */
115
- function registerShortcodes(hooks) {
116
- if (typeof hooks.registerShortcode !== 'function') return;
117
- const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
118
- hooks.registerShortcode('booking', (attrStr, _body, ctx) => {
119
- const a = ctx.parseShortcodeAttrs(attrStr || '');
120
- const s = settingsNow();
121
- const svc = a.service ? shelfNow().services.find(x => x.slug === String(a.service) && x.active !== false && x.public !== false) : null;
122
- if (a.service && !svc) return '<p class="bk-muted">That service cannot be booked just now.</p>';
123
- const cfg = {base: s.bookingPath, service: svc?.id || '', with: String(a.with || '').slice(0, 64), embedded: true};
124
- return `<div class="bk-app" data-booking='${esc(JSON.stringify(cfg))}'><p class="bk-muted">Loading the booking form… If it does not appear, <a href="${esc(s.bookingPath)}">book here</a>.</p></div>`;
125
- });
126
- }
127
-
128
- export const ASSET_V = '1.6.0';
129
-
130
- const HERE = path.dirname(fileURLToPath(import.meta.url));
131
-
132
- export default async function booking(fastify, options) {
133
- const {authenticate, requirePermission} = options.auth;
134
- const hooks = options.hooks || {};
135
- const can = (action) => ({preHandler: [authenticate, requirePermission('booking', action)]});
136
- const registry = bookingRegistry();
137
- const log = fastify.log || console;
138
-
139
- await ensureCollections(log);
140
- await refreshShelf();
141
- registerShortcodes(hooks);
142
-
143
- // The online call's rooms (set once the engine is mounted, at the end). A booking cancelled or moved away
144
- // ends the call it was in, unless someone else is still booked into that session (a class).
145
- let calls = null;
146
- // The call's chat (1.5), saved per session - set with the engine, at the end; null on an older core.
147
- let chatStore = null;
148
- let whoOf = null;
149
- const dataDir = options.dataDir || path.join(HERE, 'data');
150
- async function endCall(old) {
151
- if (!calls || old?.online !== true) return;
152
- const room = sessionOf(old);
153
- const others = (await allBookings()).some(x => x.id !== old.id && x.online === true && HOLDING.has(x.status) && sessionOf(x) === room);
154
- if (!others) calls.closeRoom(room);
155
- }
156
-
157
- const mayBook = (user, action = 'read') => {
158
- // Core's related items and the Calendar pass every role the viewer has in `roles`.
159
- const roles = Array.isArray(user?.roles) ? user.roles : getEffectiveRoles(user || {});
160
- return roles.some(r => getPermissionsFor('booking', action).includes(r));
161
- };
162
-
163
- // ---- Telling people -------------------------------------------------------------
164
-
165
- if (typeof hooks.registerNotificationSource === 'function') {
166
- try {
167
- hooks.registerNotificationSource({id: 'bookings', label: 'Bookings', severity: 'info', defaultOn: true,
168
- description: 'A booking made, moved or cancelled from the booking page.'});
169
- } catch { /* older engine */ }
170
- }
171
-
172
- function notice(b, what) {
173
- const s = settingsNow();
174
- const when = whenLabel(wallClock(b.startAt, s.timeZone));
175
- const titles = {made: 'New booking', moved: 'Booking moved', cancelled: 'Booking cancelled'};
176
- try {
177
- hooks.notify?.({
178
- title: `${titles[what]}: ${b.serviceName}, ${when}`,
179
- body: `${b.name} (${b.email})${b.bookableName ? ` with ${b.bookableName}` : ''}`.slice(0, 300),
180
- severity: what === 'cancelled' ? 'warning' : 'info',
181
- link: `#/plugins/booking/bookings/${b.id}`,
182
- source: 'bookings',
183
- dedupeKey: `booking-${what}:${b.id}:${b.startAt}`
184
- });
185
- } catch { /* a notice never breaks a booking */ }
186
- }
187
-
188
- /** Where the owner's copy goes: the person booked, else the setting, else the site. */
189
- async function ownerAddress(b) {
190
- const bk = await getBookable(b.bookableId).catch(() => null);
191
- return bk?.email || settingsNow().notifyAddress || siteAddress();
192
- }
193
-
194
- function detailsOf(b, s) {
195
- return [
196
- ['What', b.serviceName],
197
- ['Where', b.online === true ? 'Online - a video call in your browser' : ''],
198
- ['When', `${whenLabel(wallClock(b.startAt, s.timeZone))} (${b.duration || Math.round((Date.parse(b.endAt) - Date.parse(b.startAt)) / 60000)} minutes)`],
199
- ['With', [b.bookableName, ...(b.alsoNames || [])].filter(Boolean).join(', ')],
200
- ['Name', b.name],
201
- ['Email', b.email],
202
- ['Phone', b.phone],
203
- ['Notes', b.notes]
204
- ];
205
- }
206
-
207
- /**
208
- * Email the customer (and the owner) about a booking. Never awaited by a
209
- * request, never throws. `what`: made | moved | cancelled | reminder.
210
- */
211
- async function tell(b, what, {request = null, toCustomer = true, toOwner = true} = {}) {
212
- try {
213
- const s = await liveSettings();
214
- const base = siteBase(request, log);
215
- const title = siteTitle();
216
- const link = base && b.token ? manageUrl(s, b, base) : '';
217
- const may = customerMayChange(b, s) && (s.allowCancel || s.allowMove);
218
- const host = (() => { try { return new URL(base).host; } catch { return 'booking'; } })();
219
- const join = b.online === true && base ? `${base}${joinPath(s, b)}` : '';
220
- const ics = icsFor(b, {host, title: `${b.serviceName} - ${title}`, location: join ? `Online: ${join}` : '',
221
- description: [b.bookableName ? `With ${b.bookableName}` : '', join ? `Join the call: ${join}` : ''].filter(Boolean).join('\n'),
222
- cancel: what === 'cancelled', sequence: (b.history || []).length});
223
- const attachments = [{filename: what === 'cancelled' ? 'cancelled.ics' : 'booking.ics', content: ics,
224
- contentType: `text/calendar; charset=utf-8; method=${what === 'cancelled' ? 'CANCEL' : 'REQUEST'}`}];
225
- const heads = {
226
- made: [`Booking confirmed: ${b.serviceName}`, `Thank you, ${b.name}. Your booking is confirmed.`],
227
- moved: [`Booking moved: ${b.serviceName}`, `Your booking has moved. Here are the new details.`],
228
- cancelled: [`Booking cancelled: ${b.serviceName}`, `Your booking has been cancelled.`],
229
- reminder: [`Reminder: ${b.serviceName}`, `A reminder of your booking.`]
230
- };
231
- const [subject, line] = heads[what];
232
- if (toCustomer && (what !== 'made' || s.sendConfirmation)) {
233
- const after = [];
234
- if (what !== 'cancelled' && s.confirmationNote) after.push(s.confirmationNote);
235
- // Online: the call is the one link that matters; changing it is offered underneath.
236
- const online = what !== 'cancelled' && join;
237
- if (online && may) after.unshift(`To change or cancel: ${link}`);
238
- const msg = compose({subject, lines: online ? [line, 'This is an online appointment. Use the button below at the time - the call opens 10 minutes before the start. You need a camera and microphone, or you can join with just one.'] : [line],
239
- details: detailsOf(b, s),
240
- link: online ? join : what !== 'cancelled' && may ? link : '', linkText: online ? 'Join the call' : 'Change or cancel', after});
241
- send({to: b.email, replyTo: await ownerAddress(b), ...msg, attachments: what === 'reminder' ? [] : attachments}, {log});
242
- }
243
- if (toOwner && what !== 'reminder') {
244
- const to = await ownerAddress(b);
245
- const admin = base ? `${base}/admin/#/plugins/booking/bookings/${b.id}` : '';
246
- const hostLink = b.online === true && b.hostKey && base && what !== 'cancelled' ? `${base}${hostPath(s, b)}` : '';
247
- const msg = compose({subject: `${{made: 'New booking', moved: 'Booking moved', cancelled: 'Booking cancelled'}[what]}: ${b.name}, ${whenLabel(wallClock(b.startAt, s.timeZone))}`,
248
- lines: hostLink ? ['An online appointment. You are the host: start the call from the button below, and let them in when they arrive.'] : [],
249
- details: detailsOf(b, s), link: hostLink || admin, linkText: hostLink ? 'Start the call' : 'Open in Booking',
250
- after: hostLink && admin ? [`Open in Booking: ${admin}`] : []});
251
- // The host's calendar entry opens the call as host, never as the customer.
252
- const ownerAttachments = hostLink ? [{...attachments[0], content: icsFor(b, {host, title: `${b.serviceName} - ${title}`,
253
- location: `Online: ${hostLink}`, description: `With ${b.name}\nStart the call: ${hostLink}`, cancel: what === 'cancelled',
254
- sequence: (b.history || []).length})}] : attachments;
255
- if (to && to !== b.email) send({to, replyTo: b.email, ...msg, attachments: ownerAttachments}, {log});
256
- }
257
- } catch (err) {
258
- log.error?.(`[booking] could not prepare an email: ${err?.message || err}`);
259
- }
260
- }
261
-
262
- // ---- Reminders ------------------------------------------------------------------
263
-
264
- /** Send the reminders that are due. Exported through the registry for tests and Pro. */
265
- async function sendReminders(now = Date.now()) {
266
- const s = await liveSettings();
267
- if (!s.reminderHours) return 0;
268
- const due = (await allBookings()).filter(b => b.status === 'confirmed' && !b.reminderSentAt
269
- && Date.parse(b.startAt) > now && Date.parse(b.startAt) - now <= s.reminderHours * 3600000
270
- // A booking made inside the reminder window already had its confirmation.
271
- && Date.parse(b.createdAt || b.history?.[0]?.at || 0) < Date.parse(b.startAt) - s.reminderHours * 3600000);
272
- for (const b of due) {
273
- await changeBooking(b.id, {reminderSentAt: new Date(now).toISOString()});
274
- tell(b, 'reminder', {toOwner: false});
275
- }
276
- return due.length;
277
- }
278
- const timer = setInterval(() => { sendReminders().catch(err => log.warn?.(`[booking] reminders: ${err?.message || err}`)); }, 5 * 60000);
279
- timer.unref?.();
280
- fastify.addHook('onClose', async () => clearInterval(timer));
281
-
282
- // ---- What extensions may use ------------------------------------------------------
283
-
284
- registry.services = {
285
- name: NAME, liveSettings, allBookings, allServices, allBookables, getBooking, getService, getBookable,
286
- changeBooking, sendReminders,
287
- /** The site's address: `site.baseUrl`, else '' (never a request's Host). */
288
- siteBase: (request = null) => siteBase(request),
289
- /** A booking as the admin may see it (no customer token; an online one's host key as `hostUrl`). */
290
- adminBooking,
291
- /** The contact `id` when it is `userId`'s own (Contacts on), else null. */
292
- ownContact: async (id, userId) => (contactsOn() && id && userId ? ownContact(String(id), String(userId)).catch(() => null) : null),
293
- manageUrl: (b) => liveSettings().then(s => manageUrl(s, b, siteBase(null))),
294
- /** Make a booking the whole way (contacts, emails, notices, events) - a waiting list's place, a series. Throws SlotTaken. */
295
- book: (p) => bookForExtension(p),
296
- /** Cancel one, telling the customer when `notify`. */
297
- cancel: async (id, {notify = true, reason = '', by = ''} = {}) => {
298
- const res = await changeBooking(id, {status: 'cancelled', reason}, by);
299
- if (!res) return null;
300
- if (res.from !== 'cancelled') {
301
- if (notify) tell(res.booking, 'cancelled', {toOwner: false});
302
- registry.emit('cancelled', res.booking, res.from);
303
- endCall(res.booking).catch(() => {});
304
- }
305
- return res.booking;
306
- },
307
- /**
308
- * "Call now" (1.4): open an online booking's call now, even when it is booked for later - for everyone
309
- * booked into that session (a class shares one call). The customer's own link then works at once.
310
- * Throws with `code`: 'none' | 'not-online' | 'cancelled'.
311
- */
312
- openCall: async (id, {by = ''} = {}) => {
313
- const b = await getBooking(String(id || ''));
314
- const refuse = (code, message) => Object.assign(new Error(message), {code});
315
- if (!b) throw refuse('none', 'No such booking.');
316
- if (b.online !== true || !b.hostKey) throw refuse('not-online', 'That booking is not an online one, so it has no call.');
317
- if (!HOLDING.has(b.status) || b.status === 'cancelled') throw refuse('cancelled', 'That booking is cancelled, so it has no call.');
318
- const now = new Date().toISOString();
319
- const room = sessionOf(b);
320
- const session = (await allBookings()).filter(x => x.online === true && HOLDING.has(x.status) && sessionOf(x) === room);
321
- for (const x of session) await changeBooking(x.id, {callOpenedAt: now}, by);
322
- return getBooking(b.id);
323
- },
324
- /** An online booking's call addresses, whole: the customer's (`joinUrl`) and the host's (`hostUrl`). */
325
- callLinks: (b, request = null) => {
326
- if (b?.online !== true) return {joinUrl: '', hostUrl: ''};
327
- const s = settingsNow();
328
- const base = siteBase(request);
329
- return {joinUrl: b.token ? `${base}${joinPath(s, b)}` : '', hostUrl: b.hostKey ? `${base}${hostPath(s, b)}` : ''};
330
- },
331
- SlotTaken,
332
- // Booking's own helpers, so an extension never imports Booking's files.
333
- mail: {send: (msg) => send(msg, {log}), compose, mailReady},
334
- time: {wallClock, atWallClock, whenLabel, addDays},
335
- timeZone: () => settingsNow().timeZone
336
- };
337
-
338
- /**
339
- * `contactId` (1.4): the caller's own contact (`userId` = the caller) to book as - checked, dropped when it is
340
- * not theirs. `request`: the admin request it came from, for the links in the emails.
341
- */
342
- async function bookForExtension({serviceId, bookableId = '', startAt, customer: raw = {}, source = 'extension', ext = {}, force = false, notify = true, by = '',
343
- contactId: askedContact = '', userId = '', request = null}) {
344
- const s = await liveSettings();
345
- const {service, candidates, rules} = await candidatesFor(String(serviceId || ''), String(bookableId || ''), {includeInactive: true});
346
- if (!service || !candidates.length) throw new Error('That service cannot be booked.');
347
- const {data: customer, errors} = cleanCustomer(raw, {askPhone: true});
348
- if (Object.keys(errors).length) throw new Error(Object.values(errors)[0]);
349
- const contactId = askedContact && userId && await ownContact(String(askedContact), String(userId)).catch(() => null) ? String(askedContact) : '';
350
- const b = await placeBooking({service, candidates, rules, startAt: new Date(startAt).toISOString(), tz: s.timeZone, force,
351
- fields: {...customer, source, by: by || customer.name, ext: extOf(ext), ...(contactId ? {contactId} : {}), ...(userId ? {createdBy: String(userId)} : {})}});
352
- if (!contactId && s.addToContacts) {
353
- const bk = candidates.find(c => c.id === b.bookableId);
354
- const id = await linkContact(customer, bk?.userId || s.contactsOwnerId, contactsOn()).catch(() => '');
355
- if (id) Object.assign(b, (await changeBooking(b.id, {contactId: id})).booking);
356
- }
357
- if (notify) tell(b, 'made', {request, toOwner: source !== 'admin'});
358
- registry.emit('made', b);
359
- return b;
360
- }
361
-
362
- // ---- Links to other Tools -------------------------------------------------------
363
-
364
- const bookingsOfContact = async (contactId) => (await allBookings()).filter(b => b.contactId === contactId);
365
- hooks.registerRelatedItems?.('contact', {
366
- id: 'booking', label: 'Bookings', icon: 'clipboard-check',
367
- actions: [{label: 'Book {name}…', icon: 'calendar', url: '#/plugins/booking/new?contact={id}', permission: {resource: 'booking', action: 'manage'}}],
368
- async list({id, user}) {
369
- if (!mayBook(user)) return [];
370
- const now = new Date().toISOString();
371
- const rows = (await bookingsOfContact(id)).map(b => ({
372
- id: b.id, title: `${b.serviceName}${b.bookableName ? ` with ${b.bookableName}` : ''}`, startAt: b.startAt,
373
- past: b.startAt < now, meta: b.status === 'confirmed' ? '' : b.status, url: `#/plugins/booking/bookings/${b.id}`
374
- }));
375
- return [...rows.filter(r => !r.past).sort((a, b) => a.startAt.localeCompare(b.startAt)),
376
- ...rows.filter(r => r.past).sort((a, b) => b.startAt.localeCompare(a.startAt)).slice(0, 5)];
377
- }
378
- });
379
- // Core 0.103+: "Book Sam…" on an email's menu. An older core refuses the kind and nothing shows.
380
- hooks.registerRelatedItems?.('message', {
381
- id: 'booking', label: 'Booking', icon: 'calendar',
382
- actions: [{label: 'Book {name}…', icon: 'calendar', url: '#/plugins/booking/new?email={email}&name={name}', permission: {resource: 'booking', action: 'manage'}}]
383
- });
384
-
385
- hooks.registerCalendarSource?.({
386
- id: 'bookings', label: 'Bookings', icon: 'clipboard-check', tone: 'primary',
387
- async list({from, to, user}) {
388
- if (!mayBook(user)) return [];
389
- return (await allBookings())
390
- .filter(b => HOLDING.has(b.status) && b.startAt < to && b.endAt > from)
391
- .map(b => ({id: b.id, title: `${b.serviceName}: ${b.name}`, startAt: b.startAt, endAt: b.endAt,
392
- meta: b.bookableName, url: `#/plugins/booking/bookings/${b.id}`}));
393
- }
394
- });
395
-
396
- // ---- Admin: bootstrap, badge ----------------------------------------------------
397
-
398
- async function bootstrap() {
399
- const [s, services, bookables] = await Promise.all([liveSettings(), allServices(), allBookables()]);
400
- let users = [];
401
- try { users = (await listUsers()).filter(u => u.isActive !== false).map(u => ({id: u.id, name: u.name || u.email, email: u.email})); } catch { /* none */ }
402
- return {
403
- settings: s, services, bookables, users,
404
- mailReady: mailReady(),
405
- contacts: contactsOn(),
406
- calendar: Boolean(getPluginStates().calendar?.enabled),
407
- tabs: registry.tabs(),
408
- sections: registry.admin(),
409
- actions: typeof registry.actions === 'function' ? registry.actions() : [],
410
- now: new Date().toISOString(),
411
- today: wallClock(Date.now(), s.timeZone).date
412
- };
413
- }
414
-
415
- fastify.get('/bootstrap', can('read'), async () => bootstrap());
416
-
417
- fastify.get('/count', can('read'), async () => {
418
- const s = await liveSettings();
419
- const now = Date.now();
420
- const today = wallClock(now, s.timeZone).date;
421
- const confirmed = (await allBookings()).filter(b => b.status === 'confirmed')
422
- .sort((a, b) => a.startAt.localeCompare(b.startAt));
423
- const left = confirmed.filter(b => Date.parse(b.endAt) > now && wallClock(b.startAt, s.timeZone).date === today);
424
- const line = (b) => ({text: `${b.serviceName}: ${b.name}`, meta: `${wallClock(b.startAt, s.timeZone).date} ${wallClock(b.startAt, s.timeZone).time}`});
425
- if (left.length) {
426
- return {
427
- count: left.length,
428
- label: left.length === 1 ? '1 booking still to come today' : `${left.length} bookings still to come today`,
429
- tone: 'info',
430
- details: {title: 'Still to come today', items: left.slice(0, 8).map(line), empty: 'Nothing left today.'}
431
- };
432
- }
433
- // Calm: nothing left today, so how many bookings the next 7 days hold (an inventory).
434
- const week = confirmed.filter(b => { const t = Date.parse(b.startAt); return t > now && t < now + 7 * 86_400_000; });
435
- return {
436
- count: week.length,
437
- label: `${week.length} booking${week.length === 1 ? '' : 's'} in the next 7 days - none left today`,
438
- tone: 'info',
439
- inventory: true,
440
- details: {title: 'The next 7 days', items: week.slice(0, 8).map(line), empty: 'No bookings in the next 7 days.'}
441
- };
442
- });
443
-
444
- // ---- Admin: bookings ------------------------------------------------------------
445
-
446
- fastify.get('/bookings', can('read'), async (request) => {
447
- const from = String(request.query?.from || '');
448
- const to = String(request.query?.to || '');
449
- const contact = String(request.query?.contact || '');
450
- let list = await allBookings();
451
- if (from) list = list.filter(b => b.endAt > from);
452
- if (to) list = list.filter(b => b.startAt < to);
453
- if (contact) list = list.filter(b => b.contactId === contact);
454
- return list.sort((a, b) => a.startAt.localeCompare(b.startAt)).map(adminBooking);
455
- });
456
-
457
- fastify.get('/bookings/:id', can('read'), async (request, reply) => {
458
- const b = await getBooking(request.params.id);
459
- if (!b) return fail(reply, 404, 'No such booking.');
460
- // An online booking says how many messages its call's chat holds (the panel offers "Call chat").
461
- const callChat = b.online === true && chatStore ? (await chatStore.load(sessionOf(b))).filter(i => i.kind === 'chat').length : undefined;
462
- return reply.send({...adminBooking(b), ...(callChat !== undefined ? {callChat} : {})});
463
- });
464
-
465
- // The call's chat, read-only (1.5): the session's transcript - a class's shared call has one. Staff with
466
- // booking read only; the customer saw it in the call. Staff (host) lines are marked `mine`.
467
- fastify.get('/bookings/:id/call-chat', can('read'), async (request, reply) => {
468
- const b = await getBooking(request.params.id);
469
- if (!b || b.online !== true) return fail(reply, 404, 'No such online booking.');
470
- const room = sessionOf(b);
471
- const items = chatStore ? await chatStore.load(room) : [];
472
- const hosts = new Set(whoOf ? (await allBookings()).filter(x => x.online === true && sessionOf(x) === room)
473
- .map(x => whoOf(`${x.id}:host`, '')) : []);
474
- reply.header('Cache-Control', 'no-store');
475
- return reply.send({messages: items.filter(i => i.kind === 'chat').length,
476
- items: items.map(({from, ...i}) => ({...i, mine: i.kind === 'chat' && hosts.has(i.who)}))});
477
- });
478
-
479
- /** Service + the bookables that may take a booking of it (`with` narrows to one). */
480
- async function candidatesFor(serviceId, withId, {includeInactive = false} = {}) {
481
- const service = await getService(serviceId);
482
- if (!service || (!includeInactive && service.active === false)) return {service: null, candidates: [], rules: registry.rules({}, [])};
483
- // A switched-off person or room is only ever booked by name (staff choosing them), never as "anyone".
484
- const every = await allBookables();
485
- const bookables = every.filter(b => service.bookables.includes(b.id)
486
- && (b.active !== false || (includeInactive && withId && b.id === withId)));
487
- const candidates = withId ? bookables.filter(b => b.id === withId) : bookables;
488
- return {service, candidates, rules: registry.rules(service, every)};
489
- }
490
-
491
- fastify.post('/bookings', can('manage'), async (request, reply) => {
492
- const body = request.body || {};
493
- const s = await liveSettings();
494
- const {service, candidates, rules} = await candidatesFor(String(body.serviceId || ''), String(body.bookableId || ''), {includeInactive: true});
495
- if (!service) return fail(reply, 400, 'Pick a service.');
496
- if (!candidates.length) return fail(reply, 400, 'Nobody provides that service. Add a person or room to it first.');
497
- const startAt = new Date(String(body.startAt || ''));
498
- if (Number.isNaN(startAt.getTime())) return fail(reply, 400, 'Pick a date and time.');
499
- const {data: customer, errors} = cleanCustomer(body.customer || {}, {askPhone: true});
500
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
501
-
502
- let contactId = String(body.contactId || '');
503
- if (contactId && !(await ownContact(contactId, uidOf(request)))) contactId = '';
504
- try {
505
- // Staff may leave extension questions unanswered; what they did answer is cleaned the same way.
506
- const answers = registry.answers(service, body.answers || {}).data;
507
- const b = await placeBooking({
508
- service, candidates, rules, startAt: startAt.toISOString(), tz: s.timeZone, force: body.force === true,
509
- fields: {...customer, staffNote: String(body.staffNote || '').slice(0, 4000), source: 'admin', createdBy: uidOf(request), contactId, by: request.user?.name || '',
510
- ext: {...extOf(body.ext), ...(Object.keys(answers).length ? {answers} : {})}}
511
- });
512
- if (!contactId && s.addToContacts) {
513
- const owner = candidates.find(c => c.id === b.bookableId)?.userId || uidOf(request);
514
- const id = await linkContact(customer, owner, contactsOn()).catch(() => '');
515
- if (id) Object.assign(b, (await changeBooking(b.id, {contactId: id})).booking);
516
- }
517
- if (body.notify !== false) tell(b, 'made', {request, toOwner: false});
518
- registry.emit('made', b);
519
- return reply.code(201).send(adminBooking(b));
520
- } catch (err) {
521
- if (err instanceof SlotTaken) return fail(reply, 409, 'That time clashes with another booking or busy time. Pick another, or book it anyway.', {code: 'slot-taken'});
522
- throw err;
523
- }
524
- });
525
-
526
- fastify.put('/bookings/:id/move', can('manage'), async (request, reply) => {
527
- const body = request.body || {};
528
- const s = await liveSettings();
529
- const current = await getBooking(request.params.id);
530
- if (!current) return fail(reply, 404, 'No such booking.');
531
- if (!HOLDING.has(current.status) || current.status === 'cancelled') return fail(reply, 400, 'A cancelled booking cannot be moved.');
532
- const {service, candidates, rules} = await candidatesFor(current.serviceId, String(body.bookableId || ''), {includeInactive: true});
533
- if (!service) return fail(reply, 400, 'Its service no longer exists.');
534
- const startAt = new Date(String(body.startAt || ''));
535
- if (Number.isNaN(startAt.getTime())) return fail(reply, 400, 'Pick a date and time.');
536
- try {
537
- const b = await placeBooking({service, candidates, rules, startAt: startAt.toISOString(), tz: s.timeZone, moveId: current.id,
538
- force: body.force === true, fields: {by: request.user?.name || ''}});
539
- if (body.notify !== false) tell(b, 'moved', {request, toOwner: false});
540
- registry.emit('moved', b, current);
541
- endCall(current).catch(() => {});
542
- return adminBooking(b);
543
- } catch (err) {
544
- if (err instanceof SlotTaken) return fail(reply, 409, 'That time clashes with another booking or busy time. Pick another, or move it anyway.', {code: 'slot-taken'});
545
- throw err;
546
- }
547
- });
548
-
549
- fastify.put('/bookings/:id', can('manage'), async (request, reply) => {
550
- const body = request.body || {};
551
- const patch = {};
552
- if (body.status !== undefined) patch.status = String(body.status);
553
- if (body.staffNote !== undefined) patch.staffNote = body.staffNote;
554
- if (body.reason !== undefined) patch.reason = body.reason;
555
- if (body.customer) {
556
- const {data, errors} = cleanCustomer({...(await getBooking(request.params.id) || {}), ...body.customer}, {askPhone: true});
557
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
558
- patch.customer = data;
559
- }
560
- let res;
561
- try { res = await changeBooking(request.params.id, patch, request.user?.name || ''); }
562
- catch (err) { return fail(reply, 400, err.message); }
563
- if (!res) return fail(reply, 404, 'No such booking.');
564
- const {booking: b, from} = res;
565
- if (b.status !== from) {
566
- if (b.status === 'cancelled' && body.notify !== false) tell(b, 'cancelled', {request, toOwner: false});
567
- registry.emit(b.status === 'cancelled' ? 'cancelled' : 'status', b, from);
568
- if (b.status === 'cancelled') endCall(b).catch(() => {});
569
- }
570
- return adminBooking(b);
571
- });
572
-
573
- fastify.delete('/bookings/:id', can('manage'), async (request, reply) => {
574
- const b = await getBooking(request.params.id);
575
- if (!b) return fail(reply, 404, 'No such booking.');
576
- await removeBooking(b.id);
577
- // Its call's chat goes with it - unless someone else is still booked into that session (a class).
578
- if (b.online === true && chatStore) {
579
- const room = sessionOf(b);
580
- if (!(await allBookings()).some(x => x.online === true && sessionOf(x) === room)) await chatStore.remove(room)?.catch?.(() => {});
581
- }
582
- return {ok: true};
583
- });
584
-
585
- // ---- Free times -------------------------------------------------------------------
586
-
587
- /** Free times, for the admin (inactive services too) or the page (active, public ones). */
588
- async function freeTimes({serviceId, withId, from, to, ignoreId = '', admin = false, includeFull = false}) {
589
- const s = await liveSettings();
590
- const {service, candidates, rules} = await candidatesFor(serviceId, withId, {includeInactive: admin});
591
- if (!service || (!admin && service.public === false)) return null;
592
- const now = Date.now();
593
- // Staff may book at short notice or far ahead; the page keeps the service's rules.
594
- const timing = admin ? {...service, minNoticeMinutes: 0, maxAdvanceDays: 0} : service;
595
- const range = admin ? {first: from, last: to} : bookingRange(service, now, s.timeZone);
596
- const first = isDate(from) && from > range.first ? from : range.first;
597
- const lastWanted = isDate(to) ? to : addDays(first, 6);
598
- const last = lastWanted < range.last ? lastWanted : range.last;
599
- if (!isDate(first) || !isDate(last) || last < first) return {service, days: [], range, rules};
600
- const span = {from: atWallClock(first, 0, s.timeZone).toISOString(), to: atWallClock(addDays(last, 1), 0, s.timeZone).toISOString()};
601
- const everyone = [...candidates, ...rules.companions.flat()];
602
- const busy = s.calendarBusy ? await calendarBusy(everyone, span, s.timeZone).catch(() => ({})) : {};
603
- const days = slotsFor({service: timing, bookables: candidates, bookings: await allBookings(), busy, rules, includeFull: includeFull && rules.waitlist,
604
- from: first, to: addDays(first, 41) < last ? addDays(first, 41) : last, now, tz: s.timeZone, closures: s.closures, ignoreId});
605
- return {service, days, range, rules};
606
- }
607
-
608
- fastify.get('/slots', can('read'), async (request, reply) => {
609
- const q = request.query || {};
610
- const today = wallClock(Date.now(), settingsNow().timeZone).date;
611
- const r = await freeTimes({serviceId: String(q.service || ''), withId: String(q.with || ''), from: String(q.from || today),
612
- to: String(q.to || ''), ignoreId: String(q.ignore || ''), admin: true});
613
- return r ? {days: r.days} : fail(reply, 404, 'No such service.');
614
- });
615
-
616
- // ---- Admin: services and people & rooms ---------------------------------------------
617
-
618
- fastify.get('/services', can('read'), async () => allServices());
619
- fastify.post('/services', can('manage'), async (request, reply) => {
620
- const {data, errors} = cleanService(request.body || {});
621
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
622
- data.slug = uniqueSlug(data.slug, await allServices());
623
- return reply.code(201).send(await saveThing(SERVICES, '', data));
624
- });
625
- fastify.put('/services/:id', can('manage'), async (request, reply) => {
626
- const current = await getService(request.params.id);
627
- if (!current) return fail(reply, 404, 'No such service.');
628
- const {id, createdAt, updatedAt, ...stored} = current;
629
- const {data, errors} = cleanService(request.body || {}, stored);
630
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
631
- data.slug = uniqueSlug(data.slug, await allServices(), id);
632
- return saveThing(SERVICES, id, data);
633
- });
634
- fastify.delete('/services/:id', can('manage'), async (request, reply) => {
635
- const current = await getService(request.params.id);
636
- if (!current) return fail(reply, 404, 'No such service.');
637
- const now = new Date().toISOString();
638
- const ahead = (await allBookings()).filter(b => b.serviceId === current.id && b.status === 'confirmed' && b.startAt > now).length;
639
- if (ahead) return fail(reply, 409, `${ahead} booking${ahead === 1 ? ' is' : 's are'} still to come for this service. Cancel or move ${ahead === 1 ? 'it' : 'them'} first, or switch the service off instead.`);
640
- await removeThing(SERVICES, current.id);
641
- return {ok: true};
642
- });
643
-
644
- fastify.get('/bookables', can('read'), async () => allBookables());
645
- fastify.post('/bookables', can('manage'), async (request, reply) => {
646
- const {data, errors} = cleanBookable(request.body || {});
647
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
648
- return reply.code(201).send(await saveThing(BOOKABLES, '', data));
649
- });
650
- fastify.put('/bookables/:id', can('manage'), async (request, reply) => {
651
- const current = await getBookable(request.params.id);
652
- if (!current) return fail(reply, 404, 'No such person or room.');
653
- const {id, createdAt, updatedAt, ...stored} = current;
654
- const {data, errors} = cleanBookable(request.body || {}, stored);
655
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
656
- return saveThing(BOOKABLES, id, data);
657
- });
658
- fastify.delete('/bookables/:id', can('manage'), async (request, reply) => {
659
- const current = await getBookable(request.params.id);
660
- if (!current) return fail(reply, 404, 'No such person or room.');
661
- const now = new Date().toISOString();
662
- const ahead = (await allBookings()).filter(b => b.bookableId === current.id && b.status === 'confirmed' && b.startAt > now).length;
663
- if (ahead) return fail(reply, 409, `${ahead} booking${ahead === 1 ? ' is' : 's are'} still to come with ${current.name}. Move or cancel ${ahead === 1 ? 'it' : 'them'} first, or switch ${current.name} off instead.`);
664
- await removeThing(BOOKABLES, current.id);
665
- // Take it off every service that listed it.
666
- for (const svc of await allServices()) {
667
- if (!svc.bookables.includes(current.id)) continue;
668
- const {id, createdAt, updatedAt, ...stored} = svc;
669
- await saveThing(SERVICES, id, {...stored, bookables: svc.bookables.filter(x => x !== current.id)});
670
- }
671
- return {ok: true};
672
- });
673
-
674
- // ---- Admin: settings, contacts ----------------------------------------------------
675
-
676
- fastify.get('/settings', can('read'), async () => ({settings: await liveSettings(), mailReady: mailReady()}));
677
- fastify.put('/settings', can('manage'), async (request, reply) => {
678
- const {settings, errors} = cleanSettings(request.body || {}, await liveSettings());
679
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
680
- saveSettings(settings);
681
- return {settings: await liveSettings(), mailReady: mailReady()};
682
- });
683
-
684
- fastify.get('/contact', can('read'), async (request, reply) => {
685
- if (!contactsOn()) return fail(reply, 404, 'Contacts is switched off.');
686
- const c = await contactByEmail(request.query?.email, uidOf(request));
687
- return c || fail(reply, 404, 'No such contact.');
688
- });
689
-
690
- fastify.get('/contact/:id', can('read'), async (request, reply) => {
691
- if (!contactsOn()) return fail(reply, 404, 'Contacts is switched off.');
692
- const c = await ownContact(request.params.id, uidOf(request));
693
- return c || fail(reply, 404, 'No such contact.');
694
- });
695
-
696
- // ---- Customers --------------------------------------------------------------------
697
-
698
- fastify.get('/public/services', async () => {
699
- const {services, bookables} = await refreshShelf();
700
- const s = await liveSettings();
701
- return {
702
- title: s.pageTitle, intro: s.intro, timeZone: s.timeZone, askPhone: s.askPhone, phoneRequired: s.phoneRequired,
703
- termsUrl: s.termsUrl, today: wallClock(Date.now(), s.timeZone).date,
704
- services: services.filter(x => x.active !== false && x.public !== false).map(x => publicService(x, bookables)).filter(x => x.bookables.length)
705
- .map(x => {
706
- const svc = services.find(y => y.id === x.id);
707
- const r = registry.rules(svc, bookables);
708
- return {...x, capacity: r.capacity, online: r.online === true, waitlist: r.waitlist && Boolean(registry.waitlistUrl()), fields: publicFields(registry.form(svc))};
709
- }),
710
- waitlistUrl: registry.waitlistUrl()
711
- };
712
- });
713
-
714
- fastify.get('/public/slots', {config: {rateLimit: {max: 120, timeWindow: '1 minute'}}}, async (request, reply) => {
715
- const q = request.query || {};
716
- const r = await freeTimes({serviceId: String(q.service || ''), withId: String(q.with || ''), from: String(q.from || ''), to: String(q.to || ''),
717
- ignoreId: String(q.ignore || '').slice(0, 64), includeFull: !q.ignore && Boolean(registry.waitlistUrl())});
718
- if (!r) return fail(reply, 404, 'That service cannot be booked.');
719
- // Who is free is ours to know; the page only needs whether someone is (and, for a class, how many places).
720
- const classy = r.rules?.capacity > 1;
721
- return {range: r.range, days: r.days.map(d => ({date: d.date, slots: d.slots.map(({start, end, time, left, full}) =>
722
- ({start, end, time, ...(classy ? {left} : {}), ...(full ? {full: true} : {})}))}))};
723
- });
724
-
725
- fastify.post('/public/book', {config: {rateLimit: {max: 10, timeWindow: '10 minutes'}}}, async (request, reply) => {
726
- const body = request.body || {};
727
- // The honeypot: a field people never see. A bot that fills it is told it worked.
728
- if (body.website) return reply.code(201).send({ok: true});
729
- const s = await liveSettings();
730
- const {service, candidates} = await candidatesFor(String(body.serviceId || ''), String(body.bookableId || ''));
731
- if (!service || service.public === false || !candidates.length) return fail(reply, 400, 'That service cannot be booked.');
732
- const {data: customer, errors: customerErrors} = cleanCustomer(body.customer || body, {askPhone: s.askPhone, phoneRequired: s.phoneRequired});
733
- const {data: answers, errors: answerErrors} = registry.answers(service, body.answers || {});
734
- const errors = {...customerErrors, ...Object.fromEntries(Object.entries(answerErrors).map(([k, v]) => [`answers.${k}`, v]))};
735
- if (Object.keys(errors).length) return fail(reply, 400, Object.values(errors)[0], {errors});
736
- // The time must be one the page would offer: in the service's range, on its steps, in opening hours.
737
- const startAt = new Date(String(body.startAt || ''));
738
- if (Number.isNaN(startAt.getTime())) return fail(reply, 400, 'Pick a time.');
739
- const day = wallClock(startAt, s.timeZone).date;
740
- const r = await freeTimes({serviceId: service.id, withId: String(body.bookableId || ''), from: day, to: day}).catch(() => null);
741
- const offered = r?.days?.[0]?.slots?.find(x => x.start === startAt.toISOString() && !x.full);
742
- if (!offered) return fail(reply, 409, 'That time is no longer free. Please pick another.', {code: 'slot-taken'});
743
- const refused = await registry.check({service, customer, startAt: offered.start, source: 'public', bookings: await allBookings(), settings: s});
744
- if (refused) return fail(reply, 409, refused, {code: 'refused'});
745
- try {
746
- const b = await placeBooking({
747
- service, rules: r.rules, candidates: candidates.filter(c => offered.bookableIds.includes(c.id)), startAt: offered.start, tz: s.timeZone,
748
- fields: {...customer, source: 'public', by: customer.name, ext: Object.keys(answers).length ? {answers} : {}}
749
- });
750
- if (s.addToContacts) {
751
- const bk = candidates.find(c => c.id === b.bookableId);
752
- const id = await linkContact(customer, bk?.userId || s.contactsOwnerId, contactsOn()).catch(() => '');
753
- if (id) Object.assign(b, (await changeBooking(b.id, {contactId: id})).booking);
754
- }
755
- tell(b, 'made', {request});
756
- notice(b, 'made');
757
- registry.emit('made', b);
758
- return reply.code(201).send({ok: true, booking: publicBooking(b, s), manage: `${s.bookingPath}/manage/${b.id}?t=${b.token}`});
759
- } catch (err) {
760
- if (err instanceof SlotTaken) return fail(reply, 409, err.message, {code: 'slot-taken'});
761
- throw err;
762
- }
763
- });
764
-
765
- /** The customer's booking, when the token is right; null otherwise (a 404 either way). */
766
- async function customersBooking(id, t) {
767
- const b = await getBooking(String(id));
768
- return b && tokenOk(b, String(t || '')) ? b : null;
769
- }
770
-
771
- fastify.get('/public/booking/:id', async (request, reply) => {
772
- const b = await customersBooking(request.params.id, request.query?.t);
773
- if (!b) return fail(reply, 404, 'No such booking.');
774
- return publicBooking(b, await liveSettings());
775
- });
776
-
777
- fastify.get('/public/booking/:id/ics', async (request, reply) => {
778
- const b = await customersBooking(request.params.id, request.query?.t);
779
- if (!b) return fail(reply, 404, 'No such booking.');
780
- const host = (() => { try { return new URL(siteBase(request)).host; } catch { return 'booking'; } })();
781
- const ics = icsFor(b, {host, title: `${b.serviceName} - ${siteTitle()}`, cancel: b.status === 'cancelled', sequence: (b.history || []).length});
782
- return reply.type('text/calendar; charset=utf-8').header('Content-Disposition', 'attachment; filename="booking.ics"').send(ics);
783
- });
784
-
785
- fastify.post('/public/booking/:id/cancel', {config: {rateLimit: {max: 10, timeWindow: '10 minutes'}}}, async (request, reply) => {
786
- const s = await liveSettings();
787
- const b = await customersBooking(request.params.id, request.body?.t);
788
- if (!b) return fail(reply, 404, 'No such booking.');
789
- if (!s.allowCancel || !customerMayChange(b, s)) return fail(reply, 403, s.changeNoticeHours
790
- ? `Bookings can be cancelled here up to ${s.changeNoticeHours} hours before. Please contact us instead.`
791
- : 'This booking cannot be cancelled here. Please contact us instead.');
792
- const {booking: done} = await changeBooking(b.id, {status: 'cancelled', reason: String(request.body?.reason || '').slice(0, 300)}, b.name);
793
- tell(done, 'cancelled', {request});
794
- notice(done, 'cancelled');
795
- registry.emit('cancelled', done, 'confirmed');
796
- endCall(done).catch(() => {});
797
- return publicBooking(done, s);
798
- });
799
-
800
- fastify.post('/public/booking/:id/move', {config: {rateLimit: {max: 10, timeWindow: '10 minutes'}}}, async (request, reply) => {
801
- const s = await liveSettings();
802
- const b = await customersBooking(request.params.id, request.body?.t);
803
- if (!b) return fail(reply, 404, 'No such booking.');
804
- if (!s.allowMove || !customerMayChange(b, s)) return fail(reply, 403, s.changeNoticeHours
805
- ? `Bookings can be moved here up to ${s.changeNoticeHours} hours before. Please contact us instead.`
806
- : 'This booking cannot be moved here. Please contact us instead.');
807
- const startAt = new Date(String(request.body?.startAt || ''));
808
- if (Number.isNaN(startAt.getTime())) return fail(reply, 400, 'Pick a new time.');
809
- // The same person or room: a customer moves their time, not who they see.
810
- const r = await freeTimes({serviceId: b.serviceId, withId: b.bookableId, from: wallClock(startAt, s.timeZone).date, to: wallClock(startAt, s.timeZone).date, ignoreId: b.id});
811
- const offered = r?.days?.[0]?.slots?.find(x => x.start === startAt.toISOString() && !x.full);
812
- if (!offered) return fail(reply, 409, 'That time is no longer free. Please pick another.', {code: 'slot-taken'});
813
- const {service, candidates, rules} = await candidatesFor(b.serviceId, b.bookableId);
814
- try {
815
- const moved = await placeBooking({service, candidates, rules, startAt: offered.start, tz: s.timeZone, moveId: b.id, fields: {by: b.name}});
816
- tell(moved, 'moved', {request});
817
- notice(moved, 'moved');
818
- registry.emit('moved', moved, b);
819
- endCall(b).catch(() => {});
820
- return publicBooking(moved, s);
821
- } catch (err) {
822
- if (err instanceof SlotTaken) return fail(reply, 409, err.message, {code: 'slot-taken'});
823
- throw err;
824
- }
825
- });
826
-
827
- // ---- Online bookings: the call ------------------------------------------------------
828
- // The engine is core's (_lib/call); an older core without it simply has no calls.
829
- try {
830
- const {mountCallRoutes} = await import('../_lib/call/routes.js');
831
- // The chat is saved per session (1.5; a core with the chat store) so a call reopened later shows it.
832
- try {
833
- const {createChatStore} = await import('../_lib/call/chatStore.js');
834
- chatStore = createChatStore(path.join(dataDir, 'call-chat.json'));
835
- whoOf = (await import('../_lib/call/rooms.js')).whoOf || null;
836
- } catch { chatStore = null; }
837
- // Add people (1.6; a core with services/callInvites.js): the host searches their contacts and the team, and
838
- // each person gets their own `&g=` pass under the session's callExtraKey (never the customer's token or the
839
- // host key). They knock like the customer. Without that core the button stays hidden.
840
- let invites = null;
841
- try { invites = await import('../../server/services/callInvites.js'); } catch { invites = null; }
842
- /** The host's booking of this session (their identity is `<booking>:host`), or null. */
843
- const hostBooking = async (room, identity) => {
844
- const id = String(identity || '').endsWith(':host') ? String(identity).slice(0, -5) : '';
845
- const b = id ? await getBooking(id).catch(() => null) : null;
846
- return b && b.online === true && HOLDING.has(b.status) && sessionOf(b) === room ? b : null;
847
- };
848
- /** The session's extra key: the one a booking of it already has, else a new one - on every booking of it. */
849
- const extraKeyOf = async (b, room) => {
850
- const session = (await allBookings()).filter(x => x.online === true && HOLDING.has(x.status) && sessionOf(x) === room);
851
- const key = session.map(x => x.callExtraKey).find(Boolean) || (await import('../_lib/call/invite.js')).newInviteKey();
852
- for (const x of session) if (!x.callExtraKey) await changeBooking(x.id, {callExtraKey: key}, 'call');
853
- // Two sends at once: the first key written stays (changeBooking never replaces one) - use what is stored.
854
- return (await getBooking(b.id).catch(() => null))?.callExtraKey || key;
855
- };
856
- /**
857
- * The host's user on the site: the person's linked, active account - else '' (the host link then may be held
858
- * by someone from outside - it is emailed to the person's address and sits in the .ics - so they get no team
859
- * directory, no contacts and nothing sent in the site's name: Copy link only).
860
- */
861
- const hostUserOf = async (b) => {
862
- const bk = b?.bookableId ? await getBookable(b.bookableId).catch(() => null) : null;
863
- const u = bk?.userId ? await getUserById(bk.userId).catch(() => null) : null;
864
- return u && u.disabled !== true && u.active !== false && u.isActive !== false ? u.id : '';
865
- };
866
- const invite = invites ? {
867
- search: async (room, q, {identity}) => {
868
- const b = await hostBooking(room, identity);
869
- const owner = b ? await hostUserOf(b) : '';
870
- return owner ? invites.searchInvitees({hostUserId: owner, q}) : [];
871
- },
872
- send: async (room, people, {identity, name, via, request}) => {
873
- const b = await hostBooking(room, identity);
874
- if (!b) return {error: 'This booking has no call now.'};
875
- const owner = await hostUserOf(b);
876
- if (!owner && people.length) return {error: 'Copy the link and pass it on yourself.'};
877
- const key = await extraKeyOf(b, room);
878
- const s = await liveSettings();
879
- const base = invites.inviteOrigin ? invites.inviteOrigin(request) : siteBase(request);
880
- const newLink = () => `${base}${invitePath(s, b, key)}`;
881
- const targets = await invites.resolveInvitees(people, {hostUserId: owner});
882
- const results = await invites.deliverInvites(targets, {linkFor: newLink, hostName: name || b.bookableName || 'Your host',
883
- hostUserId: owner, title: b.serviceName, via, key: `booking:${room}`, expiresAt: callWindow(b).closesAt, log});
884
- return {link: newLink(), results};
885
- }
886
- } : null;
887
- calls = mountCallRoutes(fastify, {prefix: '/call', ns: 'booking', ...(chatStore ? {chat: chatStore} : {}), ...(invite ? {invite} : {}), resolve: async (request, room, body) => {
888
- const b = await getBooking(String(body?.b || '')).catch(() => null);
889
- // A class opened early ("Call now") is open for everyone in the session - someone who booked in
890
- // after the click too: take the session's latest opening when this booking has none of its own.
891
- if (b && b.online === true && !b.callOpenedAt) {
892
- const room0 = sessionOf(b);
893
- const opened = (await allBookings()).filter(x => x.id !== b.id && x.online === true && x.callOpenedAt && sessionOf(x) === room0)
894
- .map(x => x.callOpenedAt).sort().at(-1);
895
- if (opened) b.callOpenedAt = opened;
896
- }
897
- const who = whoIsCalling(b, room, {t: body?.t, h: body?.h, g: body?.g});
898
- // Add people for a host with no account here: Copy link only (see hostUserOf).
899
- if (who?.host && invite && !(await hostUserOf(b))) return {...who, inviteOptions: {search: false, typed: false, copyLink: true}};
900
- return who;
901
- }});
902
- } catch (err) {
903
- log.warn?.(`[booking] online calls unavailable on this CMS: ${err?.message || err}`);
904
- }
905
- }