@mccaskie-labs/workbench-bookings 0.2.2 → 0.3.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.
@@ -0,0 +1,426 @@
1
+ // Dated sessions, the waiting list and attendance
2
+ // (docs/capabilities/20-capacity-calendar.md, part 2): the part of
3
+ // createBookings for services with "sessions": true. The owner makes sessions
4
+ // on a page (a departure, a workshop, a term of classes, a stop on a
5
+ // schedule); customers book places on one, or on a whole term; a full one
6
+ // has a waiting list, whose freed places are offered in turn by tick(); and
7
+ // the owner marks who came. The SQL is migration-sessions.ts.
8
+ import { customerOf, nextReminder } from "./bookings.js";
9
+ import { BookingsError } from "./errors.js";
10
+ import { whenText } from "./format.js";
11
+ import { serviceOf } from "./slots.js";
12
+ import { addDays, durationMinutes, localInstant, todayIn, validDate } from "./time.js";
13
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/;
15
+ const MAX_SERIES = 60;
16
+ const iso = (v) => new Date(v).toISOString();
17
+ /** A session row with its times as ISO 8601 in UTC and the places left. */
18
+ export function sessionOf(s) {
19
+ const taken = Number(s.taken ?? 0);
20
+ return { ...s, starts_at: iso(s.starts_at), ends_at: iso(s.ends_at), taken, left: Math.max(0, s.capacity - taken), waiting: Number(s.waiting ?? 0) };
21
+ }
22
+ const waitOf = (w) => ({ ...w, created_at: iso(w.created_at), offered_until: w.offered_until ? iso(w.offered_until) : null });
23
+ export function sessionMethods(c) {
24
+ const { config, say, tz, locale, opts } = c;
25
+ const noticeMins = durationMinutes(config.notice ?? "2h");
26
+ const holdMins = durationMinutes(config.hold ?? "2d");
27
+ const offerMins = durationMinutes(config.waitlist?.offer ?? "12h");
28
+ const runCheckMins = durationMinutes(config.run_check ?? "2d");
29
+ const max = config.max_per_customer ?? 3;
30
+ const pending = (config.confirm ?? "instant") === "owner_approves";
31
+ const uuid = (v, what) => {
32
+ if (typeof v !== "string" || !UUID.test(v))
33
+ throw new BookingsError("bad_input", `${what} must be an id`);
34
+ return v;
35
+ };
36
+ const optional = (v, what, maxLen) => (v === undefined || v === null || (typeof v === "string" && !v.trim()) ? null : c.text(v, what, maxLen));
37
+ /** A service that is booked by sessions. */
38
+ function dated(service) {
39
+ const svc = serviceOf(config, service);
40
+ if (!svc.sessions)
41
+ throw new BookingsError("bad_input", `${service} isn't booked by sessions: give it "sessions": true in bookings.json`);
42
+ return svc;
43
+ }
44
+ async function session(id) {
45
+ const s = await c.call("session", "bookings_session_get", { p_id: uuid(id, "session"), p_now: c.now().toISOString() });
46
+ return s ? sessionOf(s) : null;
47
+ }
48
+ async function ofAccount(id, account) {
49
+ const s = await session(id);
50
+ if (!s || s.account !== account)
51
+ throw new BookingsError("unknown_session", "no such session");
52
+ return s;
53
+ }
54
+ /** The open sessions of a series that haven't started. */
55
+ async function coming(account, series, at) {
56
+ const rows = await c.call("sessions", "bookings_sessions_list", { p_account: account, p_from: at.toISOString(), p_to: new Date(at.getTime() + 3 * 366 * 86_400_000).toISOString(), p_service: null, p_series: uuid(series, "series"), p_all: false, p_now: at.toISOString() });
57
+ return (rows ?? []).map(sessionOf).filter((s) => Date.parse(s.starts_at) > at.getTime());
58
+ }
59
+ /** Where and what to bring, for the customer's emails. */
60
+ const about = (s) => [...(s.place ? [say("email.where", { place: s.place })] : []), ...(s.map_url ? [say("email.map", { url: s.map_url })] : []), ...(s.note ? [say("email.session_note", { note: s.note })] : [])];
61
+ const datesLine = (on) => (on.length > 1 ? [say("email.dates", { count: on.length, last: whenText(on[on.length - 1].starts_at, tz, locale) })] : []);
62
+ function refused(r) {
63
+ if (r.refused === "too_many")
64
+ throw new BookingsError("too_many", `this email already holds ${max} upcoming bookings`);
65
+ if (r.refused === "waitlist")
66
+ throw new BookingsError("waitlist", "a place is free, but people are waiting for it: join the waiting list");
67
+ if (r.refused === "closed")
68
+ throw new BookingsError("not_open", "that session isn't open for booking: cancelled, started, or too soon");
69
+ if (r.refused === "too_small")
70
+ throw new BookingsError("too_small", "more places are already taken than that");
71
+ if (r.refused === "not_full")
72
+ throw new BookingsError("not_full", "there is room: book instead of waiting");
73
+ if (r.refused === "already")
74
+ throw new BookingsError("already_waiting", "this email is already on the waiting list for it");
75
+ throw new BookingsError("taken", "someone took the last places first");
76
+ }
77
+ function placesOf(v, service) {
78
+ const most = serviceOf(config, service).places ?? 1;
79
+ const places = v ?? 1;
80
+ if (typeof places !== "number" || !Number.isInteger(places) || places < 1 || places > most)
81
+ throw new BookingsError("bad_input", `places: a whole number from 1 to ${most}`);
82
+ return places;
83
+ }
84
+ const memberOf = (v) => (v === undefined || v === null ? null : c.text(v, "member", 200));
85
+ async function join(account, on, target, req) {
86
+ const first = on[0];
87
+ const customer = customerOf(req.customer, config.ask);
88
+ const places = placesOf(req.places, first.service);
89
+ const member = memberOf(req.member);
90
+ const at = c.now();
91
+ await c.allowed(account);
92
+ const start = new Date(first.starts_at);
93
+ const token = c.newToken();
94
+ const r = await c.call("book", "bookings_join", {
95
+ p_session: target.session,
96
+ p_series: target.series,
97
+ p_account: account,
98
+ p_places: places,
99
+ p_status: pending ? "pending" : "confirmed",
100
+ p_name: customer.name,
101
+ p_email: customer.email,
102
+ p_phone: customer.phone ?? null,
103
+ p_note: customer.note ?? null,
104
+ p_member: member,
105
+ p_hash: await c.sha256(token),
106
+ p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
107
+ p_hold_until: pending ? new Date(Math.min(at.getTime() + holdMins * 60_000, start.getTime())).toISOString() : null,
108
+ p_max: max,
109
+ p_min_start: new Date(at.getTime() + noticeMins * 60_000).toISOString(),
110
+ p_now: at.toISOString(),
111
+ p_offer: null,
112
+ });
113
+ if (r && "refused" in r)
114
+ refused(r);
115
+ const booking = c.norm(r);
116
+ const extra = { lines: [...datesLine(on), ...about(first)] };
117
+ await c.quietly("confirmation", () => c.mailCustomer(pending ? "requested" : "booked", booking, token, 0, extra));
118
+ await c.quietly("owner's new booking", () => c.mailOwners(pending ? "request" : "new", booking));
119
+ return { booking, token };
120
+ }
121
+ function inputOf(input, service) {
122
+ const svc = dated(service);
123
+ const start = c.instant(input.start, "start");
124
+ const end = input.end === undefined || input.end === null || input.end === "" ? new Date(start.getTime() + svc.minutes * 60_000) : c.instant(input.end, "end");
125
+ if (end.getTime() <= start.getTime() || end.getTime() - start.getTime() > 31 * 86_400_000)
126
+ throw new BookingsError("bad_input", "end: after the start, within 31 days of it");
127
+ const capacity = input.capacity ?? svc.capacity ?? 1;
128
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 1000)
129
+ throw new BookingsError("bad_input", "capacity: a whole number from 1 to 1000");
130
+ const min = input.min_places ?? null;
131
+ if (min !== null && (!Number.isInteger(min) || min < 1 || min > capacity))
132
+ throw new BookingsError("bad_input", "min_places: a whole number from 1 to the session's places");
133
+ const map = optional(input.map_url, "map_url", 500);
134
+ if (map !== null && !/^https:\/\/[^\s<>"']+$/.test(map))
135
+ throw new BookingsError("bad_input", "map_url: an https link");
136
+ return {
137
+ p_service: service,
138
+ p_start: start.toISOString(),
139
+ p_end: end.toISOString(),
140
+ p_place: optional(input.place, "place", 200),
141
+ p_map_url: map,
142
+ p_note: optional(input.note, "note", 500),
143
+ p_capacity: capacity,
144
+ p_min: min,
145
+ p_bookable: input.bookable ?? true,
146
+ };
147
+ }
148
+ async function mailWait(kind, w, token) {
149
+ if (!opts.mailer)
150
+ return 0;
151
+ const at = c.now();
152
+ const on = w.session ? [await session(w.session)].filter((s) => s !== null) : await coming(w.account, w.series, at);
153
+ const first = on[0];
154
+ if (!first)
155
+ return 0;
156
+ const biz = await c.business(w.account);
157
+ const p = { service: c.titleOf(first.service), business: biz.name, when: whenText(first.starts_at, tz, locale), name: w.customer.name, places: w.places, until: w.offered_until ? whenText(w.offered_until, tz, locale) : "" };
158
+ const url = opts.links?.waitlist?.(token);
159
+ const body = [
160
+ say("email.hello", p),
161
+ "",
162
+ say(`email.${kind}.body`, p),
163
+ ...(w.places > 1 ? [say("email.places", p)] : []),
164
+ ...datesLine(on),
165
+ ...(url ? ["", say(`email.${kind}.link`, { url })] : []),
166
+ ].join("\n");
167
+ await opts.mailer.send({
168
+ to: w.customer.email,
169
+ subject: say(`email.${kind}.subject`, p),
170
+ text: body,
171
+ template: `bookings.${kind}`,
172
+ ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
173
+ idempotencyKey: await c.mailKey(`${kind}:${w.id}:${w.offered_until ?? ""}`, w.customer.email),
174
+ });
175
+ return 1;
176
+ }
177
+ async function mailShort(s) {
178
+ if (!opts.mailer || !opts.owners || (config.owner_email ?? "each") === "none")
179
+ return 0;
180
+ const p = { service: c.titleOf(s.service), when: whenText(s.starts_at, tz, locale), taken: s.taken, min: s.min_places ?? 0 };
181
+ const url = opts.links?.sessions?.(s.account);
182
+ const body = [say("email.owner.short.body", p), ...(url ? ["", say("email.owner.short.open", { url })] : []), "", say("email.owner.footer")].join("\n");
183
+ let sent = 0;
184
+ for (const o of await opts.owners(s.account)) {
185
+ if (!o || typeof o.email !== "string" || !o.email.includes("@"))
186
+ continue;
187
+ await opts.mailer.send({ to: o.email, subject: say("email.owner.short.subject", p), text: body, template: "bookings.owner.short", idempotencyKey: await c.mailKey(`owner:short:${s.id}:${s.sequence}`, o.email) });
188
+ sent++;
189
+ }
190
+ return sent;
191
+ }
192
+ const methods = {
193
+ session,
194
+ async sessions(account, o = {}) {
195
+ c.text(account, "account", 200);
196
+ if (o.service !== undefined)
197
+ dated(o.service);
198
+ const at = c.now();
199
+ const from = o.from ?? todayIn(tz, at);
200
+ if (!validDate(from))
201
+ throw new BookingsError("bad_input", "from must be a day, YYYY-MM-DD");
202
+ const days = o.days ?? config.ahead_days ?? 60;
203
+ if (!Number.isInteger(days) || days < 1 || days > 366)
204
+ throw new BookingsError("bad_input", "days must be a whole number from 1 to 366");
205
+ const lo = localInstant(from, "00:00", tz);
206
+ const rows = await c.call("sessions", "bookings_sessions_list", {
207
+ p_account: account,
208
+ // From today, a session already under way is still listed; the page says it has started.
209
+ p_from: (o.from === undefined && at > lo ? at : lo).toISOString(),
210
+ p_to: localInstant(addDays(from, days), "00:00", tz).toISOString(),
211
+ p_service: o.service ?? null,
212
+ p_series: o.series === undefined ? null : uuid(o.series, "series"),
213
+ p_all: o.all ?? false,
214
+ p_now: at.toISOString(),
215
+ });
216
+ return (rows ?? []).map(sessionOf);
217
+ },
218
+ async saveSession(account, input) {
219
+ if (!input || typeof input !== "object")
220
+ throw new BookingsError("bad_input", "saveSession takes { service, start, ... }");
221
+ const a = c.text(account, "account", 200);
222
+ const id = input.id === undefined ? null : uuid(input.id, "id");
223
+ const at = c.now();
224
+ const r = await c.call("saveSession", "bookings_session_save", { p_id: id, p_account: a, p_series: null, ...inputOf(input, input.service), p_now: at.toISOString() });
225
+ if (!r)
226
+ throw new BookingsError("unknown_session", "no such session, or it is cancelled");
227
+ if ("refused" in r)
228
+ refused(r);
229
+ const saved = sessionOf(r.session);
230
+ const moved = (r.moved ?? []).map(c.norm);
231
+ for (const b of moved) {
232
+ if (b.status === "confirmed")
233
+ await c.call("saveSession", "bookings_rearm", { p_id: b.id, p_next: nextReminder(config, new Date(b.starts_at), at)?.toISOString() ?? null, p_now: at.toISOString() });
234
+ await c.quietly("move", () => c.mailCustomer("moved", b, undefined, 0, { lines: about(saved) }));
235
+ }
236
+ return { session: saved, moved };
237
+ },
238
+ async createSeries(account, inputs) {
239
+ const a = c.text(account, "account", 200);
240
+ if (!Array.isArray(inputs) || inputs.length < 1 || inputs.length > MAX_SERIES)
241
+ throw new BookingsError("bad_input", `a series is 1 to ${MAX_SERIES} sessions`);
242
+ const service = inputs[0].service;
243
+ const rows = inputs.map((i) => {
244
+ if (i.service !== service)
245
+ throw new BookingsError("bad_input", "a series is sessions of one service");
246
+ return inputOf(i, service);
247
+ });
248
+ const series = crypto.randomUUID();
249
+ const at = c.now().toISOString();
250
+ const made = [];
251
+ for (const row of rows) {
252
+ const r = await c.call("createSeries", "bookings_session_save", { p_id: null, p_account: a, p_series: series, ...row, p_now: at });
253
+ made.push(sessionOf(r.session));
254
+ }
255
+ return { series, sessions: made.sort((x, y) => (x.starts_at < y.starts_at ? -1 : 1)) };
256
+ },
257
+ async cancelSession(id, account, reason) {
258
+ const a = c.text(account, "account", 200);
259
+ const why = optional(reason, "reason", 200);
260
+ const r = await c.call("cancelSession", "bookings_session_cancel", { p_id: uuid(id, "id"), p_account: a, p_reason: why, p_now: c.now().toISOString() });
261
+ if (!r)
262
+ throw new BookingsError("unknown_session", "no such session, or it is already cancelled");
263
+ const s = sessionOf(r.session);
264
+ const cancelled = (r.cancelled ?? []).map(c.norm);
265
+ const affected = (r.affected ?? []).map(c.norm);
266
+ const lines = why ? [say("email.reason", { reason: why })] : [];
267
+ for (const b of cancelled)
268
+ await c.quietly("cancellation", () => c.mailCustomer("session_cancelled", b, undefined, 0, { lines }));
269
+ for (const b of affected)
270
+ await c.quietly("cancellation", () => c.mailCustomer("date_cancelled", b, undefined, 0, { lines, when: whenText(s.starts_at, tz, locale) }));
271
+ return { session: s, cancelled, affected };
272
+ },
273
+ async bookSession(req) {
274
+ if (!req || typeof req !== "object")
275
+ throw new BookingsError("bad_input", "bookSession takes { account, session, customer }");
276
+ const account = c.text(req.account, "account", 200);
277
+ const s = await ofAccount(req.session, account);
278
+ return await join(account, [s], { session: s.id, series: null }, req);
279
+ },
280
+ async bookSeries(req) {
281
+ if (!req || typeof req !== "object")
282
+ throw new BookingsError("bad_input", "bookSeries takes { account, series, customer }");
283
+ const account = c.text(req.account, "account", 200);
284
+ const at = c.now();
285
+ const min = at.getTime() + noticeMins * 60_000;
286
+ const on = (await coming(account, req.series, at)).filter((s) => Date.parse(s.starts_at) >= min);
287
+ if (!on.length)
288
+ throw new BookingsError("unknown_session", "no such series, or none of it is still to come");
289
+ return await join(account, on, { session: null, series: req.series }, req);
290
+ },
291
+ async moveToSession(token, to) {
292
+ const b = await c.open(token);
293
+ if (!b.session)
294
+ throw new BookingsError("bad_input", "only a booking on a session moves to another session");
295
+ if (b.session === to)
296
+ return b;
297
+ const s = await ofAccount(to, b.account);
298
+ const at = c.now();
299
+ const r = await c.call("move", "bookings_rejoin", {
300
+ p_id: b.id,
301
+ p_session: s.id,
302
+ p_next_reminder: nextReminder(config, new Date(s.starts_at), at)?.toISOString() ?? null,
303
+ p_min_start: new Date(at.getTime() + noticeMins * 60_000).toISOString(),
304
+ p_now: at.toISOString(),
305
+ });
306
+ if (!r)
307
+ throw new BookingsError("unknown_booking", "the booking ended meanwhile");
308
+ if ("refused" in r)
309
+ refused(r);
310
+ const moved = c.norm(r);
311
+ await c.quietly("move", () => c.mailCustomer("moved", moved, token, 0, { lines: about(s) }));
312
+ await c.quietly("owner's move", () => c.mailOwners("moved", moved));
313
+ return moved;
314
+ },
315
+ async joinWaitlist(req) {
316
+ if (!req || typeof req !== "object")
317
+ throw new BookingsError("bad_input", "joinWaitlist takes { account, session or series, customer }");
318
+ const account = c.text(req.account, "account", 200);
319
+ if ((req.session === undefined) === (req.series === undefined))
320
+ throw new BookingsError("bad_input", "a session or a series, one of them");
321
+ const at = c.now();
322
+ const first = req.session !== undefined ? await ofAccount(req.session, account) : (await coming(account, req.series, at))[0];
323
+ if (!first)
324
+ throw new BookingsError("unknown_session", "no such series, or none of it is still to come");
325
+ const customer = customerOf(req.customer, { phone: config.ask?.phone ?? "no" });
326
+ const places = placesOf(req.places, first.service);
327
+ await c.allowed(account);
328
+ const token = c.newToken();
329
+ const r = await c.call("joinWaitlist", "bookings_wait", {
330
+ p_account: account,
331
+ p_session: req.session ?? null,
332
+ p_series: req.series ?? null,
333
+ p_places: places,
334
+ p_name: customer.name,
335
+ p_email: customer.email,
336
+ p_phone: customer.phone ?? null,
337
+ p_member: memberOf(req.member),
338
+ p_hash: await c.sha256(token),
339
+ p_now: at.toISOString(),
340
+ });
341
+ if (r && "refused" in r)
342
+ refused(r);
343
+ const entry = waitOf(r);
344
+ await c.quietly("waiting list", () => mailWait("waiting", entry, token));
345
+ return { entry, token };
346
+ },
347
+ async waitEntry(token) {
348
+ if (typeof token !== "string" || !TOKEN.test(token))
349
+ return null;
350
+ const w = await c.call("waitEntry", "bookings_wait_by_hash", { p_hash: await c.sha256(token) });
351
+ return w ? waitOf(w) : null;
352
+ },
353
+ async leaveWaitlist(token) {
354
+ const w = typeof token === "string" && TOKEN.test(token) ? await c.call("leaveWaitlist", "bookings_wait_leave", { p_hash: await c.sha256(token), p_now: c.now().toISOString() }) : null;
355
+ if (!w)
356
+ throw new BookingsError("unknown_booking", "no such place on a waiting list, or it has ended");
357
+ return waitOf(w);
358
+ },
359
+ async acceptOffer(token) {
360
+ const w = await methods.waitEntry(token);
361
+ const at = c.now();
362
+ if (!w || w.status !== "offered" || !w.offered_until || Date.parse(w.offered_until) <= at.getTime())
363
+ throw new BookingsError("unknown_booking", "no place is being held for this link: the offer ran out or was taken");
364
+ const on = w.session ? [await session(w.session)].filter((s) => s !== null) : await coming(w.account, w.series, at);
365
+ const first = on[0];
366
+ if (!first)
367
+ throw new BookingsError("not_open", "that session isn't open for booking: cancelled or started");
368
+ const start = new Date(first.starts_at);
369
+ const bookingToken = c.newToken();
370
+ const r = await c.call("acceptOffer", "bookings_accept", {
371
+ p_hash: await c.sha256(token),
372
+ p_booking_hash: await c.sha256(bookingToken),
373
+ p_status: pending ? "pending" : "confirmed",
374
+ p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
375
+ p_hold_until: pending ? new Date(Math.min(at.getTime() + holdMins * 60_000, start.getTime())).toISOString() : null,
376
+ p_max: max,
377
+ // An offered place can be taken right up to the start: the notice was for strangers.
378
+ p_min_start: at.toISOString(),
379
+ p_now: at.toISOString(),
380
+ });
381
+ if (!r)
382
+ throw new BookingsError("unknown_booking", "no place is being held for this link: the offer ran out or was taken");
383
+ if ("refused" in r)
384
+ refused(r);
385
+ const booking = c.norm(r);
386
+ const extra = { lines: [...datesLine(on), ...about(first)] };
387
+ await c.quietly("confirmation", () => c.mailCustomer(pending ? "requested" : "booked", booking, bookingToken, 0, extra));
388
+ await c.quietly("owner's new booking", () => c.mailOwners(pending ? "request" : "new", booking));
389
+ return { booking, token: bookingToken };
390
+ },
391
+ async roll(id, account) {
392
+ const a = c.text(account, "account", 200);
393
+ const s = await ofAccount(id, a);
394
+ const rows = await c.call("roll", "bookings_roll", { p_session: s.id, p_account: a, p_now: c.now().toISOString() });
395
+ return { session: s, entries: (rows ?? []).map(({ came, ...b }) => ({ booking: c.norm(b), came: came ?? null })) };
396
+ },
397
+ async mark(booking, account, came, on) {
398
+ if (came !== null && typeof came !== "boolean")
399
+ throw new BookingsError("bad_input", "came must be true, false or null");
400
+ const ok = await c.call("mark", "bookings_mark", { p_booking: uuid(booking, "booking"), p_account: c.text(account, "account", 200), p_session: on === undefined ? null : uuid(on, "session"), p_came: came, p_now: c.now().toISOString() });
401
+ if (!ok)
402
+ throw new BookingsError("unknown_booking", "no such booking on that session");
403
+ },
404
+ };
405
+ return {
406
+ methods,
407
+ async tick(out, at) {
408
+ const limit = opts.batch ?? 200;
409
+ const offers = (await c.call("tick", "bookings_offers", { p_now: at.toISOString(), p_until: new Date(at.getTime() + offerMins * 60_000).toISOString(), p_limit: limit })) ?? [];
410
+ for (const row of offers) {
411
+ const w = waitOf(row);
412
+ // A fresh secret for the offer's link: only hashes are kept, so the one from when they joined can't be sent again.
413
+ const token = c.newToken();
414
+ if (!(await c.call("tick", "bookings_offer_token", { p_id: w.id, p_hash: await c.sha256(token) })))
415
+ continue;
416
+ out.offered++;
417
+ out.emailed += await c.quietly("waiting list offer", () => mailWait("offer", w, token));
418
+ }
419
+ const short = (await c.call("tick", "bookings_sessions_short", { p_now: at.toISOString(), p_until: new Date(at.getTime() + runCheckMins * 60_000).toISOString(), p_limit: limit })) ?? [];
420
+ for (const row of short) {
421
+ out.short++;
422
+ out.emailed += await c.quietly("owner's minimum", () => mailShort(sessionOf(row)));
423
+ }
424
+ },
425
+ };
426
+ }
package/dist/slots.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BookingConfig, type BookingService, type Busy, type SlotDay, type WeekHours } from "./types.ts";
1
+ import { type BookingConfig, type BookingService, type Busy, type ResourceTimes, type SlotDay, type WeekHours } from "./types.ts";
2
2
  export interface SlotQuery {
3
3
  service: string;
4
4
  /** The first day (YYYY-MM-DD, local). Default today. */
@@ -11,14 +11,33 @@ export interface SlotQuery {
11
11
  hours?: WeekHours;
12
12
  /** More closed days, such as the country's public holidays. */
13
13
  closed?: readonly string[];
14
+ /** When each resource works, from the app's database (a roster). A resource left out follows bookings.json. */
15
+ resources?: Readonly<Record<string, ResourceTimes>>;
16
+ /** Only times this resource is free for: the customer's choice in the service's choose group. */
17
+ with?: string;
14
18
  now: Date;
15
19
  }
16
20
  /** The service of a name, or unknown_service. */
17
21
  export declare function serviceOf(config: BookingConfig, name: unknown): BookingService;
22
+ /** Whether a resource works from start to end: inside one shift when it has shifts, else inside its weekly hours when it has any, and never while away. Who has booked it isn't looked at. */
23
+ export declare function working(config: BookingConfig, name: string, start: number, end: number, times?: ResourceTimes): boolean;
24
+ /** The service's choose group, or undefined. */
25
+ export declare const chooseGroup: (svc: BookingService) => import("./types.ts").ServiceNeed | undefined;
26
+ /**
27
+ * For each of the service's needs, the resources that work from start to end
28
+ * (ignoring who has booked them), narrowed to `with` in the choose group.
29
+ * Null when a group has nobody, or `with` isn't someone the customer can choose.
30
+ */
31
+ export declare function candidates(config: BookingConfig, service: string, start: number, end: number, extra?: {
32
+ resources?: Readonly<Record<string, ResourceTimes>>;
33
+ with?: string;
34
+ }): string[][] | null;
18
35
  /** The free start times, day by day, in the business's time zone. */
19
36
  export declare function openSlots(config: BookingConfig, q: SlotQuery): SlotDay[];
20
37
  /** Whether `start` is a time the business offers for the service (ignoring who has booked it). */
21
38
  export declare function offered(config: BookingConfig, service: string, start: Date, now: Date, extra?: {
22
39
  hours?: WeekHours;
23
40
  closed?: readonly string[];
41
+ resources?: Readonly<Record<string, ResourceTimes>>;
42
+ with?: string;
24
43
  }): boolean;
package/dist/slots.js CHANGED
@@ -31,9 +31,94 @@ function placesLeft(config, service, start, blockEnd, busy) {
31
31
  }
32
32
  return Math.max(0, cap - same);
33
33
  }
34
+ const overlaps = (spans, start, end) => spans.some(([a, b]) => Date.parse(a) < end && Date.parse(b) > start);
35
+ /** Whether a resource works from start to end: inside one shift when it has shifts, else inside its weekly hours when it has any, and never while away. Who has booked it isn't looked at. */
36
+ export function working(config, name, start, end, times) {
37
+ if (times?.away && overlaps(times.away, start, end))
38
+ return false;
39
+ if (times?.shifts)
40
+ return times.shifts.some(([a, b]) => Date.parse(a) <= start && Date.parse(b) >= end);
41
+ const hours = times?.hours ?? config.resources?.[name]?.hours;
42
+ if (!hours)
43
+ return true;
44
+ const tz = config.time_zone;
45
+ const date = todayIn(tz, new Date(start));
46
+ return (hours[WEEKDAYS[weekdayIndex(date)]] ?? []).some(([a, b]) => localInstant(date, a, tz).getTime() <= start && localInstant(date, b, tz).getTime() >= end);
47
+ }
48
+ /** The service's choose group, or undefined. */
49
+ export const chooseGroup = (svc) => svc.needs?.find((n) => n.choose);
50
+ /**
51
+ * For each of the service's needs, the resources that work from start to end
52
+ * (ignoring who has booked them), narrowed to `with` in the choose group.
53
+ * Null when a group has nobody, or `with` isn't someone the customer can choose.
54
+ */
55
+ export function candidates(config, service, start, end, extra = {}) {
56
+ const svc = serviceOf(config, service);
57
+ if (extra.with !== undefined && !chooseGroup(svc)?.any.includes(extra.with))
58
+ return null;
59
+ const out = [];
60
+ for (const need of svc.needs ?? []) {
61
+ const able = need.any.filter((r) => (!need.choose || extra.with === undefined || r === extra.with) && working(config, r, start, end, extra.resources?.[r]));
62
+ if (!able.length)
63
+ return null;
64
+ out.push(able);
65
+ }
66
+ return out;
67
+ }
68
+ /**
69
+ * A time for a service that needs resources: the places left and who can be
70
+ * chosen, or null when it can't be booked. People booked into the same start
71
+ * with the same resources are one sitting (a class): the next person joins a
72
+ * sitting with room before a new one opens with whoever else is free.
73
+ */
74
+ function resourceSlot(config, service, svc, start, end, blockEnd, busy, q) {
75
+ const able = candidates(config, service, start, end, q);
76
+ if (!able)
77
+ return null;
78
+ const cap = svc.capacity ?? 1;
79
+ const choose = chooseGroup(svc);
80
+ const sittings = new Map();
81
+ const held = new Set();
82
+ for (const b of busy) {
83
+ if (!b.resources?.length || !(Date.parse(b.starts_at) < blockEnd && Date.parse(b.block_end) > start))
84
+ continue;
85
+ for (const r of b.resources)
86
+ held.add(r);
87
+ if (b.service !== service || Date.parse(b.starts_at) !== start)
88
+ continue;
89
+ const key = [...b.resources].sort().join(" ");
90
+ const sitting = sittings.get(key) ?? { resources: b.resources, taken: 0 };
91
+ sitting.taken += b.places ?? 1;
92
+ sittings.set(key, sitting);
93
+ }
94
+ let left = 0;
95
+ const choices = new Set();
96
+ for (const sitting of sittings.values()) {
97
+ if (sitting.taken >= cap || !able.every((g) => g.some((r) => sitting.resources.includes(r))))
98
+ continue;
99
+ left = Math.max(left, cap - sitting.taken);
100
+ for (const r of choose?.any ?? [])
101
+ if (sitting.resources.includes(r))
102
+ choices.add(r);
103
+ }
104
+ const free = able.map((g) => g.filter((r) => !held.has(r)));
105
+ if (free.every((g) => g.length)) {
106
+ left = cap;
107
+ if (choose)
108
+ for (const r of free[svc.needs.indexOf(choose)])
109
+ choices.add(r);
110
+ }
111
+ if (left === 0)
112
+ return null;
113
+ return { left, ...(choose ? { choices: choose.any.filter((r) => choices.has(r)) } : {}) };
114
+ }
34
115
  /** The free start times, day by day, in the business's time zone. */
35
116
  export function openSlots(config, q) {
36
117
  const svc = serviceOf(config, q.service);
118
+ if (svc.sessions)
119
+ throw new BookingsError("bad_input", `${q.service} is booked by sessions: list them with sessions() and book with bookSession()`);
120
+ if (q.with !== undefined && !chooseGroup(svc)?.any.includes(q.with))
121
+ throw new BookingsError("bad_input", "with: not someone this service lets the customer choose");
37
122
  const tz = config.time_zone;
38
123
  const today = todayIn(tz, q.now);
39
124
  const from = q.from ?? today;
@@ -67,12 +152,13 @@ export function openSlots(config, q) {
67
152
  if (start < earliest || todayIn(tz, new Date(start)) !== date)
68
153
  continue;
69
154
  const end = start + svc.minutes * 60_000;
70
- const left = placesLeft(config, q.service, start, end + (svc.buffer ?? 0) * 60_000, busy);
155
+ const blockEnd = end + (svc.buffer ?? 0) * 60_000;
156
+ const found = svc.needs ? resourceSlot(config, q.service, svc, start, end, blockEnd, busy, q) : { left: placesLeft(config, q.service, start, blockEnd, busy) };
71
157
  const iso = new Date(start).toISOString();
72
- if (left === 0 || seen.has(iso))
158
+ if (!found || found.left === 0 || seen.has(iso))
73
159
  continue;
74
160
  seen.add(iso);
75
- day.slots.push({ start: iso, end: new Date(end).toISOString(), left });
161
+ day.slots.push({ start: iso, end: new Date(end).toISOString(), ...found });
76
162
  }
77
163
  }
78
164
  day.slots.sort((x, y) => (x.start < y.start ? -1 : 1));
package/dist/styles.js CHANGED
@@ -49,6 +49,19 @@ export const BOOKING_STYLES = {
49
49
  states: [focus, { selector: ":hover", about: "Under the pointer", css: `border-color:${v("accent")}` }],
50
50
  },
51
51
  { name: "wb-booking-left", element: "span", about: "Places left at a time, for a class", css: `margin-left:.4rem;color:${v("muted")};font-weight:400;font-size:.85rem` },
52
+ { name: "wb-booking-choose", element: "nav", about: "Who with: the people (or rooms) the customer can choose between", css: "display:grid;gap:.4rem" },
53
+ { name: "wb-booking-choose-label", element: "p", about: "The chooser's label: Who with", css: "margin:0;font-weight:600;font-size:.95rem" },
54
+ { name: "wb-booking-choices", element: "ul", about: "The choices in a row", css: "list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:.5rem" },
55
+ { name: "wb-booking-choice-item", element: "li", about: "One choice's place in the row", css: "margin:0" },
56
+ {
57
+ name: "wb-booking-choice",
58
+ element: "a",
59
+ about: "One choice: Anyone available, or a name",
60
+ css: `${button};color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};text-decoration:none`,
61
+ states: [focus, { selector: ":hover", about: "Under the pointer", css: `border-color:${v("accent")}` }],
62
+ },
63
+ { name: "wb-booking-choice-on", element: "a", about: "The choice the times shown are for (added to wb-booking-choice)", css: `color:${v("on-accent")};background:${v("accent")};border-color:${v("accent")}` },
64
+ { name: "wb-booking-with", element: "p", about: "Who and where a booking is with: With Dr Lee, Room 1", css: "margin:0" },
52
65
  { name: "wb-booking-empty", element: "p", about: "No free times on these days", css: `margin:0;color:${v("muted")}` },
53
66
  { name: "wb-booking-more", element: "a", about: "Later dates", css: link, states: [focus] },
54
67
  { name: "wb-booking-details", element: "form", about: "The booking form: name, email, and phone or note when asked", css: box },
@@ -93,5 +106,25 @@ export const BOOKING_STYLES = {
93
106
  { name: "wb-booking-approve", element: "button", about: "Accept a request", css: main, states: [focus] },
94
107
  { name: "wb-booking-decline", element: "button", about: "Decline a request", css: quiet, states: [focus] },
95
108
  { name: "wb-booking-owner-cancel", element: "button", about: "The owner cancels a booking", css: `${button};color:${v("danger")};background:transparent;border:1px solid transparent`, states: [focus] },
109
+ { name: "wb-booking-sessions", element: "section", about: "A service's dates to book", css: box },
110
+ { name: "wb-booking-session", element: "article", about: "One date: when, where, places left", css: `display:grid;gap:.4rem;padding:.75rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-left:4px solid ${v("accent")};border-radius:${v("radius")}` },
111
+ { name: "wb-booking-place", element: "p", about: "Where a date is, with its map link", css: "margin:0;overflow-wrap:anywhere" },
112
+ { name: "wb-booking-map", element: "a", about: "Map", css: link, states: [focus] },
113
+ { name: "wb-booking-session-note", element: "p", about: "The owner's note on a date (Bring a hat), or why it was cancelled", css: `margin:0;color:${v("muted")};white-space:pre-wrap;overflow-wrap:anywhere` },
114
+ { name: "wb-booking-session-book", element: "a", about: "Book a date (a button when moving a booking to it)", css: `${main};text-decoration:none`, states: [focus] },
115
+ { name: "wb-booking-session-wait", element: "a", about: "Join the waiting list of a full date", css: `${quiet};text-decoration:none`, states: [focus] },
116
+ { name: "wb-booking-wait", element: "section", about: "A person's own waiting list page, from their link", css: box },
117
+ { name: "wb-booking-session-admin", element: "section", about: "The owner's dates", css: box },
118
+ { name: "wb-booking-session-edit", element: "a", about: "Change a date", css: link, states: [focus] },
119
+ { name: "wb-booking-session-roll", element: "a", about: "Who's coming to a date", css: link, states: [focus] },
120
+ { name: "wb-booking-session-cancel", element: "form", about: "Cancel this date, with the reason everyone booked is emailed", css: `display:grid;gap:.5rem;justify-items:start;padding-top:.5rem;border-top:1px solid ${v("line")}` },
121
+ { name: "wb-booking-session-short", element: "p", about: "A date below the fewest places it runs with", css: `margin:0;color:${v("pending")};font-weight:600` },
122
+ { name: "wb-booking-editor", element: "form", about: "The form that adds or changes a date", css: box },
123
+ { name: "wb-booking-check", element: "label", about: "A tick box with its label", css: "display:flex;gap:.6rem;align-items:center;min-height:2.75rem" },
124
+ { name: "wb-booking-checkbox", element: "input", about: "A tick box", css: `width:1.25rem;height:1.25rem;accent-color:${v("accent")}`, states: [focus] },
125
+ { name: "wb-booking-roll", element: "section", about: "Who's coming to a date", css: box },
126
+ { name: "wb-booking-roll-entry", element: "article", about: "One person on the list", css: `display:grid;gap:.4rem;padding:.75rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-left:4px solid ${v("accent")};border-radius:${v("radius")}` },
127
+ { name: "wb-booking-mark", element: "button", about: "Came, Didn't come or Clear", css: quiet, states: [focus] },
128
+ { name: "wb-booking-mark-on", element: "button", about: "The mark a person has (added to wb-booking-mark)", css: `color:${v("on-accent")};background:${v("accent")};border-color:${v("accent")}` },
96
129
  ],
97
130
  };
package/dist/time.d.ts CHANGED
@@ -19,3 +19,5 @@ export declare function addDays(date: string, n: number): string;
19
19
  export declare function weekdayIndex(date: string): number;
20
20
  /** The instant a local day and clock time ("09:30") happen in the zone. */
21
21
  export declare function localInstant(date: string, clock: string, timeZone: string): Date;
22
+ /** The zone's clock at an instant, "09:30". */
23
+ export declare function clockIn(timeZone: string, at: Date): string;
package/dist/time.js CHANGED
@@ -95,3 +95,8 @@ export function localInstant(date, clock, timeZone) {
95
95
  const mins = clockMinutes(clock) ?? 0;
96
96
  return fromLocal(Date.UTC(y, m - 1, d, Math.floor(mins / 60), mins % 60, 0), timeZone);
97
97
  }
98
+ /** The zone's clock at an instant, "09:30". */
99
+ export function clockIn(timeZone, at) {
100
+ const p = localParts(at, timeZone);
101
+ return `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}`;
102
+ }