@mccaskie-labs/workbench-bookings 0.0.0-stage → 0.1.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 +5 -0
- package/README.md +67 -2
- package/dist/bookings.d.ts +144 -0
- package/dist/bookings.js +412 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +125 -0
- package/dist/config.d.ts +9 -0
- package/dist/config.js +163 -0
- package/dist/errors.d.ts +25 -0
- package/dist/errors.js +10 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.js +24 -0
- package/dist/ical.d.ts +13 -0
- package/dist/ical.js +67 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +20 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +416 -0
- package/dist/slots.d.ts +24 -0
- package/dist/slots.js +87 -0
- package/dist/starters.d.ts +31 -0
- package/dist/starters.js +29 -0
- package/dist/styles.d.ts +34 -0
- package/dist/styles.js +94 -0
- package/dist/time.d.ts +15 -0
- package/dist/time.js +82 -0
- package/dist/types.d.ts +122 -0
- package/dist/types.js +4 -0
- package/dist/ui.d.ts +113 -0
- package/dist/ui.js +178 -0
- package/dist/words.d.ts +4 -0
- package/dist/words.js +144 -0
- package/package.json +48 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @mccaskie-labs/workbench-bookings
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- 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
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mccaskie-labs/workbench-bookings
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A bookings calendar for apps built on Workbench, a private platform: customers pick a free time on the app's booking page, give their name and email, and get a confirmation with a calendar file, reminders before it starts, and a private link to move or cancel it. The owner gets an email for each booking, a list in the app, and a feed for their own calendar. Spec: `docs/capabilities/13-bookings.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @mccaskie-labs/workbench-bookings
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
No AI. Bookings live in the app's own database; email goes through `workbench-email` and the Gateway.
|
|
10
|
+
|
|
11
|
+
## Set up
|
|
12
|
+
|
|
13
|
+
1. `npx workbench-bookings init` writes `workbench/bookings.json`: one 30-minute appointment, weekdays 9 to 5 in Sydney, confirmed at once, a reminder the day before, changes online until 24 hours before. Edit it; the client questions in `capabilities/bookings.json` say how. Set `time_zone` from the country pack and put its public holidays in `closed`.
|
|
14
|
+
2. `npx workbench-bookings generate` checks it and writes `src/bookings.generated.ts` (`BOOKING_CONFIG`). Checks can run `npx workbench-bookings generate --check`.
|
|
15
|
+
3. `npx workbench-bookings migration` writes `bookingsMigration` and its down file. It creates functions, so Control asks for approval even on staging.
|
|
16
|
+
4. Add `"*/15 * * * *"` to `triggers.crons` in `wrangler.jsonc`, and `bookings` to a plan's features in `workbench/plans.json` if the app has plans.
|
|
17
|
+
|
|
18
|
+
## Use
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createBookings } from '@mccaskie-labs/workbench-bookings'
|
|
22
|
+
import { BOOKING_CONFIG } from './bookings.generated'
|
|
23
|
+
|
|
24
|
+
const bookings = createBookings({
|
|
25
|
+
db: serviceClient, mailer, plans, config: BOOKING_CONFIG,
|
|
26
|
+
business: async (account) => ({ name: 'Harbour Physio', location: '1 The Corso, Manly' }),
|
|
27
|
+
owners: async (account) => [{ email: await ownerEmail(account) }],
|
|
28
|
+
links: { manage: (token) => `https://${host}/b/${token}`, bookings: () => `https://${host}/app/bookings` },
|
|
29
|
+
// Optional: hours and closed days the owner keeps in the app.
|
|
30
|
+
settings: async (account) => ({ closed: await leaveDays(account) }),
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
const days = await bookings.slots(account, 'appointment') // free times, a week from today
|
|
34
|
+
const { booking, token } = await bookings.book({ account, service: 'appointment', start: days[0].slots[0].start, customer: { name, email } })
|
|
35
|
+
await bookings.cancel(token) // or move(token, start): from the customer's link
|
|
36
|
+
|
|
37
|
+
// scheduled(), every 15 minutes, and cleanup() once a day:
|
|
38
|
+
ctx.waitUntil(bookings.tick())
|
|
39
|
+
```
|
|
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.
|
|
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
|
+
- 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
|
+
- 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
|
+
- 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
|
+
- 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
|
+
|
|
48
|
+
## The pages
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderSlotPicker } from '@mccaskie-labs/workbench-bookings'
|
|
52
|
+
|
|
53
|
+
const tz = BOOKING_CONFIG.time_zone
|
|
54
|
+
renderSlotPicker(days, { endpoint: '/book/details', service: 'appointment', title: 'Appointment', timeZone: tz, more: '/book?from=2026-12-07' })
|
|
55
|
+
renderBookingForm({ endpoint: '/book', service, title, start, timeZone: tz, ask: BOOKING_CONFIG.ask, confirm: BOOKING_CONFIG.confirm })
|
|
56
|
+
const r = await bookingAction(bookings, fields, { account }) // after Turnstile; r.body.text and r.body.field when it didn't go through
|
|
57
|
+
renderBookingDone(r.body.booking, { title, timeZone: tz, manage: `/b/${r.body.token}`, ics: `/b/${r.body.token}.ics` })
|
|
58
|
+
renderBookingManage(booking, { endpoint: '/book', token, title, timeZone: tz, changeable: bookings.changeable(booking), move: `/b/${token}/move` })
|
|
59
|
+
// Behind the owner's sign-in:
|
|
60
|
+
renderBookingList(await bookings.list(account), { endpoint: '/app/bookings', timeZone: tz, titleOf: (s) => BOOKING_CONFIG.services[s].title })
|
|
61
|
+
await ownerBookingAction(bookings, fields, account) // approve, decline or cancel
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
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
|
+
|
|
66
|
+
## Data
|
|
67
|
+
|
|
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.
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { type Words } from "./format.ts";
|
|
2
|
+
import type { Booking, BookingConfig, Customer, SlotDay, TickResult, WeekHours } from "./types.ts";
|
|
3
|
+
type DbError = {
|
|
4
|
+
message?: string;
|
|
5
|
+
code?: string;
|
|
6
|
+
details?: string;
|
|
7
|
+
} | null;
|
|
8
|
+
/** The part of a Supabase client bookings need. Any supabase-js client fits; use the service client. */
|
|
9
|
+
export interface BookingsClient {
|
|
10
|
+
rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
|
|
11
|
+
data: unknown;
|
|
12
|
+
error: DbError;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
15
|
+
/** The part of workbench-email's createMailer(...) bookings use. */
|
|
16
|
+
export interface BookingsMailer {
|
|
17
|
+
send(mail: {
|
|
18
|
+
to: string | string[];
|
|
19
|
+
subject: string;
|
|
20
|
+
text: string;
|
|
21
|
+
template: string;
|
|
22
|
+
replyTo?: string;
|
|
23
|
+
attachments?: {
|
|
24
|
+
filename: string;
|
|
25
|
+
mimeType: string;
|
|
26
|
+
bytes: Uint8Array;
|
|
27
|
+
}[];
|
|
28
|
+
idempotencyKey?: string;
|
|
29
|
+
}): Promise<unknown>;
|
|
30
|
+
}
|
|
31
|
+
/** The part of workbench-plans' createPlans(...) bookings use. */
|
|
32
|
+
export interface BookingsPlans {
|
|
33
|
+
can(account: string, feature: string): Promise<{
|
|
34
|
+
ok: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
}>;
|
|
37
|
+
}
|
|
38
|
+
/** What the emails and calendar files say about the business. */
|
|
39
|
+
export interface Business {
|
|
40
|
+
/** "Harbour Physio". */
|
|
41
|
+
name: string;
|
|
42
|
+
/** Where the booking happens, for the calendar file. */
|
|
43
|
+
location?: string;
|
|
44
|
+
/** Replies to the customer's emails go here. */
|
|
45
|
+
replyTo?: string;
|
|
46
|
+
}
|
|
47
|
+
/** The account's own hours and closed days, when the app keeps them in its database (settings on the owner's page). */
|
|
48
|
+
export interface AccountSettings {
|
|
49
|
+
hours?: WeekHours;
|
|
50
|
+
closed?: readonly string[];
|
|
51
|
+
}
|
|
52
|
+
export interface BookingsOptions {
|
|
53
|
+
/** The service client. */
|
|
54
|
+
db: BookingsClient;
|
|
55
|
+
/** workbench/bookings.json, or BOOKING_CONFIG from src/bookings.generated.ts. Checked here. */
|
|
56
|
+
config: unknown;
|
|
57
|
+
/** createMailer(...). Without it no email goes; the pages still work. */
|
|
58
|
+
mailer?: BookingsMailer;
|
|
59
|
+
/** createPlans(...): taking a booking needs the account's plan to have the `bookings` feature (plans.feature). */
|
|
60
|
+
plans?: BookingsPlans;
|
|
61
|
+
/** The business's name for emails and calendar files. Default: the account. */
|
|
62
|
+
business?: (account: string) => Promise<Business>;
|
|
63
|
+
/** Who gets the owner's emails. Needed for them. */
|
|
64
|
+
owners?: (account: string) => Promise<readonly {
|
|
65
|
+
email: string;
|
|
66
|
+
}[]>;
|
|
67
|
+
/** The customer's private page for a booking, from its secret (the manage link), and the owner's bookings page. */
|
|
68
|
+
links?: {
|
|
69
|
+
manage?: (token: string) => string;
|
|
70
|
+
bookings?: (account: string) => string;
|
|
71
|
+
};
|
|
72
|
+
/** The account's own hours and closed days (public holidays from the country pack, leave). */
|
|
73
|
+
settings?: (account: string) => Promise<AccountSettings | null>;
|
|
74
|
+
/** For dates and times in emails. Default en-AU. */
|
|
75
|
+
locale?: string;
|
|
76
|
+
/** The project's strings lookup, for the emails' words. */
|
|
77
|
+
t?: Words;
|
|
78
|
+
/** An email that failed: the booking stands. Default: console.error with no address in it. */
|
|
79
|
+
onEmailError?: (error: unknown, what: string) => void;
|
|
80
|
+
/** How many bookings one tick handles at most. Default 200. */
|
|
81
|
+
batch?: number;
|
|
82
|
+
/** The clock, for tests. */
|
|
83
|
+
now?: () => Date;
|
|
84
|
+
}
|
|
85
|
+
export interface BookRequest {
|
|
86
|
+
account: string;
|
|
87
|
+
service: string;
|
|
88
|
+
/** A slot's start, as slots() gave it. */
|
|
89
|
+
start: string | Date;
|
|
90
|
+
customer: Customer;
|
|
91
|
+
}
|
|
92
|
+
export interface Bookings {
|
|
93
|
+
/** The free times for a service, day by day, from `from` (default today) for `days` (default 7). */
|
|
94
|
+
slots(account: string, service: string, opts?: {
|
|
95
|
+
from?: string;
|
|
96
|
+
days?: number;
|
|
97
|
+
}): Promise<SlotDay[]>;
|
|
98
|
+
/** Books a free time. Answers the booking and the secret for its manage link (kept nowhere else: put it in the link, never in a log). */
|
|
99
|
+
book(req: BookRequest): Promise<{
|
|
100
|
+
booking: Booking;
|
|
101
|
+
token: string;
|
|
102
|
+
}>;
|
|
103
|
+
/** One booking, or null. */
|
|
104
|
+
get(id: string): Promise<Booking | null>;
|
|
105
|
+
/** The booking a manage link's secret belongs to, or null. */
|
|
106
|
+
byToken(token: string): Promise<Booking | null>;
|
|
107
|
+
/** Whether the customer can still change or cancel it online (cancel_until). */
|
|
108
|
+
changeable(b: Booking): boolean;
|
|
109
|
+
/** The customer cancels from their manage link. */
|
|
110
|
+
cancel(token: string): Promise<Booking>;
|
|
111
|
+
/** The customer moves it to another free time from their manage link. */
|
|
112
|
+
move(token: string, start: string | Date): Promise<Booking>;
|
|
113
|
+
/** The owner accepts a request (confirm: owner_approves). */
|
|
114
|
+
approve(id: string, account: string): Promise<Booking>;
|
|
115
|
+
/** The owner declines a request. */
|
|
116
|
+
decline(id: string, account: string, reason?: string): Promise<Booking>;
|
|
117
|
+
/** The owner cancels a booking. */
|
|
118
|
+
cancelByOwner(id: string, account: string, reason?: string): Promise<Booking>;
|
|
119
|
+
/** The account's bookings from `from` (default today) for `days` (default 14), every status unless open. */
|
|
120
|
+
list(account: string, opts?: {
|
|
121
|
+
from?: string;
|
|
122
|
+
days?: number;
|
|
123
|
+
open?: boolean;
|
|
124
|
+
}): Promise<Booking[]>;
|
|
125
|
+
/** The booking as a calendar file, for "Add to my calendar" (from its manage link's secret). */
|
|
126
|
+
icsFor(token: string): Promise<string | null>;
|
|
127
|
+
/** Makes the account a new calendar feed secret; the old feed address stops working. */
|
|
128
|
+
feedToken(account: string): Promise<string>;
|
|
129
|
+
/** The calendar feed a feed secret belongs to, or null. */
|
|
130
|
+
feed(token: string): Promise<string | null>;
|
|
131
|
+
/** The cron's scan, every 15 minutes: reminders, and requests nobody answered. Safe to run twice at once. */
|
|
132
|
+
tick(): Promise<TickResult>;
|
|
133
|
+
/** The daily clean-up: bookings retention_days after they end. */
|
|
134
|
+
cleanup(): Promise<{
|
|
135
|
+
bookings: number;
|
|
136
|
+
}>;
|
|
137
|
+
readonly config: BookingConfig;
|
|
138
|
+
}
|
|
139
|
+
/** The customer's details from the booking form, checked against what bookings.json asks. */
|
|
140
|
+
export declare function customerOf(v: unknown, ask?: BookingConfig["ask"]): Customer;
|
|
141
|
+
/** When the next reminder goes: the earliest reminder time after `after`, before the start. */
|
|
142
|
+
export declare function nextReminder(config: BookingConfig, start: Date, after: Date): Date | null;
|
|
143
|
+
export declare function createBookings(opts: BookingsOptions): Bookings;
|
|
144
|
+
export {};
|
package/dist/bookings.js
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
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, 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 };
|
|
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 };
|
|
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
|
+
...(manage ? ["", say("email.manage", { url: manage })] : []),
|
|
123
|
+
...(b.status === "confirmed" ? ["", say("email.calendar")] : []),
|
|
124
|
+
].join("\n");
|
|
125
|
+
await opts.mailer.send({
|
|
126
|
+
to: b.customer.email,
|
|
127
|
+
subject: say(`email.${kind}.subject`, p),
|
|
128
|
+
text: body,
|
|
129
|
+
template: `bookings.${kind}`,
|
|
130
|
+
...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
|
|
131
|
+
...(withFile ? { attachments: [{ filename: "booking.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(await ics(b, biz)) }] } : {}),
|
|
132
|
+
idempotencyKey: await mailKey(`${kind}:${b.id}:${b.sequence}:${n}`, b.customer.email),
|
|
133
|
+
});
|
|
134
|
+
return 1;
|
|
135
|
+
}
|
|
136
|
+
async function mailOwners(kind, b) {
|
|
137
|
+
if (!opts.mailer || !opts.owners || (config.owner_email ?? "each") === "none")
|
|
138
|
+
return 0;
|
|
139
|
+
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 };
|
|
141
|
+
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");
|
|
143
|
+
let sent = 0;
|
|
144
|
+
for (const o of owners) {
|
|
145
|
+
if (!o || typeof o.email !== "string" || !o.email.includes("@"))
|
|
146
|
+
continue;
|
|
147
|
+
await opts.mailer.send({
|
|
148
|
+
to: o.email,
|
|
149
|
+
subject: say(`email.owner.${kind}.subject`, p),
|
|
150
|
+
text: body,
|
|
151
|
+
template: `bookings.owner.${kind}`,
|
|
152
|
+
idempotencyKey: await mailKey(`owner:${kind}:${b.id}:${b.sequence}`, o.email),
|
|
153
|
+
});
|
|
154
|
+
sent++;
|
|
155
|
+
}
|
|
156
|
+
return sent;
|
|
157
|
+
}
|
|
158
|
+
/** Sends, and reports a failure without undoing the booking. */
|
|
159
|
+
async function quietly(what, send) {
|
|
160
|
+
try {
|
|
161
|
+
return await send();
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
report(e, what);
|
|
165
|
+
return 0;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function get(id) {
|
|
169
|
+
if (typeof id !== "string" || !UUID.test(id))
|
|
170
|
+
throw new BookingsError("bad_input", "id must be a booking's id");
|
|
171
|
+
const b = await call(db, "get", "bookings_get", { p_id: id });
|
|
172
|
+
return b ? norm(b) : null;
|
|
173
|
+
}
|
|
174
|
+
async function byToken(token) {
|
|
175
|
+
if (typeof token !== "string" || !TOKEN.test(token))
|
|
176
|
+
return null;
|
|
177
|
+
const b = await call(db, "byToken", "bookings_by_hash", { p_hash: await sha256(token) });
|
|
178
|
+
return b ? norm(b) : null;
|
|
179
|
+
}
|
|
180
|
+
const changeable = (b) => (b.status === "pending" || b.status === "confirmed") && now().getTime() <= Date.parse(b.starts_at) - cancelMins * 60_000;
|
|
181
|
+
async function open(token) {
|
|
182
|
+
const b = await byToken(token);
|
|
183
|
+
if (!b || (b.status !== "pending" && b.status !== "confirmed"))
|
|
184
|
+
throw new BookingsError("unknown_booking", "no such booking, or it has ended");
|
|
185
|
+
if (!changeable(b))
|
|
186
|
+
throw new BookingsError("too_late", `it starts within ${config.cancel_until ?? "24h"}: too late to change online`);
|
|
187
|
+
return b;
|
|
188
|
+
}
|
|
189
|
+
async function owned(id, account, from) {
|
|
190
|
+
const b = await get(id);
|
|
191
|
+
if (!b || b.account !== account || !from.includes(b.status))
|
|
192
|
+
throw new BookingsError("unknown_booking", "no such booking, or it has ended");
|
|
193
|
+
return b;
|
|
194
|
+
}
|
|
195
|
+
async function setStatus(b, status, from, reason) {
|
|
196
|
+
const at = now();
|
|
197
|
+
const next = status === "confirmed" ? nextReminder(config, new Date(b.starts_at), at) : null;
|
|
198
|
+
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() });
|
|
199
|
+
if (!r)
|
|
200
|
+
throw new BookingsError("unknown_booking", "the booking changed meanwhile");
|
|
201
|
+
return norm(r);
|
|
202
|
+
}
|
|
203
|
+
const reasonOf = (r, fallback) => (r === undefined || r === "" ? fallback : text(r, "reason", 200));
|
|
204
|
+
return {
|
|
205
|
+
config,
|
|
206
|
+
get,
|
|
207
|
+
byToken,
|
|
208
|
+
changeable,
|
|
209
|
+
async slots(account, service, o = {}) {
|
|
210
|
+
text(account, "account", 200);
|
|
211
|
+
serviceOf(config, service);
|
|
212
|
+
const at = now();
|
|
213
|
+
const from = o.from ?? todayIn(tz, at);
|
|
214
|
+
if (!validDate(from))
|
|
215
|
+
throw new BookingsError("bad_input", "from must be a day, YYYY-MM-DD");
|
|
216
|
+
const days = o.days ?? 7;
|
|
217
|
+
const s = await settings(account);
|
|
218
|
+
const lo = localInstant(addDays(from, -1), "00:00", tz);
|
|
219
|
+
const hi = localInstant(addDays(from, Math.min(Math.max(days, 1), 62) + 1), "00:00", tz);
|
|
220
|
+
const busy = (await call(db, "slots", "bookings_busy", { p_account: account, p_from: lo.toISOString(), p_to: hi.toISOString() })) ?? [];
|
|
221
|
+
return openSlots(config, { service, from, days, busy, now: at, ...s });
|
|
222
|
+
},
|
|
223
|
+
async book(req) {
|
|
224
|
+
if (!req || typeof req !== "object")
|
|
225
|
+
throw new BookingsError("bad_input", "book takes { account, service, start, customer }");
|
|
226
|
+
const account = text(req.account, "account", 200);
|
|
227
|
+
const start = instant(req.start, "start");
|
|
228
|
+
const { end, blockEnd, capacity } = times(req.service, start);
|
|
229
|
+
const customer = customerOf(req.customer, config.ask);
|
|
230
|
+
const at = now();
|
|
231
|
+
if (opts.plans) {
|
|
232
|
+
const can = await opts.plans.can(account, feature);
|
|
233
|
+
if (!can.ok)
|
|
234
|
+
throw new BookingsError("not_allowed", `the account's plan doesn't include ${feature} (${can.reason ?? "not_on_plan"})`);
|
|
235
|
+
}
|
|
236
|
+
if (!offered(config, req.service, start, at, await settings(account)))
|
|
237
|
+
throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
|
|
238
|
+
const pending = (config.confirm ?? "instant") === "owner_approves";
|
|
239
|
+
const token = newToken();
|
|
240
|
+
const holdMins = durationMinutes(config.hold ?? "2d");
|
|
241
|
+
const hold = new Date(Math.min(at.getTime() + holdMins * 60_000, start.getTime()));
|
|
242
|
+
const r = await call(db, "book", "bookings_book", {
|
|
243
|
+
p_account: account,
|
|
244
|
+
p_service: req.service,
|
|
245
|
+
p_start: start.toISOString(),
|
|
246
|
+
p_end: end.toISOString(),
|
|
247
|
+
p_block_end: blockEnd.toISOString(),
|
|
248
|
+
p_capacity: capacity,
|
|
249
|
+
p_shared: shared,
|
|
250
|
+
p_status: pending ? "pending" : "confirmed",
|
|
251
|
+
p_name: customer.name,
|
|
252
|
+
p_email: customer.email,
|
|
253
|
+
p_phone: customer.phone ?? null,
|
|
254
|
+
p_note: customer.note ?? null,
|
|
255
|
+
p_hash: await sha256(token),
|
|
256
|
+
p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
|
|
257
|
+
p_hold_until: pending ? hold.toISOString() : null,
|
|
258
|
+
p_max: config.max_per_customer ?? 3,
|
|
259
|
+
p_now: at.toISOString(),
|
|
260
|
+
});
|
|
261
|
+
if (r && "refused" in r && r.refused) {
|
|
262
|
+
if (r.refused === "too_many")
|
|
263
|
+
throw new BookingsError("too_many", `this email already holds ${config.max_per_customer ?? 3} upcoming bookings`);
|
|
264
|
+
throw new BookingsError("taken", "someone booked that time first");
|
|
265
|
+
}
|
|
266
|
+
const booking = norm(r);
|
|
267
|
+
await quietly("confirmation", () => mailCustomer(pending ? "requested" : "booked", booking, token));
|
|
268
|
+
await quietly("owner's new booking", () => mailOwners(pending ? "request" : "new", booking));
|
|
269
|
+
return { booking, token };
|
|
270
|
+
},
|
|
271
|
+
async cancel(token) {
|
|
272
|
+
const b = await open(token);
|
|
273
|
+
const done = await setStatus(b, "cancelled", ["pending", "confirmed"], "by_customer");
|
|
274
|
+
await quietly("cancellation", () => mailCustomer("cancelled", done));
|
|
275
|
+
await quietly("owner's cancellation", () => mailOwners("cancelled", done));
|
|
276
|
+
return done;
|
|
277
|
+
},
|
|
278
|
+
async move(token, startAt) {
|
|
279
|
+
const b = await open(token);
|
|
280
|
+
const start = instant(startAt, "start");
|
|
281
|
+
const at = now();
|
|
282
|
+
if (start.getTime() === Date.parse(b.starts_at))
|
|
283
|
+
return b;
|
|
284
|
+
if (!offered(config, b.service, start, at, await settings(b.account)))
|
|
285
|
+
throw new BookingsError("not_open", "that time isn't offered: outside the hours, closed, too soon or too far ahead");
|
|
286
|
+
const { end, blockEnd, capacity } = times(b.service, start);
|
|
287
|
+
const r = await call(db, "move", "bookings_move", {
|
|
288
|
+
p_id: b.id,
|
|
289
|
+
p_start: start.toISOString(),
|
|
290
|
+
p_end: end.toISOString(),
|
|
291
|
+
p_block_end: blockEnd.toISOString(),
|
|
292
|
+
p_capacity: capacity,
|
|
293
|
+
p_shared: shared,
|
|
294
|
+
p_next_reminder: nextReminder(config, start, at)?.toISOString() ?? null,
|
|
295
|
+
p_now: at.toISOString(),
|
|
296
|
+
});
|
|
297
|
+
if (!r)
|
|
298
|
+
throw new BookingsError("unknown_booking", "the booking ended meanwhile");
|
|
299
|
+
if ("refused" in r)
|
|
300
|
+
throw new BookingsError("taken", "someone booked that time first");
|
|
301
|
+
const moved = norm(r);
|
|
302
|
+
await quietly("move", () => mailCustomer("moved", moved, token));
|
|
303
|
+
await quietly("owner's move", () => mailOwners("moved", moved));
|
|
304
|
+
return moved;
|
|
305
|
+
},
|
|
306
|
+
async approve(id, account) {
|
|
307
|
+
const b = await owned(id, account, ["pending"]);
|
|
308
|
+
const done = await setStatus(b, "confirmed", ["pending"], "");
|
|
309
|
+
await quietly("confirmation", () => mailCustomer("confirmed", done));
|
|
310
|
+
return done;
|
|
311
|
+
},
|
|
312
|
+
async decline(id, account, reason) {
|
|
313
|
+
const b = await owned(id, account, ["pending"]);
|
|
314
|
+
const done = await setStatus(b, "declined", ["pending"], reasonOf(reason, "by_owner"));
|
|
315
|
+
await quietly("decline", () => mailCustomer("declined", done));
|
|
316
|
+
return done;
|
|
317
|
+
},
|
|
318
|
+
async cancelByOwner(id, account, reason) {
|
|
319
|
+
const b = await owned(id, account, ["pending", "confirmed"]);
|
|
320
|
+
const done = await setStatus(b, "cancelled", ["pending", "confirmed"], reasonOf(reason, "by_owner"));
|
|
321
|
+
await quietly("cancellation", () => mailCustomer("cancelled", done));
|
|
322
|
+
return done;
|
|
323
|
+
},
|
|
324
|
+
async list(account, o = {}) {
|
|
325
|
+
text(account, "account", 200);
|
|
326
|
+
const from = o.from ?? todayIn(tz, now());
|
|
327
|
+
if (!validDate(from))
|
|
328
|
+
throw new BookingsError("bad_input", "from must be a day, YYYY-MM-DD");
|
|
329
|
+
const days = o.days ?? 14;
|
|
330
|
+
if (!Number.isInteger(days) || days < 1 || days > 366)
|
|
331
|
+
throw new BookingsError("bad_input", "days must be a whole number from 1 to 366");
|
|
332
|
+
const rows = (await call(db, "list", "bookings_list", {
|
|
333
|
+
p_account: account,
|
|
334
|
+
p_from: localInstant(from, "00:00", tz).toISOString(),
|
|
335
|
+
p_to: localInstant(addDays(from, days), "00:00", tz).toISOString(),
|
|
336
|
+
p_open_only: o.open ?? false,
|
|
337
|
+
})) ?? [];
|
|
338
|
+
return rows.map(norm);
|
|
339
|
+
},
|
|
340
|
+
async icsFor(token) {
|
|
341
|
+
const b = await byToken(token);
|
|
342
|
+
return b ? await ics(b) : null;
|
|
343
|
+
},
|
|
344
|
+
async feedToken(account) {
|
|
345
|
+
const a = text(account, "account", 200);
|
|
346
|
+
const token = newToken();
|
|
347
|
+
await call(db, "feedToken", "bookings_feed_set", { p_account: a, p_hash: await sha256(token), p_now: now().toISOString() });
|
|
348
|
+
return token;
|
|
349
|
+
},
|
|
350
|
+
async feed(token) {
|
|
351
|
+
if (typeof token !== "string" || !TOKEN.test(token))
|
|
352
|
+
return null;
|
|
353
|
+
const account = await call(db, "feed", "bookings_feed_account", { p_hash: await sha256(token) });
|
|
354
|
+
if (!account)
|
|
355
|
+
return null;
|
|
356
|
+
const at = now();
|
|
357
|
+
const rows = (await call(db, "feed", "bookings_list", {
|
|
358
|
+
p_account: account,
|
|
359
|
+
p_from: new Date(at.getTime() - 30 * DAY_MS).toISOString(),
|
|
360
|
+
p_to: new Date(at.getTime() + ((config.ahead_days ?? 60) + 2) * DAY_MS).toISOString(),
|
|
361
|
+
p_open_only: true,
|
|
362
|
+
})) ?? [];
|
|
363
|
+
const biz = await business(account);
|
|
364
|
+
const names = config.feed?.names ?? false;
|
|
365
|
+
return feedIcs(biz.name, rows.map(norm), (b) => `${b.status === "pending" ? "? " : ""}${titleOf(b.service)}${names ? ` · ${b.customer.name}` : ""}`, at);
|
|
366
|
+
},
|
|
367
|
+
async tick() {
|
|
368
|
+
const at = now();
|
|
369
|
+
const claim = crypto.randomUUID();
|
|
370
|
+
const out = { reminded: 0, expired: 0, emailed: 0 };
|
|
371
|
+
const rows = (await call(db, "tick", "bookings_claim", {
|
|
372
|
+
p_claim: claim,
|
|
373
|
+
p_now: at.toISOString(),
|
|
374
|
+
p_until: new Date(at.getTime() + LEASE_MS).toISOString(),
|
|
375
|
+
p_limit: opts.batch ?? 200,
|
|
376
|
+
})) ?? [];
|
|
377
|
+
for (const row of rows) {
|
|
378
|
+
const b = norm(row);
|
|
379
|
+
if (b.status === "pending") {
|
|
380
|
+
const r = await call(db, "tick", "bookings_expire", { p_id: b.id, p_claim: claim, p_now: at.toISOString() });
|
|
381
|
+
if (!r)
|
|
382
|
+
continue;
|
|
383
|
+
out.expired++;
|
|
384
|
+
out.emailed += await quietly("decline", () => mailCustomer("declined", norm(r)));
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const start = new Date(b.starts_at);
|
|
388
|
+
const sent = row.reminders_sent ?? 0;
|
|
389
|
+
if (start.getTime() <= at.getTime()) {
|
|
390
|
+
await call(db, "tick", "bookings_reminded", { p_id: b.id, p_claim: claim, p_sent: sent, p_next: null, p_now: at.toISOString() });
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
out.emailed += await mailCustomer("reminder", b, undefined, sent + 1);
|
|
395
|
+
}
|
|
396
|
+
catch (e) {
|
|
397
|
+
// Try again next tick; the Idempotency-Key keeps a retry from sending twice.
|
|
398
|
+
report(e, "reminder");
|
|
399
|
+
await call(db, "tick", "bookings_release", { p_id: b.id, p_claim: claim });
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
const next = nextReminder(config, start, at);
|
|
403
|
+
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() }))
|
|
404
|
+
out.reminded++;
|
|
405
|
+
}
|
|
406
|
+
return out;
|
|
407
|
+
},
|
|
408
|
+
async cleanup() {
|
|
409
|
+
return await call(db, "cleanup", "bookings_cleanup", { p_now: now().toISOString(), p_days: config.retention_days ?? 180 });
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
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;
|