@mccaskie-labs/workbench-bookings 0.0.0-stage → 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.
@@ -0,0 +1,446 @@
1
+ // createBookings: a bookings calendar over the app's own database
2
+ // (docs/capabilities/13-bookings.md). Customers see the free times, book one
3
+ // with their name and email, and get a confirmation with a calendar file,
4
+ // reminders before it starts, and a private link to change or cancel. The
5
+ // owner gets an email for each booking, a list in the app, and a calendar
6
+ // feed for their own calendar app.
7
+ //
8
+ // No AI: every word is the package's or the project's catalogue's. Email goes
9
+ // through workbench-email (the Gateway). Use it with the service client,
10
+ // server side: the functions are the service role's only (see migration.ts).
11
+ import { checkBookingConfig } from "./config.js";
12
+ import { BookingsError } from "./errors.js";
13
+ import { DEFAULT_LOCALE, whenText, words } from "./format.js";
14
+ import { bookingIcs, feedIcs } from "./ical.js";
15
+ import { offered, openSlots, serviceOf } from "./slots.js";
16
+ import { addDays, durationMinutes, localInstant, todayIn, validDate } from "./time.js";
17
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ const TOKEN = /^[A-Za-z0-9_-]{43}$/;
19
+ const EMAIL = /^[^\s@<>(),;:"[\]\\]+@[^\s@<>(),;:"[\]\\]+\.[^\s@<>(),;:"[\]\\]+$/;
20
+ const PHONE = /^\+?[0-9 ()-]{6,40}$/;
21
+ const LEASE_MS = 10 * 60_000;
22
+ const DAY_MS = 86_400_000;
23
+ async function call(db, what, fn, args) {
24
+ const { data, error } = await db.rpc(fn, args);
25
+ if (error)
26
+ throw new BookingsError("store_failed", `${what}: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
27
+ return data;
28
+ }
29
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
30
+ const sha256 = async (s) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
31
+ /** A new secret: 32 random bytes, base64url (43 characters). */
32
+ function newToken() {
33
+ const b = crypto.getRandomValues(new Uint8Array(32));
34
+ return btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
35
+ }
36
+ function text(v, what, max) {
37
+ if (typeof v !== "string" || !v.trim() || v.trim().length > max)
38
+ throw new BookingsError("bad_input", `${what} must be text, 1 to ${max} characters`);
39
+ return v.trim();
40
+ }
41
+ function instant(v, what) {
42
+ const d = v instanceof Date ? v : typeof v === "string" ? new Date(v) : new Date(NaN);
43
+ if (Number.isNaN(d.getTime()))
44
+ throw new BookingsError("bad_input", `${what} must be a time, such as a slot's start`);
45
+ return d;
46
+ }
47
+ const iso = (v) => new Date(v).toISOString();
48
+ /** A row with its times as ISO 8601 in UTC (Postgres writes +00:00). */
49
+ function norm(b) {
50
+ return { ...b, places: b.places ?? 1, member: b.member ?? null, starts_at: iso(b.starts_at), ends_at: iso(b.ends_at), created_at: iso(b.created_at), updated_at: iso(b.updated_at) };
51
+ }
52
+ /** The customer's details from the booking form, checked against what bookings.json asks. */
53
+ export function customerOf(v, ask = {}) {
54
+ const c = (v && typeof v === "object" ? v : {});
55
+ const name = typeof c.name === "string" ? c.name.trim().replace(/\s+/g, " ") : "";
56
+ if (!name || name.length > 100)
57
+ throw new BookingsError("bad_input", "name: 1 to 100 characters");
58
+ const email = typeof c.email === "string" ? c.email.trim() : "";
59
+ if (email.length > 254 || !EMAIL.test(email))
60
+ throw new BookingsError("bad_input", "email: an email address");
61
+ const phoneRule = ask?.phone ?? "no";
62
+ const rawPhone = typeof c.phone === "string" ? c.phone.trim() : "";
63
+ let phone = null;
64
+ if (phoneRule !== "no") {
65
+ if (rawPhone && !PHONE.test(rawPhone))
66
+ throw new BookingsError("bad_input", "phone: digits, spaces, + ( ) and -");
67
+ if (!rawPhone && phoneRule === "required")
68
+ throw new BookingsError("bad_input", "phone: required");
69
+ phone = rawPhone || null;
70
+ }
71
+ let note = null;
72
+ if (ask?.note && typeof c.note === "string" && c.note.trim()) {
73
+ if (c.note.trim().length > 1000)
74
+ throw new BookingsError("bad_input", "note: up to 1000 characters");
75
+ note = c.note.trim();
76
+ }
77
+ return { name, email, phone, note };
78
+ }
79
+ /** When the next reminder goes: the earliest reminder time after `after`, before the start. */
80
+ export function nextReminder(config, start, after) {
81
+ const times = (config.reminders ?? ["1d"]).map((d) => start.getTime() - durationMinutes(d) * 60_000).filter((t) => t > after.getTime() && t < start.getTime());
82
+ return times.length ? new Date(Math.min(...times)) : null;
83
+ }
84
+ /** The Gateway's Idempotency-Key for one email: the same for a retry, and inside workbench-email's [A-Za-z0-9._:-]. */
85
+ async function mailKey(key, email) {
86
+ return `bookings:${await sha256(`${key}\n${email.trim().toLowerCase()}`)}`;
87
+ }
88
+ export function createBookings(opts) {
89
+ const config = checkBookingConfig(opts.config);
90
+ const { db } = opts;
91
+ const now = opts.now ?? (() => new Date());
92
+ const tz = config.time_zone;
93
+ const locale = opts.locale ?? DEFAULT_LOCALE;
94
+ const say = words(opts.t);
95
+ const shared = (config.calendar ?? "shared") === "shared";
96
+ const feature = config.plans?.feature ?? "bookings";
97
+ const cancelMins = durationMinutes(config.cancel_until ?? "24h");
98
+ const report = opts.onEmailError ?? ((_e, what) => console.error(`workbench-bookings: the ${what} email didn't go`));
99
+ const business = async (account) => (opts.business ? await opts.business(account) : { name: account });
100
+ const settings = async (account) => (opts.settings ? ((await opts.settings(account)) ?? {}) : {});
101
+ const titleOf = (service) => config.services[service]?.title ?? service;
102
+ function times(service, start) {
103
+ const svc = serviceOf(config, service);
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, maxPlaces: svc.places ?? 1 };
106
+ }
107
+ async function ics(b, biz) {
108
+ const info = biz ?? (await business(b.account));
109
+ return bookingIcs(b, { summary: `${titleOf(b.service)} · ${info.name}`, ...(info.location ? { location: info.location } : {}) }, now());
110
+ }
111
+ async function mailCustomer(kind, b, token, n = 0) {
112
+ if (!opts.mailer)
113
+ return 0;
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, places: b.places };
116
+ const manage = token && opts.links?.manage && b.status !== "cancelled" && b.status !== "declined" ? opts.links.manage(token) : undefined;
117
+ const withFile = b.status === "confirmed" || kind === "cancelled";
118
+ const body = [
119
+ say("email.hello", p),
120
+ "",
121
+ say(`email.${kind}.body`, p),
122
+ ...(b.places > 1 ? [say("email.places", p)] : []),
123
+ ...(manage ? ["", say("email.manage", { url: manage })] : []),
124
+ ...(b.status === "confirmed" ? ["", say("email.calendar")] : []),
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
+ }
135
+ await opts.mailer.send({
136
+ to: b.customer.email,
137
+ subject: say(`email.${kind}.subject`, p),
138
+ text: body,
139
+ template: `bookings.${kind}`,
140
+ ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
141
+ ...(files.length ? { attachments: files } : {}),
142
+ idempotencyKey: await mailKey(`${kind}:${b.id}:${b.sequence}:${n}`, b.customer.email),
143
+ });
144
+ return 1;
145
+ }
146
+ async function mailOwners(kind, b) {
147
+ if (!opts.mailer || !opts.owners || (config.owner_email ?? "each") === "none")
148
+ return 0;
149
+ const owners = await opts.owners(b.account);
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 };
151
+ const url = opts.links?.bookings?.(b.account);
152
+ const body = [say("email.owner.body", p), ...(b.places > 1 ? [say("email.places", p)] : []), ...(url ? ["", say("email.owner.open", { url })] : []), "", say("email.owner.footer")].join("\n");
153
+ let sent = 0;
154
+ for (const o of owners) {
155
+ if (!o || typeof o.email !== "string" || !o.email.includes("@"))
156
+ continue;
157
+ await opts.mailer.send({
158
+ to: o.email,
159
+ subject: say(`email.owner.${kind}.subject`, p),
160
+ text: body,
161
+ template: `bookings.owner.${kind}`,
162
+ idempotencyKey: await mailKey(`owner:${kind}:${b.id}:${b.sequence}`, o.email),
163
+ });
164
+ sent++;
165
+ }
166
+ return sent;
167
+ }
168
+ /** Sends, and reports a failure without undoing the booking. */
169
+ async function quietly(what, send) {
170
+ try {
171
+ return await send();
172
+ }
173
+ catch (e) {
174
+ report(e, what);
175
+ return 0;
176
+ }
177
+ }
178
+ async function get(id) {
179
+ if (typeof id !== "string" || !UUID.test(id))
180
+ throw new BookingsError("bad_input", "id must be a booking's id");
181
+ const b = await call(db, "get", "bookings_get", { p_id: id });
182
+ return b ? norm(b) : null;
183
+ }
184
+ async function byToken(token) {
185
+ if (typeof token !== "string" || !TOKEN.test(token))
186
+ return null;
187
+ const b = await call(db, "byToken", "bookings_by_hash", { p_hash: await sha256(token) });
188
+ return b ? norm(b) : null;
189
+ }
190
+ const changeable = (b) => (b.status === "pending" || b.status === "confirmed") && now().getTime() <= Date.parse(b.starts_at) - cancelMins * 60_000;
191
+ async function open(token) {
192
+ const b = await byToken(token);
193
+ if (!b || (b.status !== "pending" && b.status !== "confirmed"))
194
+ throw new BookingsError("unknown_booking", "no such booking, or it has ended");
195
+ if (!changeable(b))
196
+ throw new BookingsError("too_late", `it starts within ${config.cancel_until ?? "24h"}: too late to change online`);
197
+ return b;
198
+ }
199
+ async function owned(id, account, from) {
200
+ const b = await get(id);
201
+ if (!b || b.account !== account || !from.includes(b.status))
202
+ throw new BookingsError("unknown_booking", "no such booking, or it has ended");
203
+ return b;
204
+ }
205
+ async function setStatus(b, status, from, reason) {
206
+ const at = now();
207
+ const next = status === "confirmed" ? nextReminder(config, new Date(b.starts_at), at) : null;
208
+ const r = await call(db, "status", "bookings_set_status", { p_id: b.id, p_status: status, p_from: [...from], p_reason: reason, p_next_reminder: next?.toISOString() ?? null, p_now: at.toISOString() });
209
+ if (!r)
210
+ throw new BookingsError("unknown_booking", "the booking changed meanwhile");
211
+ return norm(r);
212
+ }
213
+ const reasonOf = (r, fallback) => (r === undefined || r === "" ? fallback : text(r, "reason", 200));
214
+ return {
215
+ config,
216
+ get,
217
+ byToken,
218
+ changeable,
219
+ async slots(account, service, o = {}) {
220
+ text(account, "account", 200);
221
+ serviceOf(config, service);
222
+ const at = now();
223
+ const from = o.from ?? todayIn(tz, at);
224
+ if (!validDate(from))
225
+ throw new BookingsError("bad_input", "from must be a day, YYYY-MM-DD");
226
+ const days = o.days ?? 7;
227
+ const s = await settings(account);
228
+ const lo = localInstant(addDays(from, -1), "00:00", tz);
229
+ const hi = localInstant(addDays(from, Math.min(Math.max(days, 1), 62) + 1), "00:00", tz);
230
+ const busy = (await call(db, "slots", "bookings_busy", { p_account: account, p_from: lo.toISOString(), p_to: hi.toISOString() })) ?? [];
231
+ return openSlots(config, { service, from, days, busy, now: at, ...s });
232
+ },
233
+ async book(req) {
234
+ if (!req || typeof req !== "object")
235
+ throw new BookingsError("bad_input", "book takes { account, service, start, customer }");
236
+ const account = text(req.account, "account", 200);
237
+ const start = instant(req.start, "start");
238
+ const { end, blockEnd, capacity, maxPlaces } = times(req.service, start);
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);
244
+ const at = now();
245
+ if (opts.plans) {
246
+ const can = await opts.plans.can(account, feature);
247
+ if (!can.ok)
248
+ throw new BookingsError("not_allowed", `the account's plan doesn't include ${feature} (${can.reason ?? "not_on_plan"})`);
249
+ }
250
+ if (!offered(config, req.service, start, at, await settings(account)))
251
+ throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
252
+ const pending = (config.confirm ?? "instant") === "owner_approves";
253
+ const token = newToken();
254
+ const holdMins = durationMinutes(config.hold ?? "2d");
255
+ const hold = new Date(Math.min(at.getTime() + holdMins * 60_000, start.getTime()));
256
+ const r = await call(db, "book", "bookings_book", {
257
+ p_account: account,
258
+ p_service: req.service,
259
+ p_start: start.toISOString(),
260
+ p_end: end.toISOString(),
261
+ p_block_end: blockEnd.toISOString(),
262
+ p_capacity: capacity,
263
+ p_shared: shared,
264
+ p_places: places,
265
+ p_status: pending ? "pending" : "confirmed",
266
+ p_name: customer.name,
267
+ p_email: customer.email,
268
+ p_phone: customer.phone ?? null,
269
+ p_note: customer.note ?? null,
270
+ p_member: member,
271
+ p_hash: await sha256(token),
272
+ p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
273
+ p_hold_until: pending ? hold.toISOString() : null,
274
+ p_max: config.max_per_customer ?? 3,
275
+ p_now: at.toISOString(),
276
+ });
277
+ if (r && "refused" in r && r.refused) {
278
+ if (r.refused === "too_many")
279
+ throw new BookingsError("too_many", `this email already holds ${config.max_per_customer ?? 3} upcoming bookings`);
280
+ throw new BookingsError("taken", "someone booked that time first");
281
+ }
282
+ const booking = norm(r);
283
+ await quietly("confirmation", () => mailCustomer(pending ? "requested" : "booked", booking, token));
284
+ await quietly("owner's new booking", () => mailOwners(pending ? "request" : "new", booking));
285
+ return { booking, token };
286
+ },
287
+ async cancel(token) {
288
+ const b = await open(token);
289
+ const done = await setStatus(b, "cancelled", ["pending", "confirmed"], "by_customer");
290
+ await quietly("cancellation", () => mailCustomer("cancelled", done));
291
+ await quietly("owner's cancellation", () => mailOwners("cancelled", done));
292
+ return done;
293
+ },
294
+ async move(token, startAt) {
295
+ const b = await open(token);
296
+ const start = instant(startAt, "start");
297
+ const at = now();
298
+ if (start.getTime() === Date.parse(b.starts_at))
299
+ return b;
300
+ if (!offered(config, b.service, start, at, await settings(b.account)))
301
+ throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
302
+ const { end, blockEnd, capacity } = times(b.service, start);
303
+ const r = await call(db, "move", "bookings_move", {
304
+ p_id: b.id,
305
+ p_start: start.toISOString(),
306
+ p_end: end.toISOString(),
307
+ p_block_end: blockEnd.toISOString(),
308
+ p_capacity: capacity,
309
+ p_shared: shared,
310
+ p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
311
+ p_now: at.toISOString(),
312
+ });
313
+ if (!r)
314
+ throw new BookingsError("unknown_booking", "the booking ended meanwhile");
315
+ if ("refused" in r)
316
+ throw new BookingsError("taken", "someone booked that time first");
317
+ const moved = norm(r);
318
+ await quietly("move", () => mailCustomer("moved", moved, token));
319
+ await quietly("owner's move", () => mailOwners("moved", moved));
320
+ return moved;
321
+ },
322
+ async approve(id, account) {
323
+ const b = await owned(id, account, ["pending"]);
324
+ const done = await setStatus(b, "confirmed", ["pending"], "");
325
+ await quietly("confirmation", () => mailCustomer("confirmed", done));
326
+ return done;
327
+ },
328
+ async decline(id, account, reason) {
329
+ const b = await owned(id, account, ["pending"]);
330
+ const done = await setStatus(b, "declined", ["pending"], reasonOf(reason, "by_owner"));
331
+ await quietly("decline", () => mailCustomer("declined", done));
332
+ return done;
333
+ },
334
+ async cancelByOwner(id, account, reason) {
335
+ const b = await owned(id, account, ["pending", "confirmed"]);
336
+ const done = await setStatus(b, "cancelled", ["pending", "confirmed"], reasonOf(reason, "by_owner"));
337
+ await quietly("cancellation", () => mailCustomer("cancelled", done));
338
+ return done;
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
+ },
358
+ async list(account, o = {}) {
359
+ text(account, "account", 200);
360
+ const from = o.from ?? todayIn(tz, now());
361
+ if (!validDate(from))
362
+ throw new BookingsError("bad_input", "from must be a day, YYYY-MM-DD");
363
+ const days = o.days ?? 14;
364
+ if (!Number.isInteger(days) || days < 1 || days > 366)
365
+ throw new BookingsError("bad_input", "days must be a whole number from 1 to 366");
366
+ const rows = (await call(db, "list", "bookings_list", {
367
+ p_account: account,
368
+ p_from: localInstant(from, "00:00", tz).toISOString(),
369
+ p_to: localInstant(addDays(from, days), "00:00", tz).toISOString(),
370
+ p_open_only: o.open ?? false,
371
+ })) ?? [];
372
+ return rows.map(norm);
373
+ },
374
+ async icsFor(token) {
375
+ const b = await byToken(token);
376
+ return b ? await ics(b) : null;
377
+ },
378
+ async feedToken(account) {
379
+ const a = text(account, "account", 200);
380
+ const token = newToken();
381
+ await call(db, "feedToken", "bookings_feed_set", { p_account: a, p_hash: await sha256(token), p_now: now().toISOString() });
382
+ return token;
383
+ },
384
+ async feed(token) {
385
+ if (typeof token !== "string" || !TOKEN.test(token))
386
+ return null;
387
+ const account = await call(db, "feed", "bookings_feed_account", { p_hash: await sha256(token) });
388
+ if (!account)
389
+ return null;
390
+ const at = now();
391
+ const rows = (await call(db, "feed", "bookings_list", {
392
+ p_account: account,
393
+ p_from: new Date(at.getTime() - 30 * DAY_MS).toISOString(),
394
+ p_to: new Date(at.getTime() + ((config.ahead_days ?? 60) + 2) * DAY_MS).toISOString(),
395
+ p_open_only: true,
396
+ })) ?? [];
397
+ const biz = await business(account);
398
+ const names = config.feed?.names ?? false;
399
+ return feedIcs(biz.name, rows.map(norm), (b) => `${b.status === "pending" ? "? " : ""}${titleOf(b.service)}${names ? ` · ${b.customer.name}` : ""}`, at);
400
+ },
401
+ async tick() {
402
+ const at = now();
403
+ const claim = crypto.randomUUID();
404
+ const out = { reminded: 0, expired: 0, emailed: 0 };
405
+ const rows = (await call(db, "tick", "bookings_claim", {
406
+ p_claim: claim,
407
+ p_now: at.toISOString(),
408
+ p_until: new Date(at.getTime() + LEASE_MS).toISOString(),
409
+ p_limit: opts.batch ?? 200,
410
+ })) ?? [];
411
+ for (const row of rows) {
412
+ const b = norm(row);
413
+ if (b.status === "pending") {
414
+ const r = await call(db, "tick", "bookings_expire", { p_id: b.id, p_claim: claim, p_now: at.toISOString() });
415
+ if (!r)
416
+ continue;
417
+ out.expired++;
418
+ out.emailed += await quietly("decline", () => mailCustomer("declined", norm(r)));
419
+ continue;
420
+ }
421
+ const start = new Date(b.starts_at);
422
+ const sent = row.reminders_sent ?? 0;
423
+ if (start.getTime() <= at.getTime()) {
424
+ await call(db, "tick", "bookings_reminded", { p_id: b.id, p_claim: claim, p_sent: sent, p_next: null, p_now: at.toISOString() });
425
+ continue;
426
+ }
427
+ try {
428
+ out.emailed += await mailCustomer("reminder", b, undefined, sent + 1);
429
+ }
430
+ catch (e) {
431
+ // Try again next tick; the Idempotency-Key keeps a retry from sending twice.
432
+ report(e, "reminder");
433
+ await call(db, "tick", "bookings_release", { p_id: b.id, p_claim: claim });
434
+ continue;
435
+ }
436
+ const next = nextReminder(config, start, at);
437
+ if (await call(db, "tick", "bookings_reminded", { p_id: b.id, p_claim: claim, p_sent: sent + 1, p_next: next?.toISOString() ?? null, p_now: at.toISOString() }))
438
+ out.reminded++;
439
+ }
440
+ return out;
441
+ },
442
+ async cleanup() {
443
+ return await call(db, "cleanup", "bookings_cleanup", { p_now: now().toISOString(), p_days: config.retention_days ?? 180 });
444
+ },
445
+ };
446
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import type { BookingConfig } from "./types.ts";
3
+ export declare const BOOKINGS_FILE = "workbench/bookings.json";
4
+ export declare const BOOKINGS_MODULE = "src/bookings.generated.ts";
5
+ /** The generated module for a checked config. */
6
+ export declare function moduleText(c: BookingConfig): string;
7
+ /** Reads and checks the project's bookings.json. Throws naming every problem. */
8
+ export declare function readBookings(dir: string): BookingConfig;
9
+ /** Runs one command; returns the exit code. */
10
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
package/dist/cli.js ADDED
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-bookings init [dir]`, run in a project's folder: writes
3
+ // workbench/bookings.json (STARTER_BOOKINGS). A file already there is left as
4
+ // it is.
5
+ //
6
+ // `npx workbench-bookings generate [--check] [dir]` reads
7
+ // workbench/bookings.json, checks it, and writes src/bookings.generated.ts:
8
+ // BOOKING_CONFIG for createBookings. --check writes nothing and fails when the
9
+ // file is out of date or wrong.
10
+ //
11
+ // `npx workbench-bookings migration [dir]` writes bookingsMigration into
12
+ // supabase/migrations/<timestamp>_workbench_bookings.sql, and its down file
13
+ // into supabase/rollback/, unless a bookings migration is already there.
14
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
15
+ import { dirname, join, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { bookingProblems } from "./config.js";
18
+ import { bookingsMigration } from "./migration.js";
19
+ import { STARTER_BOOKINGS } from "./starters.js";
20
+ const USAGE = "usage: workbench-bookings init [dir]\n workbench-bookings generate [--check] [dir]\n workbench-bookings migration [dir]";
21
+ export const BOOKINGS_FILE = "workbench/bookings.json";
22
+ export const BOOKINGS_MODULE = "src/bookings.generated.ts";
23
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
24
+ /** The generated module for a checked config. */
25
+ export function moduleText(c) {
26
+ return [
27
+ `// Generated by \`npx workbench-bookings generate\` from ${BOOKINGS_FILE}. Don't edit: change the`,
28
+ "// JSON and generate again (Checks runs `npx workbench-bookings generate --check`).",
29
+ "",
30
+ 'import type { BookingConfig } from "@mccaskie-labs/workbench-bookings";',
31
+ "",
32
+ `export const BOOKING_CONFIG = ${JSON.stringify(c, null, 2)} as const satisfies BookingConfig;`,
33
+ "",
34
+ "export type BookingServiceName = keyof typeof BOOKING_CONFIG.services;",
35
+ "",
36
+ ].join("\n");
37
+ }
38
+ /** Reads and checks the project's bookings.json. Throws naming every problem. */
39
+ export function readBookings(dir) {
40
+ const path = join(dir, BOOKINGS_FILE);
41
+ if (!existsSync(path))
42
+ throw new Error(`${BOOKINGS_FILE} is missing: run npx workbench-bookings init, then answer the bookings questions (capabilities/bookings.json, offer)`);
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(read(path));
46
+ }
47
+ catch (e) {
48
+ throw new Error(`${BOOKINGS_FILE}: not valid JSON (${e.message})`);
49
+ }
50
+ const problems = bookingProblems(parsed, BOOKINGS_FILE);
51
+ if (problems.length)
52
+ throw new Error(problems.join("\n"));
53
+ return parsed;
54
+ }
55
+ const migrationStamp = (at) => at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
56
+ /** Runs one command; returns the exit code. */
57
+ export function run(argv, log = console.log, err = console.error) {
58
+ const [command, ...args] = argv;
59
+ const check = args.includes("--check");
60
+ const rest = args.filter((a) => a !== "--check");
61
+ const bad = rest.find((a) => a.startsWith("--"));
62
+ if (!["init", "generate", "migration"].includes(command ?? "") || bad || (check && command !== "generate") || rest.length > 1) {
63
+ err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
64
+ return 2;
65
+ }
66
+ const dir = resolve(rest[0] ?? ".");
67
+ try {
68
+ if (command === "init") {
69
+ const at = join(dir, BOOKINGS_FILE);
70
+ if (existsSync(at))
71
+ log(`${BOOKINGS_FILE} is already there; left as it is`);
72
+ else {
73
+ mkdirSync(dirname(at), { recursive: true });
74
+ writeFileSync(at, `${JSON.stringify(STARTER_BOOKINGS, null, 2)}\n`);
75
+ log(`wrote ${BOOKINGS_FILE}`);
76
+ }
77
+ log("Now set time_zone from the country pack, the services and hours from the client's answers, and run `npx workbench-bookings generate`.");
78
+ return 0;
79
+ }
80
+ if (command === "migration") {
81
+ const folder = join(dir, "supabase/migrations");
82
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_bookings.sql"))) {
83
+ log("supabase/migrations already has the bookings migration; nothing written");
84
+ return 0;
85
+ }
86
+ const name = `${migrationStamp(new Date())}_workbench_bookings.sql`;
87
+ mkdirSync(folder, { recursive: true });
88
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
89
+ writeFileSync(join(folder, name), `-- workbench-bookings: bookings calendar (docs/capabilities/13-bookings.md)\n${bookingsMigration.up}`);
90
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${bookingsMigration.down}`);
91
+ log(`wrote supabase/migrations/${name} and its down file`);
92
+ return 0;
93
+ }
94
+ const config = readBookings(dir);
95
+ const text = moduleText(config);
96
+ const out = join(dir, BOOKINGS_MODULE);
97
+ if (check) {
98
+ if (!existsSync(out) || read(out) !== text) {
99
+ err(`${BOOKINGS_MODULE} is out of date: run npx workbench-bookings generate`);
100
+ return 1;
101
+ }
102
+ log(`${BOOKINGS_MODULE} is up to date`);
103
+ return 0;
104
+ }
105
+ mkdirSync(dirname(out), { recursive: true });
106
+ writeFileSync(out, text);
107
+ const services = Object.keys(config.services);
108
+ log(`wrote ${BOOKINGS_MODULE}: ${services.length} service${services.length === 1 ? "" : "s"} (${services.join(", ")})`);
109
+ return 0;
110
+ }
111
+ catch (e) {
112
+ err(e.message);
113
+ return 1;
114
+ }
115
+ }
116
+ const isMain = (() => {
117
+ try {
118
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
119
+ }
120
+ catch {
121
+ return false;
122
+ }
123
+ })();
124
+ if (isMain)
125
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,9 @@
1
+ import { type BookingConfig, type BookingService, type WeekHours } from "./types.ts";
2
+ /** The most reminders a booking can have. */
3
+ export declare const MAX_REMINDERS = 3;
4
+ /** Every problem with a bookings.json, or none. */
5
+ export declare function bookingProblems(value: unknown, where?: string): string[];
6
+ /** Checks workbench/bookings.json and returns it typed, or throws bad_config naming every problem. */
7
+ export declare function checkBookingConfig(value: unknown): BookingConfig;
8
+ /** A service's opening hours: its own, else the business's (or the account's, from settings). */
9
+ export declare function hoursOf(service: BookingService, hours: WeekHours): WeekHours;