@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.
package/dist/config.js ADDED
@@ -0,0 +1,165 @@
1
+ // workbench/bookings.json (docs/capabilities/13-bookings.md, "Config
2
+ // format"): checked here, by createBookings and by `npx workbench-bookings
3
+ // generate`, so a typo fails in Checks and never on a customer's phone.
4
+ import { BookingsError } from "./errors.js";
5
+ import { clockMinutes, durationMinutes, validDate, validZone } from "./time.js";
6
+ import { WEEKDAYS } from "./types.js";
7
+ const NAME = /^[a-z][a-z0-9-]{0,39}$/;
8
+ const TOP = [
9
+ "$schema",
10
+ "format",
11
+ "time_zone",
12
+ "hours",
13
+ "closed",
14
+ "services",
15
+ "calendar",
16
+ "notice",
17
+ "ahead_days",
18
+ "confirm",
19
+ "hold",
20
+ "reminders",
21
+ "cancel_until",
22
+ "ask",
23
+ "owner_email",
24
+ "feed",
25
+ "max_per_customer",
26
+ "retention_days",
27
+ "plans",
28
+ ];
29
+ const SERVICE = ["title", "minutes", "buffer", "capacity", "places", "every", "hours"];
30
+ const THIRTY_DAYS = 30 * 1440;
31
+ /** The most reminders a booking can have. */
32
+ export const MAX_REMINDERS = 3;
33
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
34
+ const whole = (v, min, max) => Number.isInteger(v) && v >= min && v <= max;
35
+ function hoursProblems(v, at) {
36
+ const p = [];
37
+ if (!isObj(v))
38
+ return [`${at} must be { "mon": [["09:00", "17:00"]], ... }, a day left out being closed`];
39
+ for (const [day, spans] of Object.entries(v)) {
40
+ if (!WEEKDAYS.includes(day)) {
41
+ p.push(`${at}.${day} isn't a day: use mon, tue, wed, thu, fri, sat or sun`);
42
+ continue;
43
+ }
44
+ if (!Array.isArray(spans)) {
45
+ p.push(`${at}.${day} must be a list of ["09:00", "17:00"] spans ([] for closed)`);
46
+ continue;
47
+ }
48
+ const mins = spans.map((s) => (Array.isArray(s) && s.length === 2 ? [clockMinutes(s[0]), clockMinutes(s[1])] : [null, null]));
49
+ if (mins.some(([a, b]) => a === null || b === null || a >= b))
50
+ p.push(`${at}.${day}: each span is ["09:00", "17:00"], 24-hour, its start before its end`);
51
+ else {
52
+ const sorted = [...mins].sort((a, b) => a[0] - b[0]);
53
+ for (let i = 1; i < sorted.length; i++)
54
+ if (sorted[i][0] < sorted[i - 1][1])
55
+ p.push(`${at}.${day}: spans overlap`);
56
+ }
57
+ }
58
+ return p;
59
+ }
60
+ function durationProblem(v, at, max, example, zero = false) {
61
+ if (v === undefined)
62
+ return [];
63
+ const m = durationMinutes(v);
64
+ return m === null || m > max || (m === 0 && !zero) ? [`${at} must be a length such as ${example} (up to ${Math.round(max / 1440)} days)`] : [];
65
+ }
66
+ /** Every problem with a bookings.json, or none. */
67
+ export function bookingProblems(value, where = "bookings.json") {
68
+ const p = [];
69
+ if (!isObj(value))
70
+ return [`${where}: not a JSON object`];
71
+ for (const k of Object.keys(value))
72
+ if (!TOP.includes(k))
73
+ p.push(`${k} isn't a bookings setting`);
74
+ if (value.format !== 1)
75
+ p.push("format must be 1");
76
+ if (!validZone(value.time_zone))
77
+ p.push("time_zone must be an IANA time zone, such as Australia/Sydney");
78
+ p.push(...hoursProblems(value.hours, "hours"));
79
+ if (value.closed !== undefined && (!Array.isArray(value.closed) || !value.closed.every(validDate) || value.closed.length > 1000)) {
80
+ p.push('closed must be a list of days, such as ["2026-12-25", "2026-12-28"]');
81
+ }
82
+ if (!isObj(value.services) || Object.keys(value.services).length === 0)
83
+ p.push("services must name at least one service");
84
+ else {
85
+ for (const [name, s] of Object.entries(value.services)) {
86
+ const at = `services.${name}`;
87
+ if (!NAME.test(name))
88
+ p.push(`${at}: a service's name is lower case letters, digits and dashes`);
89
+ if (!isObj(s)) {
90
+ p.push(`${at}: not an object`);
91
+ continue;
92
+ }
93
+ for (const k of Object.keys(s))
94
+ if (!SERVICE.includes(k))
95
+ p.push(`${at}.${k} isn't a service setting`);
96
+ if (typeof s.title !== "string" || !s.title.trim() || s.title.length > 80)
97
+ p.push(`${at}.title must be text up to 80 characters`);
98
+ if (!whole(s.minutes, 5, 720))
99
+ p.push(`${at}.minutes must be a whole number from 5 to 720`);
100
+ if (s.buffer !== undefined && !whole(s.buffer, 0, 240))
101
+ p.push(`${at}.buffer must be a whole number of minutes from 0 to 240`);
102
+ if (s.capacity !== undefined && !whole(s.capacity, 1, 100))
103
+ p.push(`${at}.capacity must be a whole number from 1 to 100`);
104
+ if (s.places !== undefined && !whole(s.places, 1, typeof s.capacity === "number" ? s.capacity : 1))
105
+ p.push(`${at}.places must be a whole number from 1 to the service's capacity`);
106
+ if (s.every !== undefined && !whole(s.every, 5, 720))
107
+ p.push(`${at}.every must be a whole number of minutes from 5 to 720`);
108
+ if (s.hours !== undefined)
109
+ p.push(...hoursProblems(s.hours, `${at}.hours`));
110
+ }
111
+ }
112
+ if (value.calendar !== undefined && value.calendar !== "shared" && value.calendar !== "per_service")
113
+ p.push("calendar must be shared or per_service");
114
+ p.push(...durationProblem(value.notice, "notice", THIRTY_DAYS, "2h", true));
115
+ if (value.ahead_days !== undefined && !whole(value.ahead_days, 1, 365))
116
+ p.push("ahead_days must be a whole number from 1 to 365");
117
+ if (value.confirm !== undefined && value.confirm !== "instant" && value.confirm !== "owner_approves")
118
+ p.push("confirm must be instant or owner_approves");
119
+ p.push(...durationProblem(value.hold, "hold", 7 * 1440, "2d"));
120
+ if (value.reminders !== undefined) {
121
+ const r = value.reminders;
122
+ if (!Array.isArray(r) || r.length > MAX_REMINDERS || r.some((d) => !durationMinutes(d) || durationMinutes(d) > 14 * 1440)) {
123
+ p.push(`reminders must be a list of up to ${MAX_REMINDERS} lengths before the start, such as ["1d", "2h"] ([] for none)`);
124
+ }
125
+ else if (new Set(r.map((d) => durationMinutes(d))).size !== r.length)
126
+ p.push("reminders: two reminders at the same time");
127
+ }
128
+ p.push(...durationProblem(value.cancel_until, "cancel_until", 14 * 1440, "24h", true));
129
+ if (value.ask !== undefined) {
130
+ const a = value.ask;
131
+ if (!isObj(a) ||
132
+ Object.keys(a).some((k) => k !== "phone" && k !== "note") ||
133
+ (a.phone !== undefined && !["no", "optional", "required"].includes(a.phone)) ||
134
+ (a.note !== undefined && typeof a.note !== "boolean")) {
135
+ p.push('ask must be { "phone": "no" | "optional" | "required", "note": true | false }');
136
+ }
137
+ }
138
+ if (value.owner_email !== undefined && value.owner_email !== "each" && value.owner_email !== "none")
139
+ p.push("owner_email must be each or none");
140
+ if (value.feed !== undefined && (!isObj(value.feed) || Object.keys(value.feed).some((k) => k !== "names") || (value.feed.names !== undefined && typeof value.feed.names !== "boolean"))) {
141
+ p.push('feed must be { "names": true | false }');
142
+ }
143
+ if (value.max_per_customer !== undefined && !whole(value.max_per_customer, 1, 20))
144
+ p.push("max_per_customer must be a whole number from 1 to 20");
145
+ if (value.retention_days !== undefined && !whole(value.retention_days, 1, 730))
146
+ p.push("retention_days must be a whole number from 1 to 730");
147
+ if (value.plans !== undefined) {
148
+ const pl = value.plans;
149
+ if (!isObj(pl) || Object.keys(pl).some((k) => k !== "feature") || (pl.feature !== undefined && (typeof pl.feature !== "string" || !/^[a-z][a-z0-9_]{0,39}$/.test(pl.feature)))) {
150
+ p.push("plans must be { feature? }, a plans.json feature name");
151
+ }
152
+ }
153
+ return p.map((x) => `${where}: ${x}`);
154
+ }
155
+ /** Checks workbench/bookings.json and returns it typed, or throws bad_config naming every problem. */
156
+ export function checkBookingConfig(value) {
157
+ const problems = bookingProblems(value);
158
+ if (problems.length)
159
+ throw new BookingsError("bad_config", problems.join("; "));
160
+ return value;
161
+ }
162
+ /** A service's opening hours: its own, else the business's (or the account's, from settings). */
163
+ export function hoursOf(service, hours) {
164
+ return service.hours ?? hours;
165
+ }
@@ -0,0 +1,25 @@
1
+ export type BookingsErrorCode =
2
+ /** workbench/bookings.json is out of shape. */
3
+ "bad_config"
4
+ /** A call's arguments are out of shape (a missing name, an email that isn't one). */
5
+ | "bad_input"
6
+ /** No such service in workbench/bookings.json. */
7
+ | "unknown_service"
8
+ /** The time isn't one the business offers: outside the hours, closed, too soon or too far ahead. */
9
+ | "not_open"
10
+ /** Someone else booked the time first. */
11
+ | "taken"
12
+ /** This email address already holds max_per_customer upcoming bookings with the account. */
13
+ | "too_many"
14
+ /** Too close to the start to change it online (cancel_until). */
15
+ | "too_late"
16
+ /** No such booking, or it has ended. */
17
+ | "unknown_booking"
18
+ /** The account's plan doesn't include bookings. Nothing was written. */
19
+ | "not_allowed"
20
+ /** The database refused or failed. */
21
+ | "store_failed";
22
+ export declare class BookingsError extends Error {
23
+ readonly code: BookingsErrorCode;
24
+ constructor(code: BookingsErrorCode, message: string);
25
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words.
3
+ export class BookingsError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "BookingsError";
8
+ this.code = code;
9
+ }
10
+ }
@@ -0,0 +1,12 @@
1
+ import { type BookingWordKey } from "./words.ts";
2
+ /** The project's strings lookup: `t('ui.wbbooking.form.submit')`. Undefined falls back to the English. */
3
+ export type Words = (key: string, params?: Readonly<Record<string, string | number>>) => string | undefined;
4
+ export declare const DEFAULT_LOCALE = "en-AU";
5
+ export type Say = (key: BookingWordKey, params?: Readonly<Record<string, string | number>>) => string;
6
+ export declare function words(t?: Words): Say;
7
+ /** "Wednesday 2 December at 10:00 am AEDT": for emails, where the reader may be somewhere else. */
8
+ export declare function whenText(iso: string, timeZone: string, locale?: string): string;
9
+ /** "Wednesday 2 December". A day (YYYY-MM-DD) is read at noon UTC, so it never slips a day. */
10
+ export declare function dayText(date: string, locale?: string): string;
11
+ /** "10:00 am". */
12
+ export declare function timeText(iso: string, timeZone: string, locale?: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,24 @@
1
+ // Dates and times for people, in the business's time zone and the project's
2
+ // locale (en-AU unless the app passes its country pack's). Words, with the
3
+ // project's strings lookup over the English.
4
+ import { BOOKING_WORDS } from "./words.js";
5
+ export const DEFAULT_LOCALE = "en-AU";
6
+ function fill(text, params = {}) {
7
+ return text.replace(/\{(\w+)\}/g, (m, k) => (Object.hasOwn(params, k) ? String(params[k]) : m));
8
+ }
9
+ export function words(t) {
10
+ return (key, params = {}) => t?.(`ui.wbbooking.${key}`, params) ?? fill(BOOKING_WORDS[key], params);
11
+ }
12
+ const fmt = (locale, timeZone, o) => new Intl.DateTimeFormat(locale, { timeZone, ...o });
13
+ /** "Wednesday 2 December at 10:00 am AEDT": for emails, where the reader may be somewhere else. */
14
+ export function whenText(iso, timeZone, locale = DEFAULT_LOCALE) {
15
+ return fmt(locale, timeZone, { weekday: "long", day: "numeric", month: "long", hour: "numeric", minute: "2-digit", timeZoneName: "short" }).format(new Date(iso));
16
+ }
17
+ /** "Wednesday 2 December". A day (YYYY-MM-DD) is read at noon UTC, so it never slips a day. */
18
+ export function dayText(date, locale = DEFAULT_LOCALE) {
19
+ return fmt(locale, "UTC", { weekday: "long", day: "numeric", month: "long" }).format(new Date(`${date}T12:00:00Z`));
20
+ }
21
+ /** "10:00 am". */
22
+ export function timeText(iso, timeZone, locale = DEFAULT_LOCALE) {
23
+ return fmt(locale, timeZone, { hour: "numeric", minute: "2-digit" }).format(new Date(iso));
24
+ }
package/dist/ical.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Booking } from "./types.ts";
2
+ export interface EventText {
3
+ /** The event's title: "30-minute consultation · Harbour Physio". */
4
+ summary: string;
5
+ /** Where, if the app knows it. */
6
+ location?: string;
7
+ /** One line of detail: the manage link. */
8
+ description?: string;
9
+ }
10
+ /** One booking as a calendar file. A cancelled or declined booking is METHOD:CANCEL, so a calendar app that has it takes it off. */
11
+ export declare function bookingIcs(b: Booking, t: EventText, now?: Date): string;
12
+ /** The owner's feed: every pending and confirmed booking given, as tentative and confirmed events. */
13
+ export declare function feedIcs(name: string, bookings: readonly Booking[], summary: (b: Booking) => string, now?: Date): string;
package/dist/ical.js ADDED
@@ -0,0 +1,67 @@
1
+ // Calendar files (RFC 5545): one booking's event, attached to the customer's
2
+ // emails and behind "Add to my calendar", and the owner's read-only feed of
3
+ // every upcoming booking, which they subscribe to in Google Calendar, Outlook
4
+ // or Apple Calendar. The feed names the service only unless bookings.json
5
+ // says feed.names: its address is a secret, but calendars leak. No note ever
6
+ // goes in either.
7
+ /** RFC 5545 TEXT: backslash, semicolon and comma escaped, line breaks as \n. */
8
+ const text = (s) => s.replace(/[\\;,]/g, (c) => `\\${c}`).replace(/\r?\n|\r/g, "\\n");
9
+ const utc = (iso) => new Date(iso).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
10
+ /** Folds a content line at 75 octets, as RFC 5545 asks, never inside a character. */
11
+ function fold(line) {
12
+ const enc = new TextEncoder();
13
+ const out = [];
14
+ let rest = line;
15
+ while (enc.encode(rest).length > 75) {
16
+ let cut = Math.min(rest.length, 75);
17
+ while (enc.encode(rest.slice(0, cut)).length > 75)
18
+ cut--;
19
+ if (/[\uD800-\uDBFF]/.test(rest[cut - 1] ?? ""))
20
+ cut--;
21
+ out.push(rest.slice(0, cut));
22
+ rest = ` ${rest.slice(cut)}`;
23
+ }
24
+ out.push(rest);
25
+ return out.join("\r\n");
26
+ }
27
+ function vevent(b, t, stamp, cancelled) {
28
+ const status = cancelled || b.status === "cancelled" || b.status === "declined" ? "CANCELLED" : b.status === "pending" ? "TENTATIVE" : "CONFIRMED";
29
+ return [
30
+ "BEGIN:VEVENT",
31
+ `UID:${b.id}@workbench-bookings`,
32
+ `DTSTAMP:${stamp}`,
33
+ `SEQUENCE:${b.sequence}`,
34
+ `DTSTART:${utc(b.starts_at)}`,
35
+ `DTEND:${utc(b.ends_at)}`,
36
+ `SUMMARY:${text(t.summary)}`,
37
+ ...(t.location ? [`LOCATION:${text(t.location)}`] : []),
38
+ ...(t.description ? [`DESCRIPTION:${text(t.description)}`] : []),
39
+ `STATUS:${status}`,
40
+ "TRANSP:OPAQUE",
41
+ "END:VEVENT",
42
+ ];
43
+ }
44
+ const wrap = (lines) => `${lines.map(fold).join("\r\n")}\r\n`;
45
+ /** One booking as a calendar file. A cancelled or declined booking is METHOD:CANCEL, so a calendar app that has it takes it off. */
46
+ export function bookingIcs(b, t, now = new Date()) {
47
+ const cancel = b.status === "cancelled" || b.status === "declined";
48
+ return wrap([
49
+ "BEGIN:VCALENDAR",
50
+ "VERSION:2.0",
51
+ "PRODID:-//Workbench//workbench-bookings//EN",
52
+ "CALSCALE:GREGORIAN",
53
+ `METHOD:${cancel ? "CANCEL" : "PUBLISH"}`,
54
+ ...vevent(b, t, utc(now.toISOString()), cancel),
55
+ "END:VCALENDAR",
56
+ ]);
57
+ }
58
+ /** The owner's feed: every pending and confirmed booking given, as tentative and confirmed events. */
59
+ export function feedIcs(name, bookings, summary, now = new Date()) {
60
+ const stamp = utc(now.toISOString());
61
+ const lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Workbench//workbench-bookings//EN", "CALSCALE:GREGORIAN", "METHOD:PUBLISH", `X-WR-CALNAME:${text(name)}`];
62
+ const sorted = [...bookings].filter((b) => b.status === "pending" || b.status === "confirmed").sort((x, y) => (x.starts_at < y.starts_at ? -1 : x.starts_at > y.starts_at ? 1 : x.id < y.id ? -1 : 1));
63
+ for (const b of sorted)
64
+ lines.push(...vevent(b, { summary: summary(b) }, stamp, false));
65
+ lines.push("END:VCALENDAR");
66
+ return wrap(lines);
67
+ }
@@ -0,0 +1,13 @@
1
+ export { createBookings, customerOf, nextReminder, type AccountSettings, type BookRequest, type Bookings, type BookingsClient, type BookingsMailer, type BookingsOptions, type BookingsPlans, type Business } from "./bookings.ts";
2
+ export { bookingProblems, checkBookingConfig, MAX_REMINDERS } from "./config.ts";
3
+ export { openSlots, offered, type SlotQuery } from "./slots.ts";
4
+ export { bookingIcs, feedIcs, type EventText } from "./ical.ts";
5
+ export { bookingsMigration } from "./migration.ts";
6
+ export { STARTER_BOOKINGS } from "./starters.ts";
7
+ export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, type ActionResult, type DoneOptions, type FormField, type FormOptions, type ListOptions, type ManageOptions, type MineOptions, type PickerOptions, } from "./ui.ts";
8
+ export { whenText, type Words } from "./format.ts";
9
+ export { BOOKING_WORDS, BOOKING_WORD_KEYS, type BookingWordKey } from "./words.ts";
10
+ export { BOOKING_STYLES } from "./styles.ts";
11
+ export { BookingsError, type BookingsErrorCode } from "./errors.ts";
12
+ export { BOOKING_STATUSES, WEEKDAYS } from "./types.ts";
13
+ export type { Booking, BookingConfig, BookingConfig as BookingSettings, BookingService, BookingStatus, Busy, CalendarMode, ConfirmMode, Customer, Duration, Slot, SlotDay, TickResult, Weekday, WeekHours } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ // @mccaskie-labs/workbench-bookings: a bookings calendar
2
+ // (docs/capabilities/13-bookings.md). Customers pick a free time, book it
3
+ // with their name and email, and get a confirmation with a calendar file,
4
+ // reminders, and a private link to change or cancel; the owner gets an email
5
+ // for each booking, a list in the app and a calendar feed. A store in the
6
+ // app's own database (bookingsMigration), a settings file
7
+ // (workbench/bookings.json), and tick() from the app's cron every 15 minutes.
8
+ // No AI.
9
+ export { createBookings, customerOf, nextReminder } from "./bookings.js";
10
+ export { bookingProblems, checkBookingConfig, MAX_REMINDERS } from "./config.js";
11
+ export { openSlots, offered } from "./slots.js";
12
+ export { bookingIcs, feedIcs } from "./ical.js";
13
+ export { bookingsMigration } from "./migration.js";
14
+ export { STARTER_BOOKINGS } from "./starters.js";
15
+ export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, } from "./ui.js";
16
+ export { whenText } from "./format.js";
17
+ export { BOOKING_WORDS, BOOKING_WORD_KEYS } from "./words.js";
18
+ export { BOOKING_STYLES } from "./styles.js";
19
+ export { BookingsError } from "./errors.js";
20
+ export { BOOKING_STATUSES, WEEKDAYS } from "./types.js";
@@ -0,0 +1,4 @@
1
+ export declare const bookingsMigration: {
2
+ up: string;
3
+ down: string;
4
+ };