@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.
@@ -2,3 +2,15 @@ export declare const bookingsMigration: {
2
2
  up: string;
3
3
  down: string;
4
4
  };
5
+ /**
6
+ * Every bookings migration, oldest first. `name` ends each file's name in
7
+ * supabase/migrations (`<timestamp>_<name>.sql`), which is how `npx
8
+ * workbench-bookings migration` knows the ones a project already has. A
9
+ * project applies them in order, and each down file reverses only its own up.
10
+ */
11
+ export declare const bookingsMigrations: readonly {
12
+ name: string;
13
+ about: string;
14
+ up: string;
15
+ down: string;
16
+ }[];
package/dist/migration.js CHANGED
@@ -25,6 +25,8 @@
25
25
  //
26
26
  // It creates functions, so Control asks for approval to apply it even on
27
27
  // staging. The down file drops everything the up file made.
28
+ import { bookingsResourcesMigration } from "./migration-resources.js";
29
+ import { bookingsSessionsMigration } from "./migration-sessions.js";
28
30
  export const bookingsMigration = {
29
31
  up: `create table public.bookings (
30
32
  id uuid primary key default gen_random_uuid(),
@@ -439,3 +441,14 @@ drop table public.booking_feeds;
439
441
  drop table public.bookings;
440
442
  `,
441
443
  };
444
+ /**
445
+ * Every bookings migration, oldest first. `name` ends each file's name in
446
+ * supabase/migrations (`<timestamp>_<name>.sql`), which is how `npx
447
+ * workbench-bookings migration` knows the ones a project already has. A
448
+ * project applies them in order, and each down file reverses only its own up.
449
+ */
450
+ export const bookingsMigrations = [
451
+ { name: "workbench_bookings", about: "bookings calendar (docs/capabilities/13-bookings.md)", ...bookingsMigration },
452
+ { name: "workbench_bookings_resources", about: "named resources (docs/capabilities/20-capacity-calendar.md)", ...bookingsResourcesMigration },
453
+ { name: "workbench_bookings_sessions", about: "sessions, series, the waiting list and attendance (docs/capabilities/20-capacity-calendar.md, part 2)", ...bookingsSessionsMigration },
454
+ ];
@@ -0,0 +1,136 @@
1
+ import { BookingsError } from "./errors.ts";
2
+ import { type Words } from "./format.ts";
3
+ import type { SessionBookings } from "./sessions.ts";
4
+ import type { Booking, BookingConfig, RollEntry, Session, WaitEntry } from "./types.ts";
5
+ import { type ActionResult, type Common, type FormField } from "./ui.ts";
6
+ export interface SessionListOptions extends Common {
7
+ /** The service's title, shown under the heading. */
8
+ title: string;
9
+ /** The details page for a date (GET). */
10
+ book: (s: Session) => string;
11
+ /** The waiting list form for a full date (GET). Left out: full dates only say Full. */
12
+ wait?: (s: Session) => string;
13
+ /** Moving a booking: the project's action endpoint and the manage link's secret. Choosing a date then moves it at once. */
14
+ move?: {
15
+ endpoint: string;
16
+ token: string;
17
+ };
18
+ /** A term: the page that books every date together, and how many dates. */
19
+ series?: {
20
+ href: string;
21
+ count: number;
22
+ };
23
+ /** The clock, for tests. */
24
+ now?: Date;
25
+ }
26
+ /** A service's dates, earliest first: when, where, the owner's note, the places left, and Book or Join the waiting list. */
27
+ export declare function renderSessionList(sessions: readonly Session[], o: SessionListOptions): string;
28
+ export interface SessionFormOptions extends Common {
29
+ /** The project's action endpoint (POST), which hands the fields to sessionAction. */
30
+ endpoint: string;
31
+ title: string;
32
+ /** book: places on this date. series: every date of its term (pass them all in `dates`). wait: the waiting list. */
33
+ mode?: "book" | "series" | "wait";
34
+ /** With mode series: the term's dates still to come. */
35
+ dates?: readonly Session[];
36
+ /** The most places to offer: the smaller of the service's places and the places left (for the waiting list, the service's places). */
37
+ places?: number;
38
+ ask?: BookingConfig["ask"];
39
+ confirm?: BookingConfig["confirm"];
40
+ values?: Partial<Record<FormField, string>>;
41
+ field?: FormField;
42
+ message?: string;
43
+ /** The dates page, for "Choose another date". */
44
+ back?: string;
45
+ }
46
+ /** The details form for a date, a whole term, or the waiting list of a full one. */
47
+ export declare function renderSessionForm(s: Session, o: SessionFormOptions): string;
48
+ export interface WaitPageOptions extends Common {
49
+ /** The project's action endpoint (POST). */
50
+ endpoint: string;
51
+ /** The secret from the link. */
52
+ token: string;
53
+ title: string;
54
+ /** The date waited for (for a term, its first date to come), when the app looked it up. */
55
+ session?: Session;
56
+ }
57
+ /** A person's own waiting list page: waiting (Leave), offered a place (Take the place, No thanks), or how it ended. */
58
+ export declare function renderWaitPage(w: WaitEntry, o: WaitPageOptions): string;
59
+ export interface SessionAdminOptions extends Common {
60
+ /** The project's owner endpoint (POST, behind the sign-in), which hands the fields to ownerSessionAction. */
61
+ endpoint: string;
62
+ titleOf: (service: string) => string;
63
+ /** The page that adds a date. */
64
+ add?: string;
65
+ /** The page that changes one. */
66
+ edit?: (s: Session) => string;
67
+ /** The who's coming page of one. */
68
+ roll?: (s: Session) => string;
69
+ }
70
+ /** The owner's dates, earliest first: how many are booked and waiting, with Change, Who's coming and Cancel this date. */
71
+ export declare function renderSessionAdmin(sessions: readonly Session[], o: SessionAdminOptions): string;
72
+ export interface SessionEditorOptions extends Common {
73
+ /** The project's owner endpoint (POST). */
74
+ endpoint: string;
75
+ /** The services booked by sessions: name and title (bookings.config.services with "sessions": true). */
76
+ services: readonly {
77
+ name: string;
78
+ title: string;
79
+ capacity?: number;
80
+ }[];
81
+ /** The date being changed. Left out: a new one. */
82
+ session?: Session;
83
+ /** Why it didn't save (ownerSessionAction's `text`). */
84
+ message?: string;
85
+ /** The owner's dates page. */
86
+ back?: string;
87
+ }
88
+ /** The form that adds a date (repeated weekly for a term when asked) or changes one. */
89
+ export declare function renderSessionEditor(o: SessionEditorOptions): string;
90
+ export interface RollOptions extends Common {
91
+ endpoint: string;
92
+ title: string;
93
+ back?: string;
94
+ }
95
+ /** Who's coming to a date, by name, with Came and Didn't come for each. */
96
+ export declare function renderRoll(s: Session, entries: readonly RollEntry[], o: RollOptions): string;
97
+ export interface SessionActionResult {
98
+ status: number;
99
+ body: {
100
+ ok: true;
101
+ action: string;
102
+ booking?: Booking;
103
+ token?: string;
104
+ entry?: WaitEntry;
105
+ session?: Session;
106
+ sessions?: Session[];
107
+ series?: string;
108
+ cancelled?: Booking[];
109
+ } | Extract<ActionResult["body"], {
110
+ ok: false;
111
+ }>;
112
+ cause?: BookingsError;
113
+ }
114
+ /**
115
+ * The customer's posts on the session pages: `book_session` (session, name,
116
+ * email, places, and phone or note when asked), `book_series` (series),
117
+ * `wait` (session or series: joins the waiting list), `leave` and `accept`
118
+ * (token, from the waiting list page) and `move_session` (the manage link's
119
+ * token, session). Put Turnstile or the app's rate limit in front of it.
120
+ * `member` is the signed-in member's id from the app's own sign-in.
121
+ */
122
+ export declare function sessionAction(bookings: SessionBookings, body: Record<string, unknown>, ctx: {
123
+ account: string;
124
+ member?: string;
125
+ t?: Words;
126
+ }): Promise<SessionActionResult>;
127
+ /**
128
+ * The owner's posts on the session pages, behind the app's sign-in, with the
129
+ * signed-in owner's account: `save_session` (the editor's fields; `weeks`
130
+ * above 1 makes one a week, and `term` makes them a series booked together),
131
+ * `cancel_session` (session, reason) and `mark` (booking, session, came: yes,
132
+ * no or empty to clear).
133
+ */
134
+ export declare function ownerSessionAction(bookings: SessionBookings, body: Record<string, unknown>, account: string, ctx?: {
135
+ t?: Words;
136
+ }): Promise<SessionActionResult>;
@@ -0,0 +1,247 @@
1
+ // The pages for dated sessions (docs/capabilities/20-capacity-calendar.md,
2
+ // part 2): plain HTML strings, no script, mobile first, as ui.ts. Public: the
3
+ // dates of a service (each a link to its form, or to the waiting list when
4
+ // full), the details form, and a person's own waiting list page from the
5
+ // link in their emails. Behind the app's sign-in: the owner's dates, the form
6
+ // that adds or changes one, and who's coming with Came and Didn't come.
7
+ // Every element carries a wb-booking-* class (BOOKING_STYLES).
8
+ import { BookingsError } from "./errors.js";
9
+ import { dayText, DEFAULT_LOCALE, timeText, whenText, words } from "./format.js";
10
+ import { addDays, clockIn, localInstant, todayIn, validDate } from "./time.js";
11
+ import { detailFields, esc, failed, hidden, str } from "./ui.js";
12
+ const span = (s, tz, locale) => `${dayText(todayIn(tz, new Date(s.starts_at)), locale)}, ${timeText(s.starts_at, tz, locale)} to ${timeText(s.ends_at, tz, locale)}`;
13
+ function placeLine(s, say) {
14
+ if (!s.place && !s.map_url)
15
+ return "";
16
+ const map = s.map_url ? `<a class="wb-booking-map" href="${esc(s.map_url)}" rel="noopener">${esc(say("session.map"))}</a>` : "";
17
+ return `<p class="wb-booking-place">${esc(s.place ?? "")}${s.place && map ? " " : ""}${map}</p>`;
18
+ }
19
+ /** A service's dates, earliest first: when, where, the owner's note, the places left, and Book or Join the waiting list. */
20
+ export function renderSessionList(sessions, o) {
21
+ const say = words(o.t);
22
+ const locale = o.locale ?? DEFAULT_LOCALE;
23
+ const at = (o.now ?? new Date()).getTime();
24
+ const head = `<h2 class="wb-booking-heading">${esc(say("session.title"))}</h2><p class="wb-booking-service">${esc(o.title)}</p>`;
25
+ if (sessions.length === 0)
26
+ return `<section class="wb-booking-sessions">${head}<p class="wb-booking-empty">${esc(say("session.empty"))}</p></section>`;
27
+ const item = (s) => {
28
+ const cancelled = s.status === "cancelled";
29
+ const started = Date.parse(s.starts_at) <= at;
30
+ const full = s.left < 1 || s.waiting > 0;
31
+ const state = cancelled ? say("session.cancelled") : started ? say("session.started") : !s.bookable ? "" : full ? say("session.full") : say("session.left", { left: s.left });
32
+ const action = cancelled || started || !s.bookable
33
+ ? ""
34
+ : full
35
+ ? o.wait && !o.move
36
+ ? `<a class="wb-booking-session-wait" href="${esc(o.wait(s))}">${esc(say("session.wait"))}</a>`
37
+ : ""
38
+ : o.move
39
+ ? `<form class="wb-booking-form" method="post" action="${esc(o.move.endpoint)}">${hidden("action", "move_session")}${hidden("token", o.move.token)}${hidden("session", s.id)}<button class="wb-booking-session-book" type="submit">${esc(say("session.book"))}</button></form>`
40
+ : `<a class="wb-booking-session-book" href="${esc(o.book(s))}">${esc(say("session.book"))}</a>`;
41
+ return `<li class="wb-booking-item"><article class="wb-booking-session${cancelled ? " wb-booking-ended" : ""}" id="wb-booking-session-${esc(s.id)}"><h3 class="wb-booking-title">${esc(span(s, o.timeZone, locale))}</h3>${placeLine(s, say)}${s.note ? `<p class="wb-booking-session-note">${esc(s.note)}</p>` : ""}${cancelled && s.reason ? `<p class="wb-booking-session-note">${esc(s.reason)}</p>` : ""}${state ? `<p class="wb-booking-status">${esc(state)}</p>` : ""}${action ? `<div class="wb-booking-actions">${action}</div>` : ""}</article></li>`;
42
+ };
43
+ const series = o.series && !o.move ? `<a class="wb-booking-more" href="${esc(o.series.href)}">${esc(say("session.series", { count: o.series.count }))}</a>` : "";
44
+ return `<section class="wb-booking-sessions">${head}${series}<ul class="wb-booking-items">${sessions.map(item).join("")}</ul></section>`;
45
+ }
46
+ /** The details form for a date, a whole term, or the waiting list of a full one. */
47
+ export function renderSessionForm(s, o) {
48
+ const say = words(o.t);
49
+ const locale = o.locale ?? DEFAULT_LOCALE;
50
+ const mode = o.mode ?? "book";
51
+ const dates = mode === "series" && o.dates && o.dates.length > 1 ? `<p class="wb-booking-text">${esc(say("session.dates", { count: o.dates.length, last: whenText(o.dates[o.dates.length - 1].starts_at, o.timeZone, locale) }))}</p>` : "";
52
+ const target = mode === "series" || (mode === "wait" && o.dates) ? hidden("series", s.series ?? "") : hidden("session", s.id);
53
+ return [
54
+ `<form class="wb-booking-details" method="post" action="${esc(o.endpoint)}">`,
55
+ `<h2 class="wb-booking-heading">${esc(say(mode === "wait" ? "session.form.wait_title" : "form.title"))}</h2>`,
56
+ `<p class="wb-booking-when">${esc(o.title)}, ${esc(whenText(s.starts_at, o.timeZone, locale))}</p>`,
57
+ dates,
58
+ placeLine(s, say),
59
+ s.note ? `<p class="wb-booking-session-note">${esc(s.note)}</p>` : "",
60
+ mode === "wait" ? `<p class="wb-booking-text">${esc(say("session.form.wait_body"))}</p>` : "",
61
+ o.message ? `<p class="wb-booking-message" role="alert">${esc(o.message)}</p>` : "",
62
+ hidden("action", mode === "wait" ? "wait" : mode === "series" ? "book_series" : "book_session"),
63
+ target,
64
+ detailFields({ ...o, ...(mode === "wait" ? { ask: { phone: o.ask?.phone ?? "no" } } : {}) }),
65
+ `<div class="wb-booking-actions"><button class="wb-booking-submit" type="submit">${esc(say(mode === "wait" ? "session.form.submit_wait" : o.confirm === "owner_approves" ? "form.submit_request" : "form.submit"))}</button>`,
66
+ o.back ? `<a class="wb-booking-back" href="${esc(o.back)}">${esc(say("session.form.back"))}</a>` : "",
67
+ "</div></form>",
68
+ ].join("");
69
+ }
70
+ /** A person's own waiting list page: waiting (Leave), offered a place (Take the place, No thanks), or how it ended. */
71
+ export function renderWaitPage(w, o) {
72
+ const say = words(o.t);
73
+ const locale = o.locale ?? DEFAULT_LOCALE;
74
+ const button = (action, cls, label) => `<form class="wb-booking-form" method="post" action="${esc(o.endpoint)}">${hidden("action", action)}${hidden("token", o.token)}<button class="${cls}" type="submit">${esc(label)}</button></form>`;
75
+ const line = w.status === "offered" ? say("wait.offered", { until: w.offered_until ? whenText(w.offered_until, o.timeZone, locale) : "" }) : say(`wait.${w.status}`);
76
+ const actions = w.status === "offered" ? `${button("accept", "wb-booking-submit", say("wait.accept"))}${button("leave", "wb-booking-cancel", say("wait.decline"))}` : w.status === "waiting" ? button("leave", "wb-booking-cancel", say("wait.leave")) : "";
77
+ return `<section class="wb-booking-wait" role="status"><h2 class="wb-booking-heading">${esc(say("wait.title"))}</h2><p class="wb-booking-when">${esc(o.title)}${o.session ? `, ${esc(whenText(o.session.starts_at, o.timeZone, locale))}` : ""}</p>${w.places > 1 ? `<p class="wb-booking-places">${esc(say("list.places", { places: w.places }))}</p>` : ""}<p class="wb-booking-text">${esc(line)}</p>${actions ? `<div class="wb-booking-actions">${actions}</div>` : ""}</section>`;
78
+ }
79
+ /** The owner's dates, earliest first: how many are booked and waiting, with Change, Who's coming and Cancel this date. */
80
+ export function renderSessionAdmin(sessions, o) {
81
+ const say = words(o.t);
82
+ const locale = o.locale ?? DEFAULT_LOCALE;
83
+ const head = `<h2 class="wb-booking-heading">${esc(say("sessions.title"))}</h2>`;
84
+ const add = o.add ? `<a class="wb-booking-more" href="${esc(o.add)}">${esc(say("sessions.add"))}</a>` : "";
85
+ if (sessions.length === 0)
86
+ return `<section class="wb-booking-session-admin">${head}<p class="wb-booking-empty">${esc(say("sessions.empty"))}</p>${add}</section>`;
87
+ const item = (s) => {
88
+ const cancelled = s.status === "cancelled";
89
+ const short = !cancelled && s.min_places !== null && s.taken < s.min_places;
90
+ const facts = [
91
+ s.bookable ? say("sessions.booked", { taken: s.taken, capacity: s.capacity }) : say("sessions.show_only"),
92
+ ...(s.waiting > 0 ? [say("sessions.waiting", { waiting: s.waiting })] : []),
93
+ ].join(" · ");
94
+ const links = cancelled
95
+ ? ""
96
+ : `<div class="wb-booking-actions">${o.edit ? `<a class="wb-booking-session-edit" href="${esc(o.edit(s))}">${esc(say("sessions.edit"))}</a>` : ""}${o.roll && s.bookable ? `<a class="wb-booking-session-roll" href="${esc(o.roll(s))}">${esc(say("sessions.roll"))}</a>` : ""}</div><form class="wb-booking-session-cancel" method="post" action="${esc(o.endpoint)}">${hidden("action", "cancel_session")}${hidden("session", s.id)}<label class="wb-booking-field"><span class="wb-booking-label">${esc(say("sessions.reason"))}</span><input class="wb-booking-input" type="text" name="reason" maxlength="200"></label><button class="wb-booking-owner-cancel" type="submit">${esc(say("sessions.cancel"))}</button></form>`;
97
+ return `<li class="wb-booking-item"><article class="wb-booking-session${cancelled ? " wb-booking-ended" : ""}${short ? " wb-booking-pending" : ""}" id="wb-booking-session-${esc(s.id)}"><h3 class="wb-booking-title">${esc(span(s, o.timeZone, locale))} · ${esc(o.titleOf(s.service))}</h3>${placeLine(s, say)}<p class="wb-booking-status">${esc(cancelled ? say("session.cancelled") : facts)}</p>${short ? `<p class="wb-booking-session-short">${esc(say("sessions.min", { min: s.min_places }))}</p>` : ""}${links}</article></li>`;
98
+ };
99
+ return `<section class="wb-booking-session-admin">${head}${add}<ul class="wb-booking-items">${sessions.map(item).join("")}</ul></section>`;
100
+ }
101
+ /** The form that adds a date (repeated weekly for a term when asked) or changes one. */
102
+ export function renderSessionEditor(o) {
103
+ const say = words(o.t);
104
+ const s = o.session;
105
+ const field = (label, control) => `<label class="wb-booking-field"><span class="wb-booking-label">${esc(label)}</span>${control}</label>`;
106
+ const input = (name, type, value, more = "") => `<input class="wb-booking-input" type="${type}" name="${name}" value="${esc(value)}"${more}>`;
107
+ const check = (name, label, on) => `<label class="wb-booking-check"><input class="wb-booking-checkbox" type="checkbox" name="${name}" value="1"${on ? " checked" : ""}><span class="wb-booking-label">${esc(label)}</span></label>`;
108
+ const start = s ? new Date(s.starts_at) : null;
109
+ const end = s ? new Date(s.ends_at) : null;
110
+ return [
111
+ `<form class="wb-booking-editor" method="post" action="${esc(o.endpoint)}">`,
112
+ `<h2 class="wb-booking-heading">${esc(say(s ? "editor.title_edit" : "editor.title_new"))}</h2>`,
113
+ o.message ? `<p class="wb-booking-message" role="alert">${esc(o.message)}</p>` : "",
114
+ hidden("action", "save_session"),
115
+ s ? `${hidden("id", s.id)}${hidden("service", s.service)}` : field(say("editor.service"), `<select class="wb-booking-select" name="service">${o.services.map((x) => `<option value="${esc(x.name)}">${esc(x.title)}</option>`).join("")}</select>`),
116
+ field(say("editor.date"), input("date", "date", start ? todayIn(o.timeZone, start) : "", " required")),
117
+ field(say("editor.start"), input("start", "time", start ? clockIn(o.timeZone, start) : "", " required")),
118
+ field(say("editor.end"), input("end", "time", end ? clockIn(o.timeZone, end) : "")),
119
+ field(say("editor.place"), input("place", "text", s?.place ?? "", ' maxlength="200"')),
120
+ field(say("editor.map"), input("map_url", "url", s?.map_url ?? "", ' maxlength="500" placeholder="https://"')),
121
+ field(say("editor.note"), `<textarea class="wb-booking-textarea" name="note" rows="3" maxlength="500">${esc(s?.note ?? "")}</textarea>`),
122
+ field(say("editor.capacity"), input("capacity", "number", s ? String(s.capacity) : String(o.services[0]?.capacity ?? ""), ' min="1" max="1000" inputmode="numeric"')),
123
+ field(say("editor.min"), input("min_places", "number", s?.min_places != null ? String(s.min_places) : "", ' min="1" max="1000" inputmode="numeric"')),
124
+ check("bookable", say("editor.bookable"), s ? s.bookable : true),
125
+ s ? "" : field(say("editor.weeks"), input("weeks", "number", "1", ' min="1" max="52" inputmode="numeric"')),
126
+ s ? "" : check("term", say("editor.term"), false),
127
+ `<div class="wb-booking-actions"><button class="wb-booking-submit" type="submit">${esc(say("editor.save"))}</button>`,
128
+ o.back ? `<a class="wb-booking-back" href="${esc(o.back)}">${esc(say("editor.back"))}</a>` : "",
129
+ "</div></form>",
130
+ ].join("");
131
+ }
132
+ /** Who's coming to a date, by name, with Came and Didn't come for each. */
133
+ export function renderRoll(s, entries, o) {
134
+ const say = words(o.t);
135
+ const locale = o.locale ?? DEFAULT_LOCALE;
136
+ const head = `<h2 class="wb-booking-heading">${esc(say("roll.title"))}</h2><p class="wb-booking-when">${esc(o.title)}, ${esc(whenText(s.starts_at, o.timeZone, locale))}</p>`;
137
+ const back = o.back ? `<a class="wb-booking-back" href="${esc(o.back)}">${esc(say("roll.back"))}</a>` : "";
138
+ if (entries.length === 0)
139
+ return `<section class="wb-booking-roll">${head}<p class="wb-booking-empty">${esc(say("roll.empty"))}</p>${back}</section>`;
140
+ const button = (b, came, label, on) => `<form class="wb-booking-form" method="post" action="${esc(o.endpoint)}">${hidden("action", "mark")}${hidden("booking", b.id)}${hidden("session", s.id)}${hidden("came", came)}<button class="wb-booking-mark${on ? " wb-booking-mark-on" : ""}" type="submit"${on ? ' aria-pressed="true"' : ""}>${esc(label)}</button></form>`;
141
+ const item = ({ booking: b, came }) => `<li class="wb-booking-item"><article class="wb-booking-roll-entry${b.status === "pending" ? " wb-booking-pending" : ""}"><h3 class="wb-booking-title">${esc(b.customer.name)}</h3><p class="wb-booking-who">${esc([b.customer.email, b.customer.phone].filter(Boolean).join(" · "))}</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>` : ""}<div class="wb-booking-actions">${button(b, "yes", say("roll.came"), came === true)}${button(b, "no", say("roll.missed"), came === false)}${came !== null ? button(b, "", say("roll.clear"), false) : ""}</div></article></li>`;
142
+ return `<section class="wb-booking-roll">${head}<ul class="wb-booking-items">${entries.map(item).join("")}</ul>${back}</section>`;
143
+ }
144
+ const count = (v) => (v !== undefined && v !== "" ? { places: /^[0-9]{1,3}$/.test(str(v)) ? Number(v) : NaN } : {});
145
+ /**
146
+ * The customer's posts on the session pages: `book_session` (session, name,
147
+ * email, places, and phone or note when asked), `book_series` (series),
148
+ * `wait` (session or series: joins the waiting list), `leave` and `accept`
149
+ * (token, from the waiting list page) and `move_session` (the manage link's
150
+ * token, session). Put Turnstile or the app's rate limit in front of it.
151
+ * `member` is the signed-in member's id from the app's own sign-in.
152
+ */
153
+ export async function sessionAction(bookings, body, ctx) {
154
+ const max = bookings.config.max_per_customer ?? 3;
155
+ try {
156
+ const action = str(body.action);
157
+ const who = { customer: { name: str(body.name), email: str(body.email), phone: str(body.phone), note: str(body.note) }, ...count(body.places), ...(ctx.member ? { member: ctx.member } : {}) };
158
+ if (action === "book_session")
159
+ return { status: 201, body: { ok: true, action, ...(await bookings.bookSession({ account: ctx.account, session: str(body.session), ...who })) } };
160
+ if (action === "book_series")
161
+ return { status: 201, body: { ok: true, action, ...(await bookings.bookSeries({ account: ctx.account, series: str(body.series), ...who })) } };
162
+ if (action === "wait")
163
+ return { status: 201, body: { ok: true, action, ...(await bookings.joinWaitlist({ account: ctx.account, ...(str(body.series) ? { series: str(body.series) } : { session: str(body.session) }), ...who })) } };
164
+ if (action === "leave")
165
+ return { status: 200, body: { ok: true, action, entry: await bookings.leaveWaitlist(str(body.token)) } };
166
+ if (action === "accept")
167
+ return { status: 201, body: { ok: true, action, ...(await bookings.acceptOffer(str(body.token))) } };
168
+ if (action === "move_session")
169
+ return { status: 200, body: { ok: true, action, booking: await bookings.moveToSession(str(body.token), str(body.session)) } };
170
+ throw new BookingsError("bad_input", "action must be book_session, book_series, wait, leave, accept or move_session");
171
+ }
172
+ catch (e) {
173
+ return failed(e, { ...(ctx.t ? { t: ctx.t } : {}), max });
174
+ }
175
+ }
176
+ /** The editor's fields as sessions: one, or one a week for `weeks`. Times are the business's clock. */
177
+ function editorInputs(body, timeZone) {
178
+ const date = str(body.date);
179
+ if (!validDate(date))
180
+ throw new BookingsError("bad_input", "date: a day, YYYY-MM-DD");
181
+ const clock = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
182
+ if (!clock.test(str(body.start)))
183
+ throw new BookingsError("bad_input", "start: a time, such as 09:30");
184
+ if (str(body.end) && !clock.test(str(body.end)))
185
+ throw new BookingsError("bad_input", "end: a time, such as 10:30");
186
+ const num = (v) => (str(v) === "" ? undefined : /^[0-9]{1,4}$/.test(str(v)) ? Number(v) : NaN);
187
+ const weeks = num(body.weeks) ?? 1;
188
+ if (!Number.isInteger(weeks) || weeks < 1 || weeks > 52)
189
+ throw new BookingsError("bad_input", "weeks: a whole number from 1 to 52");
190
+ const capacity = num(body.capacity);
191
+ const min = num(body.min_places);
192
+ return Array.from({ length: weeks }, (_, i) => {
193
+ const day = addDays(date, i * 7);
194
+ const start = localInstant(day, str(body.start), timeZone);
195
+ // An end at or before the start's clock is the next day (a night market).
196
+ const end = str(body.end) ? localInstant(str(body.end) <= str(body.start) ? addDays(day, 1) : day, str(body.end), timeZone) : undefined;
197
+ return {
198
+ service: str(body.service),
199
+ start,
200
+ ...(end ? { end } : {}),
201
+ place: str(body.place),
202
+ map_url: str(body.map_url),
203
+ note: str(body.note),
204
+ ...(capacity !== undefined ? { capacity } : {}),
205
+ min_places: min ?? null,
206
+ bookable: str(body.bookable) !== "",
207
+ };
208
+ });
209
+ }
210
+ /**
211
+ * The owner's posts on the session pages, behind the app's sign-in, with the
212
+ * signed-in owner's account: `save_session` (the editor's fields; `weeks`
213
+ * above 1 makes one a week, and `term` makes them a series booked together),
214
+ * `cancel_session` (session, reason) and `mark` (booking, session, came: yes,
215
+ * no or empty to clear).
216
+ */
217
+ export async function ownerSessionAction(bookings, body, account, ctx = {}) {
218
+ try {
219
+ const action = str(body.action);
220
+ if (action === "save_session") {
221
+ const inputs = editorInputs(body, bookings.config.time_zone);
222
+ if (str(body.id))
223
+ return { status: 200, body: { ok: true, action, session: (await bookings.saveSession(account, { ...inputs[0], id: str(body.id) })).session } };
224
+ if (str(body.term) && inputs.length > 1) {
225
+ const made = await bookings.createSeries(account, inputs);
226
+ return { status: 201, body: { ok: true, action, series: made.series, sessions: made.sessions } };
227
+ }
228
+ const made = [];
229
+ for (const input of inputs)
230
+ made.push((await bookings.saveSession(account, input)).session);
231
+ return { status: 201, body: { ok: true, action, session: made[0], sessions: made } };
232
+ }
233
+ if (action === "cancel_session") {
234
+ const r = await bookings.cancelSession(str(body.session), account, str(body.reason).trim().slice(0, 200) || undefined);
235
+ return { status: 200, body: { ok: true, action, session: r.session, cancelled: r.cancelled } };
236
+ }
237
+ if (action === "mark") {
238
+ const came = str(body.came);
239
+ await bookings.mark(str(body.booking), account, came === "yes" ? true : came === "no" ? false : null, str(body.session) || undefined);
240
+ return { status: 200, body: { ok: true, action } };
241
+ }
242
+ throw new BookingsError("bad_input", "action must be save_session, cancel_session or mark");
243
+ }
244
+ catch (e) {
245
+ return failed(e, ctx.t ? { t: ctx.t } : {});
246
+ }
247
+ }
@@ -0,0 +1,97 @@
1
+ import type { Bookings, StoreContext } from "./bookings.ts";
2
+ import type { Booking, Customer, RollEntry, Session, SessionInput, TickResult, WaitEntry } from "./types.ts";
3
+ /** A session row with its times as ISO 8601 in UTC and the places left. */
4
+ export declare function sessionOf(s: Session): Session;
5
+ export interface SessionBookRequest {
6
+ account: string;
7
+ /** The session's id, from sessions(). */
8
+ session: string;
9
+ customer: Customer;
10
+ /** How many places, 1 to the service's places. Default 1. */
11
+ places?: number;
12
+ /** The signed-in member's id from the app's own sign-in. Never from the form. */
13
+ member?: string;
14
+ }
15
+ export interface SeriesBookRequest extends Omit<SessionBookRequest, "session"> {
16
+ /** The series' id (a session's `series`). */
17
+ series: string;
18
+ }
19
+ export interface WaitRequest {
20
+ account: string;
21
+ /** One of the two: the full session, or the full series. */
22
+ session?: string;
23
+ series?: string;
24
+ /** Name, email and (when bookings.json asks) phone. No note. */
25
+ customer: Customer;
26
+ places?: number;
27
+ member?: string;
28
+ }
29
+ export interface SessionMethods {
30
+ /** The account's sessions from `from` (default today) for `days` (default ahead_days), earliest first; `all` also gives cancelled ones (the owner's page). */
31
+ sessions(account: string, opts?: {
32
+ service?: string;
33
+ series?: string;
34
+ from?: string;
35
+ days?: number;
36
+ all?: boolean;
37
+ }): Promise<Session[]>;
38
+ /** One session, or null. */
39
+ session(id: string): Promise<Session | null>;
40
+ /** The owner makes a session, or with `id` changes one. A new time moves the bookings on it and emails each customer. */
41
+ saveSession(account: string, input: SessionInput & {
42
+ id?: string;
43
+ }): Promise<{
44
+ session: Session;
45
+ moved: Booking[];
46
+ }>;
47
+ /** The owner makes a series (a term): sessions of one service that are booked together. */
48
+ createSeries(account: string, inputs: readonly SessionInput[]): Promise<{
49
+ series: string;
50
+ sessions: Session[];
51
+ }>;
52
+ /** The owner cancels a session: every booking on it is cancelled and emailed the reason, and the app refunds from `cancelled`. */
53
+ cancelSession(id: string, account: string, reason?: string): Promise<{
54
+ session: Session;
55
+ cancelled: Booking[];
56
+ affected: Booking[];
57
+ }>;
58
+ /** Books places on a session. */
59
+ bookSession(req: SessionBookRequest): Promise<{
60
+ booking: Booking;
61
+ token: string;
62
+ }>;
63
+ /** Books places on every session still to come of a series. */
64
+ bookSeries(req: SeriesBookRequest): Promise<{
65
+ booking: Booking;
66
+ token: string;
67
+ }>;
68
+ /** The customer moves a booking to another session of the same service, from their manage link. */
69
+ moveToSession(token: string, session: string): Promise<Booking>;
70
+ /** Joins the waiting list of a full session or series. Answers the entry and the secret for its page. */
71
+ joinWaitlist(req: WaitRequest): Promise<{
72
+ entry: WaitEntry;
73
+ token: string;
74
+ }>;
75
+ /** The waiting list entry a secret belongs to, or null. */
76
+ waitEntry(token: string): Promise<WaitEntry | null>;
77
+ /** Leaves the list, or turns an offered place down. */
78
+ leaveWaitlist(token: string): Promise<WaitEntry>;
79
+ /** Takes an offered place: books it with the details given when they joined. */
80
+ acceptOffer(token: string): Promise<{
81
+ booking: Booking;
82
+ token: string;
83
+ }>;
84
+ /** Everyone booked on one of the account's sessions, by name, with whether each came. */
85
+ roll(session: string, account: string): Promise<{
86
+ session: Session;
87
+ entries: RollEntry[];
88
+ }>;
89
+ /** The owner marks whether a booking came (null clears it). `session` says which date, for a series booking. */
90
+ mark(booking: string, account: string, came: boolean | null, session?: string): Promise<void>;
91
+ }
92
+ export declare function sessionMethods(c: StoreContext): {
93
+ methods: SessionMethods;
94
+ tick(out: TickResult, at: Date): Promise<void>;
95
+ };
96
+ /** The part of Bookings the session pages use. */
97
+ export type SessionBookings = Pick<Bookings, keyof SessionMethods | "config">;