@profitstudio/booking-engine 2.0.0-beta.3 → 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 CHANGED
@@ -1,5 +1,55 @@
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
+
3
53
  ## 2.0.0-beta.3 — 2026-11-06
4
54
 
5
55
  Honest email health in 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.3 — 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.
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
 
@@ -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
- return [
30
- {
31
- status: 'cancelled',
32
- label: 'Decline',
33
- tone: 'danger',
34
- confirm: {
35
- title: `Decline ${b.customer.name}’s request?`,
36
- body: `The time opens again for other customers. ${notifies(b, delivery)}`,
37
- confirmLabel: 'Decline request',
38
- cancelLabel: 'Keep the request',
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
- { status: 'confirmed', label: 'Confirm', tone: 'primary' },
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 = {
@@ -17,4 +17,15 @@ export declare const DEMO_EMAIL: {
17
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
18
  readonly recentTitle: "What would have been emailed";
19
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>.";
20
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;
@@ -17,4 +17,20 @@ export const DEMO_EMAIL = {
17
17
  testSub: 'In this demo no test email is sent. On your own website, a delivered test email is what unlocks online booking.',
18
18
  recentTitle: 'What would have been emailed',
19
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>.',
20
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
+ }
@@ -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. Changing it does not move existing appointments.',
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,9 +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 } from '../email-health.js';
6
+ import { DEMO_EMAIL, emailHealth, hidesRealEmail } from '../email-health.js';
7
7
  import { EMAIL_GROUP } from '../fields.js';
8
8
  import { Icon } from '../icons.js';
9
+ import { businessReady } from '../setup.js';
9
10
  import { Badge, Button, ErrorNotice, Field, Notice, PageHeader, SkeletonBlock, formatAgo, useResult } from '../ui.js';
10
11
  import { SettingsSection } from './SettingsSection.js';
11
12
  const KIND_LABELS = {
@@ -59,7 +60,7 @@ function reveal(id) {
59
60
  }
60
61
  /** Email health, test email, the online-booking switch and email settings. */
61
62
  export function EmailSection() {
62
- const { engine, settings, refreshSettings, toast, view, emailDelivery } = useAdmin();
63
+ const { engine, settings, refreshSettings, toast, view, emailDelivery, go } = useAdmin();
63
64
  const [load, reload] = useResult(() => engine.admin.emailStatus(), []);
64
65
  // Where new-request alerts go (the alerts address, else the public email); the test email goes there by default.
65
66
  const alerts = alertsAddress(settings);
@@ -142,7 +143,8 @@ export function EmailSection() {
142
143
  const r = await engine.admin.updateSettings({ onlineBookingEnabled: on });
143
144
  if (!r.ok) {
144
145
  setBusy(null);
145
- setProblem(r.error.message);
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);
146
148
  return;
147
149
  }
148
150
  await refreshSettings();
@@ -171,19 +173,24 @@ export function EmailSection() {
171
173
  const { demo, working, failing } = emailHealth(status, emailDelivery);
172
174
  const wired = status ? WIRING.every((w) => status.wiring[w.key]) : true;
173
175
  const online = settings.onlineBookingEnabled;
174
- // Going live needs both: customers receive their codes, and the owner hears about every request.
175
- const canGoLive = working && Boolean(alerts);
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);
176
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'
177
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.'
178
- : `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
179
184
  ? 'Customers can request appointments on your website.'
180
- : !working
181
- ? 'Send a test email first: customers must be able to receive their code before they can book.'
182
- : demo
183
- ? 'Switch online booking on to take requests on the demo website.'
184
- : !alerts
185
- ? 'Email works. Choose where new-request alerts go, then switch online booking on.'
186
- : '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" })) : (_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
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
187
194
  ? DEMO_EMAIL.sub
188
195
  : working
189
196
  ? `Last delivered ${formatAgo(status.mailer.lastSuccessAt)} (${when(status.mailer.lastSuccessAt)}).`
@@ -106,13 +106,16 @@ function Requests({ requests, services, now, onOpen, onAnswered, }) {
106
106
  const isEnded = !holdRunning(b, now);
107
107
  const actions = actionsFor(b, now, emailDelivery);
108
108
  const decline = actions.find((a) => a.status === 'cancelled');
109
+ // Absent once the request's time has started: it can only be declined.
109
110
  const confirm = actions.find((a) => a.status === 'confirmed');
110
111
  const error = errors[b.id];
111
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
112
- ? b.holdExpiresAt
113
- ? `${formatSpan(now - Date.parse(b.holdExpiresAt))} ago · confirm if free`
114
- : 'confirm if free'
115
- : `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" }), _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" })] }), error ? (_jsx("div", { className: "pbe-request-error", children: _jsx(Notice, { kind: "error", children: error }) })) : null] }, b.id));
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));
116
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] })] }));
117
120
  }
118
121
  // ---------------------------------------------------------------- KPIs ---
@@ -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;
@@ -7,6 +7,12 @@ import { useAdmin } from './context.js';
7
7
  import { emailHealth } from './email-health.js';
8
8
  import { Icon } from './icons.js';
9
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';
10
16
  export function SetupChecklist() {
11
17
  const { engine, settings, go, emailDelivery } = useAdmin();
12
18
  const [counts, setCounts] = useState(null);
@@ -26,7 +32,7 @@ export function SetupChecklist() {
26
32
  // Every new request is emailed to this address: without one, nobody hears about it.
27
33
  const alerts = alertsAddress(settings);
28
34
  const items = [
29
- { id: 'business', done: settings.businessName !== 'My Business' && settings.timezone !== 'UTC', text: 'Set your business name and time zone', section: 'business' },
35
+ { id: 'business', done: businessReady(settings), text: 'Set your business name and time zone', section: 'business' },
30
36
  { id: 'services', done: counts.services > 0, text: 'Add your services and prices', section: 'services' },
31
37
  { id: 'hours', done: counts.hours > 0, text: 'Set your opening hours', section: 'hours' },
32
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
- return ok(booking);
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.3";
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-alpha.10";
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";
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-alpha.10";
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
- /** pending = a verified request the business will confirm or decline; confirmed = booked. */
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;
@@ -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
  |---|---|
@@ -1,8 +1,9 @@
1
1
  # Booking Engine — Integration Contract
2
2
 
3
- `@profitstudio/booking-engine` · engine 2.0.0-beta.3 · database schema 2.0.0-alpha.10
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.3 # exact version from the guide
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
- - Calling it again with the same code returns the same result (safe on retry
354
- or double click). Show `reference` on the confirmation.
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`, `NETWORK`. After `CODE_EXPIRED`,
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 confirmation),
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): show the confirmation by calling
477
- `verifyBooking` with the same code instead of going back.
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 pending/confirmed wording.
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
@@ -811,6 +827,30 @@ an upgrade guide. A site that does not upgrade keeps working on its version.
811
827
  `sync` also updates `supabase/functions/booking-mailer/`; redeploy it with
812
828
  `npx supabase@2 functions deploy booking-mailer --no-verify-jwt --use-api`.
813
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
+
814
854
  ### Upgrading from 2.0.0-alpha.13
815
855
 
816
856
  No migration and no website code change: `npm install` + `sync`, rebuild.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "package": "@profitstudio/booking-engine",
3
- "version": "2.0.0-beta.3",
4
- "schemaVersion": "2.0.0-alpha.10",
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",
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-alpha.10",
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.