@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @mccaskie-labs/workbench-bookings
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Named resources (`docs/capabilities/20-capacity-calendar.md`): `"calendar": "resources"` gives each person, room or thing in `resources` its own diary, and a service's `needs` (up to 3 groups) says what a booking takes, one from each. The new database functions `bookings_take` and `bookings_retime` pick them under the account's lock, so two people can't take the same practitioner or room for overlapping times; "anyone" goes to whoever is free with the lighter day. `choose: true` lets the customer pick (`slots(..., { with })`, each slot's `choices`, `book({ with })`, `renderSlotPicker`'s `choose`, `renderBookingForm`'s `with`), and a moved booking keeps its person. A class shares its instructor and room. `settings` can return `resources` (a roster's `shifts`, `hours`, `away`) to say who works when. `Booking.resources`, `bookings.resourceTitles()`, the pages' `resourceTitles` option, the words `picker.choose`, `picker.anyone`, `with` and `email.with`, and the classes `wb-booking-choose`, `-choose-label`, `-choices`, `-choice-item`, `-choice`, `-choice-on` and `-with`. The manifest asks `bookings.who` and `bookings.choose`.
8
+ - Dated sessions (`docs/capabilities/20-capacity-calendar.md`, part 2): a service with `"sessions": true` is booked by dates the owner makes on a page (a tour departure, a workshop, a term of classes, a food truck's stop that is only shown), each with its own time, place, map link, note, places and optional minimum. `sessions()`, `session()`, `saveSession()`, `createSeries()` (a term booked together) and `cancelSession()` (cancels and emails everyone on it, and answers who to refund); `bookSession()`, `bookSeries()` and `moveToSession()`; a waiting list for full dates (`joinWaitlist()`, `waitEntry()`, `leaveWaitlist()`, `acceptOffer()`), whose freed places `tick()` offers in turn and holds for `waitlist.offer` (default 12 hours) while direct bookings are told to join the list; `run_check` (default 2 days) emails the owner once about a date below its minimum; and attendance (`roll()`, `mark()`). Pages `renderSessionList`, `renderSessionForm`, `renderWaitPage`, `renderSessionAdmin`, `renderSessionEditor` and `renderRoll` with `sessionAction` and `ownerSessionAction`, twenty new `wb-booking-*` classes and their words. A term booking's calendar file has an event for each date (`seriesIcs`), and the owner's feed shows one event per date with how many are booked. New failures `unknown_session`, `waitlist`, `not_full`, `already_waiting` and `too_small`; `Booking.session` and `Booking.series`; `tick()` also answers `offered` and `short`, and `cleanup()` `sessions` and `waits`. `links.waitlist` and `links.sessions`. The manifest asks `bookings.waitlist` and `bookings.minimum`.
9
+ - A third migration, `workbench_bookings_sessions`, which only adds (three tables, two columns on `bookings`, nineteen functions; `bookings_row` and `bookings_cleanup` replaced with the same signatures). Until it is applied everything else works as before; `tick()` runs its waiting list step only when a service is booked by sessions.
10
+ - `detailFields` is exported for apps that build their own booking form around the standard fields.
11
+ - A second migration, `workbench_bookings_resources`, which only adds (a column, an index, three functions, and the two read functions replaced to answer resources). `bookingsMigrations` lists every migration in order, and `npx workbench-bookings migration` writes the ones a project doesn't have yet. `bookingsMigration` is still the first.
12
+
3
13
  ## 0.2.2
4
14
 
5
15
  ### Patch Changes
package/README.md CHANGED
@@ -47,6 +47,69 @@ ctx.waitUntil(bookings.tick())
47
47
  - `attachments: async (booking) => [{ filename, mimeType, bytes }]` adds the project's files (a tax invoice from workbench-pdf) to the confirmation, after the calendar file. If it fails, the email goes without them and `onEmailError` hears `attachment`.
48
48
  - If the app keeps customer records, record the customer when a booking is made, for example `contacts.record({ account, person: { name, email }, from: { kind: 'booking', type: 'booking', id: booking.id } })`. A booking is never consent to marketing.
49
49
 
50
+ ## Several staff, rooms and things
51
+
52
+ One person and one room need none of this: leave `calendar` as it is. With several, give each its own diary:
53
+
54
+ ```json
55
+ {
56
+ "calendar": "resources",
57
+ "resources": {
58
+ "dr-lee": { "title": "Dr Lee", "kind": "person" },
59
+ "dr-ng": { "title": "Dr Ng", "kind": "person", "hours": { "tue": [["09:00", "17:00"]], "wed": [["09:00", "17:00"]] } },
60
+ "room-1": { "title": "Room 1", "kind": "room" },
61
+ "room-2": { "title": "Room 2", "kind": "room" }
62
+ },
63
+ "services": {
64
+ "consult": { "title": "Consultation", "minutes": 30, "needs": [{ "any": ["dr-lee", "dr-ng"], "choose": true }, { "any": ["room-1", "room-2"] }] },
65
+ "call": { "title": "Phone call", "minutes": 30 }
66
+ }
67
+ }
68
+ ```
69
+
70
+ - A service's `needs` is up to 3 groups; a booking takes **one from each**, picked under the same lock that books, so a practitioner and a room can't both be double-booked. A time is free while one of each is. A service with no `needs` is never blocked by them.
71
+ - `choose: true` on one group lets the customer pick: `slots(account, service, { with: "dr-ng" })` gives that person's times, each slot's `choices` says who is free then, and `book({ ..., with })` keeps the choice or answers `taken`. Left out, the booking goes to whoever is free with the lighter day. `renderSlotPicker`'s `choose` option draws "Anyone available" and each name; `renderBookingForm`'s `with` sends the choice back. A booking that is moved stays with the same person.
72
+ - `booking.resources` is what it holds; `bookings.resourceTitles(booking)` gives the titles, people first, and the pages' `resourceTitles` option draws "With Dr Lee, Room 1". The customer's emails name people only.
73
+ - A class (`capacity` above 1) shares its resources: people booked into the same start join the same instructor and room until it is full.
74
+ - Who works when can come from the app's database, such as a roster: `settings: async (account) => ({ resources: { "dr-lee": { shifts: [[start, end], ...] }, "dr-ng": { away: [[start, end]] } } })`. `shifts` are the only spans that person works, `hours` replaces their weekly hours, and `away` wins over both.
75
+
76
+ Run `npx workbench-bookings migration` again after updating: it adds the second migration (`workbench_bookings_resources`), which only adds to the first.
77
+
78
+ ## Dates the owner makes: tours, workshops, terms, stops
79
+
80
+ Give a service `"sessions": true` and it is booked by dates the owner adds on a page, not by opening hours:
81
+
82
+ ```json
83
+ "services": { "walk": { "title": "Harbour walk", "minutes": 120, "capacity": 8, "places": 4, "sessions": true } },
84
+ "waitlist": { "offer": "12h" },
85
+ "run_check": "2d"
86
+ ```
87
+
88
+ ```ts
89
+ // The owner, behind the sign-in (or ownerSessionAction with the editor's fields):
90
+ const { session } = await bookings.saveSession(account, { service: 'walk', start, place: 'Circular Quay, wharf 6', map_url, note: 'Bring a hat', min_places: 4 })
91
+ const term = await bookings.createSeries(account, weeklyDates) // booked together with bookSeries()
92
+ const { cancelled } = await bookings.cancelSession(session.id, account, 'Storm warning') // everyone is emailed; refund `cancelled`
93
+
94
+ // The customer:
95
+ const dates = await bookings.sessions(account, { service: 'walk' }) // each has left and waiting
96
+ await bookings.bookSession({ account, session: dates[0].id, customer, places: 2 })
97
+ await bookings.joinWaitlist({ account, session: full.id, customer }) // when left is 0 or waiting is above 0
98
+ await bookings.acceptOffer(token) // from the link in the offer email
99
+
100
+ // The day itself:
101
+ const { entries } = await bookings.roll(session.id, account)
102
+ await bookings.mark(entries[0].booking.id, account, true, session.id)
103
+ ```
104
+
105
+ - A freed place goes to the waiting list first: `tick()` emails the next person it fits and holds it for `waitlist.offer`; meanwhile `bookSession()` answers `waitlist`.
106
+ - A date with `min_places` that is short `run_check` before it starts is emailed to the owner once. The owner decides; nothing is cancelled automatically.
107
+ - `bookable: false` makes a date that is only shown (a stop on a schedule).
108
+ - Taking payment is the app's job: charge through workbench-payments with the booking's id, and refund the bookings `cancelSession()` hands back.
109
+ - Pass `links.waitlist` and `links.sessions` so the emails can link to the waiting list page and the owner's dates.
110
+
111
+ Pages: `renderSessionList`, `renderSessionForm` (`mode: "book" | "series" | "wait"`), `renderWaitPage`, and for the owner `renderSessionAdmin`, `renderSessionEditor` and `renderRoll`; posts go to `sessionAction` and `ownerSessionAction`.
112
+
50
113
  ## The pages
51
114
 
52
115
  ```ts
@@ -70,4 +133,4 @@ Every element carries a `wb-booking-*` class with a default style (`BOOKING_STYL
70
133
 
71
134
  ## Data
72
135
 
73
- `bookings` (service, times, status, places, the signed-in member's id when there is one, the customer's name, email, optional phone and optional note, the manage secret's SHA-256, reminder state) and `booking_feeds` (each account's feed secret's SHA-256), in the app's own database, service role only. `cleanup()` deletes a booking `retention_days` (180) after it ends. Workbench never holds any of it.
136
+ `bookings` (service, times, status, places, the resources and the date or term it holds, the signed-in member's id when there is one, the customer's name, email, optional phone and optional note, the manage secret's SHA-256, reminder state), `booking_feeds` (each account's feed secret's SHA-256), `booking_sessions` (dates: time, place, note, places; nothing personal), `booking_waitlist` (the name, email and optional phone of people waiting, and their secret's SHA-256) and `booking_attendance` (came or didn't), in the app's own database, service role only. `cleanup()` deletes a booking `retention_days` (180) after it ends, its date once no booking is left on it, and waiting list entries 30 days after they were settled. Workbench never holds any of it.
@@ -1,5 +1,6 @@
1
- import { type Words } from "./format.ts";
2
- import type { Booking, BookingConfig, Customer, SlotDay, TickResult, WeekHours } from "./types.ts";
1
+ import { type Say, type Words } from "./format.ts";
2
+ import { type SessionMethods } from "./sessions.ts";
3
+ import type { Booking, BookingConfig, Customer, ResourceTimes, SlotDay, TickResult, WeekHours } from "./types.ts";
3
4
  type DbError = {
4
5
  message?: string;
5
6
  code?: string;
@@ -48,6 +49,8 @@ export interface Business {
48
49
  export interface AccountSettings {
49
50
  hours?: WeekHours;
50
51
  closed?: readonly string[];
52
+ /** When each resource works (calendar "resources"): a roster's shifts, leave, or its own weekly hours. A resource left out follows bookings.json. */
53
+ resources?: Readonly<Record<string, ResourceTimes>>;
51
54
  }
52
55
  export interface BookingsOptions {
53
56
  /** The service client. */
@@ -68,6 +71,10 @@ export interface BookingsOptions {
68
71
  links?: {
69
72
  manage?: (token: string) => string;
70
73
  bookings?: (account: string) => string;
74
+ /** A person's own waiting list page, from its secret: where they leave the list or take an offered place. */
75
+ waitlist?: (token: string) => string;
76
+ /** The owner's sessions page, for the email about a session below its minimum. */
77
+ sessions?: (account: string) => string;
71
78
  };
72
79
  /** The account's own hours and closed days (public holidays from the country pack, leave). */
73
80
  settings?: (account: string) => Promise<AccountSettings | null>;
@@ -98,13 +105,18 @@ export interface BookRequest {
98
105
  places?: number;
99
106
  /** The signed-in member's id from the app's own sign-in, when they're signed in. Never from the form. */
100
107
  member?: string;
108
+ /** The resource the customer chose (one of the slot's choices), when the service lets them. Left out: anyone free. */
109
+ with?: string;
101
110
  }
102
- export interface Bookings {
111
+ export interface Bookings extends SessionMethods {
103
112
  /** The free times for a service, day by day, from `from` (default today) for `days` (default 7). */
104
113
  slots(account: string, service: string, opts?: {
105
114
  from?: string;
106
115
  days?: number;
116
+ with?: string;
107
117
  }): Promise<SlotDay[]>;
118
+ /** What to call the resources a booking holds, people first: ["Dr Lee", "Room 1"]. */
119
+ resourceTitles(b: Pick<Booking, "resources">): string[];
108
120
  /** Books a free time. Answers the booking and the secret for its manage link (kept nowhere else: put it in the link, never in a log). */
109
121
  book(req: BookRequest): Promise<{
110
122
  booking: Booking;
@@ -144,11 +156,13 @@ export interface Bookings {
144
156
  feedToken(account: string): Promise<string>;
145
157
  /** The calendar feed a feed secret belongs to, or null. */
146
158
  feed(token: string): Promise<string | null>;
147
- /** The cron's scan, every 15 minutes: reminders, and requests nobody answered. Safe to run twice at once. */
159
+ /** The cron's scan, every 15 minutes: reminders, requests nobody answered, waiting list offers and sessions below their minimum. Safe to run twice at once. */
148
160
  tick(): Promise<TickResult>;
149
- /** The daily clean-up: bookings retention_days after they end. */
161
+ /** The daily clean-up: bookings retention_days after they end, and with them their sessions and settled waiting list entries. */
150
162
  cleanup(): Promise<{
151
163
  bookings: number;
164
+ sessions?: number;
165
+ waits?: number;
152
166
  }>;
153
167
  readonly config: BookingConfig;
154
168
  }
@@ -156,5 +170,36 @@ export interface Bookings {
156
170
  export declare function customerOf(v: unknown, ask?: BookingConfig["ask"]): Customer;
157
171
  /** When the next reminder goes: the earliest reminder time after `after`, before the start. */
158
172
  export declare function nextReminder(config: BookingConfig, start: Date, after: Date): Date | null;
173
+ type CustomerMail = "booked" | "requested" | "confirmed" | "declined" | "cancelled" | "moved" | "reminder" | "session_cancelled" | "date_cancelled";
174
+ /** Lines a session adds to a customer's email, and the time to name when it isn't the booking's own. */
175
+ interface MailExtra {
176
+ lines?: readonly string[];
177
+ when?: string;
178
+ }
179
+ /** What sessions.ts borrows from createBookings. */
180
+ export interface StoreContext {
181
+ db: BookingsClient;
182
+ config: BookingConfig;
183
+ opts: BookingsOptions;
184
+ now: () => Date;
185
+ say: Say;
186
+ tz: string;
187
+ locale: string;
188
+ call<T>(what: string, fn: string, args: Record<string, unknown>): Promise<T>;
189
+ sha256(s: string): Promise<string>;
190
+ newToken(): string;
191
+ text(v: unknown, what: string, max: number): string;
192
+ instant(v: unknown, what: string): Date;
193
+ norm(b: Booking): Booking;
194
+ mailKey(key: string, email: string): Promise<string>;
195
+ business(account: string): Promise<Business>;
196
+ titleOf(service: string): string;
197
+ allowed(account: string): Promise<void>;
198
+ open(token: string): Promise<Booking>;
199
+ mailCustomer(kind: CustomerMail, b: Booking, token?: string, n?: number, extra?: MailExtra): Promise<number>;
200
+ mailOwners(kind: OwnerMail, b: Booking): Promise<number>;
201
+ quietly(what: string, send: () => Promise<number>): Promise<number>;
202
+ }
203
+ type OwnerMail = "new" | "request" | "cancelled" | "moved";
159
204
  export declare function createBookings(opts: BookingsOptions): Bookings;
160
205
  export {};
package/dist/bookings.js CHANGED
@@ -11,8 +11,9 @@
11
11
  import { checkBookingConfig } from "./config.js";
12
12
  import { BookingsError } from "./errors.js";
13
13
  import { DEFAULT_LOCALE, whenText, words } from "./format.js";
14
- import { bookingIcs, feedIcs } from "./ical.js";
15
- import { offered, openSlots, serviceOf } from "./slots.js";
14
+ import { bookingIcs, feedIcs, seriesIcs } from "./ical.js";
15
+ import { sessionMethods, sessionOf } from "./sessions.js";
16
+ import { candidates, chooseGroup, offered, openSlots, serviceOf } from "./slots.js";
16
17
  import { addDays, durationMinutes, localInstant, minusDuration, todayIn, validDate } from "./time.js";
17
18
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
19
  const TOKEN = /^[A-Za-z0-9_-]{43}$/;
@@ -47,7 +48,7 @@ function instant(v, what) {
47
48
  const iso = (v) => new Date(v).toISOString();
48
49
  /** A row with its times as ISO 8601 in UTC (Postgres writes +00:00). */
49
50
  function norm(b) {
50
- return { ...b, places: b.places ?? 1, member: b.member ?? null, starts_at: iso(b.starts_at), ends_at: iso(b.ends_at), created_at: iso(b.created_at), updated_at: iso(b.updated_at) };
51
+ return { ...b, places: b.places ?? 1, resources: b.resources ?? [], member: b.member ?? null, session: b.session ?? null, series: b.series ?? null, starts_at: iso(b.starts_at), ends_at: iso(b.ends_at), created_at: iso(b.created_at), updated_at: iso(b.updated_at) };
51
52
  }
52
53
  /** The customer's details from the booking form, checked against what bookings.json asks. */
53
54
  export function customerOf(v, ask = {}) {
@@ -99,27 +100,49 @@ export function createBookings(opts) {
99
100
  const business = async (account) => (opts.business ? await opts.business(account) : { name: account });
100
101
  const settings = async (account) => (opts.settings ? ((await opts.settings(account)) ?? {}) : {});
101
102
  const titleOf = (service) => config.services[service]?.title ?? service;
103
+ const resourceOf = (name) => config.resources?.[name];
104
+ const resourceTitles = (b) => [...(b.resources ?? [])].sort((x, y) => Number(resourceOf(y)?.kind === "person") - Number(resourceOf(x)?.kind === "person")).map((r) => resourceOf(r)?.title ?? r);
105
+ /** The people a booking is with, for the customer's emails: "Dr Lee", or "" when it holds only rooms and things. */
106
+ const peopleOf = (b) => (b.resources ?? []).filter((r) => resourceOf(r)?.kind === "person").map((r) => resourceOf(r).title).join(", ");
102
107
  function times(service, start) {
103
108
  const svc = serviceOf(config, service);
104
109
  const end = new Date(start.getTime() + svc.minutes * 60_000);
105
110
  return { svc, end, blockEnd: new Date(end.getTime() + (svc.buffer ?? 0) * 60_000), capacity: svc.capacity ?? 1, maxPlaces: svc.places ?? 1 };
106
111
  }
112
+ /** A booking's session, or its series' open sessions (a calendar file has one event for each). Without the third migration there are none. */
113
+ async function sessionsOf(b) {
114
+ if (b.session) {
115
+ const s = await call(db, "session", "bookings_session_get", { p_id: b.session, p_now: now().toISOString() });
116
+ return s ? [sessionOf(s)] : [];
117
+ }
118
+ if (!b.series)
119
+ return [];
120
+ const rows = await call(db, "sessions", "bookings_sessions_list", { p_account: b.account, p_from: b.starts_at, p_to: new Date(Date.parse(b.ends_at) + 1).toISOString(), p_service: null, p_series: b.series, p_all: false, p_now: now().toISOString() });
121
+ return (rows ?? []).map(sessionOf);
122
+ }
107
123
  async function ics(b, biz) {
108
124
  const info = biz ?? (await business(b.account));
109
- return bookingIcs(b, { summary: `${titleOf(b.service)} · ${info.name}`, ...(info.location ? { location: info.location } : {}) }, now());
125
+ const summary = `${titleOf(b.service)} · ${info.name}`;
126
+ const on = await sessionsOf(b);
127
+ if (b.series && on.length)
128
+ return seriesIcs(b, on.map((s) => ({ id: s.id, starts_at: s.starts_at, ends_at: s.ends_at, sequence: s.sequence, text: { summary, ...((s.place ?? info.location) ? { location: (s.place ?? info.location) } : {}) } })), now());
129
+ const place = on[0]?.place ?? info.location;
130
+ return bookingIcs(b, { summary, ...(place ? { location: place } : {}) }, now());
110
131
  }
111
- async function mailCustomer(kind, b, token, n = 0) {
132
+ async function mailCustomer(kind, b, token, n = 0, extra = {}) {
112
133
  if (!opts.mailer)
113
134
  return 0;
114
135
  const biz = await business(b.account);
115
- const p = { service: titleOf(b.service), business: biz.name, when: whenText(b.starts_at, tz, locale), name: b.customer.name, places: b.places };
136
+ const p = { service: titleOf(b.service), business: biz.name, when: extra.when ?? whenText(b.starts_at, tz, locale), name: b.customer.name, places: b.places };
116
137
  const manage = token && opts.links?.manage && b.status !== "cancelled" && b.status !== "declined" ? opts.links.manage(token) : undefined;
117
- const withFile = b.status === "confirmed" || kind === "cancelled";
138
+ const withFile = b.status === "confirmed" || kind === "cancelled" || kind === "session_cancelled";
118
139
  const body = [
119
140
  say("email.hello", p),
120
141
  "",
121
142
  say(`email.${kind}.body`, p),
122
143
  ...(b.places > 1 ? [say("email.places", p)] : []),
144
+ ...(peopleOf(b) && kind !== "declined" && kind !== "cancelled" ? [say("email.with", { who: peopleOf(b) })] : []),
145
+ ...(extra.lines ?? []),
123
146
  ...(manage ? ["", say("email.manage", { url: manage })] : []),
124
147
  ...(b.status === "confirmed" ? ["", say("email.calendar")] : []),
125
148
  ].join("\n");
@@ -139,7 +162,7 @@ export function createBookings(opts) {
139
162
  template: `bookings.${kind}`,
140
163
  ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
141
164
  ...(files.length ? { attachments: files } : {}),
142
- idempotencyKey: await mailKey(`${kind}:${b.id}:${b.sequence}:${n}`, b.customer.email),
165
+ idempotencyKey: await mailKey(`${kind}:${b.id}:${b.sequence}:${n}${extra.when ? `:${extra.when}` : ""}`, b.customer.email),
143
166
  });
144
167
  return 1;
145
168
  }
@@ -149,7 +172,8 @@ export function createBookings(opts) {
149
172
  const owners = await opts.owners(b.account);
150
173
  const p = { service: titleOf(b.service), when: whenText(b.starts_at, tz, locale), name: b.customer.name, email: b.customer.email, places: b.places };
151
174
  const url = opts.links?.bookings?.(b.account);
152
- const body = [say("email.owner.body", p), ...(b.places > 1 ? [say("email.places", p)] : []), ...(url ? ["", say("email.owner.open", { url })] : []), "", say("email.owner.footer")].join("\n");
175
+ const held = resourceTitles(b).join(", ");
176
+ const body = [say("email.owner.body", p), ...(b.places > 1 ? [say("email.places", p)] : []), ...(held ? [say("email.with", { who: held })] : []), ...(url ? ["", say("email.owner.open", { url })] : []), "", say("email.owner.footer")].join("\n");
153
177
  let sent = 0;
154
178
  for (const o of owners) {
155
179
  if (!o || typeof o.email !== "string" || !o.email.includes("@"))
@@ -211,14 +235,48 @@ export function createBookings(opts) {
211
235
  return norm(r);
212
236
  }
213
237
  const reasonOf = (r, fallback) => (r === undefined || r === "" ? fallback : text(r, "reason", 200));
238
+ async function allowed(account) {
239
+ if (!opts.plans)
240
+ return;
241
+ const can = await opts.plans.can(account, feature);
242
+ if (!can.ok)
243
+ throw new BookingsError("not_allowed", `the account's plan doesn't include ${feature} (${can.reason ?? "not_on_plan"})`);
244
+ }
245
+ const bySession = Object.values(config.services).some((s) => s.sessions);
246
+ const sessions = sessionMethods({
247
+ db,
248
+ config,
249
+ opts,
250
+ now,
251
+ say,
252
+ tz,
253
+ locale,
254
+ call: (what, fn, args) => call(db, what, fn, args),
255
+ sha256,
256
+ newToken,
257
+ text,
258
+ instant,
259
+ norm,
260
+ mailKey,
261
+ business,
262
+ titleOf,
263
+ allowed,
264
+ open,
265
+ mailCustomer,
266
+ mailOwners,
267
+ quietly,
268
+ });
214
269
  return {
270
+ ...sessions.methods,
215
271
  config,
216
272
  get,
217
273
  byToken,
218
274
  changeable,
275
+ resourceTitles,
219
276
  async slots(account, service, o = {}) {
220
277
  text(account, "account", 200);
221
- serviceOf(config, service);
278
+ if (serviceOf(config, service).sessions)
279
+ throw new BookingsError("bad_input", `${service} is booked by sessions: list them with sessions()`);
222
280
  const at = now();
223
281
  const from = o.from ?? todayIn(tz, at);
224
282
  if (!validDate(from))
@@ -228,39 +286,44 @@ export function createBookings(opts) {
228
286
  const lo = localInstant(addDays(from, -1), "00:00", tz);
229
287
  const hi = localInstant(addDays(from, Math.min(Math.max(days, 1), 62) + 1), "00:00", tz);
230
288
  const busy = (await call(db, "slots", "bookings_busy", { p_account: account, p_from: lo.toISOString(), p_to: hi.toISOString() })) ?? [];
231
- return openSlots(config, { service, from, days, busy, now: at, ...s });
289
+ return openSlots(config, { service, from, days, busy, now: at, ...s, ...(o.with !== undefined ? { with: text(o.with, "with", 40) } : {}) });
232
290
  },
233
291
  async book(req) {
234
292
  if (!req || typeof req !== "object")
235
293
  throw new BookingsError("bad_input", "book takes { account, service, start, customer }");
236
294
  const account = text(req.account, "account", 200);
237
295
  const start = instant(req.start, "start");
238
- const { end, blockEnd, capacity, maxPlaces } = times(req.service, start);
296
+ const { svc, end, blockEnd, capacity, maxPlaces } = times(req.service, start);
297
+ if (svc.sessions)
298
+ throw new BookingsError("bad_input", `${req.service} is booked by sessions: use bookSession()`);
299
+ const chosen = req.with === undefined || req.with === null || req.with === "" ? undefined : text(req.with, "with", 40);
300
+ if (chosen !== undefined && !chooseGroup(svc)?.any.includes(chosen))
301
+ throw new BookingsError("bad_input", "with: not someone this service lets the customer choose");
239
302
  const customer = customerOf(req.customer, config.ask);
240
303
  const places = req.places ?? 1;
241
304
  if (!Number.isInteger(places) || places < 1 || places > maxPlaces)
242
305
  throw new BookingsError("bad_input", `places: a whole number from 1 to ${maxPlaces}`);
243
306
  const member = req.member === undefined || req.member === null ? null : text(req.member, "member", 200);
244
307
  const at = now();
245
- if (opts.plans) {
246
- const can = await opts.plans.can(account, feature);
247
- if (!can.ok)
248
- throw new BookingsError("not_allowed", `the account's plan doesn't include ${feature} (${can.reason ?? "not_on_plan"})`);
249
- }
250
- if (!offered(config, req.service, start, at, await settings(account)))
308
+ await allowed(account);
309
+ const set = await settings(account);
310
+ const needs = svc.needs ? candidates(config, req.service, start.getTime(), end.getTime(), { ...(set.resources ? { resources: set.resources } : {}), ...(chosen !== undefined ? { with: chosen } : {}) }) : null;
311
+ if (!offered(config, req.service, start, at, { ...set, ...(chosen !== undefined ? { with: chosen } : {}) }) || (svc.needs && !needs)) {
251
312
  throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
313
+ }
252
314
  const pending = (config.confirm ?? "instant") === "owner_approves";
253
315
  const token = newToken();
254
316
  const holdMins = durationMinutes(config.hold ?? "2d");
255
317
  const hold = new Date(Math.min(at.getTime() + holdMins * 60_000, start.getTime()));
256
- const r = await call(db, "book", "bookings_book", {
318
+ // A service that needs resources is booked by bookings_take, which picks one of each under the lock.
319
+ const r = await call(db, "book", needs ? "bookings_take" : "bookings_book", {
257
320
  p_account: account,
258
321
  p_service: req.service,
259
322
  p_start: start.toISOString(),
260
323
  p_end: end.toISOString(),
261
324
  p_block_end: blockEnd.toISOString(),
262
325
  p_capacity: capacity,
263
- p_shared: shared,
326
+ ...(needs ? { p_needs: needs } : { p_shared: shared }),
264
327
  p_places: places,
265
328
  p_status: pending ? "pending" : "confirmed",
266
329
  p_name: customer.name,
@@ -293,20 +356,27 @@ export function createBookings(opts) {
293
356
  },
294
357
  async move(token, startAt) {
295
358
  const b = await open(token);
359
+ if (b.session || b.series)
360
+ throw new BookingsError("bad_input", "a booking on a session moves to another session: use moveToSession()");
296
361
  const start = instant(startAt, "start");
297
362
  const at = now();
298
363
  if (start.getTime() === Date.parse(b.starts_at))
299
364
  return b;
300
- if (!offered(config, b.service, start, at, await settings(b.account)))
365
+ const { svc, end, blockEnd, capacity } = times(b.service, start);
366
+ const set = await settings(b.account);
367
+ // The person the customer has stays theirs when the service lets customers choose; rooms and things are picked again.
368
+ const kept = chooseGroup(svc)?.any.find((r) => b.resources.includes(r));
369
+ const needs = svc.needs ? candidates(config, b.service, start.getTime(), end.getTime(), { ...(set.resources ? { resources: set.resources } : {}), ...(kept !== undefined ? { with: kept } : {}) }) : null;
370
+ if (!offered(config, b.service, start, at, { ...set, ...(kept !== undefined ? { with: kept } : {}) }) || (svc.needs && !needs)) {
301
371
  throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
302
- const { end, blockEnd, capacity } = times(b.service, start);
303
- const r = await call(db, "move", "bookings_move", {
372
+ }
373
+ const r = await call(db, "move", needs ? "bookings_retime" : "bookings_move", {
304
374
  p_id: b.id,
305
375
  p_start: start.toISOString(),
306
376
  p_end: end.toISOString(),
307
377
  p_block_end: blockEnd.toISOString(),
308
378
  p_capacity: capacity,
309
- p_shared: shared,
379
+ ...(needs ? { p_needs: needs } : { p_shared: shared }),
310
380
  p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
311
381
  p_now: at.toISOString(),
312
382
  });
@@ -396,12 +466,21 @@ export function createBookings(opts) {
396
466
  })) ?? [];
397
467
  const biz = await business(account);
398
468
  const names = config.feed?.names ?? false;
399
- return feedIcs(biz.name, rows.map(norm), (b) => `${b.status === "pending" ? "? " : ""}${titleOf(b.service)}${names ? ` · ${b.customer.name}` : ""}`, at);
469
+ // A session is one event with how many are booked, not an event for each person on it.
470
+ const dated = bySession
471
+ ? ((await call(db, "feed", "bookings_sessions_list", { p_account: account, p_from: new Date(at.getTime() - 30 * DAY_MS).toISOString(), p_to: new Date(at.getTime() + 366 * DAY_MS).toISOString(), p_service: null, p_series: null, p_all: false, p_now: at.toISOString() })) ?? []).map(sessionOf)
472
+ : [];
473
+ const counts = new Map(dated.map((s) => [s.id, `${titleOf(s.service)} (${s.taken}/${s.capacity})`]));
474
+ const events = [
475
+ ...rows.map(norm).filter((b) => !b.session && !b.series),
476
+ ...dated.map((s) => ({ id: s.id, account, service: s.service, starts_at: s.starts_at, ends_at: s.ends_at, status: "confirmed", places: 1, resources: [], customer: { name: "", email: "" }, session: null, series: null, member: null, sequence: s.sequence, reason: null, created_at: s.starts_at, updated_at: s.starts_at })),
477
+ ];
478
+ return feedIcs(biz.name, events, (b) => counts.get(b.id) ?? `${b.status === "pending" ? "? " : ""}${titleOf(b.service)}${names ? ` · ${b.customer.name}` : ""}`, at);
400
479
  },
401
480
  async tick() {
402
481
  const at = now();
403
482
  const claim = crypto.randomUUID();
404
- const out = { reminded: 0, expired: 0, emailed: 0 };
483
+ const out = { reminded: 0, expired: 0, emailed: 0, offered: 0, short: 0 };
405
484
  const rows = (await call(db, "tick", "bookings_claim", {
406
485
  p_claim: claim,
407
486
  p_now: at.toISOString(),
@@ -437,6 +516,9 @@ export function createBookings(opts) {
437
516
  if (await call(db, "tick", "bookings_reminded", { p_id: b.id, p_claim: claim, p_sent: sent + 1, p_next: next?.toISOString() ?? null, p_now: at.toISOString() }))
438
517
  out.reminded++;
439
518
  }
519
+ // The waiting list and the minimum check, only where a service is booked by sessions (their tables come with the third migration).
520
+ if (bySession)
521
+ await sessions.tick(out, at);
440
522
  return out;
441
523
  },
442
524
  async cleanup() {
package/dist/cli.js CHANGED
@@ -10,12 +10,14 @@
10
10
  //
11
11
  // `npx workbench-bookings migration [dir]` writes bookingsMigration into
12
12
  // supabase/migrations/<timestamp>_workbench_bookings.sql, and its down file
13
- // into supabase/rollback/, unless a bookings migration is already there.
13
+ // into supabase/rollback/, and the same for each later bookings migration
14
+ // (bookingsMigrations) the project doesn't have yet. Run it again after
15
+ // updating the package.
14
16
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
15
17
  import { dirname, join, resolve } from "node:path";
16
18
  import { fileURLToPath } from "node:url";
17
19
  import { bookingProblems } from "./config.js";
18
- import { bookingsMigration } from "./migration.js";
20
+ import { bookingsMigrations } from "./migration.js";
19
21
  import { STARTER_BOOKINGS } from "./starters.js";
20
22
  const USAGE = "usage: workbench-bookings init [dir]\n workbench-bookings generate [--check] [dir]\n workbench-bookings migration [dir]";
21
23
  export const BOOKINGS_FILE = "workbench/bookings.json";
@@ -79,16 +81,22 @@ export function run(argv, log = console.log, err = console.error) {
79
81
  }
80
82
  if (command === "migration") {
81
83
  const folder = join(dir, "supabase/migrations");
82
- if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_bookings.sql"))) {
83
- log("supabase/migrations already has the bookings migration; nothing written");
84
+ const have = existsSync(folder) ? readdirSync(folder) : [];
85
+ const missing = bookingsMigrations.filter((m) => !have.some((f) => f.endsWith(`_${m.name}.sql`)));
86
+ if (!missing.length) {
87
+ log("supabase/migrations already has every bookings migration; nothing written");
84
88
  return 0;
85
89
  }
86
- const name = `${migrationStamp(new Date())}_workbench_bookings.sql`;
87
90
  mkdirSync(folder, { recursive: true });
88
91
  mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
89
- writeFileSync(join(folder, name), `-- workbench-bookings: bookings calendar (docs/capabilities/13-bookings.md)\n${bookingsMigration.up}`);
90
- writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${bookingsMigration.down}`);
91
- log(`wrote supabase/migrations/${name} and its down file`);
92
+ const at = Date.now();
93
+ missing.forEach((m, i) => {
94
+ // A second apart, so they apply in order.
95
+ const name = `${migrationStamp(new Date(at + i * 1000))}_${m.name}.sql`;
96
+ writeFileSync(join(folder, name), `-- workbench-bookings: ${m.about}\n${m.up}`);
97
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${m.down}`);
98
+ log(`wrote supabase/migrations/${name} and its down file`);
99
+ });
92
100
  return 0;
93
101
  }
94
102
  const config = readBookings(dir);
package/dist/config.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { type BookingConfig, type BookingService, type WeekHours } from "./types.ts";
2
+ /** The most groups a service can need, and the most resources in one. */
3
+ export declare const MAX_NEEDS = 3;
2
4
  /** The most reminders a booking can have. */
3
5
  export declare const MAX_REMINDERS = 3;
4
6
  /** Every problem with a bookings.json, or none. */