@mccaskie-labs/workbench-bookings 0.1.0 → 0.2.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,11 @@
1
1
  # @mccaskie-labs/workbench-bookings
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Bookings 0.2.0: places per booking (a service's `places`, 1 to its capacity), signed-in members (book() takes the app's member id; `mine()`, `cancelAsMember()` and `renderMyBookings` give a My bookings page), files attached to the confirmation (the `attachments` option, for a tax invoice), and `cancel_until: "0m"` for cancelling up to the start. The manifest asks `bookings.places` and `bookings.members`. 0.1.0 was never published, so its migration is replaced, not added to.
8
+
3
9
  ## 0.1.0
4
10
 
5
11
  - First version (`docs/capabilities/13-bookings.md`): a bookings calendar over the app's own database. `workbench/bookings.json` (opening hours, closed days, services with their length, buffer, places and start times, notice, how far ahead, instant or owner-approved, reminders, the change cut-off, what the form asks) is checked by `checkBookingConfig` and `npx workbench-bookings generate`, with `init` (an Australian starter: weekdays 9 to 5 in Sydney) and `migration`. `openSlots` gives the free times as a pure function, across daylight saving. `createBookings` with `bookingsMigration` (service role only): `slots()`, `book()` (under the account's lock, so two people never take the last place; refused with `not_allowed` when the plan lacks `bookings`, `too_many` past three upcoming bookings an email address), the customer's `cancel()` and `move()` from a manage link whose secret is kept only as a SHA-256, the owner's `approve()`, `decline()`, `cancelByOwner()` and `list()`, a calendar feed (`feedToken()`, `feed()`, no customer names unless asked) and each booking's calendar file (`icsFor()`). Emails through workbench-email: a confirmation with the calendar file, a request received, confirmed, declined, moved and cancelled, and the owner's new booking, request, move and cancellation. `tick()` from the cron every 15 minutes sends each reminder once even when runs overlap, and declines requests nobody answered within `hold`; `cleanup()` deletes bookings 180 days after they end. Pages as plain HTML (`renderSlotPicker`, `renderBookingForm`, `renderBookingDone`, `renderBookingManage`, `renderBookingList`, with `bookingAction` and `ownerBookingAction`), `wb-booking-*` classes with `BOOKING_STYLES`, and words in Australian English under `ui.wbbooking.*`. No AI.
package/README.md CHANGED
@@ -38,17 +38,19 @@ await bookings.cancel(token) // or move
38
38
  ctx.waitUntil(bookings.tick())
39
39
  ```
40
40
 
41
- - `book()` takes the account's lock and counts what overlaps (with each service's `buffer`), so two people never get the last place; a service with `capacity` fills place by place. In a `shared` diary (the default) any booking blocks every other service; `per_service` gives each its own.
41
+ - `book()` takes the account's lock and counts what overlaps (with each service's `buffer`), so two people never get the last place; a service with `capacity` fills place by place, and with `places` one booking can take several (a member and friends). In a `shared` diary (the default) any booking blocks every other service; `per_service` gives each its own.
42
42
  - `confirm: "owner_approves"` makes each booking a request that holds its time until the owner accepts or declines it; one nobody answers in `hold` (2 days) is declined by `tick()`.
43
43
  - The manage `token` is the only way to the customer's booking: only its SHA-256 is stored. Put it in the link, never in a log.
44
44
  - Emails: the customer's confirmation (with `booking.ics`), request received, confirmed, declined, moved, cancelled and reminders; the owner's new booking, request, move and cancellation (`owner_email: "none"` turns those off). A failed email never undoes a booking (`onEmailError`); each has an Idempotency-Key, so a retried reminder goes once.
45
45
  - The owner's calendar feed: `feedToken(account)` makes a secret (a new one retires the old), and `feed(token)` answers the `.ics` for a GET route. It names the service only unless `feed.names` is true.
46
+ - Members: when customers sign in to book, pass the signed-in member's id from the app's own session (`bookingAction(bookings, fields, { account, member: session.userId })`, or `book({ ..., member })`), never from the form. `mine(account, member)` lists their bookings for a My bookings page (`renderMyBookings`), and `cancelAsMember(id, account, member)` cancels one of theirs until `cancel_until` (`"0m"`: up to the start). The emailed link keeps working.
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`.
46
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.
47
49
 
48
50
  ## The pages
49
51
 
50
52
  ```ts
51
- import { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderSlotPicker } from '@mccaskie-labs/workbench-bookings'
53
+ import { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker } from '@mccaskie-labs/workbench-bookings'
52
54
 
53
55
  const tz = BOOKING_CONFIG.time_zone
54
56
  renderSlotPicker(days, { endpoint: '/book/details', service: 'appointment', title: 'Appointment', timeZone: tz, more: '/book?from=2026-12-07' })
@@ -59,10 +61,12 @@ renderBookingManage(booking, { endpoint: '/book', token, title, timeZone: tz, ch
59
61
  // Behind the owner's sign-in:
60
62
  renderBookingList(await bookings.list(account), { endpoint: '/app/bookings', timeZone: tz, titleOf: (s) => BOOKING_CONFIG.services[s].title })
61
63
  await ownerBookingAction(bookings, fields, account) // approve, decline or cancel
64
+ // A signed-in member's own bookings (bookingAction's cancel takes the booking's id when ctx.member is set):
65
+ renderMyBookings(await bookings.mine(account, member), { endpoint: '/me/bookings', timeZone: tz, titleOf, changeable: bookings.changeable, book: '/book' })
62
66
  ```
63
67
 
64
68
  Every element carries a `wb-booking-*` class with a default style (`BOOKING_STYLES`, written by `npx workbench-ui styles`). Words are in `BOOKING_WORDS` (Australian English) under `ui.wbbooking.*`; pass the project's `t` for other languages, and `locale` for dates (default `en-AU`).
65
69
 
66
70
  ## Data
67
71
 
68
- `bookings` (service, times, status, 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.
72
+ `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.
@@ -75,6 +75,12 @@ export interface BookingsOptions {
75
75
  locale?: string;
76
76
  /** The project's strings lookup, for the emails' words. */
77
77
  t?: Words;
78
+ /** Files to attach to the customer's confirmation (booked or confirmed), besides the calendar file: a tax invoice from workbench-pdf. A failure here sends the email without them and is reported. */
79
+ attachments?: (b: Booking) => Promise<readonly {
80
+ filename: string;
81
+ mimeType: string;
82
+ bytes: Uint8Array;
83
+ }[]>;
78
84
  /** An email that failed: the booking stands. Default: console.error with no address in it. */
79
85
  onEmailError?: (error: unknown, what: string) => void;
80
86
  /** How many bookings one tick handles at most. Default 200. */
@@ -88,6 +94,10 @@ export interface BookRequest {
88
94
  /** A slot's start, as slots() gave it. */
89
95
  start: string | Date;
90
96
  customer: Customer;
97
+ /** How many places, 1 to the service's places. Default 1. */
98
+ places?: number;
99
+ /** The signed-in member's id from the app's own sign-in, when they're signed in. Never from the form. */
100
+ member?: string;
91
101
  }
92
102
  export interface Bookings {
93
103
  /** The free times for a service, day by day, from `from` (default today) for `days` (default 7). */
@@ -116,6 +126,12 @@ export interface Bookings {
116
126
  decline(id: string, account: string, reason?: string): Promise<Booking>;
117
127
  /** The owner cancels a booking. */
118
128
  cancelByOwner(id: string, account: string, reason?: string): Promise<Booking>;
129
+ /** A signed-in member's bookings that haven't ended (with `past`, from 30 days back), every status, earliest first. */
130
+ mine(account: string, member: string, opts?: {
131
+ past?: boolean;
132
+ }): Promise<Booking[]>;
133
+ /** A signed-in member cancels one of their own bookings (until cancel_until). Ask the app's sign-in for a fresh code first when the project wants it. */
134
+ cancelAsMember(id: string, account: string, member: string): Promise<Booking>;
119
135
  /** The account's bookings from `from` (default today) for `days` (default 14), every status unless open. */
120
136
  list(account: string, opts?: {
121
137
  from?: string;
package/dist/bookings.js CHANGED
@@ -47,7 +47,7 @@ function instant(v, what) {
47
47
  const iso = (v) => new Date(v).toISOString();
48
48
  /** A row with its times as ISO 8601 in UTC (Postgres writes +00:00). */
49
49
  function norm(b) {
50
- return { ...b, starts_at: iso(b.starts_at), ends_at: iso(b.ends_at), created_at: iso(b.created_at), updated_at: iso(b.updated_at) };
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
51
  }
52
52
  /** The customer's details from the booking form, checked against what bookings.json asks. */
53
53
  export function customerOf(v, ask = {}) {
@@ -102,7 +102,7 @@ export function createBookings(opts) {
102
102
  function times(service, start) {
103
103
  const svc = serviceOf(config, service);
104
104
  const end = new Date(start.getTime() + svc.minutes * 60_000);
105
- return { svc, end, blockEnd: new Date(end.getTime() + (svc.buffer ?? 0) * 60_000), capacity: svc.capacity ?? 1 };
105
+ return { svc, end, blockEnd: new Date(end.getTime() + (svc.buffer ?? 0) * 60_000), capacity: svc.capacity ?? 1, maxPlaces: svc.places ?? 1 };
106
106
  }
107
107
  async function ics(b, biz) {
108
108
  const info = biz ?? (await business(b.account));
@@ -112,23 +112,33 @@ export function createBookings(opts) {
112
112
  if (!opts.mailer)
113
113
  return 0;
114
114
  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 };
115
+ const p = { service: titleOf(b.service), business: biz.name, when: whenText(b.starts_at, tz, locale), name: b.customer.name, places: b.places };
116
116
  const manage = token && opts.links?.manage && b.status !== "cancelled" && b.status !== "declined" ? opts.links.manage(token) : undefined;
117
117
  const withFile = b.status === "confirmed" || kind === "cancelled";
118
118
  const body = [
119
119
  say("email.hello", p),
120
120
  "",
121
121
  say(`email.${kind}.body`, p),
122
+ ...(b.places > 1 ? [say("email.places", p)] : []),
122
123
  ...(manage ? ["", say("email.manage", { url: manage })] : []),
123
124
  ...(b.status === "confirmed" ? ["", say("email.calendar")] : []),
124
125
  ].join("\n");
126
+ const files = withFile ? [{ filename: "booking.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(await ics(b, biz)) }] : [];
127
+ if (opts.attachments && b.status === "confirmed" && (kind === "booked" || kind === "confirmed")) {
128
+ try {
129
+ files.push(...(await opts.attachments(b)));
130
+ }
131
+ catch (e) {
132
+ report(e, "attachment");
133
+ }
134
+ }
125
135
  await opts.mailer.send({
126
136
  to: b.customer.email,
127
137
  subject: say(`email.${kind}.subject`, p),
128
138
  text: body,
129
139
  template: `bookings.${kind}`,
130
140
  ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
131
- ...(withFile ? { attachments: [{ filename: "booking.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(await ics(b, biz)) }] } : {}),
141
+ ...(files.length ? { attachments: files } : {}),
132
142
  idempotencyKey: await mailKey(`${kind}:${b.id}:${b.sequence}:${n}`, b.customer.email),
133
143
  });
134
144
  return 1;
@@ -137,9 +147,9 @@ export function createBookings(opts) {
137
147
  if (!opts.mailer || !opts.owners || (config.owner_email ?? "each") === "none")
138
148
  return 0;
139
149
  const owners = await opts.owners(b.account);
140
- const p = { service: titleOf(b.service), when: whenText(b.starts_at, tz, locale), name: b.customer.name, email: b.customer.email };
150
+ const p = { service: titleOf(b.service), when: whenText(b.starts_at, tz, locale), name: b.customer.name, email: b.customer.email, places: b.places };
141
151
  const url = opts.links?.bookings?.(b.account);
142
- const body = [say("email.owner.body", p), ...(url ? ["", say("email.owner.open", { url })] : []), "", say("email.owner.footer")].join("\n");
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");
143
153
  let sent = 0;
144
154
  for (const o of owners) {
145
155
  if (!o || typeof o.email !== "string" || !o.email.includes("@"))
@@ -225,8 +235,12 @@ export function createBookings(opts) {
225
235
  throw new BookingsError("bad_input", "book takes { account, service, start, customer }");
226
236
  const account = text(req.account, "account", 200);
227
237
  const start = instant(req.start, "start");
228
- const { end, blockEnd, capacity } = times(req.service, start);
238
+ const { end, blockEnd, capacity, maxPlaces } = times(req.service, start);
229
239
  const customer = customerOf(req.customer, config.ask);
240
+ const places = req.places ?? 1;
241
+ if (!Number.isInteger(places) || places < 1 || places > maxPlaces)
242
+ throw new BookingsError("bad_input", `places: a whole number from 1 to ${maxPlaces}`);
243
+ const member = req.member === undefined || req.member === null ? null : text(req.member, "member", 200);
230
244
  const at = now();
231
245
  if (opts.plans) {
232
246
  const can = await opts.plans.can(account, feature);
@@ -247,11 +261,13 @@ export function createBookings(opts) {
247
261
  p_block_end: blockEnd.toISOString(),
248
262
  p_capacity: capacity,
249
263
  p_shared: shared,
264
+ p_places: places,
250
265
  p_status: pending ? "pending" : "confirmed",
251
266
  p_name: customer.name,
252
267
  p_email: customer.email,
253
268
  p_phone: customer.phone ?? null,
254
269
  p_note: customer.note ?? null,
270
+ p_member: member,
255
271
  p_hash: await sha256(token),
256
272
  p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
257
273
  p_hold_until: pending ? hold.toISOString() : null,
@@ -321,6 +337,24 @@ export function createBookings(opts) {
321
337
  await quietly("cancellation", () => mailCustomer("cancelled", done));
322
338
  return done;
323
339
  },
340
+ async mine(account, member, o = {}) {
341
+ const a = text(account, "account", 200);
342
+ const m = text(member, "member", 200);
343
+ const from = o.past ? new Date(now().getTime() - 30 * DAY_MS) : now();
344
+ return ((await call(db, "mine", "bookings_mine", { p_account: a, p_member: m, p_from: from.toISOString() })) ?? []).map(norm);
345
+ },
346
+ async cancelAsMember(id, account, member) {
347
+ const m = text(member, "member", 200);
348
+ const b = await owned(id, account, ["pending", "confirmed"]);
349
+ if (b.member !== m)
350
+ throw new BookingsError("unknown_booking", "no such booking, or it has ended");
351
+ if (!changeable(b))
352
+ throw new BookingsError("too_late", `it starts within ${config.cancel_until ?? "24h"}: too late to change online`);
353
+ const done = await setStatus(b, "cancelled", ["pending", "confirmed"], "by_customer");
354
+ await quietly("cancellation", () => mailCustomer("cancelled", done));
355
+ await quietly("owner's cancellation", () => mailOwners("cancelled", done));
356
+ return done;
357
+ },
324
358
  async list(account, o = {}) {
325
359
  text(account, "account", 200);
326
360
  const from = o.from ?? todayIn(tz, now());
package/dist/cli.js CHANGED
File without changes
package/dist/config.js CHANGED
@@ -26,7 +26,7 @@ const TOP = [
26
26
  "retention_days",
27
27
  "plans",
28
28
  ];
29
- const SERVICE = ["title", "minutes", "buffer", "capacity", "every", "hours"];
29
+ const SERVICE = ["title", "minutes", "buffer", "capacity", "places", "every", "hours"];
30
30
  const THIRTY_DAYS = 30 * 1440;
31
31
  /** The most reminders a booking can have. */
32
32
  export const MAX_REMINDERS = 3;
@@ -57,11 +57,11 @@ function hoursProblems(v, at) {
57
57
  }
58
58
  return p;
59
59
  }
60
- function durationProblem(v, at, max, example) {
60
+ function durationProblem(v, at, max, example, zero = false) {
61
61
  if (v === undefined)
62
62
  return [];
63
63
  const m = durationMinutes(v);
64
- return m === null || m > max ? [`${at} must be a length such as ${example} (up to ${Math.round(max / 1440)} days)`] : [];
64
+ return m === null || m > max || (m === 0 && !zero) ? [`${at} must be a length such as ${example} (up to ${Math.round(max / 1440)} days)`] : [];
65
65
  }
66
66
  /** Every problem with a bookings.json, or none. */
67
67
  export function bookingProblems(value, where = "bookings.json") {
@@ -101,6 +101,8 @@ export function bookingProblems(value, where = "bookings.json") {
101
101
  p.push(`${at}.buffer must be a whole number of minutes from 0 to 240`);
102
102
  if (s.capacity !== undefined && !whole(s.capacity, 1, 100))
103
103
  p.push(`${at}.capacity must be a whole number from 1 to 100`);
104
+ if (s.places !== undefined && !whole(s.places, 1, typeof s.capacity === "number" ? s.capacity : 1))
105
+ p.push(`${at}.places must be a whole number from 1 to the service's capacity`);
104
106
  if (s.every !== undefined && !whole(s.every, 5, 720))
105
107
  p.push(`${at}.every must be a whole number of minutes from 5 to 720`);
106
108
  if (s.hours !== undefined)
@@ -109,7 +111,7 @@ export function bookingProblems(value, where = "bookings.json") {
109
111
  }
110
112
  if (value.calendar !== undefined && value.calendar !== "shared" && value.calendar !== "per_service")
111
113
  p.push("calendar must be shared or per_service");
112
- p.push(...durationProblem(value.notice, "notice", THIRTY_DAYS, "2h"));
114
+ p.push(...durationProblem(value.notice, "notice", THIRTY_DAYS, "2h", true));
113
115
  if (value.ahead_days !== undefined && !whole(value.ahead_days, 1, 365))
114
116
  p.push("ahead_days must be a whole number from 1 to 365");
115
117
  if (value.confirm !== undefined && value.confirm !== "instant" && value.confirm !== "owner_approves")
@@ -117,13 +119,13 @@ export function bookingProblems(value, where = "bookings.json") {
117
119
  p.push(...durationProblem(value.hold, "hold", 7 * 1440, "2d"));
118
120
  if (value.reminders !== undefined) {
119
121
  const r = value.reminders;
120
- if (!Array.isArray(r) || r.length > MAX_REMINDERS || r.some((d) => durationMinutes(d) === null || durationMinutes(d) > 14 * 1440)) {
122
+ if (!Array.isArray(r) || r.length > MAX_REMINDERS || r.some((d) => !durationMinutes(d) || durationMinutes(d) > 14 * 1440)) {
121
123
  p.push(`reminders must be a list of up to ${MAX_REMINDERS} lengths before the start, such as ["1d", "2h"] ([] for none)`);
122
124
  }
123
125
  else if (new Set(r.map((d) => durationMinutes(d))).size !== r.length)
124
126
  p.push("reminders: two reminders at the same time");
125
127
  }
126
- p.push(...durationProblem(value.cancel_until, "cancel_until", 14 * 1440, "24h"));
128
+ p.push(...durationProblem(value.cancel_until, "cancel_until", 14 * 1440, "24h", true));
127
129
  if (value.ask !== undefined) {
128
130
  const a = value.ask;
129
131
  if (!isObj(a) ||
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { openSlots, offered, type SlotQuery } from "./slots.ts";
4
4
  export { bookingIcs, feedIcs, type EventText } from "./ical.ts";
5
5
  export { bookingsMigration } from "./migration.ts";
6
6
  export { STARTER_BOOKINGS } from "./starters.ts";
7
- export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderSlotPicker, type ActionResult, type DoneOptions, type FormField, type FormOptions, type ListOptions, type ManageOptions, type PickerOptions, } from "./ui.ts";
7
+ export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, type ActionResult, type DoneOptions, type FormField, type FormOptions, type ListOptions, type ManageOptions, type MineOptions, type PickerOptions, } from "./ui.ts";
8
8
  export { whenText, type Words } from "./format.ts";
9
9
  export { BOOKING_WORDS, BOOKING_WORD_KEYS, type BookingWordKey } from "./words.ts";
10
10
  export { BOOKING_STYLES } from "./styles.ts";
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { openSlots, offered } from "./slots.js";
12
12
  export { bookingIcs, feedIcs } from "./ical.js";
13
13
  export { bookingsMigration } from "./migration.js";
14
14
  export { STARTER_BOOKINGS } from "./starters.js";
15
- export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderSlotPicker, } from "./ui.js";
15
+ export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, } from "./ui.js";
16
16
  export { whenText } from "./format.js";
17
17
  export { BOOKING_WORDS, BOOKING_WORD_KEYS } from "./words.js";
18
18
  export { BOOKING_STYLES } from "./styles.js";
package/dist/migration.js CHANGED
@@ -4,7 +4,8 @@
4
4
  //
5
5
  // Only the service role reaches them: the app's public booking pages call
6
6
  // slots(), book(), cancel() and move() server side (a customer is known by
7
- // the secret in their manage link, never by a sign-in), and the owner's pages
7
+ // the secret in their manage link, or by the member id the app passes for a
8
+ // signed-in member, never by a sign-in of the package's own), and the owner's pages
8
9
  // call list(), approve(), decline() and cancelByOwner() behind the app's own
9
10
  // sign-in, checking the account themselves. So the tables have RLS on with no
10
11
  // policies and the functions are granted to service_role only.
@@ -33,10 +34,12 @@ export const bookingsMigration = {
33
34
  ends_at timestamptz not null,
34
35
  block_end timestamptz not null,
35
36
  status text not null check (status in ('pending', 'confirmed', 'cancelled', 'declined')),
37
+ places smallint not null default 1 check (places between 1 and 100),
36
38
  customer_name text not null check (char_length(customer_name) between 1 and 100),
37
39
  customer_email text not null check (char_length(customer_email) between 3 and 254),
38
40
  customer_phone text check (char_length(customer_phone) <= 40),
39
41
  note text check (char_length(note) <= 1000),
42
+ member text check (char_length(member) between 1 and 200),
40
43
  token_hash text not null unique check (token_hash ~ '^[0-9a-f]{64}$'),
41
44
  sequence integer not null default 0 check (sequence >= 0),
42
45
  reason text check (char_length(reason) <= 200),
@@ -51,10 +54,11 @@ export const bookingsMigration = {
51
54
  check (status = 'pending' or hold_until is null)
52
55
  );
53
56
 
54
- comment on table public.bookings is 'Bookings customers made on the app''s booking page (workbench-bookings): service, times, status, and the customer''s name, email, optional phone and optional note as they typed them. Deleted retention_days (default 180) after the booking ends. Service role only.';
57
+ comment on table public.bookings is 'Bookings customers made on the app''s booking page (workbench-bookings): service, times, status, and the customer''s name, email, optional phone and optional note as they typed them, and the signed-in member''s id when the app passed one. Deleted retention_days (default 180) after the booking ends. Service role only.';
55
58
 
56
59
  create index bookings_account_time on public.bookings (account, starts_at) where status in ('pending', 'confirmed');
57
60
  create index bookings_account_all on public.bookings (account, starts_at);
61
+ create index bookings_member on public.bookings (account, member, starts_at) where member is not null;
58
62
  create index bookings_customer on public.bookings (account, lower(customer_email)) where status in ('pending', 'confirmed');
59
63
  create index bookings_reminders on public.bookings (next_reminder_at) where status = 'confirmed' and next_reminder_at is not null;
60
64
  create index bookings_holds on public.bookings (hold_until) where status = 'pending';
@@ -82,21 +86,21 @@ security invoker
82
86
  set search_path = ''
83
87
  as $$
84
88
  select jsonb_build_object('id', b.id, 'account', b.account, 'service', b.service, 'starts_at', b.starts_at, 'ends_at', b.ends_at,
85
- 'status', b.status, 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone, 'note', b.note),
89
+ 'status', b.status, 'places', b.places, 'member', b.member, 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone, 'note', b.note),
86
90
  'sequence', b.sequence, 'reason', b.reason, 'created_at', b.created_at, 'updated_at', b.updated_at);
87
91
  $$;
88
92
 
89
- -- Whether a booking of p_service from p_start to p_block_end clashes with
90
- -- what already holds time: p_capacity of the same service, or (p_shared) any
91
- -- other service. p_except leaves out the booking being moved.
92
- create function public.bookings_clash(p_account text, p_service text, p_start timestamptz, p_block_end timestamptz, p_capacity integer, p_shared boolean, p_except uuid)
93
+ -- Whether p_places of p_service from p_start to p_block_end clash with what
94
+ -- already holds time: more than p_capacity places of the same service, or
95
+ -- (p_shared) any other service. p_except leaves out the booking being moved.
96
+ create function public.bookings_clash(p_account text, p_service text, p_start timestamptz, p_block_end timestamptz, p_capacity integer, p_shared boolean, p_places integer, p_except uuid)
93
97
  returns boolean
94
98
  language sql
95
99
  stable
96
100
  security invoker
97
101
  set search_path = ''
98
102
  as $$
99
- select coalesce(count(*) filter (where b.service = p_service) >= p_capacity or (p_shared and bool_or(b.service <> p_service)), false)
103
+ select coalesce(sum(b.places) filter (where b.service = p_service), 0) + p_places > p_capacity or (p_shared and coalesce(bool_or(b.service <> p_service), false))
100
104
  from public.bookings b
101
105
  where b.account = p_account and b.status in ('pending', 'confirmed') and b.id is distinct from p_except
102
106
  and b.starts_at < p_block_end and b.block_end > p_start;
@@ -104,8 +108,8 @@ $$;
104
108
 
105
109
  -- Books a time if it is still free, under the account's lock. Answers the
106
110
  -- booking, or { "refused": "taken" | "too_many" }.
107
- create function public.bookings_book(p_account text, p_service text, p_start timestamptz, p_end timestamptz, p_block_end timestamptz, p_capacity integer, p_shared boolean,
108
- p_status text, p_name text, p_email text, p_phone text, p_note text, p_hash text, p_next_reminder timestamptz, p_hold_until timestamptz, p_max integer, p_now timestamptz)
111
+ create function public.bookings_book(p_account text, p_service text, p_start timestamptz, p_end timestamptz, p_block_end timestamptz, p_capacity integer, p_shared boolean, p_places integer,
112
+ p_status text, p_name text, p_email text, p_phone text, p_note text, p_member text, p_hash text, p_next_reminder timestamptz, p_hold_until timestamptz, p_max integer, p_now timestamptz)
109
113
  returns jsonb
110
114
  language plpgsql
111
115
  security invoker
@@ -117,17 +121,20 @@ begin
117
121
  if p_status not in ('pending', 'confirmed') then
118
122
  raise exception using errcode = '22023', message = 'bookings: a new booking is pending or confirmed';
119
123
  end if;
124
+ if p_places is null or p_places < 1 or p_places > p_capacity then
125
+ raise exception using errcode = '22023', message = 'bookings: places is 1 to the capacity';
126
+ end if;
120
127
  perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
121
128
  if (select count(*) from public.bookings
122
129
  where account = p_account and lower(customer_email) = lower(p_email) and status in ('pending', 'confirmed') and ends_at > p_now) >= p_max then
123
130
  return jsonb_build_object('refused', 'too_many');
124
131
  end if;
125
- if public.bookings_clash(p_account, p_service, p_start, p_block_end, p_capacity, p_shared, null) then
132
+ if public.bookings_clash(p_account, p_service, p_start, p_block_end, p_capacity, p_shared, p_places, null) then
126
133
  return jsonb_build_object('refused', 'taken');
127
134
  end if;
128
- insert into public.bookings (account, service, starts_at, ends_at, block_end, status, customer_name, customer_email, customer_phone, note, token_hash,
135
+ insert into public.bookings (account, service, starts_at, ends_at, block_end, status, places, customer_name, customer_email, customer_phone, note, member, token_hash,
129
136
  next_reminder_at, hold_until, created_at, updated_at)
130
- values (p_account, p_service, p_start, p_end, p_block_end, p_status, p_name, p_email, p_phone, p_note, p_hash,
137
+ values (p_account, p_service, p_start, p_end, p_block_end, p_status, p_places, p_name, p_email, p_phone, p_note, p_member, p_hash,
131
138
  case when p_status = 'confirmed' then p_next_reminder end, case when p_status = 'pending' then p_hold_until end, p_now, p_now)
132
139
  returning * into b;
133
140
  return public.bookings_row(b);
@@ -151,7 +158,7 @@ begin
151
158
  return null;
152
159
  end if;
153
160
  perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || b.account));
154
- if public.bookings_clash(b.account, b.service, p_start, p_block_end, p_capacity, p_shared, p_id) then
161
+ if public.bookings_clash(b.account, b.service, p_start, p_block_end, p_capacity, p_shared, b.places, p_id) then
155
162
  return jsonb_build_object('refused', 'taken');
156
163
  end if;
157
164
  update public.bookings
@@ -204,7 +211,7 @@ stable
204
211
  security invoker
205
212
  set search_path = ''
206
213
  as $$
207
- select coalesce(jsonb_agg(jsonb_build_object('service', b.service, 'starts_at', b.starts_at, 'block_end', b.block_end) order by b.starts_at), '[]'::jsonb)
214
+ select coalesce(jsonb_agg(jsonb_build_object('service', b.service, 'starts_at', b.starts_at, 'block_end', b.block_end, 'places', b.places) order by b.starts_at), '[]'::jsonb)
208
215
  from public.bookings b
209
216
  where b.account = p_account and b.status in ('pending', 'confirmed') and b.starts_at < p_to and b.block_end > p_from;
210
217
  $$;
@@ -244,6 +251,21 @@ as $$
244
251
  order by starts_at, id limit 1000) b;
245
252
  $$;
246
253
 
254
+ -- A signed-in member's bookings that end after p_from, every status, earliest
255
+ -- first. At most 100.
256
+ create function public.bookings_mine(p_account text, p_member text, p_from timestamptz)
257
+ returns jsonb
258
+ language sql
259
+ stable
260
+ security invoker
261
+ set search_path = ''
262
+ as $$
263
+ select coalesce(jsonb_agg(public.bookings_row(b) order by b.starts_at, b.id), '[]'::jsonb)
264
+ from (select * from public.bookings
265
+ where account = p_account and member = p_member and ends_at > p_from
266
+ order by starts_at, id limit 100) b;
267
+ $$;
268
+
247
269
  -- The cron's scan: claims up to p_limit bookings with a reminder due or a
248
270
  -- request whose hold has run out, with a lease until p_until.
249
271
  create function public.bookings_claim(p_claim uuid, p_now timestamptz, p_until timestamptz, p_limit integer)
@@ -361,14 +383,15 @@ end;
361
383
  $$;
362
384
 
363
385
  revoke execute on function public.bookings_row(public.bookings) from public, anon, authenticated;
364
- revoke execute on function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, uuid) from public, anon, authenticated;
365
- revoke execute on function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz) from public, anon, authenticated;
386
+ revoke execute on function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, integer, uuid) from public, anon, authenticated;
387
+ revoke execute on function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, integer, text, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz) from public, anon, authenticated;
366
388
  revoke execute on function public.bookings_move(uuid, timestamptz, timestamptz, timestamptz, integer, boolean, timestamptz, timestamptz) from public, anon, authenticated;
367
389
  revoke execute on function public.bookings_set_status(uuid, text, text[], text, timestamptz, timestamptz) from public, anon, authenticated;
368
390
  revoke execute on function public.bookings_busy(text, timestamptz, timestamptz) from public, anon, authenticated;
369
391
  revoke execute on function public.bookings_get(uuid) from public, anon, authenticated;
370
392
  revoke execute on function public.bookings_by_hash(text) from public, anon, authenticated;
371
393
  revoke execute on function public.bookings_list(text, timestamptz, timestamptz, boolean) from public, anon, authenticated;
394
+ revoke execute on function public.bookings_mine(text, text, timestamptz) from public, anon, authenticated;
372
395
  revoke execute on function public.bookings_claim(uuid, timestamptz, timestamptz, integer) from public, anon, authenticated;
373
396
  revoke execute on function public.bookings_reminded(uuid, uuid, integer, timestamptz, timestamptz) from public, anon, authenticated;
374
397
  revoke execute on function public.bookings_expire(uuid, uuid, timestamptz) from public, anon, authenticated;
@@ -377,14 +400,15 @@ revoke execute on function public.bookings_feed_set(text, text, timestamptz) fro
377
400
  revoke execute on function public.bookings_feed_account(text) from public, anon, authenticated;
378
401
  revoke execute on function public.bookings_cleanup(timestamptz, integer) from public, anon, authenticated;
379
402
  grant execute on function public.bookings_row(public.bookings) to service_role;
380
- grant execute on function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, uuid) to service_role;
381
- grant execute on function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz) to service_role;
403
+ grant execute on function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, integer, uuid) to service_role;
404
+ grant execute on function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, integer, text, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz) to service_role;
382
405
  grant execute on function public.bookings_move(uuid, timestamptz, timestamptz, timestamptz, integer, boolean, timestamptz, timestamptz) to service_role;
383
406
  grant execute on function public.bookings_set_status(uuid, text, text[], text, timestamptz, timestamptz) to service_role;
384
407
  grant execute on function public.bookings_busy(text, timestamptz, timestamptz) to service_role;
385
408
  grant execute on function public.bookings_get(uuid) to service_role;
386
409
  grant execute on function public.bookings_by_hash(text) to service_role;
387
410
  grant execute on function public.bookings_list(text, timestamptz, timestamptz, boolean) to service_role;
411
+ grant execute on function public.bookings_mine(text, text, timestamptz) to service_role;
388
412
  grant execute on function public.bookings_claim(uuid, timestamptz, timestamptz, integer) to service_role;
389
413
  grant execute on function public.bookings_reminded(uuid, uuid, integer, timestamptz, timestamptz) to service_role;
390
414
  grant execute on function public.bookings_expire(uuid, uuid, timestamptz) to service_role;
@@ -401,14 +425,15 @@ drop function public.bookings_release(uuid, uuid);
401
425
  drop function public.bookings_expire(uuid, uuid, timestamptz);
402
426
  drop function public.bookings_reminded(uuid, uuid, integer, timestamptz, timestamptz);
403
427
  drop function public.bookings_claim(uuid, timestamptz, timestamptz, integer);
428
+ drop function public.bookings_mine(text, text, timestamptz);
404
429
  drop function public.bookings_list(text, timestamptz, timestamptz, boolean);
405
430
  drop function public.bookings_by_hash(text);
406
431
  drop function public.bookings_get(uuid);
407
432
  drop function public.bookings_busy(text, timestamptz, timestamptz);
408
433
  drop function public.bookings_set_status(uuid, text, text[], text, timestamptz, timestamptz);
409
434
  drop function public.bookings_move(uuid, timestamptz, timestamptz, timestamptz, integer, boolean, timestamptz, timestamptz);
410
- drop function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz);
411
- drop function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, uuid);
435
+ drop function public.bookings_book(text, text, timestamptz, timestamptz, timestamptz, integer, boolean, integer, text, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz);
436
+ drop function public.bookings_clash(text, text, timestamptz, timestamptz, integer, boolean, integer, uuid);
412
437
  drop function public.bookings_row(public.bookings);
413
438
  drop table public.booking_feeds;
414
439
  drop table public.bookings;
package/dist/slots.js CHANGED
@@ -25,7 +25,7 @@ function placesLeft(config, service, start, blockEnd, busy) {
25
25
  if (!(s < blockEnd && e > start))
26
26
  continue;
27
27
  if (b.service === service)
28
- same++;
28
+ same += b.places ?? 1;
29
29
  else if (shared)
30
30
  return 0;
31
31
  }
package/dist/styles.js CHANGED
@@ -57,6 +57,7 @@ export const BOOKING_STYLES = {
57
57
  { name: "wb-booking-field", element: "label", about: "One field with its label", css: "display:grid;gap:.35rem" },
58
58
  { name: "wb-booking-label", element: "span", about: "A field's label", css: "font-weight:600;font-size:.95rem" },
59
59
  { name: "wb-booking-input", element: "input", about: "Name, email or phone", css: field, states: [focus] },
60
+ { name: "wb-booking-select", element: "select", about: "How many places, when the service allows more than one", css: field, states: [focus] },
60
61
  { name: "wb-booking-textarea", element: "textarea", about: "The note, when asked", css: `${field};min-height:6rem;resize:vertical`, states: [focus] },
61
62
  { name: "wb-booking-error", element: "span", about: "What's wrong with a field", css: `color:${v("danger")};font-size:.9rem` },
62
63
  { name: "wb-booking-actions", element: "div", about: "A row of buttons and links", css: "display:flex;flex-wrap:wrap;gap:.75rem;align-items:center" },
@@ -73,6 +74,7 @@ export const BOOKING_STYLES = {
73
74
  { name: "wb-booking-move", element: "a", about: "Choose another time, on the customer's page", css: link, states: [focus] },
74
75
  { name: "wb-booking-locked", element: "p", about: "Too close to the start to change online", css: `margin:0;color:${v("muted")}` },
75
76
  { name: "wb-booking-list", element: "section", about: "The owner's bookings", css: box },
77
+ { name: "wb-booking-mine", element: "section", about: "A signed-in member's own bookings", css: box },
76
78
  { name: "wb-booking-items", element: "ul", about: "The bookings", css: "list-style:none;margin:0;padding:0;display:grid;gap:.75rem" },
77
79
  { name: "wb-booking-item", element: "li", about: "One booking's place in the list", css: "margin:0" },
78
80
  {
@@ -85,6 +87,7 @@ export const BOOKING_STYLES = {
85
87
  { name: "wb-booking-ended", element: "article", about: "A cancelled or declined booking (added to wb-booking)", css: `border-left-color:${v("line")};opacity:.7` },
86
88
  { name: "wb-booking-title", element: "h3", about: "The time and the service", css: "margin:0;font-size:1rem;font-weight:600" },
87
89
  { name: "wb-booking-who", element: "p", about: "The customer: name, email, phone", css: "margin:0;overflow-wrap:anywhere" },
90
+ { name: "wb-booking-places", element: "p", about: "How many places a booking takes, when more than one", css: "margin:0;font-weight:600" },
88
91
  { name: "wb-booking-note", element: "p", about: "The customer's note, when asked for", css: `margin:0;color:${v("muted")};white-space:pre-wrap;overflow-wrap:anywhere` },
89
92
  { name: "wb-booking-form", element: "form", about: "One owner button's form", css: "display:contents" },
90
93
  { name: "wb-booking-approve", element: "button", about: "Accept a request", css: main, states: [focus] },
package/dist/time.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Time in the business's time zone: opening hours on the local clock (right
2
2
  // across a daylight saving change), "today", and lengths such as "24h".
3
3
  // Plain code, no AI. The zone helpers are workbench-nudges' own.
4
- const DURATION = /^([1-9][0-9]{0,3})([mhd])$/;
4
+ const DURATION = /^(0|[1-9][0-9]{0,3})([mhd])$/;
5
5
  const CLOCK = /^([01][0-9]|2[0-3]):([0-5][0-9])$/;
6
6
  /** A duration in minutes, or null when it isn't one ("3d", "12h", "30m"). */
7
7
  export function durationMinutes(text) {
package/dist/types.d.ts CHANGED
@@ -15,6 +15,8 @@ export interface BookingService {
15
15
  buffer?: number;
16
16
  /** How many people can book the same time (a class), 1 to 100. Default 1. */
17
17
  capacity?: number;
18
+ /** The most places one booking can take (a member bringing friends), 1 to capacity. Default 1. */
19
+ places?: number;
18
20
  /** Minutes between start times, 5 to 720. Default: the service's minutes. */
19
21
  every?: number;
20
22
  /** Its own opening hours, when they differ from the business's. */
@@ -45,7 +47,7 @@ export interface BookingConfig {
45
47
  hold?: Duration;
46
48
  /** Reminder emails to the customer, each this long before the start. Up to 3. Default ["1d"]. [] for none. */
47
49
  reminders?: readonly Duration[];
48
- /** Customers can cancel or move a booking online until this long before it starts. Default 24h. */
50
+ /** Customers can cancel or move a booking online until this long before it starts ("0m": up to the start). Default 24h. */
49
51
  cancel_until?: Duration;
50
52
  /** What the booking form asks besides name and email. Default: no phone, no note. */
51
53
  ask?: {
@@ -85,7 +87,11 @@ export interface Booking {
85
87
  starts_at: string;
86
88
  ends_at: string;
87
89
  status: BookingStatus;
90
+ /** How many places it takes (1 unless the service allows more). */
91
+ places: number;
88
92
  customer: Customer;
93
+ /** The signed-in member who booked it (the app's user id), or null for a booking made without signing in. */
94
+ member: string | null;
89
95
  /** Goes up each time the booking moves or ends, for calendar apps. */
90
96
  sequence: number;
91
97
  /** Why it was cancelled or declined: by_customer, by_owner, not_answered, or the owner's words. */
@@ -113,6 +119,8 @@ export interface Busy {
113
119
  starts_at: string;
114
120
  /** The end plus the service's buffer. */
115
121
  block_end: string;
122
+ /** Places it takes. Default 1. */
123
+ places?: number;
116
124
  }
117
125
  export interface TickResult {
118
126
  reminded: number;
package/dist/ui.d.ts CHANGED
@@ -24,7 +24,7 @@ export interface PickerOptions extends Common {
24
24
  }
25
25
  /** The free times, a day at a time. Days with none are left out. */
26
26
  export declare function renderSlotPicker(days: readonly SlotDay[], o: PickerOptions): string;
27
- export type FormField = "name" | "email" | "phone" | "note";
27
+ export type FormField = "name" | "email" | "phone" | "note" | "places";
28
28
  export interface FormOptions extends Common {
29
29
  /** The project's action endpoint (POST), which hands the fields to bookingAction. */
30
30
  endpoint: string;
@@ -32,6 +32,8 @@ export interface FormOptions extends Common {
32
32
  title: string;
33
33
  /** The chosen slot's start. */
34
34
  start: string;
35
+ /** The most places to offer: the smaller of the service's places and the slot's left. Above 1 the form asks how many. */
36
+ places?: number;
35
37
  /** bookings.config.ask. */
36
38
  ask?: BookingConfig["ask"];
37
39
  /** bookings.config.confirm: owner_approves says Send request. */
@@ -78,6 +80,18 @@ export interface ListOptions extends Common {
78
80
  }
79
81
  /** The owner's bookings, earliest first, with Accept and Decline for requests and Cancel for the rest. */
80
82
  export declare function renderBookingList(bookings: readonly Booking[], o: ListOptions): string;
83
+ export interface MineOptions extends Common {
84
+ /** The project's action endpoint (POST, behind the member's sign-in), which hands the fields to bookingAction with the member. */
85
+ endpoint: string;
86
+ /** A service's title (bookings.config.services[name].title). */
87
+ titleOf: (service: string) => string;
88
+ /** bookings.changeable. */
89
+ changeable: (b: Booking) => boolean;
90
+ /** The booking page, for "Make a booking". */
91
+ book?: string;
92
+ }
93
+ /** A signed-in member's own bookings (bookings.mine), with Cancel while they still can. */
94
+ export declare function renderMyBookings(bookings: readonly Booking[], o: MineOptions): string;
81
95
  export interface ActionResult {
82
96
  status: number;
83
97
  body: {
@@ -94,14 +108,18 @@ export interface ActionResult {
94
108
  };
95
109
  }
96
110
  /**
97
- * The customer's posts, on the public booking page: `book` (service, start,
98
- * name, email and phone or note when asked; answers the booking and its
99
- * manage secret), `cancel` (token) and `move` (token, start). Put Turnstile
100
- * or the app's rate limit in front of it. `text` is the line to show the
101
- * customer when it didn't go through, and `field` the field to mark.
111
+ * The customer's posts, on the booking page: `book` (service, start, name,
112
+ * email, places when the service allows more than one, and phone or note when
113
+ * asked; answers the booking and its manage secret), `cancel` (token, or with
114
+ * a signed-in member the booking's id) and `move` (token, start). Put
115
+ * Turnstile or the app's rate limit in front of it. `member` is the signed-in
116
+ * member's id from the app's own sign-in, never from the form. `text` is the
117
+ * line to show the customer when it didn't go through, and `field` the field
118
+ * to mark.
102
119
  */
103
120
  export declare function bookingAction(bookings: Bookings, body: Record<string, unknown>, ctx: {
104
121
  account: string;
122
+ member?: string;
105
123
  t?: Words;
106
124
  }): Promise<ActionResult>;
107
125
  /**
package/dist/ui.js CHANGED
@@ -47,6 +47,9 @@ export function renderBookingForm(o) {
47
47
  input("name", say("form.name"), "text", "name", true),
48
48
  input("email", say("form.email"), "email", "email", true),
49
49
  phone === "no" ? "" : input("phone", say(phone === "required" ? "form.phone" : "form.phone_optional"), "tel", "tel", phone === "required"),
50
+ (o.places ?? 1) > 1
51
+ ? `<label class="wb-booking-field"><span class="wb-booking-label">${esc(say("form.places"))}</span><select class="wb-booking-select" name="places"${aria("places")}>${Array.from({ length: Math.min(o.places, 100) }, (_, i) => `<option value="${i + 1}"${String(i + 1) === (v.places ?? "1") ? " selected" : ""}>${i + 1}</option>`).join("")}</select>${err("places")}</label>`
52
+ : "",
50
53
  o.ask?.note
51
54
  ? `<label class="wb-booking-field"><span class="wb-booking-label">${esc(say("form.note"))}</span><textarea class="wb-booking-textarea" name="note" rows="4" maxlength="1000"${aria("note")}>${esc(v.note ?? "")}</textarea>${err("note")}</label>`
52
55
  : "",
@@ -93,10 +96,30 @@ export function renderBookingList(bookings, o) {
93
96
  : b.status === "confirmed"
94
97
  ? form(b, "cancel", "wb-booking-owner-cancel", say("list.cancel"))
95
98
  : "";
96
- return `<li class="wb-booking-item"><article class="${cls}" id="wb-booking-${esc(b.id)}"><h3 class="wb-booking-title">${esc(whenText(b.starts_at, o.timeZone, locale))} · ${esc(o.titleOf(b.service))}</h3><p class="wb-booking-who">${esc(who)}</p>${b.customer.note ? `<p class="wb-booking-note">${esc(b.customer.note)}</p>` : ""}<p class="wb-booking-status">${esc(say(`status.${b.status}`))}</p>${buttons ? `<div class="wb-booking-actions">${buttons}</div>` : ""}</article></li>`;
99
+ return `<li class="wb-booking-item"><article class="${cls}" id="wb-booking-${esc(b.id)}"><h3 class="wb-booking-title">${esc(whenText(b.starts_at, o.timeZone, locale))} · ${esc(o.titleOf(b.service))}</h3><p class="wb-booking-who">${esc(who)}</p>${b.places > 1 ? `<p class="wb-booking-places">${esc(say("list.places", { places: b.places }))}</p>` : ""}${b.customer.note ? `<p class="wb-booking-note">${esc(b.customer.note)}</p>` : ""}<p class="wb-booking-status">${esc(say(`status.${b.status}`))}</p>${buttons ? `<div class="wb-booking-actions">${buttons}</div>` : ""}</article></li>`;
97
100
  };
98
101
  return `<section class="wb-booking-list">${head}<ul class="wb-booking-items">${bookings.map(item).join("")}</ul></section>`;
99
102
  }
103
+ /** A signed-in member's own bookings (bookings.mine), with Cancel while they still can. */
104
+ export function renderMyBookings(bookings, o) {
105
+ const say = words(o.t);
106
+ const locale = o.locale ?? DEFAULT_LOCALE;
107
+ const head = `<h2 class="wb-booking-heading">${esc(say("mine.title"))}</h2>`;
108
+ const book = o.book ? `<a class="wb-booking-more" href="${esc(o.book)}">${esc(say("mine.book"))}</a>` : "";
109
+ if (bookings.length === 0)
110
+ return `<section class="wb-booking-mine">${head}<p class="wb-booking-empty">${esc(say("mine.empty"))}</p>${book}</section>`;
111
+ const item = (b) => {
112
+ const live = b.status === "pending" || b.status === "confirmed";
113
+ const cls = ["wb-booking", b.status === "pending" ? "wb-booking-pending" : "", live ? "" : "wb-booking-ended"].filter(Boolean).join(" ");
114
+ const action = !live
115
+ ? ""
116
+ : o.changeable(b)
117
+ ? `<div class="wb-booking-actions"><form class="wb-booking-cancel-form" method="post" action="${esc(o.endpoint)}">${hidden("action", "cancel")}${hidden("booking", b.id)}<button class="wb-booking-cancel" type="submit">${esc(say("mine.cancel"))}</button></form></div>`
118
+ : `<p class="wb-booking-locked">${esc(say("manage.locked"))}</p>`;
119
+ return `<li class="wb-booking-item"><article class="${cls}" id="wb-booking-${esc(b.id)}"><h3 class="wb-booking-title">${esc(whenText(b.starts_at, o.timeZone, locale))} · ${esc(o.titleOf(b.service))}</h3>${b.places > 1 ? `<p class="wb-booking-places">${esc(say("list.places", { places: b.places }))}</p>` : ""}<p class="wb-booking-status">${esc(say(`status.${b.status}`))}</p>${action}</article></li>`;
120
+ };
121
+ return `<section class="wb-booking-mine">${head}<ul class="wb-booking-items">${bookings.map(item).join("")}</ul>${book}</section>`;
122
+ }
100
123
  const STATUS = {
101
124
  bad_config: 500,
102
125
  bad_input: 400,
@@ -113,7 +136,7 @@ function failed(e, o) {
113
136
  if (!(e instanceof BookingsError))
114
137
  throw e;
115
138
  const say = words(o.t);
116
- const field = e.code === "bad_input" ? /^(name|email|phone|note):/.exec(e.message)?.[1] : undefined;
139
+ const field = e.code === "bad_input" ? /^(name|email|phone|note|places):/.exec(e.message)?.[1] : undefined;
117
140
  const text = field !== undefined
118
141
  ? say(`form.error.${field}`)
119
142
  : e.code === "taken" || e.code === "not_open" || e.code === "too_late" || e.code === "not_allowed" || e.code === "unknown_booking"
@@ -125,11 +148,14 @@ function failed(e, o) {
125
148
  }
126
149
  const str = (v) => (typeof v === "string" ? v : "");
127
150
  /**
128
- * The customer's posts, on the public booking page: `book` (service, start,
129
- * name, email and phone or note when asked; answers the booking and its
130
- * manage secret), `cancel` (token) and `move` (token, start). Put Turnstile
131
- * or the app's rate limit in front of it. `text` is the line to show the
132
- * customer when it didn't go through, and `field` the field to mark.
151
+ * The customer's posts, on the booking page: `book` (service, start, name,
152
+ * email, places when the service allows more than one, and phone or note when
153
+ * asked; answers the booking and its manage secret), `cancel` (token, or with
154
+ * a signed-in member the booking's id) and `move` (token, start). Put
155
+ * Turnstile or the app's rate limit in front of it. `member` is the signed-in
156
+ * member's id from the app's own sign-in, never from the form. `text` is the
157
+ * line to show the customer when it didn't go through, and `field` the field
158
+ * to mark.
133
159
  */
134
160
  export async function bookingAction(bookings, body, ctx) {
135
161
  const max = bookings.config.max_per_customer ?? 3;
@@ -141,9 +167,13 @@ export async function bookingAction(bookings, body, ctx) {
141
167
  service: str(body.service),
142
168
  start: str(body.start),
143
169
  customer: { name: str(body.name), email: str(body.email), phone: str(body.phone), note: str(body.note) },
170
+ ...(body.places !== undefined && body.places !== "" ? { places: /^[0-9]{1,3}$/.test(str(body.places)) ? Number(body.places) : NaN } : {}),
171
+ ...(ctx.member ? { member: ctx.member } : {}),
144
172
  });
145
173
  return { status: 201, body: { ok: true, action, booking, token } };
146
174
  }
175
+ if (action === "cancel" && ctx.member && str(body.booking))
176
+ return { status: 200, body: { ok: true, action, booking: await bookings.cancelAsMember(str(body.booking), ctx.account, ctx.member) } };
147
177
  if (action === "cancel")
148
178
  return { status: 200, body: { ok: true, action, booking: await bookings.cancel(str(body.token)) } };
149
179
  if (action === "move")
package/dist/words.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const BOOKING_WORD_KEYS: readonly ["picker.title", "picker.empty", "picker.more", "picker.left", "form.title", "form.name", "form.email", "form.phone", "form.phone_optional", "form.note", "form.submit", "form.submit_request", "form.back", "form.error.name", "form.error.email", "form.error.phone", "form.error.note", "error.taken", "error.not_open", "error.too_many", "error.too_late", "error.not_allowed", "error.unknown_booking", "error.failed", "done.confirmed.title", "done.confirmed.body", "done.pending.title", "done.pending.body", "done.ics", "done.manage", "manage.title", "manage.cancel", "manage.move", "manage.locked", "status.pending", "status.confirmed", "status.cancelled", "status.declined", "list.title", "list.empty", "list.approve", "list.decline", "list.cancel", "email.hello", "email.booked.subject", "email.booked.body", "email.requested.subject", "email.requested.body", "email.confirmed.subject", "email.confirmed.body", "email.declined.subject", "email.declined.body", "email.cancelled.subject", "email.cancelled.body", "email.moved.subject", "email.moved.body", "email.reminder.subject", "email.reminder.body", "email.manage", "email.calendar", "email.owner.new.subject", "email.owner.request.subject", "email.owner.cancelled.subject", "email.owner.moved.subject", "email.owner.body", "email.owner.open", "email.owner.footer"];
1
+ export declare const BOOKING_WORD_KEYS: readonly ["picker.title", "picker.empty", "picker.more", "picker.left", "form.title", "form.name", "form.email", "form.phone", "form.phone_optional", "form.note", "form.places", "form.error.places", "form.submit", "form.submit_request", "form.back", "form.error.name", "form.error.email", "form.error.phone", "form.error.note", "error.taken", "error.not_open", "error.too_many", "error.too_late", "error.not_allowed", "error.unknown_booking", "error.failed", "done.confirmed.title", "done.confirmed.body", "done.pending.title", "done.pending.body", "done.ics", "done.manage", "manage.title", "manage.cancel", "manage.move", "manage.locked", "status.pending", "status.confirmed", "status.cancelled", "status.declined", "list.title", "list.empty", "list.approve", "list.decline", "list.cancel", "list.places", "mine.title", "mine.empty", "mine.cancel", "mine.book", "email.hello", "email.booked.subject", "email.booked.body", "email.requested.subject", "email.requested.body", "email.confirmed.subject", "email.confirmed.body", "email.declined.subject", "email.declined.body", "email.cancelled.subject", "email.cancelled.body", "email.moved.subject", "email.moved.body", "email.reminder.subject", "email.reminder.body", "email.places", "email.manage", "email.calendar", "email.owner.new.subject", "email.owner.request.subject", "email.owner.cancelled.subject", "email.owner.moved.subject", "email.owner.body", "email.owner.open", "email.owner.footer"];
2
2
  export type BookingWordKey = (typeof BOOKING_WORD_KEYS)[number];
3
3
  /** The words in Australian English, as `ui.wbbooking.<key>` would hold them. */
4
4
  export declare const BOOKING_WORDS: Readonly<Record<BookingWordKey, string>>;
package/dist/words.js CHANGED
@@ -14,6 +14,8 @@ export const BOOKING_WORD_KEYS = [
14
14
  "form.phone",
15
15
  "form.phone_optional",
16
16
  "form.note",
17
+ "form.places",
18
+ "form.error.places",
17
19
  "form.submit",
18
20
  "form.submit_request",
19
21
  "form.back",
@@ -47,6 +49,11 @@ export const BOOKING_WORD_KEYS = [
47
49
  "list.approve",
48
50
  "list.decline",
49
51
  "list.cancel",
52
+ "list.places",
53
+ "mine.title",
54
+ "mine.empty",
55
+ "mine.cancel",
56
+ "mine.book",
50
57
  "email.hello",
51
58
  "email.booked.subject",
52
59
  "email.booked.body",
@@ -62,6 +69,7 @@ export const BOOKING_WORD_KEYS = [
62
69
  "email.moved.body",
63
70
  "email.reminder.subject",
64
71
  "email.reminder.body",
72
+ "email.places",
65
73
  "email.manage",
66
74
  "email.calendar",
67
75
  "email.owner.new.subject",
@@ -84,6 +92,7 @@ export const BOOKING_WORDS = {
84
92
  "form.phone": "Phone",
85
93
  "form.phone_optional": "Phone (optional)",
86
94
  "form.note": "Anything we should know? (optional)",
95
+ "form.places": "How many places",
87
96
  "form.submit": "Book",
88
97
  "form.submit_request": "Send request",
89
98
  "form.back": "Choose another time",
@@ -91,6 +100,7 @@ export const BOOKING_WORDS = {
91
100
  "form.error.email": "Please enter an email address we can send the confirmation to.",
92
101
  "form.error.phone": "Please enter a phone number.",
93
102
  "form.error.note": "Please keep the note under 1,000 characters.",
103
+ "form.error.places": "Please choose how many places.",
94
104
  "error.taken": "Sorry, someone has just booked that time. Please choose another.",
95
105
  "error.not_open": "That time isn't available. Please choose another.",
96
106
  "error.too_many": "You already have {max} upcoming bookings with us. Change or cancel one first.",
@@ -117,6 +127,11 @@ export const BOOKING_WORDS = {
117
127
  "list.approve": "Accept",
118
128
  "list.decline": "Decline",
119
129
  "list.cancel": "Cancel",
130
+ "list.places": "{places} places",
131
+ "mine.title": "My bookings",
132
+ "mine.empty": "You have no upcoming bookings.",
133
+ "mine.cancel": "Cancel booking",
134
+ "mine.book": "Make a booking",
120
135
  "email.hello": "Hi {name},",
121
136
  "email.booked.subject": "Booked: {service}, {when}",
122
137
  "email.booked.body": "You're booked for {service} with {business} on {when}.",
@@ -132,6 +147,7 @@ export const BOOKING_WORDS = {
132
147
  "email.moved.body": "Your booking for {service} with {business} is now on {when}.",
133
148
  "email.reminder.subject": "Reminder: {service}, {when}",
134
149
  "email.reminder.body": "A reminder of your booking for {service} with {business} on {when}.",
150
+ "email.places": "Places: {places}",
135
151
  "email.manage": "To change or cancel it: {url}",
136
152
  "email.calendar": "Open the attached calendar file to add it to your calendar.",
137
153
  "email.owner.new.subject": "New booking: {service}, {when}",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-bookings",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A bookings calendar for Workbench apps: customers pick a free time, book it with their name and email, and get a confirmation email with a calendar file, reminders before it starts and a private link to change or cancel. The owner gets an email for each booking, a list in the app and a calendar feed. Stored in the app's own database, with tick() from the app's cron for reminders. No AI.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",