@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.1

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.
Files changed (114) hide show
  1. package/CHANGELOG.md +562 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +22 -0
  9. package/dist/admin/BookingAdmin.js +337 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +37 -0
  14. package/dist/admin/booking-detail.js +149 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +37 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +6 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +182 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1109 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,203 @@
1
+ # Build a site on the Booking Engine — the short guide
2
+
3
+ Everything a new website needs, in one read. The full contract is
4
+ `INTEGRATION.md`; open one of its sections only when this guide points there.
5
+ The public API is what `@profitstudio/booking-engine`, `…/admin` and `…/vite`
6
+ export (`dist/index.d.ts`, `dist/admin/index.d.ts`, `dist/vite.d.ts`).
7
+
8
+ **The engine does:** database, availability, holds, email codes, every booking
9
+ email, the owner dashboard (`/admin/`), website-content storage and publishing.
10
+ **You do:** the public website — design, copy, photos, the booking UI — on one
11
+ page, rendered from engine data.
12
+
13
+ ## 1. Wiring (copy, then adjust names)
14
+
15
+ `src/lib/engine.ts`
16
+ ```ts
17
+ import { createBookingEngine } from '@profitstudio/booking-engine';
18
+ import { sitePreset } from './preset'; // hair salons may use hairSalonPreset instead
19
+
20
+ export const engine = createBookingEngine({
21
+ supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
22
+ supabaseKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
23
+ allowPreview: import.meta.env.DEV, // sample data while no backend is connected
24
+ preview: { preset: sitePreset, business: { name: 'Business Name', timezone: 'America/New_York',
25
+ contact: { address: '1 Example St, City', phone: '+1 555 0100', email: 'hello@example.com' } } },
26
+ });
27
+ ```
28
+
29
+ `src/lib/preset.ts` — sample data for preview and the dashboard's starter set
30
+ (every field required; prices in cents; weekday 1 = Monday … 7 = Sunday):
31
+ ```ts
32
+ import type { Preset } from '@profitstudio/booking-engine';
33
+ export const sitePreset = {
34
+ id: 'barbershop', label: 'Barbershop',
35
+ terminology: { customer: 'client', customers: 'clients', booking: 'appointment', bookings: 'appointments' },
36
+ previewBusiness: { name: 'Sample Barbershop', currency: 'USD', locale: 'en-US',
37
+ contact: { email: 'hello@example.com', phone: '+1 555 0100', address: '123 Example Street, Springfield' } },
38
+ policies: { slotIntervalMinutes: 15, minNoticeMinutes: 60, maxAdvanceDays: 30, autoConfirm: false,
39
+ requirePhone: true, pendingHoldMinutes: 1440, verificationWindowMinutes: 15 },
40
+ workingHours: [{ weekday: 2, start: '10:00', end: '19:00' }],
41
+ services: [{ name: 'Classic Cut', description: '…', durationMinutes: 30, bufferAfterMinutes: 10, priceCents: 4000 }],
42
+ } satisfies Preset;
43
+ ```
44
+
45
+ `src/vite-env.d.ts`
46
+ ```ts
47
+ /// <reference types="vite/client" />
48
+ interface ImportMetaEnv { readonly VITE_SUPABASE_URL?: string; readonly VITE_SUPABASE_PUBLISHABLE_KEY?: string }
49
+ interface ImportMeta { readonly env: ImportMetaEnv }
50
+ ```
51
+
52
+ `admin/index.html` (the packaged dashboard at `/admin/`)
53
+ ```html
54
+ <!doctype html>
55
+ <html lang="en">
56
+ <head>
57
+ <meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />
58
+ <meta name="robots" content="noindex" /><link rel="icon" href="/favicon.svg" /><title>Dashboard</title>
59
+ </head>
60
+ <body><div id="admin"></div><script type="module" src="/src/admin-main.tsx"></script></body>
61
+ </html>
62
+ ```
63
+
64
+ `src/admin-main.tsx`
65
+ ```tsx
66
+ import { createRoot } from 'react-dom/client';
67
+ import { BookingAdmin } from '@profitstudio/booking-engine/admin';
68
+ import '@profitstudio/booking-engine/admin.css';
69
+ import './admin-theme.css';
70
+ import { siteContent } from './content/site';
71
+ import { engine } from './lib/engine';
72
+ import { sitePreset } from './lib/preset';
73
+
74
+ createRoot(document.getElementById('admin')!).render(
75
+ <BookingAdmin engine={engine} siteUrl="/" content={siteContent} presets={[sitePreset]} />,
76
+ );
77
+ ```
78
+
79
+ `src/admin-theme.css` — the dashboard is shared; brand it with its accent only:
80
+ ```css
81
+ :root .pbe-admin[data-mode='light'] { --pbe-accent: #1e5a40; --pbe-accent-text: #ffffff; }
82
+ :root .pbe-admin[data-mode='dark'] { --pbe-accent: #93cdb4; --pbe-accent-text: #0b1a14; }
83
+ ```
84
+
85
+ `vite.config.ts` — two pages, and the published content baked into `index.html`:
86
+ ```ts
87
+ import { defineConfig, loadEnv } from 'vite';
88
+ import react from '@vitejs/plugin-react';
89
+ import { fileURLToPath } from 'node:url';
90
+ import { publishedSiteContent } from '@profitstudio/booking-engine/vite';
91
+ import { siteContent } from './src/content/site.ts';
92
+
93
+ export default defineConfig(({ mode }) => ({
94
+ plugins: [react(), publishedSiteContent({ schema: siteContent, env: loadEnv(mode, process.cwd(), 'VITE_'),
95
+ meta: (v) => ({ title: v['seo.title'], description: v['seo.description'] }) })],
96
+ build: { rolldownOptions: { input: { // Vite 7: rollupOptions
97
+ main: fileURLToPath(new URL('./index.html', import.meta.url)),
98
+ admin: fileURLToPath(new URL('./admin/index.html', import.meta.url)) } } },
99
+ }));
100
+ ```
101
+
102
+ ## 2. Owner-editable content
103
+
104
+ `src/content/site.ts` is plain data (it also runs in Node during the build: import
105
+ only the engine and `.ts` files with their extension; default images are
106
+ public-folder URLs). Your copy and photos are the defaults; the dashboard's
107
+ Website editor is built from these fields.
108
+ ```ts
109
+ import { defineSiteContent } from '@profitstudio/booking-engine';
110
+ export const siteContent = defineSiteContent({ sections: [
111
+ { id: 'seo', label: 'Search & sharing', fields: [
112
+ { type: 'text', id: 'seo.title', label: 'Search title', default: 'Business — what it is, where', maxLength: 70 },
113
+ { type: 'longText', id: 'seo.description', label: 'Search description', default: '…', maxLength: 160 } ] },
114
+ { id: 'hero', label: 'Hero', fields: [
115
+ { type: 'text', id: 'hero.title', label: 'Headline', default: '…', maxLength: 60, required: true },
116
+ { type: 'image', id: 'hero.photo', label: 'Photo', default: { src: '/photos/hero-1440.webp', alt: '…', width: 1440, height: 1800 }, aspectRatio: 4 / 5 } ] },
117
+ ] });
118
+ ```
119
+ Field types: `text`, `longText`, `link`, `image`, `color` (`contrastWith`, `minContrast`),
120
+ `choice`, `toggle`, `list` (items: `text`, `longText`, `link`, `image`, `toggle`; list
121
+ images have no defaults). Never put services, prices, hours or contact details in
122
+ content — they come from the engine. Render values as text, never as HTML.
123
+
124
+ ```ts
125
+ import { createSiteContentStore, readSiteContentSnapshot } from '@profitstudio/booking-engine';
126
+ export const contentStore = createSiteContentStore(engine, siteContent, { snapshot: readSiteContentSnapshot() });
127
+ // const [content, setContent] = useState(() => contentStore.initial());
128
+ // useEffect(() => { void contentStore.load().then(setContent); }, []); → content.values['hero.title']
129
+ ```
130
+
131
+ ## 3. Data for the page
132
+
133
+ | Call | Use |
134
+ |---|---|
135
+ | `engine.mode` | `'preview'` → show “Preview — sample data, bookings are not saved”; `'unconfigured'` → “Online booking is not available yet” instead of the flow |
136
+ | `getBusiness()` | name, `timezone`, `currency`, `locale`, `contact`, `policies.onlineBookingEnabled` (false → show contact details instead of the form), `openingHours` |
137
+ | `listServices()` | name, description, `durationMinutes`, `priceCents`, `priceFrom`, optional `image` (`url`, `alt`, `width`, `height` or null — design for none, some, all) |
138
+ | `getOpeningTimes({ from, to })` | the real hours after closures, for “Open now until 6:00 PM” |
139
+ | `getAvailability({ serviceId, from, to })` | days (`status`: available, full, closed, unavailable) with `slots` (`startsAt`, `endsAt`, `time`); one call per visible month (≤ 42 days) |
140
+
141
+ Every call returns `{ ok: true, data } | { ok: false, error: { code, message, field?, attemptsLeft?, retryAfterSeconds? } }`.
142
+ Helpers: `formatMoney(cents, currency, locale)`, `formatDate`, `formatClockTime(slot.time, locale)`
143
+ (label times from `slot.time`, keep them on one line), `todayInTimeZone`, `addDays`,
144
+ `monthGrid`, `weekDates`, `groupSlotsByPartOfDay`, `isFewLeft`, `nextAvailableDay`.
145
+ Never compute availability yourself; show times in the business time zone.
146
+
147
+ ## 4. The booking flow
148
+
149
+ 1. **Service** → 2. **Day and time** (server slots only) → 3. **Details** (name,
150
+ email, phone if `policies.requirePhone`, optional note) →
151
+ `requestBooking({ serviceId, startsAt: slot.startsAt, customer: { name, email, phone }, notes })`
152
+ holds the time and emails a code; `data`: `requestId`, `email` (masked), `expiresAt`,
153
+ `codeLength`, `resendAfterSeconds`, `resendsLeft`, `delivery` (`'preview'`: no email).
154
+ 4. **Code** — one `inputmode="numeric" autocomplete="one-time-code"` field that keeps
155
+ digits only (also on paste) → `verifyBooking({ requestId, code })`. “Send a new code”:
156
+ `resendVerificationCode(requestId)`. “Choose another time”: **await**
157
+ `cancelBookingRequest(requestId)`, then reload availability.
158
+ 5. **Done** only when `verifyBooking` returned `ok: true`: `data.status` `'pending'`
159
+ (“Request received — we'll confirm shortly”) or `'confirmed'`, plus `reference`.
160
+
161
+ | Error | Show |
162
+ |---|---|
163
+ | `INVALID_INPUT` (`field`) | inline message on that field |
164
+ | `SLOT_UNAVAILABLE` | “That time was just taken” + fresh times |
165
+ | `INVALID_CODE` (`attemptsLeft`) | wrong code, tries left |
166
+ | `CODE_EXPIRED`, `TOO_MANY_ATTEMPTS` | back to times (keep typed details), reload |
167
+ | `RESEND_TOO_SOON` (`retryAfterSeconds`), `RESEND_LIMIT` | when a new code is possible / no more codes (the current one still works) |
168
+ | `TOO_MANY_BOOKINGS` | end the flow; suggest contacting the business |
169
+ | `BOOKING_DISABLED`, `NOT_CONFIGURED` | contact details instead of the form |
170
+ | `PREVIEW_MODE` | “Preview — nothing was saved” (never a success screen) |
171
+ | `RATE_LIMITED`, `NETWORK`, others | the message, and a way to try again |
172
+
173
+ **Book buttons elsewhere on the page** (header, hero, menu rows) must work in every
174
+ state of the booking section — loading, the flow, online booking off, no services,
175
+ a load error: scroll to the section and focus its heading, then let the flow
176
+ preselect a service if it is showing. A CTA wired only to the flow does nothing
177
+ while the flow is not on the page.
178
+
179
+ Phones first: the step's name always visible, the chosen service/time/price in view,
180
+ 44 px targets, focus moves to each new step's heading.
181
+
182
+ ## 5. Photos — prepared by the engine's CLI
183
+
184
+ Put the originals in `photos/source/` (licensed and downloaded, never hot-linked;
185
+ record them in `PHOTOS.md`), describe each use in `photos/photos.json`, then
186
+ `npm install --save-dev sharp` and run `npx booking-engine photos`:
187
+ ```json
188
+ { "out": "public/photos",
189
+ "photos": [ { "src": "photos/source/hero.jpg", "name": "hero", "aspect": "4:5", "widths": [640, 1024, 1440], "position": "attention" } ] }
190
+ ```
191
+ It crops to the aspect ratio (`position`: `center`, `top`, `bottom`, `left`, `right`,
192
+ `attention`), writes `<out>/<name>-<width>.avif` and `.webp`, removes camera data
193
+ and prints each size for `width`/`height`. Serve them with `<picture>`, `srcset`,
194
+ `sizes`, `width`/`height`, fixed `aspect-ratio` frames and `object-fit: cover`.
195
+
196
+ ## 6. Checks
197
+
198
+ ```bash
199
+ npm run build && npx booking-engine doctor --dist dist
200
+ ```
201
+ More: INTEGRATION.md §5 presets · §6 API details · §7 every error · §8–§9 calendar ·
202
+ §10 dashboard theme · §11 connecting Supabase (`npx booking-engine connect`) ·
203
+ §12 deploy · §15 content.
@@ -0,0 +1,224 @@
1
+ # Booking emails — setup, limits and costs
2
+
3
+ `@profitstudio/booking-engine` 2.0.0-alpha.10
4
+
5
+ Online booking needs email: every customer proves their address with a
6
+ 6-digit code before a request reaches the business, and the engine emails
7
+ customers and the owner about every change. This page sets that up once per
8
+ project. It takes about 20 minutes plus DNS waiting time.
9
+
10
+ ## What gets sent
11
+
12
+ | Email | To | When |
13
+ |---|---|---|
14
+ | Booking code | Customer | They submit the booking form (and when they ask for a new code) |
15
+ | Request received | Customer | They entered the code; the owner still has to confirm |
16
+ | Booking confirmed | Customer | The owner confirms — or at once, when instant confirmation is on |
17
+ | Request declined | Customer | The owner declines a request |
18
+ | Request expired | Customer | The owner did not answer before the hold ended |
19
+ | Booking cancelled | Customer | The owner cancels a confirmed booking |
20
+ | New booking request | Owner | A customer verified their request (instant confirmation: “New booking”) |
21
+ | Test email | Anyone | The owner clicks “Send test email” in the dashboard |
22
+
23
+ **Where owner alerts go:** dashboard → Email & online booking → “Send new-request
24
+ alerts to”, or, when that is empty, the public business email (Business). With
25
+ neither, nobody is told about a new request — so the dashboard's setup checklist
26
+ asks for an address, the Email page warns while none is set, and online booking
27
+ cannot be switched on until there is one. Send the test email to that address.
28
+
29
+ How it works: the database queues each email in the same transaction as the
30
+ booking change, then starts the `booking-mailer` Edge Function (pg_net, with a
31
+ mailer-only token), which sends through Resend. A job runs every minute
32
+ (pg_cron) for retries and expiry notices. The website never sends email and
33
+ never sees a provider key; the database never holds a Supabase key.
34
+
35
+ ## What you need
36
+
37
+ - A **domain you control** (e.g. bought at Hostinger), to send from. Customers'
38
+ inboxes trust mail from a verified domain; a free mailbox address cannot be
39
+ used.
40
+ - A **Resend** account (resend.com). The free plan is enough to start.
41
+ - The Supabase project the site already uses.
42
+
43
+ ## 1. Verify a sending domain in Resend
44
+
45
+ 1. Resend → **Domains → Add domain**. Use a **subdomain** of your domain, e.g.
46
+ `mail.yourdomain.com` — this keeps booking email separate from your main
47
+ domain's mail reputation. Pick the region closest to your customers.
48
+ 2. Resend shows the DNS records to add. Typically:
49
+
50
+ | Type | Name (host) | Value | Purpose |
51
+ |---|---|---|---|
52
+ | TXT | `resend._domainkey.mail` | `p=MIGfMA0GCSq…` (long key) | DKIM: proves Resend may sign your mail |
53
+ | MX | `send.mail` | `feedback-smtp.<region>.amazonses.com` (priority 10) | Bounces and complaints come back |
54
+ | TXT | `send.mail` | `v=spf1 include:amazonses.com ~all` | SPF: allowed senders |
55
+ | TXT (recommended) | `_dmarc` | `v=DMARC1; p=none;` | DMARC: tells inboxes what to do with failures |
56
+
57
+ Copy the exact names and values from Resend — they differ per domain and
58
+ region. The table assumes the domain `mail.yourdomain.com` at a DNS
59
+ provider that adds `yourdomain.com` itself.
60
+ 3. Add them where your domain's DNS is managed. **Hostinger:** hPanel →
61
+ **Domains** → your domain → **DNS / Nameservers** → **DNS records** → add
62
+ each record; in “Name” type only the host part shown above (`send.mail`,
63
+ not `send.mail.yourdomain.com`). **Cloudflare:** set records to “DNS only”
64
+ (grey cloud).
65
+ 4. Back in Resend, click **Verify DNS records**. Usually verified within 15
66
+ minutes; DNS can take up to 72 hours.
67
+
68
+ ## 2. Create a Resend API key
69
+
70
+ Resend → **API Keys → Create API key**: permission **Sending access**, domain:
71
+ the one you verified. Copy it (`re_…`). It is shown once.
72
+
73
+ Keep it out of the website: no `.env` file of the site, no `VITE_` variable,
74
+ no source file, no Git. `npx booking-engine doctor` fails if it finds one.
75
+
76
+ ## 3. Give the key to the mailer (Supabase Edge Function secrets)
77
+
78
+ Supabase → **Edge Functions → Secrets** (or **Project Settings → Edge
79
+ Functions**) → add (the third, `BOOKING_MAILER_TOKEN`, comes from step 5):
80
+
81
+ | Name | Value |
82
+ |---|---|
83
+ | `RESEND_API_KEY` | `re_…` from step 2 |
84
+ | `BOOKING_EMAIL_FROM` | `Your Business <bookings@mail.yourdomain.com>` — any address on the verified domain. An address alone (`bookings@mail.yourdomain.com`) uses the business name from the dashboard. |
85
+ | `BOOKING_ADMIN_URL` (optional) | `https://yourdomain.com/admin/` — adds an “Open your dashboard” button to owner alerts |
86
+
87
+ Replies: customer emails have **Reply-To** set to the public business email
88
+ (dashboard → Business), so customer replies reach the owner. Owner alerts have
89
+ Reply-To set to the customer. **Set the public business email**: without it,
90
+ customer emails cannot invite a reply (the sending address usually has no
91
+ inbox) — since alpha.7 they then ask customers to call the business phone, or
92
+ simply to contact the business, instead of “reply to this email”.
93
+
94
+ ## 4. Deploy the mailer
95
+
96
+ **Easiest:** `npx booking-engine connect` does steps 4 and 5 for you — it deploys
97
+ the mailer, runs the SQL and stores the token as `BOOKING_MAILER_TOKEN` without
98
+ showing it (INTEGRATION.md §11). By hand, from the project folder (after
99
+ `npx supabase@2 link`):
100
+
101
+ ```bash
102
+ npx supabase@2 functions deploy booking-mailer --no-verify-jwt --use-api
103
+ ```
104
+
105
+ `--use-api` bundles the function on Supabase's servers, so Docker is not needed
106
+ on your computer.
107
+
108
+ `--no-verify-jwt` is correct here: the function is called by your own database
109
+ with a mailer-only token (step 5), which the function checks itself in constant
110
+ time — the pattern Supabase's `@supabase/server` documents for endpoints with
111
+ their own authentication. Anonymous calls, website keys and even Supabase
112
+ secret keys are refused. `booking-engine init` also writes this to
113
+ `supabase/config.toml`.
114
+
115
+ ## 5. Let the database start the mailer (once, SQL Editor)
116
+
117
+ 1. Run `npx booking-engine mailer-sql` and paste the output into the Supabase
118
+ **SQL Editor**, then run it. It enables `pg_net` and `pg_cron`, schedules
119
+ the every-minute job and stores the function address. Running it again is
120
+ safe.
121
+ 2. The result row shows `booking_mailer_token` (64 characters) and a setup
122
+ check. Copy the token into **Edge Functions → Secrets** as
123
+ `BOOKING_MAILER_TOKEN`.
124
+
125
+ This token can only start the mailer — which can only send emails your
126
+ database already queued. It is not a Supabase key: no Supabase secret key is
127
+ needed anywhere for email. New token (if it was ever exposed):
128
+ `select * from booking.configure_mailer('<the same address>', p_rotate => true);`
129
+ then update the secret.
130
+
131
+ ## 6. Test, then open online booking
132
+
133
+ Website → `/admin/` → **Email & online booking**:
134
+
135
+ 1. **Send test email** to your own address. It should arrive within a minute
136
+ (check spam the first time). The dashboard shows it as *Sent*.
137
+ 2. **Turn online booking on.** It can only be switched on after a test email
138
+ was delivered, so a site never accepts requests it cannot verify.
139
+ 3. Book an appointment on the website with your own email address: you get the
140
+ code, then “Request received”; the owner address gets “New booking request”.
141
+
142
+ ## Limits and costs
143
+
144
+ | | Free | Pro (from $20/month) |
145
+ |---|---|---|
146
+ | Emails per month | 3,000 | 50,000 (higher tiers available) |
147
+ | Emails per day | **100** | no daily limit |
148
+ | Verified domains | 3 | 10 |
149
+ | API rate | 10 requests/second (the mailer stays below it) | same, can be raised |
150
+
151
+ (Resend's published pricing, checked 2026-11-01; confirm on resend.com/pricing.)
152
+ Supabase: Edge Function invocations (500,000/month free), pg_net and pg_cron
153
+ cost nothing extra on any plan; the mailer runs only when an email is due.
154
+
155
+ **How many emails is a booking?** About 4: code, request received, owner
156
+ alert, and the confirmation or decline (3 with instant confirmation). The free
157
+ plan's 100 a day covers roughly 20–25 bookings a day; above that, use Pro.
158
+
159
+ **Built-in protection of your email budget** (dashboard → Email settings):
160
+
161
+ - Code emails per day for the whole website: default **50** (leaves room for
162
+ the other emails on the free plan). Raise it on a paid plan.
163
+ - Per address: at most 5 code emails an hour and 10 a day.
164
+ - Per visitor: 10 booking requests an hour; whole website: the “Booking
165
+ requests per hour” policy (default 30).
166
+ - A code works for the verification window (default 15 minutes, 5–30), 5
167
+ attempts, at most 3 new codes per request. An unverified request holds its
168
+ time only for that window and is then deleted.
169
+ - When the daily Resend quota is used up, emails are retried for about an hour
170
+ and then marked *Failed* in the dashboard; booking keeps working, but
171
+ customers cannot receive codes until the quota resets (midnight UTC).
172
+
173
+ ## When Resend (or the email setup) is down
174
+
175
+ Booking emails are queued in the database first, so nothing is lost and
176
+ nothing is booked by mistake:
177
+
178
+ | Keeps working | Stops or waits |
179
+ |---|---|
180
+ | The website, services, availability, the dashboard | **New customers cannot finish booking**: their code does not arrive, and the held time is released after the code window. Nothing is ever booked without the code |
181
+ | Existing appointments; confirming, declining and cancelling in the dashboard | The emails about them wait in the queue and are retried after 1, 4, 16 and 64 minutes |
182
+ | Requests already verified (they are real and stay with the owner) | After about 85 minutes of failures an email is marked *Failed* |
183
+
184
+ The dashboard shows a warning on every page while emails are failing or have
185
+ been waiting for more than 5 minutes. Once the problem is fixed, **Email &
186
+ online booking → Retry failed emails** sends again everything from the last 23
187
+ hours (never twice: Resend recognises a retried email for 24 hours). If the
188
+ outage will be long, switch online booking off so the website shows your phone
189
+ and email instead of a form whose codes cannot arrive.
190
+
191
+ ## Testing without emailing real people
192
+
193
+ - **Designing the site (preview mode):** no backend, no email. The code step
194
+ says nothing was sent; any 6 digits continue to an honest “Preview — nothing
195
+ was saved”.
196
+ - **A staging Supabase project:** use your own address (Gmail-style
197
+ `you+test1@gmail.com` gives you as many addresses as you need) or Resend's
198
+ test inbox `delivered+anything@resend.dev` (accepted and never delivered;
199
+ counts toward the quota). Never use made-up addresses at real domains: bounces
200
+ hurt your sender reputation.
201
+ - **The engine's own automated tests** use a local fake of Resend's API; no
202
+ real email is ever sent by them.
203
+
204
+ ## Troubleshooting
205
+
206
+ | Dashboard shows | Cause | Fix |
207
+ |---|---|---|
208
+ | “No email has been delivered yet” and the test email stays *Queued* | The database cannot start the mailer | Check the dashboard's “Last start of the mailer”: 401 → `BOOKING_MAILER_TOKEN` does not match the token from `configure_mailer`; 503 → the secret is missing; 404 → the function is not deployed at that address; no start at all → run the `mailer-sql` output (step 5) |
209
+ | *Failed* — “RESEND_API_KEY is not set” / “BOOKING_EMAIL_FROM is not set” | Missing function secret | Step 3, then send a new test email |
210
+ | *Failed* — “Resend 403 validation_error … domain is not verified” | Sending from an unverified domain | Finish step 1; `BOOKING_EMAIL_FROM` must use the verified domain |
211
+ | *Failed* — “Resend 401 … API key is invalid” | Wrong or deleted key | Create a new key (step 2), update the secret, then **Retry failed emails** |
212
+ | *Failed* — “Resend 429 daily_quota_exceeded” | Free plan's 100 emails/day used | Wait for midnight UTC or upgrade Resend |
213
+ | Emails arrive in spam | New domain or missing DMARC | Add the DMARC record; send a few real emails to yourself and mark them “not spam” |
214
+
215
+ ## Replacing the provider
216
+
217
+ The mailer talks to the provider through one small interface
218
+ (`supabase/functions/booking-mailer/providers/`): `send({ idempotencyKey, from,
219
+ to, replyTo, subject, html, text })` returning `{ ok, id }` or
220
+ `{ ok: false, permanent, error }`. Resend is the one built in; other providers
221
+ (Postmark, Amazon SES, an SMTP relay) are added by the engine as new provider
222
+ files selected with the `BOOKING_EMAIL_PROVIDER` secret. Do not edit the
223
+ function files in a project — `booking-engine doctor` reports changes and
224
+ `sync` refuses to overwrite them.