@profitstudio/booking-engine 2.0.0-beta.2 → 2.0.0-beta.4
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 +69 -0
- package/README.md +1 -1
- package/dist/admin/BookingAdmin.js +6 -4
- package/dist/admin/booking-detail.js +14 -13
- package/dist/admin/email-health.d.ts +31 -0
- package/dist/admin/email-health.js +36 -0
- package/dist/admin/fields.js +1 -1
- package/dist/admin/sections/EmailSection.js +26 -12
- package/dist/admin/sections/OverviewSection.js +16 -8
- package/dist/admin/setup.d.ts +7 -0
- package/dist/admin/setup.js +11 -4
- package/dist/client.js +19 -2
- package/dist/errors.js +3 -0
- package/dist/generated/manifest.d.ts +2 -2
- package/dist/generated/manifest.js +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/types.d.ts +18 -2
- package/docs/BUILD-A-SITE.md +2 -0
- package/docs/INTEGRATION.md +54 -12
- package/engine.manifest.json +8 -2
- package/migrations/0009_reliable_answers.sql +303 -0
- package/package.json +2 -2
- package/templates/BOOKING_ENGINE.md +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,74 @@
|
|
|
1
1
|
# Changelog — @profitstudio/booking-engine
|
|
2
2
|
|
|
3
|
+
## 2.0.0-beta.4 — 2026-11-20 (prepared, not published)
|
|
4
|
+
|
|
5
|
+
Reliability fixes. **One migration, `0009_reliable_answers`** (schema
|
|
6
|
+
2.0.0-beta.4): bug fixes only — two functions replaced with the same
|
|
7
|
+
signatures, one private admin-only helper added; no table, column,
|
|
8
|
+
constraint, policy or data change. `requiredSchemaVersion` stays 2.0.0-alpha.5:
|
|
9
|
+
beta.3 clients keep working on a beta.4 database, and beta.4 clients on older
|
|
10
|
+
ones. No CLI or Edge Function change.
|
|
11
|
+
|
|
12
|
+
**Fixed:**
|
|
13
|
+
|
|
14
|
+
- **A declined or lapsed request could be shown as booked.** Verifying again
|
|
15
|
+
with an accepted code (a website does this after a lost answer, a double
|
|
16
|
+
click, or the `already_verified` answer of a re-send or cancel) returned the
|
|
17
|
+
booking's current status as a success — `cancelled` and `expired` included —
|
|
18
|
+
although `BookingConfirmation.status` is typed `'pending' | 'confirmed'`; a
|
|
19
|
+
site that treated every status but `'pending'` as booked said "booked". Now
|
|
20
|
+
the database answers an inactive booking as `{ result: 'inactive', status,
|
|
21
|
+
reference }`, and `verifyBooking` returns `ok` only for `'pending'` or
|
|
22
|
+
`'confirmed'`; anything else is the new error code **`BOOKING_INACTIVE`**
|
|
23
|
+
(`error.bookingStatus`: `cancelled`, `expired`, `completed` or `no_show`;
|
|
24
|
+
`error.reference`). The client applies this against older databases too.
|
|
25
|
+
Pending and confirmed answers are unchanged, and verifying again never
|
|
26
|
+
changes anything.
|
|
27
|
+
- **The owner could confirm an expired request after its time had started**
|
|
28
|
+
(the customer was told "expired", then "confirmed" for a past time). The
|
|
29
|
+
database now refuses it (`INVALID_TRANSITION`, `already_started`), and the
|
|
30
|
+
dashboard (Bookings and Today) offers only Decline.
|
|
31
|
+
- **Confirming an expired request said "Someone else has booked this time"**
|
|
32
|
+
when the only thing in the way was a hold that had already lapsed but was not
|
|
33
|
+
released yet. Such holds are now released first, exactly as a visitor's
|
|
34
|
+
request for the time would. A visitor still entering their code for that
|
|
35
|
+
time gets its own message (`CONFLICT`, `slot_held`); a real request or
|
|
36
|
+
booking keeps `slot_taken`. The double-booking constraint is unchanged.
|
|
37
|
+
- **Online booking could be switched on before the business step** (default
|
|
38
|
+
name "My Business", time zone UTC). The dashboard's switch now waits for the
|
|
39
|
+
same rule as the setup checklist's first step. The time-zone help text no
|
|
40
|
+
longer says a change leaves existing appointments as they were: their moment
|
|
41
|
+
is kept, so their local time changes.
|
|
42
|
+
- **`emailDelivery="none"` in front of a real database:** if that database
|
|
43
|
+
refuses to switch online booking on, the dashboard explains the demo mode
|
|
44
|
+
instead of asking for a test email it says it never sends; and if the
|
|
45
|
+
database has sent or tried to send real email, the Email page warns that
|
|
46
|
+
delivery problems are hidden. `emailHealth` is unchanged.
|
|
47
|
+
|
|
48
|
+
**Website code (recommended):** say "booked" only when `status === 'confirmed'`
|
|
49
|
+
and handle `BOOKING_INACTIVE` at the code step (INTEGRATION.md §6–§8). A site
|
|
50
|
+
that does not handle it yet falls back to its generic error — never a
|
|
51
|
+
confirmation.
|
|
52
|
+
|
|
53
|
+
## 2.0.0-beta.3 — 2026-11-06
|
|
54
|
+
|
|
55
|
+
Honest email health in public demos. **No migration** (schema 2.0.0-alpha.10),
|
|
56
|
+
no client, CLI or Edge Function change, and no change for real sites.
|
|
57
|
+
|
|
58
|
+
**Fixed:**
|
|
59
|
+
|
|
60
|
+
- With `<BookingAdmin emailDelivery="none">` the dashboard no longer reports
|
|
61
|
+
deliveries that never happened. The Today health line says "Demo: no emails
|
|
62
|
+
are sent"; the Email page's status card says email is simulated, with no
|
|
63
|
+
"last delivered" time and no sent / code / waiting / failed counters; the
|
|
64
|
+
list of emails is titled "What would have been emailed" and marks every row
|
|
65
|
+
"Not sent (demo)"; the test-email card says no test email is sent; the
|
|
66
|
+
"emails not getting out" banner never shows. The demo still counts as ready,
|
|
67
|
+
so online booking can be switched on and off.
|
|
68
|
+
- Without the prop (or with `'live'`), every rule and text is exactly as in
|
|
69
|
+
2.0.0-beta.2: one helper (`admin/email-health.ts`) now feeds the Today line,
|
|
70
|
+
the Email page, the banner and the setup checklist with those same rules.
|
|
71
|
+
|
|
3
72
|
## 2.0.0-beta.2 — 2026-11-04
|
|
4
73
|
|
|
5
74
|
A dashboard option for public demos. **No migration** (schema 2.0.0-alpha.10),
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ an AI builder.
|
|
|
12
12
|
- Changes and upgrade notes: [CHANGELOG.md](CHANGELOG.md)
|
|
13
13
|
- Versions: see `engine.manifest.json`
|
|
14
14
|
|
|
15
|
-
**Status:** 2.0.0-beta.
|
|
15
|
+
**Status:** 2.0.0-beta.4 — public beta (owner-editable website content, the Studio dashboard, calendar helpers for booking UIs, optional service photos, opening times with closures; builds check the Supabase connection; the dashboard asks where new-request alerts go; `connect` sets up Supabase and email, `photos` prepares a site's photos). Install the exact version.
|
|
16
16
|
|
|
17
17
|
## Licence
|
|
18
18
|
|
|
@@ -4,6 +4,7 @@ import { presets as builtInPresets } from '../presets/index.js';
|
|
|
4
4
|
import { formatTime, timeZoneLabel } from '../time.js';
|
|
5
5
|
import { ALERTS_VIEW, alertsAddress } from './alerts.js';
|
|
6
6
|
import { AdminContext, useAdmin } from './context.js';
|
|
7
|
+
import { emailHealth } from './email-health.js';
|
|
7
8
|
import { ToastRegion, useConfirm, useToasts } from './feedback.js';
|
|
8
9
|
import { Icon } from './icons.js';
|
|
9
10
|
import { ADMIN_SECTIONS, NAV_GROUPS } from './sections.js';
|
|
@@ -252,7 +253,7 @@ function BusinessClock({ timezone, locale }) {
|
|
|
252
253
|
}
|
|
253
254
|
/** On every page: say so when booking emails are not getting out (customers then cannot receive codes). */
|
|
254
255
|
function EmailHealthBanner() {
|
|
255
|
-
const { engine, settings, go } = useAdmin();
|
|
256
|
+
const { engine, settings, go, emailDelivery } = useAdmin();
|
|
256
257
|
const [status, setStatus] = useState(null);
|
|
257
258
|
useEffect(() => {
|
|
258
259
|
let alive = true;
|
|
@@ -264,10 +265,11 @@ function EmailHealthBanner() {
|
|
|
264
265
|
alive = false;
|
|
265
266
|
};
|
|
266
267
|
}, [engine]);
|
|
267
|
-
|
|
268
|
+
// A demo sends nothing, so there is nothing to warn about.
|
|
269
|
+
if (!status || emailDelivery === 'none')
|
|
268
270
|
return null;
|
|
269
|
-
const {
|
|
270
|
-
const failing =
|
|
271
|
+
const { lastError } = status.mailer;
|
|
272
|
+
const { failing } = emailHealth(status, emailDelivery);
|
|
271
273
|
const stuck = Boolean(status.counts.oldestQueuedAt && Date.now() - Date.parse(status.counts.oldestQueuedAt) > 5 * 60_000);
|
|
272
274
|
// The same count and 24-hour window the database uses to refuse new codes (RATE_LIMITED).
|
|
273
275
|
const capReached = settings.onlineBookingEnabled && status.counts.codesLast24h >= settings.maxVerificationEmailsPerDay;
|
|
@@ -26,20 +26,21 @@ export const answerNote = (b, delivery = 'live') => delivery === 'none'
|
|
|
26
26
|
export function actionsFor(b, now = Date.now(), delivery = 'live') {
|
|
27
27
|
const started = Date.parse(b.startsAt) <= now;
|
|
28
28
|
if (b.status === 'pending' || b.status === 'expired') {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
29
|
+
const decline = {
|
|
30
|
+
status: 'cancelled',
|
|
31
|
+
label: 'Decline',
|
|
32
|
+
tone: 'danger',
|
|
33
|
+
confirm: {
|
|
34
|
+
title: `Decline ${b.customer.name}’s request?`,
|
|
35
|
+
body: started
|
|
36
|
+
? `Its time has already started, so it can no longer be confirmed. ${notifies(b, delivery)}`
|
|
37
|
+
: `The time opens again for other customers. ${notifies(b, delivery)}`,
|
|
38
|
+
confirmLabel: 'Decline request',
|
|
39
|
+
cancelLabel: 'Keep the request',
|
|
40
40
|
},
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
};
|
|
42
|
+
// A request is confirmed only for a time still ahead (the database refuses the rest).
|
|
43
|
+
return started ? [decline] : [decline, { status: 'confirmed', label: 'Confirm', tone: 'primary' }];
|
|
43
44
|
}
|
|
44
45
|
if (b.status === 'confirmed') {
|
|
45
46
|
const cancel = {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { EmailStatus } from '../types.js';
|
|
2
|
+
import type { EmailDelivery } from './context.js';
|
|
3
|
+
export interface EmailHealth {
|
|
4
|
+
/** A demo: email is simulated, nothing is delivered. */
|
|
5
|
+
demo: boolean;
|
|
6
|
+
/** Ready for online booking: an email was delivered (live), or a demo. */
|
|
7
|
+
working: boolean;
|
|
8
|
+
/** The last delivery attempt failed (live only). */
|
|
9
|
+
failing: boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare function emailHealth(status: EmailStatus | null, delivery?: EmailDelivery): EmailHealth;
|
|
12
|
+
/** What the demo says wherever a live dashboard reports deliveries. */
|
|
13
|
+
export declare const DEMO_EMAIL: {
|
|
14
|
+
readonly health: "Demo: no emails are sent";
|
|
15
|
+
readonly title: "Email is simulated in this demo";
|
|
16
|
+
readonly sub: "Nothing is delivered from this demo. On your own website, this card shows when booking emails were last delivered and how many went out.";
|
|
17
|
+
readonly testSub: "In this demo no test email is sent. On your own website, a delivered test email is what unlocks online booking.";
|
|
18
|
+
readonly recentTitle: "What would have been emailed";
|
|
19
|
+
readonly notSent: "Not sent (demo)";
|
|
20
|
+
/** A real booking database refused to switch online booking on (it needs a delivered test email). */
|
|
21
|
+
readonly refused: "This dashboard is in demo email mode (emailDelivery=\"none\"), but it is connected to a real booking database, which switches online booking on only after a test email was delivered. A public demo needs the demo engine; a real website must not set emailDelivery=\"none\".";
|
|
22
|
+
/** 'none' in front of a mailer that has really sent (or tried to send) email. */
|
|
23
|
+
readonly realEmail: "This dashboard is in demo email mode (emailDelivery=\"none\"), but its booking database has sent or tried to send real email, so delivery problems are hidden here. On a real website, remove emailDelivery=\"none\" from <BookingAdmin>.";
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* 2.0.0-beta.4: 'none' in front of a real mailer. A demo never records a
|
|
27
|
+
* delivery attempt, so any recorded attempt, success or failure means the
|
|
28
|
+
* dashboard is hiding real email (a real website shipped with the demo prop).
|
|
29
|
+
* `emailHealth` is unchanged: the dashboard warns instead.
|
|
30
|
+
*/
|
|
31
|
+
export declare function hidesRealEmail(status: EmailStatus | null, delivery?: EmailDelivery): boolean;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export function emailHealth(status, delivery = 'live') {
|
|
2
|
+
if (delivery === 'none')
|
|
3
|
+
return { demo: true, working: true, failing: false };
|
|
4
|
+
const lastSuccessAt = status?.mailer.lastSuccessAt ?? null;
|
|
5
|
+
const lastFailureAt = status?.mailer.lastFailureAt ?? null;
|
|
6
|
+
return {
|
|
7
|
+
demo: false,
|
|
8
|
+
working: Boolean(lastSuccessAt),
|
|
9
|
+
failing: Boolean(lastFailureAt && (!lastSuccessAt || Date.parse(lastFailureAt) > Date.parse(lastSuccessAt))),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** What the demo says wherever a live dashboard reports deliveries. */
|
|
13
|
+
export const DEMO_EMAIL = {
|
|
14
|
+
health: 'Demo: no emails are sent',
|
|
15
|
+
title: 'Email is simulated in this demo',
|
|
16
|
+
sub: 'Nothing is delivered from this demo. On your own website, this card shows when booking emails were last delivered and how many went out.',
|
|
17
|
+
testSub: 'In this demo no test email is sent. On your own website, a delivered test email is what unlocks online booking.',
|
|
18
|
+
recentTitle: 'What would have been emailed',
|
|
19
|
+
notSent: 'Not sent (demo)',
|
|
20
|
+
/** A real booking database refused to switch online booking on (it needs a delivered test email). */
|
|
21
|
+
refused: 'This dashboard is in demo email mode (emailDelivery="none"), but it is connected to a real booking database, which switches online booking on only after a test email was delivered. A public demo needs the demo engine; a real website must not set emailDelivery="none".',
|
|
22
|
+
/** 'none' in front of a mailer that has really sent (or tried to send) email. */
|
|
23
|
+
realEmail: 'This dashboard is in demo email mode (emailDelivery="none"), but its booking database has sent or tried to send real email, so delivery problems are hidden here. On a real website, remove emailDelivery="none" from <BookingAdmin>.',
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* 2.0.0-beta.4: 'none' in front of a real mailer. A demo never records a
|
|
27
|
+
* delivery attempt, so any recorded attempt, success or failure means the
|
|
28
|
+
* dashboard is hiding real email (a real website shipped with the demo prop).
|
|
29
|
+
* `emailHealth` is unchanged: the dashboard warns instead.
|
|
30
|
+
*/
|
|
31
|
+
export function hidesRealEmail(status, delivery = 'live') {
|
|
32
|
+
if (delivery !== 'none' || !status)
|
|
33
|
+
return false;
|
|
34
|
+
const { lastAttemptAt, lastSuccessAt, lastFailureAt } = status.mailer;
|
|
35
|
+
return Boolean(lastAttemptAt || lastSuccessAt || lastFailureAt);
|
|
36
|
+
}
|
package/dist/admin/fields.js
CHANGED
|
@@ -7,7 +7,7 @@ export const BUSINESS_GROUP = {
|
|
|
7
7
|
{
|
|
8
8
|
key: 'timezone',
|
|
9
9
|
label: 'Time zone',
|
|
10
|
-
help: 'Where your appointments take place. All booking times use this zone, whatever the customer’s device says.
|
|
10
|
+
help: 'Where your appointments take place. All booking times use this zone, whatever the customer’s device says. Set it before you take bookings: changing it later keeps each existing appointment at the same moment, so its local time shown here and in emails changes.',
|
|
11
11
|
kind: 'timezone',
|
|
12
12
|
},
|
|
13
13
|
{
|
|
@@ -3,8 +3,10 @@ import { useEffect, useRef, useState } from 'react';
|
|
|
3
3
|
import { formatDateTime } from '../../time.js';
|
|
4
4
|
import { ALERTS_VIEW, TEST_EMAIL_VIEW, alertsAddress } from '../alerts.js';
|
|
5
5
|
import { useAdmin } from '../context.js';
|
|
6
|
+
import { DEMO_EMAIL, emailHealth, hidesRealEmail } from '../email-health.js';
|
|
6
7
|
import { EMAIL_GROUP } from '../fields.js';
|
|
7
8
|
import { Icon } from '../icons.js';
|
|
9
|
+
import { businessReady } from '../setup.js';
|
|
8
10
|
import { Badge, Button, ErrorNotice, Field, Notice, PageHeader, SkeletonBlock, formatAgo, useResult } from '../ui.js';
|
|
9
11
|
import { SettingsSection } from './SettingsSection.js';
|
|
10
12
|
const KIND_LABELS = {
|
|
@@ -58,7 +60,7 @@ function reveal(id) {
|
|
|
58
60
|
}
|
|
59
61
|
/** Email health, test email, the online-booking switch and email settings. */
|
|
60
62
|
export function EmailSection() {
|
|
61
|
-
const { engine, settings, refreshSettings, toast, view, emailDelivery } = useAdmin();
|
|
63
|
+
const { engine, settings, refreshSettings, toast, view, emailDelivery, go } = useAdmin();
|
|
62
64
|
const [load, reload] = useResult(() => engine.admin.emailStatus(), []);
|
|
63
65
|
// Where new-request alerts go (the alerts address, else the public email); the test email goes there by default.
|
|
64
66
|
const alerts = alertsAddress(settings);
|
|
@@ -141,7 +143,8 @@ export function EmailSection() {
|
|
|
141
143
|
const r = await engine.admin.updateSettings({ onlineBookingEnabled: on });
|
|
142
144
|
if (!r.ok) {
|
|
143
145
|
setBusy(null);
|
|
144
|
-
|
|
146
|
+
// In demo email mode, "send a test email first" would contradict the page (no test email is sent).
|
|
147
|
+
setProblem(emailDelivery === 'none' && r.error.field === 'onlineBookingEnabled' ? DEMO_EMAIL.refused : r.error.message);
|
|
145
148
|
return;
|
|
146
149
|
}
|
|
147
150
|
await refreshSettings();
|
|
@@ -166,19 +169,30 @@ export function EmailSection() {
|
|
|
166
169
|
}
|
|
167
170
|
const status = load.state === 'ready' ? load.data : null;
|
|
168
171
|
const lastStart = status ? describeLastStart(status.wiring.lastStart) : null;
|
|
169
|
-
|
|
170
|
-
const
|
|
172
|
+
// In a demo ('none') nothing is delivered: no time, count or "Sent" is shown, and online booking can still be switched.
|
|
173
|
+
const { demo, working, failing } = emailHealth(status, emailDelivery);
|
|
171
174
|
const wired = status ? WIRING.every((w) => status.wiring[w.key]) : true;
|
|
172
175
|
const online = settings.onlineBookingEnabled;
|
|
173
|
-
//
|
|
174
|
-
const
|
|
176
|
+
// Every booking time and email uses the business's name and time zone: set them first.
|
|
177
|
+
const ready = businessReady(settings);
|
|
178
|
+
// Going live needs all three: the business is set up, customers receive their codes, and the owner hears about every request.
|
|
179
|
+
const canGoLive = ready && working && Boolean(alerts);
|
|
180
|
+
const realEmailHidden = hidesRealEmail(status, emailDelivery);
|
|
175
181
|
return (_jsxs("section", { "aria-labelledby": "pbe-email-title", className: "pbe-page", children: [_jsx(PageHeader, { id: "pbe-email-title", title: "Email & online booking", sub: emailDelivery === 'none'
|
|
176
182
|
? 'This demo sends no email. On your own website, customers confirm their email address with a code before a request reaches you, get an email when you confirm, decline or cancel, and you are emailed about every new request.'
|
|
177
|
-
: `Customers confirm their email address with a code before a request reaches you, and get an email when you confirm, decline or cancel.${alerts ? ` You are emailed about every new request at ${alerts}.` : ''}` }), problem ? _jsx(Notice, { kind: "error", children: problem }) : null, !alerts ? (_jsxs(Notice, { kind: "warning", children: [_jsx("strong", { children: "New-request alerts have no address." }), " Nobody is emailed when a customer asks for an appointment, so a request could wait unanswered until its hold ends. Choose an address under \u201CSend new-request alerts to\u201D, or add a public email in Business.", ' ', _jsx("button", { type: "button", className: "pbe-link-button", onClick: () => reveal(ALERTS_FIELD), children: "Choose an address" })] })) : null, _jsxs("div", { className: "pbe-grid-2", children: [_jsxs("div", { className: "pbe-card pbe-card--pad pbe-stack", "aria-labelledby": "pbe-online-title", role: "region", children: [_jsxs("div", { className: "pbe-status-head", children: [_jsx("span", { className: `pbe-status-icon${online ? ' pbe-status-icon--ok' : ''}`, "aria-hidden": "true", children: _jsx(Icon, { name: "online", size: 20 }) }), _jsxs("div", { children: [_jsxs("h2", { id: "pbe-online-title", className: "pbe-card-title", children: ["Online booking is ", online ? 'on' : 'off'] }), _jsx("p", { className: "pbe-card-sub", children: online
|
|
183
|
+
: `Customers confirm their email address with a code before a request reaches you, and get an email when you confirm, decline or cancel.${alerts ? ` You are emailed about every new request at ${alerts}.` : ''}` }), problem ? _jsx(Notice, { kind: "error", children: problem }) : null, realEmailHidden ? _jsx(Notice, { kind: "warning", children: DEMO_EMAIL.realEmail }) : null, !alerts ? (_jsxs(Notice, { kind: "warning", children: [_jsx("strong", { children: "New-request alerts have no address." }), " Nobody is emailed when a customer asks for an appointment, so a request could wait unanswered until its hold ends. Choose an address under \u201CSend new-request alerts to\u201D, or add a public email in Business.", ' ', _jsx("button", { type: "button", className: "pbe-link-button", onClick: () => reveal(ALERTS_FIELD), children: "Choose an address" })] })) : null, _jsxs("div", { className: "pbe-grid-2", children: [_jsxs("div", { className: "pbe-card pbe-card--pad pbe-stack", "aria-labelledby": "pbe-online-title", role: "region", children: [_jsxs("div", { className: "pbe-status-head", children: [_jsx("span", { className: `pbe-status-icon${online ? ' pbe-status-icon--ok' : ''}`, "aria-hidden": "true", children: _jsx(Icon, { name: "online", size: 20 }) }), _jsxs("div", { children: [_jsxs("h2", { id: "pbe-online-title", className: "pbe-card-title", children: ["Online booking is ", online ? 'on' : 'off'] }), _jsx("p", { className: "pbe-card-sub", children: online
|
|
178
184
|
? 'Customers can request appointments on your website.'
|
|
179
|
-
: !
|
|
180
|
-
? '
|
|
181
|
-
: !
|
|
182
|
-
? '
|
|
183
|
-
:
|
|
185
|
+
: !ready
|
|
186
|
+
? 'Set your business name and time zone first: every booking time and email uses them.'
|
|
187
|
+
: !working
|
|
188
|
+
? 'Send a test email first: customers must be able to receive their code before they can book.'
|
|
189
|
+
: demo
|
|
190
|
+
? 'Switch online booking on to take requests on the demo website.'
|
|
191
|
+
: !alerts
|
|
192
|
+
? 'Email works. Choose where new-request alerts go, then switch online booking on.'
|
|
193
|
+
: 'Email works. Switch online booking on when you are ready for requests.' })] })] }), _jsx("div", { className: "pbe-form-actions", children: online ? (_jsx(Button, { loading: busy === 'online', onClick: () => void setOnline(false), children: "Turn online booking off" })) : (_jsxs(_Fragment, { children: [!ready ? _jsx(Button, { onClick: () => go('business'), children: "Open Business" }) : null, _jsx(Button, { variant: "primary", loading: busy === 'online', disabled: !canGoLive, onClick: () => void setOnline(true), children: "Turn online booking on" })] })) })] }), _jsxs("div", { className: "pbe-card pbe-card--pad pbe-stack", "aria-labelledby": "pbe-sending-title", role: "region", children: [load.state === 'loading' ? _jsx(SkeletonBlock, { lines: 2, label: "Checking booking emails\u2026" }) : null, load.state === 'error' ? _jsx(ErrorNotice, { error: load.error, onRetry: reload }) : null, status ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "pbe-status-head", children: [_jsx("span", { className: `pbe-status-icon${demo ? '' : failing ? ' pbe-status-icon--bad' : working ? ' pbe-status-icon--ok' : ' pbe-status-icon--warn'}`, "aria-hidden": "true", children: _jsx(Icon, { name: failing ? 'mail-problem' : 'mail-ok', size: 20 }) }), _jsxs("div", { children: [_jsx("h2", { id: "pbe-sending-title", className: "pbe-card-title", children: demo ? DEMO_EMAIL.title : failing ? 'Booking emails are failing' : working ? 'Booking emails are working' : 'No email delivered yet' }), _jsx("p", { className: "pbe-card-sub", children: demo
|
|
194
|
+
? DEMO_EMAIL.sub
|
|
195
|
+
: working
|
|
196
|
+
? `Last delivered ${formatAgo(status.mailer.lastSuccessAt)} (${when(status.mailer.lastSuccessAt)}).`
|
|
197
|
+
: 'Send a test email to check the set-up.' })] })] }), failing ? (_jsxs(Notice, { kind: "warning", children: ["Last problem (", when(status.mailer.lastFailureAt), "): ", status.mailer.lastError ?? 'unknown error'] })) : null, demo ? null : (_jsxs("p", { className: "pbe-stats-line", children: [_jsxs("span", { children: [_jsx("b", { children: status.counts.sentLast24h }), "sent in 24 h"] }), _jsxs("span", { children: [_jsx("b", { children: status.counts.codesLast24h }), "of ", settings.maxVerificationEmailsPerDay, " code emails"] }), _jsxs("span", { children: [_jsx("b", { children: status.counts.queued }), "waiting"] }), _jsxs("span", { children: [_jsx("b", { children: status.counts.failedLast7Days }), "failed in 7 days"] })] })), !demo && status.counts.retryable > 0 ? (_jsxs("div", { className: "pbe-form-actions", children: [_jsxs(Button, { icon: "retry", loading: busy === 'retry', onClick: () => void retryFailed(), children: ["Retry ", status.counts.retryable, " failed email", status.counts.retryable === 1 ? '' : 's'] }), _jsx("span", { className: "pbe-help", children: "Emails from the last 23 hours; nobody gets one twice." })] })) : null] })) : null] })] }), _jsxs("div", { className: "pbe-card", role: "region", "aria-labelledby": "pbe-test-title", children: [_jsx("div", { className: "pbe-card-head pbe-card-head--rule", children: _jsxs("div", { children: [_jsx("h2", { id: "pbe-test-title", className: "pbe-card-title", children: "Send a test email" }), _jsx("p", { className: "pbe-card-sub", children: demo ? DEMO_EMAIL.testSub : 'A delivered test email is what unlocks online booking.' })] }) }), _jsxs("form", { className: "pbe-form pbe-card-form", onSubmit: sendTest, children: [_jsxs("div", { className: "pbe-test-row", children: [_jsx("div", { className: "pbe-test-field", children: _jsx(Field, { id: "pbe-test-recipient", label: "Send a test email to", help: "Use an inbox you can check now.", children: _jsx("input", { id: "pbe-test-recipient", type: "email", required: true, autoComplete: "email", value: recipient, onChange: (e) => setRecipient(e.target.value) }) }) }), _jsx("div", { className: "pbe-test-action", children: _jsx(Button, { type: "submit", variant: "primary", icon: "send", loading: busy === 'test', children: "Send test email" }) })] }), test ? _jsx(Notice, { kind: test.kind, children: test.text }) : null] }), status ? (_jsxs("details", { className: "pbe-details pbe-card-details", open: !wired || (lastStart ? !lastStart.ok : false), children: [_jsxs("summary", { children: ["Technical details", _jsx("span", { className: "pbe-push" }), wired && (!lastStart || lastStart.ok) ? _jsx(Badge, { tone: "ok", children: "Set up" }) : _jsx(Badge, { tone: "warn", children: "Needs attention" }), _jsx(Icon, { name: "down" })] }), _jsxs("div", { className: "pbe-details-body", children: [_jsxs("ul", { className: "pbe-checklist", "aria-label": "Automatic sending", children: [WIRING.map((w) => (_jsxs("li", { className: status.wiring[w.key] ? 'pbe-done' : undefined, children: [_jsx("span", { className: "pbe-checklist-mark", "aria-hidden": "true", children: status.wiring[w.key] ? _jsx(Icon, { name: "check" }) : null }), _jsxs("span", { children: [w.label, _jsx("span", { className: "pbe-sr-only", children: status.wiring[w.key] ? ' (done)' : ' (missing)' })] })] }, w.key))), lastStart ? (_jsxs("li", { className: lastStart.ok ? 'pbe-done' : 'pbe-bad', children: [_jsx("span", { className: "pbe-checklist-mark", "aria-hidden": "true", children: _jsx(Icon, { name: lastStart.ok ? 'check' : 'close' }) }), _jsxs("span", { children: ["Last start of the mailer (", when(status.wiring.lastStart?.at ?? null), "): ", lastStart.text] })] })) : null] }), !wired ? (_jsxs("p", { className: "pbe-help", children: ["Set up once from your project folder: run ", _jsx("code", { className: "pbe-inline-code", children: "npx booking-engine mailer-sql" }), ", paste its output into the Supabase SQL Editor, then add the token it returns as the Edge Function secret ", _jsx("code", { className: "pbe-inline-code", children: "BOOKING_MAILER_TOKEN" }), "."] })) : null] })] })) : null] }), status && status.recent.length ? (_jsxs("div", { className: "pbe-stack", role: "region", "aria-labelledby": "pbe-recent-title", children: [_jsx("h2", { id: "pbe-recent-title", className: "pbe-section-title", children: demo ? DEMO_EMAIL.recentTitle : 'Recent emails' }), _jsxs("table", { className: "pbe-table pbe-table--card", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Email" }), _jsx("th", { scope: "col", children: "To" }), _jsx("th", { scope: "col", children: "Status" }), _jsx("th", { scope: "col", children: "Queued" })] }) }), _jsx("tbody", { children: (showAll ? status.recent : status.recent.slice(0, 8)).map((m) => (_jsxs("tr", { children: [_jsx("td", { children: KIND_LABELS[m.kind] ?? m.kind }), _jsx("td", { className: "pbe-tnum", children: m.recipient }), _jsxs("td", { children: [demo ? (_jsx(Badge, { tone: "neutral", children: DEMO_EMAIL.notSent })) : (_jsx(Badge, { tone: DELIVERY[m.status].tone, children: DELIVERY[m.status].label })), !demo && m.status === 'failed' && m.lastError ? _jsx("div", { className: "pbe-help", children: m.lastError }) : null] }), _jsx("td", { className: "pbe-nowrap pbe-tnum", children: when(m.createdAt) })] }, m.id))) })] }), status.recent.length > 8 && !showAll ? (_jsxs(Button, { size: "sm", className: "pbe-table-more", onClick: () => setShowAll(true), children: ["Show all ", status.recent.length] })) : null] })) : null, _jsx(SettingsSection, { group: EMAIL_GROUP, embedded: true })] }));
|
|
184
198
|
}
|
|
@@ -8,6 +8,7 @@ import { addDays, formatClockTime, formatDate, formatDateTime, formatMoney, form
|
|
|
8
8
|
import { ALERTS_VIEW, alertsAddress } from '../alerts.js';
|
|
9
9
|
import { BookingDrawer, actionsFor, dayWord, priceText, useBookingActions } from '../booking-detail.js';
|
|
10
10
|
import { useAdmin } from '../context.js';
|
|
11
|
+
import { DEMO_EMAIL, emailHealth } from '../email-health.js';
|
|
11
12
|
import { Icon } from '../icons.js';
|
|
12
13
|
import { SetupChecklist } from '../setup.js';
|
|
13
14
|
import { OCCUPYING, bookingSpan, byUrgency, closuresOn, freeSpans, holdRunning, holdState, openSpans, overlapMinutes, toMinutes, total, weekStart, } from '../today.js';
|
|
@@ -105,13 +106,16 @@ function Requests({ requests, services, now, onOpen, onAnswered, }) {
|
|
|
105
106
|
const isEnded = !holdRunning(b, now);
|
|
106
107
|
const actions = actionsFor(b, now, emailDelivery);
|
|
107
108
|
const decline = actions.find((a) => a.status === 'cancelled');
|
|
109
|
+
// Absent once the request's time has started: it can only be declined.
|
|
108
110
|
const confirm = actions.find((a) => a.status === 'confirmed');
|
|
109
111
|
const error = errors[b.id];
|
|
110
112
|
return (_jsxs("li", { className: `pbe-request${hold?.soon ? ' pbe-request--soon' : ''}${isEnded ? ' pbe-request--ended' : ''}${error ? ' pbe-request--error' : ''}`, children: [_jsx(Ring, { size: 24, fraction: hold?.fraction ?? 0, tone: isEnded ? 'ended' : hold?.soon ? 'soon' : 'pending' }), _jsxs("span", { className: "pbe-request-hold", children: [_jsx("span", { className: "pbe-request-left", children: isEnded ? 'Hold ended' : `${formatSpan(hold.left)} left` }), _jsx("span", { className: "pbe-request-until", children: isEnded
|
|
111
|
-
?
|
|
112
|
-
?
|
|
113
|
-
:
|
|
114
|
-
|
|
113
|
+
? !confirm
|
|
114
|
+
? 'its time has passed'
|
|
115
|
+
: b.holdExpiresAt
|
|
116
|
+
? `${formatSpan(now - Date.parse(b.holdExpiresAt))} ago · confirm if free`
|
|
117
|
+
: 'confirm if free'
|
|
118
|
+
: `until ${until(b.holdExpiresAt)}` })] }), _jsx("button", { type: "button", className: "pbe-request-name", onClick: () => onOpen(b), children: b.customer.name }), _jsxs("span", { className: "pbe-request-meta", children: [_jsxs("span", { className: "pbe-request-svc", children: [b.serviceName, " \u00B7 ", priceText(b, services, locale)] }), _jsxs("span", { className: "pbe-request-when", children: [dayWord(b.date, tz, locale), " \u00B7 ", formatClockTime(b.time, locale)] })] }), _jsxs("span", { className: "pbe-request-actions", children: [_jsx(Button, { size: "sm", "aria-label": `Decline ${b.customer.name}`, loading: busy?.id === b.id && busy.status === 'cancelled', disabled: busy !== null && busy.id !== b.id, onClick: () => void act(b, decline, index), children: "Decline" }), confirm ? (_jsx(Button, { size: "sm", variant: "primary", icon: "check", "aria-label": `Confirm ${b.customer.name}`, loading: busy?.id === b.id && busy.status === 'confirmed', disabled: busy !== null && busy.id !== b.id, onClick: () => void act(b, confirm, index), children: "Confirm" })) : null] }), error ? (_jsx("div", { className: "pbe-request-error", children: _jsx(Notice, { kind: "error", children: error }) })) : null] }, b.id));
|
|
115
119
|
}) }), n > limit ? (_jsxs("button", { type: "button", className: "pbe-requests-more", "aria-expanded": expanded, "aria-controls": "pbe-requests-list", onClick: () => setExpanded((x) => !x), children: [expanded ? 'Show fewer' : `Show all ${n}`, _jsx(Icon, { name: expanded ? 'up' : 'down' })] })) : null] })] }));
|
|
116
120
|
}
|
|
117
121
|
// ---------------------------------------------------------------- KPIs ---
|
|
@@ -375,11 +379,15 @@ function ClosuresAhead({ closures, today }) {
|
|
|
375
379
|
return (_jsxs("section", { className: "pbe-card", "aria-labelledby": "pbe-closures-ahead-title", children: [_jsxs("div", { className: "pbe-card-head", children: [_jsx("h2", { id: "pbe-closures-ahead-title", className: "pbe-card-title", children: "Closures ahead" }), _jsx("div", { className: "pbe-card-actions", children: _jsxs("button", { type: "button", className: "pbe-link-button pbe-link-button--quiet", onClick: () => go('hours'), children: ["Hours & closures ", _jsx(Icon, { name: "arrow" })] }) })] }), closures === null ? (_jsx("div", { className: "pbe-card-body", children: _jsxs("div", { className: "pbe-skeleton", "aria-hidden": "true", children: [_jsx("span", { className: "pbe-sk" }), _jsx("span", { className: "pbe-sk" })] }) })) : upcoming.length ? (_jsx("ul", { className: "pbe-list-rows", children: upcoming.map((c) => (_jsxs("li", { className: "pbe-list-row", children: [_jsx("span", { className: "pbe-list-row-date", children: date(c.startsOn) }), _jsxs("span", { className: "pbe-list-row-main", children: [_jsx("span", { children: c.endsOn !== c.startsOn ? `Until ${date(c.endsOn)}` : c.startTime ? `${formatClockTime(c.startTime, locale)} – ${formatClockTime(c.endTime ?? '24:00', locale)}` : 'All day' }), _jsx("span", { children: c.reason ?? 'No note' })] })] }, c.id))) })) : (_jsx("div", { className: "pbe-card-body", children: _jsx("p", { className: "pbe-help", children: "No closures planned. Add holidays and time off so nobody can book them." }) }))] }));
|
|
376
380
|
}
|
|
377
381
|
function useHealth(email) {
|
|
378
|
-
const { settings, contentSchema, website } = useAdmin();
|
|
382
|
+
const { settings, contentSchema, website, emailDelivery } = useAdmin();
|
|
379
383
|
const items = [];
|
|
380
|
-
if (email) {
|
|
381
|
-
|
|
382
|
-
|
|
384
|
+
if (email && emailDelivery === 'none') {
|
|
385
|
+
// A demo delivers nothing: say so, with no "last sent" time.
|
|
386
|
+
items.push({ key: 'email', tone: 'ok', text: DEMO_EMAIL.health, section: 'email' });
|
|
387
|
+
}
|
|
388
|
+
else if (email) {
|
|
389
|
+
const { lastSuccessAt } = email.mailer;
|
|
390
|
+
const { failing } = emailHealth(email, emailDelivery);
|
|
383
391
|
items.push(failing
|
|
384
392
|
? { key: 'email', tone: 'bad', text: 'Booking emails failing', section: 'email' }
|
|
385
393
|
: lastSuccessAt
|
package/dist/admin/setup.d.ts
CHANGED
|
@@ -1 +1,8 @@
|
|
|
1
|
+
import type { AdminSettings } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The business step is done: a real name (not the default "My Business") and a
|
|
4
|
+
* chosen time zone (not the default UTC). Every booking time and email uses the
|
|
5
|
+
* zone, so online booking waits for it.
|
|
6
|
+
*/
|
|
7
|
+
export declare const businessReady: (s: Pick<AdminSettings, "businessName" | "timezone">) => boolean;
|
|
1
8
|
export declare function SetupChecklist(): import("react").JSX.Element | null;
|
package/dist/admin/setup.js
CHANGED
|
@@ -4,28 +4,35 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
4
4
|
import { useEffect, useState } from 'react';
|
|
5
5
|
import { ALERTS_VIEW, TEST_EMAIL_VIEW, alertsAddress } from './alerts.js';
|
|
6
6
|
import { useAdmin } from './context.js';
|
|
7
|
+
import { emailHealth } from './email-health.js';
|
|
7
8
|
import { Icon } from './icons.js';
|
|
8
9
|
import { Meter } from './ui.js';
|
|
10
|
+
/**
|
|
11
|
+
* The business step is done: a real name (not the default "My Business") and a
|
|
12
|
+
* chosen time zone (not the default UTC). Every booking time and email uses the
|
|
13
|
+
* zone, so online booking waits for it.
|
|
14
|
+
*/
|
|
15
|
+
export const businessReady = (s) => s.businessName !== 'My Business' && s.timezone !== 'UTC';
|
|
9
16
|
export function SetupChecklist() {
|
|
10
|
-
const { engine, settings, go } = useAdmin();
|
|
17
|
+
const { engine, settings, go, emailDelivery } = useAdmin();
|
|
11
18
|
const [counts, setCounts] = useState(null);
|
|
12
19
|
useEffect(() => {
|
|
13
20
|
let alive = true;
|
|
14
21
|
Promise.all([engine.admin.listServices(), engine.admin.getWorkingHours(), engine.admin.emailStatus()]).then(([s, h, e]) => {
|
|
15
22
|
if (alive && s.ok && h.ok) {
|
|
16
|
-
setCounts({ services: s.data.length, hours: h.data.length, emailWorks: e.ok
|
|
23
|
+
setCounts({ services: s.data.length, hours: h.data.length, emailWorks: emailHealth(e.ok ? e.data : null, emailDelivery).working });
|
|
17
24
|
}
|
|
18
25
|
});
|
|
19
26
|
return () => {
|
|
20
27
|
alive = false;
|
|
21
28
|
};
|
|
22
|
-
}, [engine, settings.onlineBookingEnabled]);
|
|
29
|
+
}, [engine, settings.onlineBookingEnabled, emailDelivery]);
|
|
23
30
|
if (!counts)
|
|
24
31
|
return null;
|
|
25
32
|
// Every new request is emailed to this address: without one, nobody hears about it.
|
|
26
33
|
const alerts = alertsAddress(settings);
|
|
27
34
|
const items = [
|
|
28
|
-
{ id: 'business', done: settings
|
|
35
|
+
{ id: 'business', done: businessReady(settings), text: 'Set your business name and time zone', section: 'business' },
|
|
29
36
|
{ id: 'services', done: counts.services > 0, text: 'Add your services and prices', section: 'services' },
|
|
30
37
|
{ id: 'hours', done: counts.hours > 0, text: 'Set your opening hours', section: 'hours' },
|
|
31
38
|
{ id: 'alerts', done: Boolean(alerts), text: 'Choose where new-request alerts go', section: 'email', view: ALERTS_VIEW },
|
package/dist/client.js
CHANGED
|
@@ -59,6 +59,16 @@ const VERIFY_OUTCOMES = {
|
|
|
59
59
|
slot_unavailable: 'SLOT_UNAVAILABLE',
|
|
60
60
|
too_many_bookings: 'TOO_MANY_BOOKINGS',
|
|
61
61
|
};
|
|
62
|
+
const INACTIVE_STATUSES = new Set(['cancelled', 'expired', 'completed', 'no_show']);
|
|
63
|
+
/** The code was accepted earlier, but the booking is no longer active: never an `ok` a site could show as booked. */
|
|
64
|
+
function inactiveBooking(status, reference) {
|
|
65
|
+
const error = engineError('BOOKING_INACTIVE');
|
|
66
|
+
if (typeof status === 'string' && INACTIVE_STATUSES.has(status))
|
|
67
|
+
error.bookingStatus = status;
|
|
68
|
+
if (typeof reference === 'string' && reference)
|
|
69
|
+
error.reference = reference;
|
|
70
|
+
return { ok: false, error };
|
|
71
|
+
}
|
|
62
72
|
export function createBookingEngine(options = {}) {
|
|
63
73
|
assertPublishableKey(options.supabaseKey);
|
|
64
74
|
const url = options.supabaseUrl?.trim() || null;
|
|
@@ -458,8 +468,15 @@ export function createBookingEngine(options = {}) {
|
|
|
458
468
|
if (!result.ok)
|
|
459
469
|
return result;
|
|
460
470
|
const { result: outcome, booking, attemptsLeft } = result.data;
|
|
461
|
-
if (outcome === 'verified' && booking)
|
|
462
|
-
|
|
471
|
+
if (outcome === 'verified' && booking) {
|
|
472
|
+
if (booking.status === 'pending' || booking.status === 'confirmed')
|
|
473
|
+
return ok({ ...booking, status: booking.status });
|
|
474
|
+
// A database before schema 2.0.0-beta.4 answers a repeated verification
|
|
475
|
+
// with the booking's current status, which may be cancelled or expired.
|
|
476
|
+
return inactiveBooking(booking.status, booking.reference);
|
|
477
|
+
}
|
|
478
|
+
if (outcome === 'inactive')
|
|
479
|
+
return inactiveBooking(result.data.status, result.data.reference);
|
|
463
480
|
const error = engineError(VERIFY_OUTCOMES[outcome] ?? 'UNKNOWN');
|
|
464
481
|
if (outcome === 'invalid_code' && typeof attemptsLeft === 'number')
|
|
465
482
|
error.attemptsLeft = attemptsLeft;
|
package/dist/errors.js
CHANGED
|
@@ -21,6 +21,7 @@ const MESSAGES = {
|
|
|
21
21
|
TOO_MANY_BOOKINGS: 'You already have the maximum number of upcoming bookings. Please contact us to book more.',
|
|
22
22
|
RESEND_TOO_SOON: 'Please wait a moment before asking for a new code.',
|
|
23
23
|
RESEND_LIMIT: 'No more codes can be sent for this request. Please choose your time again.',
|
|
24
|
+
BOOKING_INACTIVE: 'This booking is no longer active. Please contact us, or choose a new time.',
|
|
24
25
|
};
|
|
25
26
|
const FIELD_MESSAGES = {
|
|
26
27
|
'customer.name': 'Please enter your name.',
|
|
@@ -39,6 +40,8 @@ const FIELD_MESSAGES = {
|
|
|
39
40
|
services_exist: 'Starter services can only be added to an empty service list.',
|
|
40
41
|
service_has_bookings: 'This service has bookings. Deactivate it instead of deleting it.',
|
|
41
42
|
slot_taken: 'Someone else has booked this time since the request expired. Contact the client to choose another time.',
|
|
43
|
+
slot_held: 'Another customer is entering their email code for this time right now. Try again in a few minutes, or contact the client to choose another time.',
|
|
44
|
+
already_started: 'This time has already started, so the request can no longer be confirmed. Contact the client to choose another time.',
|
|
42
45
|
pendingHoldMinutes: 'Choose a hold between 15 minutes and 7 days.',
|
|
43
46
|
code: 'Enter the 6-digit code from the email.',
|
|
44
47
|
requestId: 'This booking request is no longer open. Please choose your time again.',
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export declare const ENGINE_PACKAGE = "@profitstudio/booking-engine";
|
|
2
|
-
export declare const ENGINE_VERSION = "2.0.0-beta.
|
|
2
|
+
export declare const ENGINE_VERSION = "2.0.0-beta.4";
|
|
3
3
|
/** Schema version this package's migrations produce. */
|
|
4
|
-
export declare const SCHEMA_VERSION = "2.0.0-
|
|
4
|
+
export declare const SCHEMA_VERSION = "2.0.0-beta.4";
|
|
5
5
|
/** Oldest database schema this package can talk to (same major). */
|
|
6
6
|
export declare const REQUIRED_SCHEMA_VERSION = "2.0.0-alpha.5";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// GENERATED by scripts/build.mjs from package.json — do not edit.
|
|
2
2
|
export const ENGINE_PACKAGE = "@profitstudio/booking-engine";
|
|
3
|
-
export const ENGINE_VERSION = "2.0.0-beta.
|
|
3
|
+
export const ENGINE_VERSION = "2.0.0-beta.4";
|
|
4
4
|
/** Schema version this package's migrations produce. */
|
|
5
|
-
export const SCHEMA_VERSION = "2.0.0-
|
|
5
|
+
export const SCHEMA_VERSION = "2.0.0-beta.4";
|
|
6
6
|
/** Oldest database schema this package can talk to (same major). */
|
|
7
7
|
export const REQUIRED_SCHEMA_VERSION = "2.0.0-alpha.5";
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { createBookingEngine, assertPublishableKey, SERVICE_MEDIA_SCHEMA, SITE_C
|
|
|
2
2
|
export type { AdminApi, AuthApi, BookingEngine, BookingEngineOptions, PreviewOptions } from './client.js';
|
|
3
3
|
export { BACKEND_ENV, BACKEND_ENV_ALIASES, checkBackendEnv } from './config.js';
|
|
4
4
|
export type { BackendEnvCheck } from './config.js';
|
|
5
|
-
export type { AdminBooking, AdminIdentity, AdminService, AdminSettings, AdminSiteContent, Availability, AvailabilityDay, AvailabilityException, AvailabilityQuery, BookingConfirmation, BookingListQuery, BookingPolicies, BookingRequest, BookingStatus, Business, CodeResent, DayStatus, EmailDeliveryStatus, EmailKind, EmailStatus, EngineError, EngineErrorCode, EngineInfo, EngineMode, ExceptionInput, OpeningHoursInterval, OpeningTimes, OpeningTimesDay, OpeningTimesQuery, PendingVerification, Preset, PresetService, PublishedSiteContent, RequestDiagnostics, RequestReleased, Result, Service, ServiceImage, ServiceImageInput, ServiceInput, SettingsPatch, Slot, UploadedSiteImage, VerifyBookingInput, Weekday, } from './types.js';
|
|
5
|
+
export type { AdminBooking, AdminIdentity, AdminService, AdminSettings, AdminSiteContent, Availability, AvailabilityDay, AvailabilityException, AvailabilityQuery, BookingConfirmation, BookingListQuery, BookingPolicies, BookingRequest, BookingStatus, Business, CodeResent, DayStatus, EmailDeliveryStatus, EmailKind, EmailStatus, EngineError, EngineErrorCode, EngineInfo, EngineMode, InactiveBookingStatus, ExceptionInput, OpeningHoursInterval, OpeningTimes, OpeningTimesDay, OpeningTimesQuery, PendingVerification, Preset, PresetService, PublishedSiteContent, RequestDiagnostics, RequestReleased, Result, Service, ServiceImage, ServiceImageInput, ServiceInput, SettingsPatch, Slot, UploadedSiteImage, VerifyBookingInput, Weekday, } from './types.js';
|
|
6
6
|
export { addDays, deviceTimeZone, formatDate, formatClockTime, formatDateTime, formatMoney, formatTime, isDifferentTimeZone, localTimeLabel, timeZoneLabel, todayInTimeZone, weekdayOf, } from './time.js';
|
|
7
7
|
export { FEW_LEFT_MAX, PARTS_OF_DAY, addMonths, daysInMonth, firstDayOfWeek, groupSlotsByPartOfDay, isFewLeft, monthGrid, monthOf, nextAvailableDay, partOfDay, startOfWeek, weekDates, } from './calendar.js';
|
|
8
8
|
export type { MonthGrid, PartOfDay } from './calendar.js';
|
package/dist/types.d.ts
CHANGED
|
@@ -22,7 +22,15 @@ export type EngineErrorCode = 'INVALID_INPUT' | 'SERVICE_UNAVAILABLE' | 'SLOT_UN
|
|
|
22
22
|
/** A new code can be sent after `retryAfterSeconds`. */
|
|
23
23
|
| 'RESEND_TOO_SOON'
|
|
24
24
|
/** No more codes for this request (3 re-sends). */
|
|
25
|
-
| 'RESEND_LIMIT'
|
|
25
|
+
| 'RESEND_LIMIT'
|
|
26
|
+
/**
|
|
27
|
+
* The code was accepted earlier, but the booking is no longer active: the
|
|
28
|
+
* owner declined or cancelled it, the request's hold lapsed, or it was marked
|
|
29
|
+
* done or a no-show (`bookingStatus` says which). Never show it as booked.
|
|
30
|
+
*/
|
|
31
|
+
| 'BOOKING_INACTIVE';
|
|
32
|
+
/** Why a verified booking is no longer active (BOOKING_INACTIVE). */
|
|
33
|
+
export type InactiveBookingStatus = 'cancelled' | 'expired' | 'completed' | 'no_show';
|
|
26
34
|
export interface EngineError {
|
|
27
35
|
code: EngineErrorCode;
|
|
28
36
|
/** Safe, human-readable English. Sites may map `code` (and `field`) to their own copy. */
|
|
@@ -33,6 +41,10 @@ export interface EngineError {
|
|
|
33
41
|
attemptsLeft?: number;
|
|
34
42
|
/** RESEND_TOO_SOON: seconds until a new code can be requested. */
|
|
35
43
|
retryAfterSeconds?: number;
|
|
44
|
+
/** BOOKING_INACTIVE: what became of the booking. */
|
|
45
|
+
bookingStatus?: InactiveBookingStatus;
|
|
46
|
+
/** BOOKING_INACTIVE: the booking's reference, for "contact us about …". */
|
|
47
|
+
reference?: string;
|
|
36
48
|
}
|
|
37
49
|
/** Every engine call resolves to a Result. Engine calls never throw for expected failures. */
|
|
38
50
|
export type Result<T> = {
|
|
@@ -222,7 +234,11 @@ export interface CodeResent {
|
|
|
222
234
|
}
|
|
223
235
|
export interface BookingConfirmation {
|
|
224
236
|
reference: string;
|
|
225
|
-
/**
|
|
237
|
+
/**
|
|
238
|
+
* pending = a verified request the business will confirm or decline; confirmed = booked.
|
|
239
|
+
* Never anything else: a booking that is no longer active is the error BOOKING_INACTIVE.
|
|
240
|
+
* Say "booked" only when status === 'confirmed'.
|
|
241
|
+
*/
|
|
226
242
|
status: 'pending' | 'confirmed';
|
|
227
243
|
startsAt: string;
|
|
228
244
|
endsAt: string;
|
package/docs/BUILD-A-SITE.md
CHANGED
|
@@ -157,6 +157,8 @@ Never compute availability yourself; show times in the business time zone.
|
|
|
157
157
|
`cancelBookingRequest(requestId)`, then reload availability.
|
|
158
158
|
5. **Done** only when `verifyBooking` returned `ok: true`: `data.status` `'pending'`
|
|
159
159
|
(“Request received — we'll confirm shortly”) or `'confirmed'`, plus `reference`.
|
|
160
|
+
Say “booked” only when `data.status === 'confirmed'`. `BOOKING_INACTIVE` (the code was
|
|
161
|
+
accepted earlier, but the request was declined or lapsed meanwhile) is never a success.
|
|
160
162
|
|
|
161
163
|
| Error | Show |
|
|
162
164
|
|---|---|
|
package/docs/INTEGRATION.md
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# Booking Engine — Integration Contract
|
|
2
2
|
|
|
3
|
-
`@profitstudio/booking-engine` · engine 2.0.0-beta.
|
|
3
|
+
`@profitstudio/booking-engine` · engine 2.0.0-beta.4 · database schema 2.0.0-beta.4
|
|
4
4
|
(booking works from schema alpha.5; website content (§15) needs alpha.7;
|
|
5
|
-
service photos and opening times need alpha.10
|
|
5
|
+
service photos and opening times need alpha.10; the owner-confirmation fixes of
|
|
6
|
+
beta.4 need beta.4 — the website client gives the answers of §6 on every schema)
|
|
6
7
|
|
|
7
8
|
This document is the contract between the engine and the website built around
|
|
8
9
|
it. It is written for developers **and for AI coding assistants**. Where a
|
|
@@ -56,7 +57,7 @@ prompt and this document disagree on a technical point, this document wins.
|
|
|
56
57
|
## 3. Install
|
|
57
58
|
|
|
58
59
|
```bash
|
|
59
|
-
npm install --save-exact @profitstudio/booking-engine@2.0.0-beta.
|
|
60
|
+
npm install --save-exact @profitstudio/booking-engine@2.0.0-beta.4 # exact version from the guide
|
|
60
61
|
npx booking-engine init # a hair salon may add: --preset hair-salon
|
|
61
62
|
```
|
|
62
63
|
|
|
@@ -350,12 +351,22 @@ const v = await engine.verifyBooking({ requestId, code }); // spaces and dashe
|
|
|
350
351
|
email.” (The wording is yours.)
|
|
351
352
|
- `status: 'confirmed'` — the owner turned on instant confirmation: it is
|
|
352
353
|
booked (“You're booked — a confirmation is on its way.”).
|
|
353
|
-
-
|
|
354
|
-
|
|
354
|
+
- **Say “booked” only when `status === 'confirmed'`**, “request received” only
|
|
355
|
+
when it is `'pending'` — never `status === 'pending' ? request : booked`.
|
|
356
|
+
`ok` never carries any other status.
|
|
357
|
+
- Calling it again with the same code answers with the booking **as it stands
|
|
358
|
+
now** (safe on retry, a double click, or an answer lost on the way): the same
|
|
359
|
+
confirmation while it is still pending or confirmed (a pending request the
|
|
360
|
+
owner has confirmed meanwhile comes back `'confirmed'`), and
|
|
361
|
+
`BOOKING_INACTIVE` once the owner declined or cancelled it, its hold lapsed,
|
|
362
|
+
or it was marked done or a no-show. Show `reference` on the confirmation.
|
|
355
363
|
- Errors: `INVALID_INPUT` (`field`: `code` — not 6 digits, not counted as an
|
|
356
364
|
attempt; or `requestId`), `INVALID_CODE` (`attemptsLeft`), `CODE_EXPIRED`,
|
|
357
365
|
`TOO_MANY_ATTEMPTS`, `SLOT_UNAVAILABLE` (the owner closed the time
|
|
358
|
-
meanwhile), `TOO_MANY_BOOKINGS`, `
|
|
366
|
+
meanwhile), `TOO_MANY_BOOKINGS`, `BOOKING_INACTIVE` (the code was accepted
|
|
367
|
+
earlier, but the booking is no longer active: `bookingStatus` is
|
|
368
|
+
`'cancelled'`, `'expired'`, `'completed'` or `'no_show'`, and
|
|
369
|
+
`reference` names it), `NETWORK`. After `CODE_EXPIRED`,
|
|
359
370
|
`TOO_MANY_ATTEMPTS`, `SLOT_UNAVAILABLE` and `TOO_MANY_BOOKINGS` the request
|
|
360
371
|
is closed and its time released: entering the code again returns
|
|
361
372
|
`CODE_EXPIRED`.
|
|
@@ -372,7 +383,8 @@ Errors: `RESEND_TOO_SOON` (`retryAfterSeconds`), `RESEND_LIMIT` (no more new
|
|
|
372
383
|
codes — **the current code still works until `expiresAt`**: keep the code
|
|
373
384
|
step), `CODE_EXPIRED`, `RATE_LIMITED` (the current code still works),
|
|
374
385
|
`CONFLICT` with `field: 'already_verified'` (the code was already accepted —
|
|
375
|
-
call `verifyBooking` with it again to show the
|
|
386
|
+
call `verifyBooking` with it again to show where the booking stands: the
|
|
387
|
+
confirmation, or `BOOKING_INACTIVE`),
|
|
376
388
|
`INVALID_INPUT` (`requestId`), `NETWORK`. Preview: works like live (60 s apart,
|
|
377
389
|
at most 3) but sends nothing.
|
|
378
390
|
|
|
@@ -397,7 +409,7 @@ Package and database schema versions, `mode`, and `compatible`.
|
|
|
397
409
|
|
|
398
410
|
## 7. Errors — handle every code
|
|
399
411
|
|
|
400
|
-
`EngineError = { code, message, field?, attemptsLeft?, retryAfterSeconds? }`.
|
|
412
|
+
`EngineError = { code, message, field?, attemptsLeft?, retryAfterSeconds?, bookingStatus?, reference? }`.
|
|
401
413
|
`message` is safe English text; you may show it or map `code` to your own wording.
|
|
402
414
|
|
|
403
415
|
| Code | Meaning | What the UI should do |
|
|
@@ -413,6 +425,7 @@ Package and database schema versions, `mode`, and `compatible`.
|
|
|
413
425
|
| `TOO_MANY_BOOKINGS` | This (verified) address already has the maximum number of upcoming bookings; the request was closed and its time released | End the code step; suggest contacting the business |
|
|
414
426
|
| `RESEND_TOO_SOON` | A new code can be sent after `retryAfterSeconds` | Allow “Send a new code” after that — a countdown, or a calm “in a minute” where the site's tone rules out timers |
|
|
415
427
|
| `RESEND_LIMIT` | No more new codes for this request; the current code still works until `expiresAt` | Keep the code step; say no more codes can be sent |
|
|
428
|
+
| `BOOKING_INACTIVE` | The code was accepted earlier, but the booking is no longer active (`bookingStatus`: `cancelled` — declined or cancelled by the business; `expired` — the request was not answered in time; `completed` / `no_show`) | End the code step: “This request is no longer active — please contact us” (with `reference`), and offer to choose a new time. Never a success screen |
|
|
416
429
|
| `PREVIEW_MODE` | No backend (preview) | Show “Preview: nothing was saved” — never a success screen |
|
|
417
430
|
| `VERIFICATION_REQUIRED` | The site still calls the removed `createBooking` | Developer error: switch to `requestBooking` + `verifyBooking` |
|
|
418
431
|
| `NOT_CONFIGURED` | No backend in production | “Online booking is not available yet” |
|
|
@@ -473,10 +486,13 @@ A good flow (layout and style are yours):
|
|
|
473
486
|
then reloads availability (otherwise the released time may be missing from
|
|
474
487
|
the reload), and remind the customer to check their spam folder. If the
|
|
475
488
|
cancel answers `CONFLICT` / `already_verified`, the code was already
|
|
476
|
-
accepted (an earlier answer was lost):
|
|
477
|
-
|
|
489
|
+
accepted (an earlier answer was lost): call `verifyBooking` with the same
|
|
490
|
+
code instead of going back, and show what it answers — the confirmation, or
|
|
491
|
+
`BOOKING_INACTIVE` (the owner may have declined it, or its hold lapsed,
|
|
492
|
+
meanwhile).
|
|
478
493
|
6. **Done** — on success a confirmation with service, date (`formatDate`),
|
|
479
|
-
time, reference and the
|
|
494
|
+
time, reference and the wording for its status: “booked” only for
|
|
495
|
+
`'confirmed'`, “request received” for `'pending'`.
|
|
480
496
|
|
|
481
497
|
Requirements: buttons and inputs are keyboard-operable with visible focus;
|
|
482
498
|
inputs have labels; errors are announced (`role="alert"` or `aria-live`); move
|
|
@@ -627,7 +643,9 @@ owner has no services; default the engine's own — pass the site's preset from
|
|
|
627
643
|
§5 for any other kind of business) and `emailDelivery` (optional, since
|
|
628
644
|
2.0.0-beta.2: `'live'` by default; `'none'` only for a public demo or showcase
|
|
629
645
|
that never emails anyone — the dashboard then never says a customer gets an
|
|
630
|
-
email
|
|
646
|
+
email, and, since 2.0.0-beta.3, never reports a delivery: the Today health
|
|
647
|
+
line, the Email page's status card and its list of emails say that email is
|
|
648
|
+
simulated, with no delivery time, count or "Sent". A real site never sets it).
|
|
631
649
|
|
|
632
650
|
The dashboard handles sign-in, the admin check, a **Today** overview (the
|
|
633
651
|
requests waiting for an answer, with their hold countdown and Confirm /
|
|
@@ -809,6 +827,30 @@ an upgrade guide. A site that does not upgrade keeps working on its version.
|
|
|
809
827
|
`sync` also updates `supabase/functions/booking-mailer/`; redeploy it with
|
|
810
828
|
`npx supabase@2 functions deploy booking-mailer --no-verify-jwt --use-api`.
|
|
811
829
|
|
|
830
|
+
### Upgrading from 2.0.0-beta.3 (and earlier betas)
|
|
831
|
+
|
|
832
|
+
`sync` adds migration `0009_reliable_answers` (bug fixes only; no table or
|
|
833
|
+
data changes; run `db push`). Website code: show “booked” only when
|
|
834
|
+
`verifyBooking` returns `status === 'confirmed'`, and handle the new error
|
|
835
|
+
`BOOKING_INACTIVE` at the code step (§6, §7) — a site that does not handle it
|
|
836
|
+
yet treats it as `UNKNOWN`, which never claims a booking. What changed:
|
|
837
|
+
|
|
838
|
+
- Verifying again with an accepted code (after a lost answer, a double click,
|
|
839
|
+
or the `already_verified` answer of a re-send or cancel) used to return the
|
|
840
|
+
booking's current status as a success, `cancelled` and `expired`
|
|
841
|
+
included, and a site that treated every status but `'pending'` as booked
|
|
842
|
+
could say “booked” for a declined or lapsed request. Now `ok` is only ever
|
|
843
|
+
`'pending'` or `'confirmed'`; anything else is `BOOKING_INACTIVE`. The
|
|
844
|
+
client applies this on every schema, so it holds even before `db push`.
|
|
845
|
+
- The owner can no longer confirm a request whose time has started; the
|
|
846
|
+
dashboard no longer offers it.
|
|
847
|
+
- Confirming an expired request no longer fails with “Someone else has booked
|
|
848
|
+
this time” because of a hold that had already lapsed; a visitor still
|
|
849
|
+
entering their code for that time gets its own message.
|
|
850
|
+
- The dashboard switches online booking on only once the business name and
|
|
851
|
+
time zone are set (the first setup step), and with `emailDelivery="none"`
|
|
852
|
+
it warns if the database has sent real email.
|
|
853
|
+
|
|
812
854
|
### Upgrading from 2.0.0-alpha.13
|
|
813
855
|
|
|
814
856
|
No migration and no website code change: `npm install` + `sync`, rebuild.
|
package/engine.manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"package": "@profitstudio/booking-engine",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
4
|
-
"schemaVersion": "2.0.0-
|
|
3
|
+
"version": "2.0.0-beta.4",
|
|
4
|
+
"schemaVersion": "2.0.0-beta.4",
|
|
5
5
|
"requiredSchemaVersion": "2.0.0-alpha.5",
|
|
6
6
|
"migrations": [
|
|
7
7
|
{
|
|
@@ -51,6 +51,12 @@
|
|
|
51
51
|
"file": "migrations/0008_service_images_opening_times.sql",
|
|
52
52
|
"schemaVersion": "2.0.0-alpha.10",
|
|
53
53
|
"sha256": "7bd73c7a71cf11cfcf1c20c00072f2bd163f6656af6314186e95a107b26ff6b8"
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"id": "0009_reliable_answers",
|
|
57
|
+
"file": "migrations/0009_reliable_answers.sql",
|
|
58
|
+
"schemaVersion": "2.0.0-beta.4",
|
|
59
|
+
"sha256": "ec4300201569a87451e05bf3fddecc1762fd28683cd3fbb98c0b13866a3b1774"
|
|
54
60
|
}
|
|
55
61
|
],
|
|
56
62
|
"functions": [
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
-- ============================================================================
|
|
2
|
+
-- Profit Studio Booking Engine — migration 0009_reliable_answers
|
|
3
|
+
-- Engine schema version: 2.0.0-beta.4
|
|
4
|
+
--
|
|
5
|
+
-- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
|
|
6
|
+
--
|
|
7
|
+
-- Bug fixes only (no table, column, constraint, policy or grant on existing
|
|
8
|
+
-- objects changes; the two replaced functions keep their signatures):
|
|
9
|
+
-- 1. Verifying again with an accepted code answers with the booking as it
|
|
10
|
+
-- stands now, and only an active one (pending or confirmed) is
|
|
11
|
+
-- `verified`. A declined, cancelled, lapsed, completed or no-show booking is
|
|
12
|
+
-- `{ result: 'inactive', status, reference }`, never a booking a website
|
|
13
|
+
-- could show as booked. (Before: `verified` with the current status,
|
|
14
|
+
-- e.g. 'cancelled'.)
|
|
15
|
+
-- 2. The owner can no longer confirm a request whose time has started
|
|
16
|
+
-- (INVALID_TRANSITION, detail `already_started`).
|
|
17
|
+
-- 3. Confirming an expired request first releases holds that lapsed but were
|
|
18
|
+
-- not released yet, so only a real conflict refuses it: a request or
|
|
19
|
+
-- booking (CONFLICT `slot_taken`, as before) or a visitor entering their
|
|
20
|
+
-- code for that time right now (CONFLICT `slot_held`, new).
|
|
21
|
+
--
|
|
22
|
+
-- No row changes. Bookings, holds, emails and settings are untouched.
|
|
23
|
+
-- ============================================================================
|
|
24
|
+
|
|
25
|
+
do $$
|
|
26
|
+
declare
|
|
27
|
+
v text;
|
|
28
|
+
begin
|
|
29
|
+
select e.schema_version into v from booking.engine_info e where e.id;
|
|
30
|
+
if v is distinct from '2.0.0-alpha.10' then
|
|
31
|
+
raise exception 'Booking Engine 0009_reliable_answers expects schema 2.0.0-alpha.10, found %', coalesce(v, 'none');
|
|
32
|
+
end if;
|
|
33
|
+
end
|
|
34
|
+
$$;
|
|
35
|
+
|
|
36
|
+
-- ----------------------------------------------------------------------------
|
|
37
|
+
-- 1. Verifying again: only an active booking is an answer of 'verified'
|
|
38
|
+
-- ----------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
create or replace function booking.verify_booking(p_request_id uuid, p_code text)
|
|
41
|
+
returns jsonb
|
|
42
|
+
language plpgsql
|
|
43
|
+
volatile
|
|
44
|
+
security definer
|
|
45
|
+
set search_path = ''
|
|
46
|
+
as $$
|
|
47
|
+
declare
|
|
48
|
+
c_max_attempts constant int := 5;
|
|
49
|
+
v_code text := regexp_replace(coalesce(p_code, ''), '[[:space:]-]', '', 'g');
|
|
50
|
+
v booking.verifications%rowtype;
|
|
51
|
+
b booking.bookings%rowtype;
|
|
52
|
+
v_settings booking.settings%rowtype;
|
|
53
|
+
v_local_day date;
|
|
54
|
+
v_count int;
|
|
55
|
+
v_status text;
|
|
56
|
+
begin
|
|
57
|
+
if p_request_id is null then
|
|
58
|
+
perform booking.raise_error('INVALID_INPUT', 'requestId');
|
|
59
|
+
end if;
|
|
60
|
+
if v_code !~ '^[0-9]{6}$' then
|
|
61
|
+
perform booking.raise_error('INVALID_INPUT', 'code');
|
|
62
|
+
end if;
|
|
63
|
+
|
|
64
|
+
-- Results are returned, not raised, so counted attempts are kept.
|
|
65
|
+
select * into v from booking.verifications where id = p_request_id for update;
|
|
66
|
+
if not found then
|
|
67
|
+
return jsonb_build_object('result', 'expired');
|
|
68
|
+
end if;
|
|
69
|
+
select * into b from booking.bookings where id = v.booking_id for update;
|
|
70
|
+
|
|
71
|
+
-- Already verified: the same code gives the booking's answer as it stands now
|
|
72
|
+
-- (retries, double clicks, an answer lost on the way). Only a booking that is
|
|
73
|
+
-- still active is an answer of 'verified'; one the owner declined or
|
|
74
|
+
-- cancelled, a request whose hold lapsed, or an appointment marked done or a
|
|
75
|
+
-- no-show is 'inactive', so no website can show it as booked.
|
|
76
|
+
if v.verified_at is not null then
|
|
77
|
+
if b.id is not null and v.code_hash = booking.code_hash(v.id, v_code) then
|
|
78
|
+
v_status := booking.effective_status(b.status, b.hold_expires_at);
|
|
79
|
+
if v_status in ('pending', 'confirmed') then
|
|
80
|
+
return jsonb_build_object('result', 'verified', 'booking', booking.public_booking_json(b));
|
|
81
|
+
end if;
|
|
82
|
+
return jsonb_build_object('result', 'inactive', 'status', v_status, 'reference', b.reference);
|
|
83
|
+
end if;
|
|
84
|
+
return jsonb_build_object('result', 'invalid_code', 'attemptsLeft', 0);
|
|
85
|
+
end if;
|
|
86
|
+
|
|
87
|
+
if v.attempts >= c_max_attempts then
|
|
88
|
+
if b.id is not null and b.status = 'unverified' then
|
|
89
|
+
delete from booking.bookings where id = b.id;
|
|
90
|
+
end if;
|
|
91
|
+
return jsonb_build_object('result', 'locked');
|
|
92
|
+
end if;
|
|
93
|
+
|
|
94
|
+
if b.id is null or b.status <> 'unverified' or v.expires_at <= now() or b.hold_expires_at <= now() then
|
|
95
|
+
if b.id is not null and b.status = 'unverified' then
|
|
96
|
+
delete from booking.bookings where id = b.id;
|
|
97
|
+
end if;
|
|
98
|
+
return jsonb_build_object('result', 'expired');
|
|
99
|
+
end if;
|
|
100
|
+
|
|
101
|
+
if v.code_hash <> booking.code_hash(v.id, v_code) then
|
|
102
|
+
update booking.verifications set attempts = attempts + 1 where id = v.id returning * into v;
|
|
103
|
+
if v.attempts >= c_max_attempts then
|
|
104
|
+
delete from booking.bookings where id = b.id;
|
|
105
|
+
return jsonb_build_object('result', 'locked');
|
|
106
|
+
end if;
|
|
107
|
+
return jsonb_build_object('result', 'invalid_code', 'attemptsLeft', c_max_attempts - v.attempts);
|
|
108
|
+
end if;
|
|
109
|
+
|
|
110
|
+
-- The code is right. Recheck the time as it was offered when requested:
|
|
111
|
+
-- the hold kept other customers out, but the owner may have closed it.
|
|
112
|
+
select * into v_settings from booking.settings where id;
|
|
113
|
+
v_local_day := (b.starts_at at time zone v_settings.timezone)::date;
|
|
114
|
+
if b.starts_at <= now() or not exists (
|
|
115
|
+
select 1
|
|
116
|
+
from booking.compute_slots(b.service_id, v_local_day, v_local_day, b.created_at, b.resource_id, b.id) as cs
|
|
117
|
+
where cs.starts_at = b.starts_at
|
|
118
|
+
) then
|
|
119
|
+
delete from booking.bookings where id = b.id;
|
|
120
|
+
return jsonb_build_object('result', 'slot_unavailable');
|
|
121
|
+
end if;
|
|
122
|
+
|
|
123
|
+
-- The per-address cap applies only now: the person asking owns the address.
|
|
124
|
+
perform pg_advisory_xact_lock(hashtextextended('booking_engine:verified:' || lower(b.customer_email), 0));
|
|
125
|
+
select count(*) into v_count
|
|
126
|
+
from booking.bookings x
|
|
127
|
+
where lower(x.customer_email) = lower(b.customer_email)
|
|
128
|
+
and x.id <> b.id
|
|
129
|
+
and x.status in ('pending', 'confirmed')
|
|
130
|
+
and (x.status = 'confirmed' or x.hold_expires_at is null or x.hold_expires_at > now())
|
|
131
|
+
and x.starts_at > now();
|
|
132
|
+
if v_count >= v_settings.max_active_bookings_per_email then
|
|
133
|
+
delete from booking.bookings where id = b.id;
|
|
134
|
+
return jsonb_build_object('result', 'too_many_bookings');
|
|
135
|
+
end if;
|
|
136
|
+
|
|
137
|
+
v_status := case when v_settings.auto_confirm then 'confirmed' else 'pending' end;
|
|
138
|
+
update booking.bookings
|
|
139
|
+
set status = v_status,
|
|
140
|
+
email_verified_at = now(),
|
|
141
|
+
status_changed_at = now(),
|
|
142
|
+
hold_expires_at = case when v_status = 'pending'
|
|
143
|
+
then least(now() + make_interval(mins => v_settings.pending_hold_minutes), b.starts_at) end
|
|
144
|
+
where id = b.id
|
|
145
|
+
returning * into b;
|
|
146
|
+
update booking.verifications set verified_at = now() where id = v.id;
|
|
147
|
+
|
|
148
|
+
insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor)
|
|
149
|
+
values (b.id, 'status_changed', 'unverified', v_status, 'customer');
|
|
150
|
+
|
|
151
|
+
perform booking.enqueue_email(
|
|
152
|
+
case when v_status = 'confirmed' then 'booking_confirmed' else 'request_received' end,
|
|
153
|
+
b.customer_email, b.id, booking.booking_email_payload(b, false),
|
|
154
|
+
case when v_status = 'confirmed' then 'booking_confirmed:' else 'request_received:' end || b.id);
|
|
155
|
+
perform booking.enqueue_email('owner_new_request',
|
|
156
|
+
coalesce(v_settings.owner_notification_email, v_settings.public_email), b.id,
|
|
157
|
+
booking.booking_email_payload(b, true), 'owner_new_request:' || b.id);
|
|
158
|
+
|
|
159
|
+
return jsonb_build_object('result', 'verified', 'booking', booking.public_booking_json(b));
|
|
160
|
+
end;
|
|
161
|
+
$$;
|
|
162
|
+
|
|
163
|
+
comment on function booking.verify_booking(uuid, text) is
|
|
164
|
+
'PRIVILEGED (SECURITY DEFINER), private schema. Checks a one-time code (5 attempts, single use), rechecks the time and turns the hold into a request or a confirmed booking; queues the customer and owner emails. Idempotent: the same code again answers with the booking as it stands now — verified while pending or confirmed, inactive (with its status) once declined, cancelled, expired, completed or a no-show. Reached through public.booking_verify.';
|
|
165
|
+
|
|
166
|
+
-- ----------------------------------------------------------------------------
|
|
167
|
+
-- 2 and 3. The owner's answer to a request
|
|
168
|
+
-- ----------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
-- Releases the holds around one booking's time that lapsed but were not
|
|
171
|
+
-- released yet — exactly what a visitor's request for that time does
|
|
172
|
+
-- (booking.expire_lapsed). Live holds and every other booking are untouched.
|
|
173
|
+
-- Admins only; used by booking_admin_set_booking_status, which runs with the
|
|
174
|
+
-- admin's own rights and cannot delete holds itself.
|
|
175
|
+
create function booking.release_lapsed_holds(p_booking_id uuid)
|
|
176
|
+
returns int
|
|
177
|
+
language plpgsql
|
|
178
|
+
volatile
|
|
179
|
+
security definer
|
|
180
|
+
set search_path = ''
|
|
181
|
+
as $$
|
|
182
|
+
declare
|
|
183
|
+
b booking.bookings%rowtype;
|
|
184
|
+
begin
|
|
185
|
+
perform booking.require_admin();
|
|
186
|
+
select * into b from booking.bookings where id = p_booking_id;
|
|
187
|
+
if not found then
|
|
188
|
+
return 0;
|
|
189
|
+
end if;
|
|
190
|
+
return booking.expire_lapsed(b.resource_id, b.starts_at, b.blocked_until);
|
|
191
|
+
end;
|
|
192
|
+
$$;
|
|
193
|
+
comment on function booking.release_lapsed_holds(uuid) is
|
|
194
|
+
'PRIVILEGED (SECURITY DEFINER), private schema, admins only. Releases lapsed holds overlapping one booking''s time (booking.expire_lapsed) before the owner confirms an expired request. Reached through public.booking_admin_set_booking_status.';
|
|
195
|
+
|
|
196
|
+
create or replace function public.booking_admin_set_booking_status(p_booking_id uuid, p_status text)
|
|
197
|
+
returns jsonb
|
|
198
|
+
language plpgsql
|
|
199
|
+
volatile
|
|
200
|
+
security invoker
|
|
201
|
+
set search_path = ''
|
|
202
|
+
as $$
|
|
203
|
+
declare
|
|
204
|
+
v_uid uuid;
|
|
205
|
+
v_tz text;
|
|
206
|
+
b booking.bookings%rowtype;
|
|
207
|
+
v_from text;
|
|
208
|
+
v_stored text;
|
|
209
|
+
begin
|
|
210
|
+
v_uid := booking.require_admin();
|
|
211
|
+
if p_status is null or p_status not in ('confirmed', 'cancelled', 'completed', 'no_show') then
|
|
212
|
+
perform booking.raise_error('INVALID_INPUT', 'status');
|
|
213
|
+
end if;
|
|
214
|
+
|
|
215
|
+
select * into b from booking.bookings where id = p_booking_id for update;
|
|
216
|
+
if not found or b.status = 'unverified' then
|
|
217
|
+
perform booking.raise_error('NOT_FOUND', 'booking');
|
|
218
|
+
end if;
|
|
219
|
+
select s.timezone into v_tz from booking.settings s where s.id;
|
|
220
|
+
|
|
221
|
+
v_stored := b.status;
|
|
222
|
+
v_from := booking.effective_status(b.status, b.hold_expires_at);
|
|
223
|
+
if v_from = p_status then
|
|
224
|
+
return booking.booking_json(b, v_tz);
|
|
225
|
+
end if;
|
|
226
|
+
if not (
|
|
227
|
+
(v_from in ('pending', 'expired') and p_status in ('confirmed', 'cancelled'))
|
|
228
|
+
or (v_from = 'confirmed' and p_status in ('cancelled', 'completed', 'no_show'))
|
|
229
|
+
) then
|
|
230
|
+
perform booking.raise_error('INVALID_TRANSITION', v_from || '->' || p_status);
|
|
231
|
+
end if;
|
|
232
|
+
if p_status in ('completed', 'no_show') and b.starts_at > now() then
|
|
233
|
+
perform booking.raise_error('INVALID_TRANSITION', 'not_started');
|
|
234
|
+
end if;
|
|
235
|
+
-- A request can be confirmed only for a time still ahead: once it has
|
|
236
|
+
-- started, the customer has been told it expired, and a confirmation would
|
|
237
|
+
-- be for a time that has passed.
|
|
238
|
+
if p_status = 'confirmed' and b.starts_at <= now() then
|
|
239
|
+
perform booking.raise_error('INVALID_TRANSITION', 'already_started');
|
|
240
|
+
end if;
|
|
241
|
+
|
|
242
|
+
-- An expired request no longer holds its time. Before it takes the time
|
|
243
|
+
-- back, holds that lapsed but were not released yet (the regular sweep runs
|
|
244
|
+
-- every few minutes) are released, as a visitor asking for the time would.
|
|
245
|
+
-- A request still stored as pending holds its time, so nothing overlaps it.
|
|
246
|
+
if p_status = 'confirmed' and v_stored = 'expired' then
|
|
247
|
+
perform booking.release_lapsed_holds(b.id);
|
|
248
|
+
end if;
|
|
249
|
+
|
|
250
|
+
begin
|
|
251
|
+
update booking.bookings
|
|
252
|
+
set status = p_status, hold_expires_at = null, status_changed_at = now()
|
|
253
|
+
where id = b.id
|
|
254
|
+
returning * into b;
|
|
255
|
+
exception
|
|
256
|
+
when exclusion_violation then
|
|
257
|
+
-- The time is no longer free: a request or booking took it meanwhile, or
|
|
258
|
+
-- a visitor is entering their email code for it right now (a live hold
|
|
259
|
+
-- that ends within the verification window).
|
|
260
|
+
if exists (
|
|
261
|
+
select 1 from booking.bookings x
|
|
262
|
+
where x.resource_id = b.resource_id
|
|
263
|
+
and x.id <> b.id
|
|
264
|
+
and x.status in ('pending', 'confirmed')
|
|
265
|
+
and tstzrange(x.starts_at, x.blocked_until, '[)') && tstzrange(b.starts_at, b.blocked_until, '[)')
|
|
266
|
+
) then
|
|
267
|
+
perform booking.raise_error('CONFLICT', 'slot_taken');
|
|
268
|
+
end if;
|
|
269
|
+
perform booking.raise_error('CONFLICT', 'slot_held');
|
|
270
|
+
end;
|
|
271
|
+
|
|
272
|
+
insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor, actor_user_id)
|
|
273
|
+
values (b.id, 'status_changed', v_from, p_status, 'admin', v_uid);
|
|
274
|
+
|
|
275
|
+
-- Tell the customer. Only verified addresses are emailed; a customer whose
|
|
276
|
+
-- request was already reported as expired is not told twice.
|
|
277
|
+
if b.email_verified_at is not null then
|
|
278
|
+
if p_status = 'confirmed' then
|
|
279
|
+
perform booking.enqueue_email('booking_confirmed', b.customer_email, b.id,
|
|
280
|
+
booking.booking_email_payload(b, false), 'booking_confirmed:' || b.id);
|
|
281
|
+
elsif p_status = 'cancelled' and v_from = 'confirmed' then
|
|
282
|
+
perform booking.enqueue_email('booking_cancelled', b.customer_email, b.id,
|
|
283
|
+
booking.booking_email_payload(b, false), 'booking_cancelled:' || b.id);
|
|
284
|
+
elsif p_status = 'cancelled' and v_stored = 'pending' then
|
|
285
|
+
perform booking.enqueue_email('booking_declined', b.customer_email, b.id,
|
|
286
|
+
booking.booking_email_payload(b, false), 'booking_declined:' || b.id);
|
|
287
|
+
end if;
|
|
288
|
+
end if;
|
|
289
|
+
|
|
290
|
+
return booking.booking_json(b, v_tz);
|
|
291
|
+
end;
|
|
292
|
+
$$;
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
-- ----------------------------------------------------------------------------
|
|
296
|
+
-- Privileges: the new helper starts with no access, then admins (signed in).
|
|
297
|
+
-- `create or replace` keeps the grants of the two replaced functions.
|
|
298
|
+
-- ----------------------------------------------------------------------------
|
|
299
|
+
|
|
300
|
+
revoke all on function booking.release_lapsed_holds(uuid) from public, anon, authenticated, service_role;
|
|
301
|
+
grant execute on function booking.release_lapsed_holds(uuid) to authenticated;
|
|
302
|
+
|
|
303
|
+
update booking.engine_info set schema_version = '2.0.0-beta.4', updated_at = now() where id;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@profitstudio/booking-engine",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.4",
|
|
4
4
|
"description": "Secure, versioned booking engine for independently owned small-business websites: Supabase migrations, a typed client, an admin dashboard and a CLI.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Youssef Es-salhi",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"node": ">=20.19"
|
|
55
55
|
},
|
|
56
56
|
"bookingEngine": {
|
|
57
|
-
"schemaVersion": "2.0.0-
|
|
57
|
+
"schemaVersion": "2.0.0-beta.4",
|
|
58
58
|
"requiredSchemaVersion": "2.0.0-alpha.5"
|
|
59
59
|
},
|
|
60
60
|
"scripts": {
|
|
@@ -21,7 +21,9 @@ Connect Supabase and email: `npx booking-engine connect` (INTEGRATION.md §11)
|
|
|
21
21
|
"Choose another time" (`cancelBookingRequest()`, then reload availability).
|
|
22
22
|
- Handle `ok: false` on every engine call (see the error table in INTEGRATION.md).
|
|
23
23
|
- Show success only when `verifyBooking()` returned `ok: true`, and say whether the
|
|
24
|
-
booking is a request (`pending`, the business will confirm) or `confirmed`.
|
|
24
|
+
booking is a request (`pending`, the business will confirm) or `confirmed`. Say
|
|
25
|
+
"booked" only when `status === 'confirmed'`; `BOOKING_INACTIVE` (declined or lapsed
|
|
26
|
+
meanwhile) is never a success.
|
|
25
27
|
- When `business.policies.onlineBookingEnabled` is false, show contact details instead of the form.
|
|
26
28
|
- Every Book button on the page reaches the booking section in every state (also while
|
|
27
29
|
booking is off, loading or failed) — never a click that does nothing.
|