@proveanything/smartlinks 2.2.8 → 2.2.10

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.
@@ -1,442 +1,539 @@
1
- # Bookings: slots, bookings and allocations
2
-
3
- Generic booking objects for **any** booking app: event tickets, classes, tours, table reservations,
4
- one-to-one appointments, room and equipment hire. The platform gives you the objects and the
5
- guarantees. Your app owns the rest: schedule, policy, pricing, payment and UI.
6
-
7
- ```ts
8
- import { bookings, utils } from '@proveanything/smartlinks'
9
- ```
10
-
11
- ---
12
-
13
- ## What the platform guarantees (and what it doesn't)
14
-
15
- | The platform | Your app |
16
- |---|---|
17
- | **No double-booking** of a person / room / table, however many requests arrive at once | The schedule (opening hours) and its UI |
18
- | **No overselling** a slot's capacity | Booking policy: notice, durations, who may book |
19
- | **Atomic** writes: a booking with several parts (a stylist *and* a chair) succeeds whole or not at all | Pricing, ticket types, payment or credits, refunds |
20
- | **Idempotent** creates (`idempotencyKey`): a retried request never books twice | Queues, waiting rooms, throttling for high-demand sales |
21
- | **Holds** that expire and give the place back | Confirmation / reminder content (flows on booking events) |
22
- | Who may book publicly, by **per-app rules** (like records / cases) | |
23
-
24
- ---
25
-
26
- ## The three objects
27
-
28
- - **Slot** — a time window with a **capacity**: an event performance, a class, a tour at 2pm. Seats
29
- are counted (`booked`, `remaining`).
30
- - **Booking** — the customer's reservation and its lifecycle. This is what "my bookings" lists.
31
- - **Allocation** — what a booking actually claims: seats on a slot (`mode: 'capacity'`) or
32
- exclusive time on a resource (`mode: 'exclusive'`). Most apps never touch these directly: they're
33
- returned on `booking.allocations`.
34
-
35
- **Resources are not a new object.** Staff, rooms, tables and equipment are whatever you already use —
36
- app records, contacts, products — referenced by type + id: `{ resourceType: 'record', resourceId: 'staff-sam' }`.
37
-
38
- ### Booking statuses
39
-
40
- | Status | Holds a place? | Meaning |
41
- |---|---|---|
42
- | `held` | yes, until `holdExpiresAt` | Claimed while the customer pays / confirms; expires automatically |
43
- | `pending` | yes | Claimed, waiting for the business to approve |
44
- | `confirmed` | yes | Booked |
45
- | `completed` / `no_show` | yes (the time was used) | Outcome after the event (admin) |
46
- | `cancelled` | no | `cancelReason`: `admin`, `owner`, `hold_expired` or your own |
47
- | `waitlisted` | no | Waiting; confirming it claims the place if one is free |
48
-
49
- ---
50
-
51
- ## Events and classes — slots
52
-
53
- ```ts
54
- // Admin (Studio, or your app's server function): publish the sessions
55
- const slot = await bookings.slots.create(collectionId, appId, {
56
- startsAt: '2026-11-14T19:30:00Z', endsAt: '2026-11-14T21:00:00Z',
57
- capacity: 200,
58
- perContactLimit: 4, // max 4 seats per person on this slot, enforced atomically
59
- data: { title: 'Autumn concert' },
60
- })
61
-
62
- // A class that also needs its instructor free: the slot blocks the instructor's time too
63
- await bookings.slots.create(collectionId, appId, {
64
- startsAt, endsAt, capacity: 12,
65
- resourceType: 'record', resourceId: 'instructor-ana', blockResource: true,
66
- })
67
-
68
- // A series, all-or-nothing (max 500)
69
- await bookings.slots.createMany(collectionId, appId, sessions, { seriesId })
70
-
71
- // Public: open slots with places left
72
- const { data } = await bookings.slots.list(collectionId, appId, { from, to, available: true })
73
- data[0].remaining
74
- ```
75
-
76
- Book seats:
77
-
78
- ```ts
79
- const booking = await bookings.create(collectionId, appId, { slotId: slot.id, quantity: 2, idempotencyKey })
80
- ```
81
-
82
- Recurring events are **expanded into concrete slots** (`seriesId`); there's no recurrence rule
83
- stored on a slot.
84
-
85
- ---
86
-
87
- ## Appointments — exclusive time on a resource
88
-
89
- ```ts
90
- await bookings.create(collectionId, appId, {
91
- resourceType: 'record', resourceId: 'staff-sam',
92
- startsAt: '2026-11-03T10:00:00Z', endsAt: '2026-11-03T10:30:00Z',
93
- bufferAfter: 15, // admin: blocks 10:30–10:45 too (clean-up); the booking still shows 10:00–10:30
94
- }, true)
95
- ```
96
-
97
- Several resources at once — all-or-nothing:
98
-
99
- ```ts
100
- await bookings.create(collectionId, appId, {
101
- startsAt, endsAt,
102
- allocations: [
103
- { resourceType: 'record', resourceId: 'stylist-jo' },
104
- { resourceType: 'record', resourceId: 'chair-2' },
105
- ],
106
- }, true)
107
- ```
108
-
109
- A pool with no fixed times (3 kayaks, bookable any time) is three resources; your app picks a free one.
110
-
111
- ### Blocked time
112
-
113
- ```ts
114
- await bookings.blocks.create(collectionId, appId, { resourceType: 'record', resourceId: 'staff-sam', startsAt, endsAt, data: { reason: 'training' } })
115
- ```
116
-
117
- Planned time off usually belongs in your schedule (an override); blocks are for ad-hoc blocked time.
118
-
119
- ---
120
-
121
- ## Schedules and free times
122
-
123
- **Your app owns the schedule.** Store it however you like — usually an app record. For the time maths,
124
- the SDK ships a pure helper:
125
-
126
- ```ts
127
- const schedule = {
128
- timezone: 'Europe/London',
129
- weekly: { mon: [{ start: '09:00', end: '12:30' }, { start: '13:30', end: '17:00' }], tue: [{ start: '09:00', end: '17:00' }] },
130
- overrides: [{ from: '2026-12-24', to: '2026-12-28', hours: [] }, { date: '2026-11-07', hours: [{ start: '10:00', end: '13:00' }] }],
131
- }
132
-
133
- const fb = await bookings.freebusy(collectionId, appId, { resources: ['record:staff-sam'], from, to }, true)
134
- const times = utils.freeTimes({
135
- hours: schedule, busy: fb.resources[0].busy,
136
- from, to, duration: 30, step: 30, bufferAfter: 15, minNotice: 240,
137
- })
138
- // → [{ start, end }, …] in UTC; render in the booker's timezone
139
- ```
140
-
141
- - Times are **local wall-clock** in `timezone`, so "9 to 5" stays 9 to 5 across daylight-saving changes.
142
- - A missing day is closed; hours never cross midnight (split them); `end` may be `'24:00'`.
143
- - `overrides` win over `weekly` (`hours: []` = closed).
144
- - Also exported: `utils.withinSchedule`, `utils.openIntervals`, `utils.subtractIntervals`, `utils.validateSchedule`.
145
-
146
- `freebusy` returns busy intervals only (bookings, blocks, slots that block a resource) — never who
147
- booked. It's collection-wide: a resource is busy whichever app booked it.
148
-
149
- ---
150
-
151
- ## Who can book — per-app rules
152
-
153
- Exactly like records, cases and threads:
154
-
155
- - **Admin calls are unconditional** — Studio users, and **your app's own server functions** (they call
156
- the admin routes with your app's authority). Pass `admin = true`.
157
- - **Public calls** (`admin = false`, the default for `create`) follow your app's config in
158
- `sites/{collectionId}/apps/{appId}` (`POST /admin/collection/:cId/apps/:appId`). With no config,
159
- **public booking is refused** — only admins (and your functions) can book.
160
-
161
- Pick a mode per app:
162
-
163
- | Mode | Config | Suits |
164
- |---|---|---|
165
- | **Public booking** | `publicCreate.bookings` allows anonymous and/or signed-in callers | "Book an appointment with me", simple events — no server code |
166
- | **Admin-only booking** | no `publicCreate.bookings` | Extra validation, queues, payment-first, high demand: book through your server function |
167
-
168
- ### `publicCreate.bookings`
169
-
170
- ```json
171
- {
172
- "publicCreate": {
173
- "bookings": {
174
- "anonymous": {
175
- "allow": true,
176
- "enforce": { "status": "held" },
177
- "limits": { "maxQuantity": 4, "holdMinutes": 15 },
178
- "rules": { "targets": ["slots"], "minNoticeMinutes": 60, "horizonDays": 90 },
179
- "edit": { "editToken": true }
180
- },
181
- "authenticated": {
182
- "allow": true,
183
- "enforce": { "status": "confirmed", "visibility": "owner" },
184
- "rules": {
185
- "targets": ["slots", "resources"],
186
- "schedule": true,
187
- "resourceTypes": ["record"],
188
- "durations": [30, 60],
189
- "minNoticeMinutes": 240,
190
- "bufferAfter": 15
191
- }
192
- }
193
- }
194
- }
195
- }
196
- ```
197
-
198
- | Field | Meaning |
199
- |---|---|
200
- | `enforce.status` | `confirmed` (instant), `pending` (business approves), `held` (pay / confirm next). Default `pending`. The caller can't override it. |
201
- | `enforce.visibility` | Default: `owner` for signed-in, `admin` for anonymous |
202
- | `limits.maxQuantity` | Max seats / claims per booking |
203
- | `limits.holdMinutes` | Hold length for public `held` bookings (default 15, max 60) |
204
- | `rules.targets` | `slots` (only your published slots) and/or `resources` (free-form time). Default `['slots']` |
205
- | `rules.schedule` | **Required for `resources`.** The platform checks the requested time against the resource's schedule: an app record of **your app** with `recordType: 'availability'`, `parentType` / `parentId` = the resource, `data` in the standard shape above |
206
- | `rules.resourceTypes` | Which resource types the public may book |
207
- | `rules.durations` | Allowed lengths in minutes |
208
- | `rules.minNoticeMinutes`, `rules.horizonDays` | How soon / how far ahead |
209
- | `rules.bufferBefore`, `rules.bufferAfter` | Applied to every public booking (the caller can't set buffers) |
210
- | `edit.editToken` | Anonymous only: the create response carries `editToken` **once** — store it so the guest can manage the booking. `edit.windowMinutes` limits how long it works |
211
-
212
- Public callers can't set `contactId` (signed-in callers get their own contact; guests none), the
213
- admin zone, buffers, `customId` or `sourceSystem`.
214
-
215
- ### `ownerActions.bookings` — what the booker may do afterwards
216
-
217
- ```json
218
- {
219
- "ownerActions": {
220
- "bookings": {
221
- "cancel": { "allow": true, "cutoffMinutes": 1440 },
222
- "move": { "allow": true, "cutoffMinutes": 1440 },
223
- "confirm": { "allow": true }
224
- }
225
- }
226
- }
227
- ```
228
-
229
- Default: nothing. `cutoffMinutes` = not within that time of the start (`CUTOFF_PASSED`). `move`
230
- re-checks the create rules for the new time. `confirm` turns the booker's own **held** booking into
231
- `confirmed` — only for apps that take no payment; `pending` and `waitlisted` are the business's to
232
- confirm.
233
-
234
- ```ts
235
- // Signed-in booker
236
- await bookings.cancel(collectionId, appId, bookingId)
237
- const mine = await bookings.mine(collectionId, appId, { from: new Date() })
238
-
239
- // Guest, with the token from create
240
- const b = await bookings.get(collectionId, appId, bookingId, false, { editToken })
241
- await bookings.move(collectionId, appId, bookingId, { slotId: other.id }, false, { editToken })
242
- ```
243
-
244
- ### `publicRead.bookings.freebusy`
245
-
246
- `{ "publicRead": { "bookings": { "freebusy": true } } }` lets public pages call `bookings.freebusy`.
247
- Off by default — most apps serve free times through their own function.
248
-
249
- ---
250
-
251
- ## In a server function — `ctx.sl.bookings`
252
-
253
- When public booking is off, your app books through its own server function. `ctx.sl.bookings` is
254
- the same API, admin-side, for **your app's** bookings only (`sl:bookings:read` / `sl:bookings:write`):
255
-
256
- ```ts
257
- // manifest: { name: 'book', trigger: { type: 'http' }, visibility: 'public', authority: 'collection',
258
- // capabilities: ['sl:bookings:write', 'sl:contacts:write'] }
259
- export async function book(ctx, req) {
260
- const me = await ctx.sl.contacts.forCaller() // null when signed out
261
- // … your rules: hours (utils.withinSchedule), a queue token, a member level, a price …
262
- const b = await ctx.sl.bookings.create({
263
- resourceType: 'record', resourceId: req.body.staffId,
264
- startsAt: req.body.startsAt, endsAt: req.body.endsAt, bufferAfter: 10,
265
- contactId: me?.contactId, status: 'confirmed', idempotencyKey: req.body.requestId,
266
- })
267
- return Response.json({ id: b.id, startsAt: b.startsAt })
268
- }
269
- ```
270
-
271
- `create`, `get`, `query`, `mine` (the caller's own), `update`, `confirm`, `cancel`, `move`,
272
- `extendHold`, `complete`, `noShow`, `freebusy`, `slots.*`, `blocks.*`. Errors carry `code`,
273
- `status` and `details` exactly as over HTTP. The local test harness
274
- (`@proveanything/smartlinks/testing`) runs bookings in memory with the same rules.
275
-
276
- ---
277
-
278
- ## Payments and high-demand sales
279
-
280
- The platform takes no payments. It gives you what a payment or credits flow needs:
281
-
282
- 1. Create the booking **`held`** (claims the place; `holdMinutes`).
283
- 2. Take payment. Slow step? `bookings.extendHold(…, minutes)` (admin; capped at 24h from creation).
284
- 3. **Confirm after payment** — from your function or payment webhook handler. Confirm is idempotent, so
285
- a repeated webhook is harmless. A run-out hold fails with `HOLD_EXPIRED`.
286
- 4. If it's never confirmed, the hold expires within a minute: the booking becomes `cancelled`
287
- (`cancelReason: 'hold_expired'`) and the place goes back. Void the payment intent on the
288
- `booking.hold_expired` event.
289
-
290
- Keep payment references, amounts, credits and refunds in the booking's `admin` / `owner` zones.
291
-
292
- **High demand** (queues, lotteries, bot checks): turn public booking **off** so the only way in is
293
- your server function; it checks the queue token / per-person limit / throttle, then creates a short
294
- `held` booking. The platform guarantees nothing is oversold however many requests arrive.
295
-
296
- ---
297
-
298
- ## Errors
299
-
300
- Booking calls fail with HTTP 409 and an `errorCode` you can show or act on:
301
-
302
- | Code | When |
303
- |---|---|
304
- | `SLOT_FULL` | Not enough places left (`details.remaining`) |
305
- | `SLOT_CLOSED` | The slot isn't open |
306
- | `RESOURCE_TAKEN` | The time isn't free on that resource (`details` names it) |
307
- | `PER_CONTACT_LIMIT` / `QUANTITY_LIMIT` | Per-person / per-booking limit |
308
- | `HOLD_EXPIRED` | The hold ran out before confirm / move |
309
- | `INVALID_STATE` | e.g. confirming a cancelled booking |
310
- | `SLOT_OVERBOOKED` / `SLOT_HAS_BOOKINGS` | Lowering capacity below what's booked / changing a booked slot's time or deleting it |
311
- | `TOO_SOON` / `TOO_FAR_AHEAD` / `IN_THE_PAST` / `DURATION_NOT_ALLOWED` | Public time rules |
312
- | `OUTSIDE_SCHEDULE` / `NO_SCHEDULE` / `SCHEDULE_INVALID` | Public schedule check |
313
- | `CUTOFF_PASSED` | Owner action inside its cutoff |
314
-
315
- `403 FORBIDDEN` when the app's rules don't allow the call; `404` for unknown ids.
316
-
317
- ---
318
-
319
- ## Events
320
-
321
- Recorded after each write commits, for flows and app functions (`trigger: { type: 'event', eventTypes: [...] }`):
322
-
323
- `booking.created`, `booking.confirmed`, `booking.cancelled`, `booking.moved`, `booking.completed`,
324
- `booking.no_show`, `booking.hold_expired`, `slot.full`, `slot.place_freed` (for waitlist promotion).
325
- Context: `{ appId, status, slotIds }` (bookings) / `{ appId, remaining }` (slots).
326
-
327
- Reminders before a booking (`booking.starts_in`) are coming; until then, send a reminder template to
328
- tomorrow's bookers with `bookings.message` (below) from a cron function.
329
-
330
- ---
331
-
332
- ## Confirmations and messages
333
-
334
- Nothing is emailed by default: your app decides what goes out, in **flows on booking events**, with
335
- **templates the business can reword in Studio** (Comms → Templates). The platform does the sending,
336
- the hydration and the consent.
337
-
338
- ### Flows on booking events
339
-
340
- A site, or an app on behalf of a business, sets them up through the cloud blueprint
341
- (`cloud/flows.json` in a site; `POST /admin/collection/:cId/blueprint/apply` with
342
- `{ appId, blueprint: { templates, flows } }` from an app's admin screen). Additive: re-applying never
343
- removes what is there, and a template edited in Studio keeps its edits unless the blueprint sends new
344
- wording.
345
-
346
- ```json
347
- {
348
- "templates": {
349
- "booking-confirmed": { "name": "You're booked", "email": { "subject": "{{ booking.serviceName }} on {{ booking.when.date }}", "body": "<p>Hi {{ contact.firstName }}, see you at {{ booking.when.time }}.</p>" }, "sms": { "body": "Booked: {{ booking.when.shortDate }} {{ booking.when.time }}" } },
350
- "booking-requested": { "name": "Request received", "email": { "subject": "We got your request", "body": "<p>We'll confirm shortly.</p>" } },
351
- "staff-new-booking": { "name": "You've been booked", "email": { "subject": "New appointment", "body": "<p>{{ booking.customer.name }}, {{ booking.when.dateTime }}</p>" } }
352
- },
353
- "flows": [
354
- { "when": { "event": "booking.confirmed" }, "do": [{ "send": "booking-confirmed", "to": "contact" }, { "send": "staff-new-booking", "to": "resource" }, { "send": "team-new-booking", "to": "team" }] },
355
- { "when": { "event": "booking.created", "status": "pending" }, "do": [{ "send": "booking-requested", "to": "contact" }] }
356
- ]
357
- }
358
- ```
359
-
360
- - `when.event`: `booking.created` / `confirmed` / `cancelled` / `moved` / `completed` / `no_show` /
361
- `hold_expired`, `slot.full` / `slot.place_freed`; `when.status` narrows to the booking's status at the
362
- time (`"pending"` for "request received").
363
- - `to`: `contact` — the booker, by their preferred channel (`channel` to force one; a template needs an
364
- `sms` part to go by text); `team` — the collection's team addresses; an **address** (`"hello@bloom.com"`,
365
- or a list of up to 10) — a particular inbox, written out: never built from what someone sent
366
- (`{{ … }}` is refused), at most 200 a day per template; `resource` — the booked
367
- person or room: a resource that is a contact, or a record with `data.email` / `data.contactId`.
368
- A **public** resource record (a staff profile the booking page lists) keeps its address on a
369
- **private child record** instead (`visibility: 'admin'`, `parentType: 'record'`, `parentId` = the
370
- resource) — the platform looks there too, and the address never ships with the public listing.
371
- - Any step can also take `replyTo` — an address, or `"contact"` (replies go to the person the event is
372
- about: a team notification answered straight to the booker) — and `cc` / `bcc` (written-out addresses,
373
- same rules as `to`, counted in the same daily cap; over it the person still gets their email, without the
374
- copies). A site's `cloud/email.json` (`{ "fromName", "replyTo" }`) sets the name the business's emails come
375
- from and their default reply-to; the From address is the business's verified domain.
376
- - `attach` on a step adds files (at most 5, 10 MB in all): `"calendar"` — the booking as an `.ics` invite
377
- that drops straight into the person's calendar (a cancelled booking's invite cancels it there);
378
- `{ "asset": "<assetId>" }` — a file in the collection's assets (terms, a price list);
379
- `{ "function": "<name>" }` — your app's own function makes it (a receipt PDF: server-functions.md,
380
- "Making an email attachment"). E.g. `{ "send": "booking-confirmed", "to": "contact", "attach": ["calendar"] }`.
381
- One that can't be made is left out; the email still goes.
382
- - Who gets what, in templates: `{{ booking }}` is the booking **ready-formatted**: its fields and
383
- `data`, plus `serviceName`, `staffName`, `customer`, `durationMinutes`, `when` (`date`,
384
- `shortDate`, `time`, `endTime`, `dateTime`, `timezone` — in the business's timezone) and, when the
385
- recipient's timezone is known and differs, `whenFor` (the same in theirs); `editToken` only when the
386
- recipient is the booker (a guest's manage link). `{{ contact }}` is the recipient; `{{ appConfig }}`
387
- the app's public config (a booking page's address, the business name) for sends to the contact.
388
-
389
- ### Who is reachable
390
-
391
- A **guest** who books with an email or phone gets a **contact** (found by that identity or made,
392
- filling only empty fields: a form's details never overwrite a known contact), and so does a customer
393
- **staff book in by hand** (`customer: { name, email, phone }` on the body or in `data`). Admin
394
- creates may pass `contactId` instead. A booking with no contact gets no messages: show the booker why
395
- an email is worth giving.
396
-
397
- ### Messaging everyone booked — `bookings.message`
398
-
399
- No list to build, no segment to save: send a template to everyone on a slot, or everyone booked in a
400
- window (optionally with one resource), each hydrated with **their own** booking.
401
-
402
- ```ts
403
- // Everyone on tomorrow's 10:00 class
404
- await SL.bookings.message(collectionId, appId, { templateId, slotId })
405
- // Everyone booked with Sam next week, by email even if they prefer texts
406
- await SL.bookings.message(collectionId, appId, { templateId, channel: 'email', from, to, resourceType: 'record', resourceId: samId })
407
- // Everyone on the class, each with their own calendar invite
408
- await SL.bookings.message(collectionId, appId, { templateId, slotId, attach: ['calendar'] })
409
- // → { matched, sent, skipped: { noContact, duplicate, failed }, failures: [{ bookingId, reason }] }
410
- ```
411
-
412
- `attach` takes the same files as `comms.sendTransactional` (comms.md, "Attachments"); `'calendar'` is
413
- each person's own booking.
414
-
415
- Statuses default to held, pending and confirmed; at most 500 recipients per call (narrow the window
416
- for more). One message per contact on a slot, one per booking in a window. Also
417
- `ctx.sl.bookings.message(input)` in a server function (`sl:bookings:write`) — a cron function that
418
- messages tomorrow's bookers is a reminder system in five lines.
419
-
420
- ---
421
-
422
- ## API reference
423
-
424
- All take `(collectionId, appId, …)`; `admin` is the last parameter where both exist.
425
-
426
- | Call | Admin | Public |
427
- |---|---|---|
428
- | `bookings.create(input, admin?)` | any status, any field | per `publicCreate.bookings` |
429
- | `bookings.list(params?)` | ✓ | — (use `mine`) |
430
- | `bookings.mine(params?)` | — | signed-in booker |
431
- | `bookings.get(id, admin?, { editToken }?)` | ✓ | booker / token |
432
- | `bookings.update(id, input)` | ✓ | — |
433
- | `bookings.confirm / cancel / move(…, admin?, { editToken }?)` | ✓ | per `ownerActions.bookings` |
434
- | `bookings.extendHold / complete / noShow` | ✓ | — |
435
- | `bookings.freebusy(q, admin?)` | ✓ | if `publicRead.bookings.freebusy` |
436
- | `bookings.message(input)` | ✓ | — |
437
- | `bookings.slots.create / createMany / update / remove` | ✓ | — |
438
- | `bookings.slots.list / get(…, admin?)` | ✓ | open, public slots |
439
- | `bookings.blocks.create / list / remove` | ✓ | — |
440
- | `utils.freeTimes / withinSchedule / openIntervals / subtractIntervals / validateSchedule` | pure helpers | |
441
-
442
- REST: `/{admin|public}/collection/:cId/app/:appId/bookings[/slots|/blocks|/freebusy|/mine|/:id[/confirm|/cancel|/move|/extend-hold|/complete|/no-show]]`.
1
+ # Bookings: slots, bookings and allocations
2
+
3
+ Generic booking objects for **any** booking app: event tickets, classes, tours, table reservations,
4
+ one-to-one appointments, room and equipment hire. The platform gives you the objects and the
5
+ guarantees. Your app owns the rest: schedule, policy and UI. Payment can be the platform's too: see
6
+ [Paid bookings](#paid-bookings).
7
+
8
+ ```ts
9
+ import { bookings, utils } from '@proveanything/smartlinks'
10
+ ```
11
+
12
+ ---
13
+
14
+ ## What the platform guarantees (and what it doesn't)
15
+
16
+ | The platform | Your app |
17
+ |---|---|
18
+ | **No double-booking** of a person / room / table, however many requests arrive at once | The schedule (opening hours) and its UI |
19
+ | **No overselling** a slot's capacity | Booking policy: notice, durations, who may book |
20
+ | **Atomic** writes: a booking with several parts (a stylist *and* a chair) succeeds whole or not at all | Prices and ticket types (the platform can take the payment and refund: [Paid bookings](#paid-bookings)) |
21
+ | **Idempotent** creates (`idempotencyKey`): a retried request never books twice | Queues, waiting rooms, throttling for high-demand sales |
22
+ | **Holds** that expire and give the place back | Confirmation / reminder content (flows on booking events) |
23
+ | Who may book publicly, by **per-app rules** (like records / cases) | |
24
+
25
+ ---
26
+
27
+ ## The three objects
28
+
29
+ - **Slot** — a time window with a **capacity**: an event performance, a class, a tour at 2pm. Seats
30
+ are counted (`booked`, `remaining`).
31
+ - **Booking** — the customer's reservation and its lifecycle. This is what "my bookings" lists.
32
+ - **Allocation** — what a booking actually claims: seats on a slot (`mode: 'capacity'`) or
33
+ exclusive time on a resource (`mode: 'exclusive'`). Most apps never touch these directly: they're
34
+ returned on `booking.allocations`.
35
+
36
+ **Resources are not a new object.** Staff, rooms, tables and equipment are whatever you already use —
37
+ app records, contacts, products — referenced by type + id: `{ resourceType: 'record', resourceId: 'staff-sam' }`.
38
+
39
+ ### Booking statuses
40
+
41
+ | Status | Holds a place? | Meaning |
42
+ |---|---|---|
43
+ | `held` | yes, until `holdExpiresAt` | Claimed while the customer pays / confirms; expires automatically |
44
+ | `pending` | yes | Claimed, waiting for the business to approve |
45
+ | `confirmed` | yes | Booked |
46
+ | `completed` / `no_show` | yes (the time was used) | Outcome after the event (admin) |
47
+ | `cancelled` | no | `cancelReason`: `admin`, `owner`, `hold_expired` or your own |
48
+ | `waitlisted` | no | Waiting; confirming it claims the place if one is free |
49
+
50
+ ---
51
+
52
+ ## Events and classes — slots
53
+
54
+ ```ts
55
+ // Admin (Studio, or your app's server function): publish the sessions
56
+ const slot = await bookings.slots.create(collectionId, appId, {
57
+ startsAt: '2026-11-14T19:30:00Z', endsAt: '2026-11-14T21:00:00Z',
58
+ capacity: 200,
59
+ perContactLimit: 4, // max 4 seats per person on this slot, enforced atomically
60
+ data: { title: 'Autumn concert' },
61
+ })
62
+
63
+ // A class that also needs its instructor free: the slot blocks the instructor's time too
64
+ await bookings.slots.create(collectionId, appId, {
65
+ startsAt, endsAt, capacity: 12,
66
+ resourceType: 'record', resourceId: 'instructor-ana', blockResource: true,
67
+ })
68
+
69
+ // A series, all-or-nothing (max 500)
70
+ await bookings.slots.createMany(collectionId, appId, sessions, { seriesId })
71
+
72
+ // Public: open slots with places left
73
+ const { data } = await bookings.slots.list(collectionId, appId, { from, to, available: true })
74
+ data[0].remaining
75
+ ```
76
+
77
+ Book seats:
78
+
79
+ ```ts
80
+ const booking = await bookings.create(collectionId, appId, { slotId: slot.id, quantity: 2, idempotencyKey })
81
+ ```
82
+
83
+ Recurring events are **expanded into concrete slots** (`seriesId`); there's no recurrence rule
84
+ stored on a slot.
85
+
86
+ ---
87
+
88
+ ## Appointments — exclusive time on a resource
89
+
90
+ ```ts
91
+ await bookings.create(collectionId, appId, {
92
+ resourceType: 'record', resourceId: 'staff-sam',
93
+ startsAt: '2026-11-03T10:00:00Z', endsAt: '2026-11-03T10:30:00Z',
94
+ bufferAfter: 15, // admin: blocks 10:30–10:45 too (clean-up); the booking still shows 10:00–10:30
95
+ }, true)
96
+ ```
97
+
98
+ Several resources at once — all-or-nothing:
99
+
100
+ ```ts
101
+ await bookings.create(collectionId, appId, {
102
+ startsAt, endsAt,
103
+ allocations: [
104
+ { resourceType: 'record', resourceId: 'stylist-jo' },
105
+ { resourceType: 'record', resourceId: 'chair-2' },
106
+ ],
107
+ }, true)
108
+ ```
109
+
110
+ A pool with no fixed times (3 kayaks, bookable any time) is three resources; your app picks a free one.
111
+
112
+ ### Blocked time
113
+
114
+ ```ts
115
+ await bookings.blocks.create(collectionId, appId, { resourceType: 'record', resourceId: 'staff-sam', startsAt, endsAt, data: { reason: 'training' } })
116
+ ```
117
+
118
+ Planned time off usually belongs in your schedule (an override); blocks are for ad-hoc blocked time.
119
+
120
+ ---
121
+
122
+ ## Schedules and free times
123
+
124
+ **Your app owns the schedule.** Store it however you like — usually an app record. For the time maths,
125
+ the SDK ships a pure helper:
126
+
127
+ ```ts
128
+ const schedule = {
129
+ timezone: 'Europe/London',
130
+ weekly: { mon: [{ start: '09:00', end: '12:30' }, { start: '13:30', end: '17:00' }], tue: [{ start: '09:00', end: '17:00' }] },
131
+ overrides: [{ from: '2026-12-24', to: '2026-12-28', hours: [] }, { date: '2026-11-07', hours: [{ start: '10:00', end: '13:00' }] }],
132
+ }
133
+
134
+ const fb = await bookings.freebusy(collectionId, appId, { resources: ['record:staff-sam'], from, to }, true)
135
+ const times = utils.freeTimes({
136
+ hours: schedule, busy: fb.resources[0].busy,
137
+ from, to, duration: 30, step: 30, bufferAfter: 15, minNotice: 240,
138
+ })
139
+ // → [{ start, end }, …] in UTC; render in the booker's timezone
140
+ ```
141
+
142
+ - Times are **local wall-clock** in `timezone`, so "9 to 5" stays 9 to 5 across daylight-saving changes.
143
+ - A missing day is closed; hours never cross midnight (split them); `end` may be `'24:00'`.
144
+ - `overrides` win over `weekly` (`hours: []` = closed).
145
+ - Also exported: `utils.withinSchedule`, `utils.openIntervals`, `utils.subtractIntervals`, `utils.validateSchedule`.
146
+
147
+ `freebusy` returns busy intervals only (bookings, blocks, slots that block a resource) — never who
148
+ booked. It's collection-wide: a resource is busy whichever app booked it.
149
+
150
+ ---
151
+
152
+ ## Who can book — per-app rules
153
+
154
+ Exactly like records, cases and threads:
155
+
156
+ - **Admin calls are unconditional** — Studio users, and **your app's own server functions** (they call
157
+ the admin routes with your app's authority). Pass `admin = true`.
158
+ - **Public calls** (`admin = false`, the default for `create`) follow your app's config in
159
+ `sites/{collectionId}/apps/{appId}` (`POST /admin/collection/:cId/apps/:appId`). With no config,
160
+ **public booking is refused** — only admins (and your functions) can book.
161
+
162
+ Pick a mode per app:
163
+
164
+ | Mode | Config | Suits |
165
+ |---|---|---|
166
+ | **Public booking** | `publicCreate.bookings` allows anonymous and/or signed-in callers | "Book an appointment with me", simple events — no server code |
167
+ | **Admin-only booking** | no `publicCreate.bookings` | Extra validation, queues, payment-first, high demand: book through your server function |
168
+
169
+ ### `publicCreate.bookings`
170
+
171
+ ```json
172
+ {
173
+ "publicCreate": {
174
+ "bookings": {
175
+ "anonymous": {
176
+ "allow": true,
177
+ "enforce": { "status": "held" },
178
+ "limits": { "maxQuantity": 4, "holdMinutes": 15 },
179
+ "rules": { "targets": ["slots"], "minNoticeMinutes": 60, "horizonDays": 90 },
180
+ "edit": { "editToken": true }
181
+ },
182
+ "authenticated": {
183
+ "allow": true,
184
+ "enforce": { "status": "confirmed", "visibility": "owner" },
185
+ "rules": {
186
+ "targets": ["slots", "resources"],
187
+ "schedule": true,
188
+ "resourceTypes": ["record"],
189
+ "durations": [30, 60],
190
+ "minNoticeMinutes": 240,
191
+ "bufferAfter": 15
192
+ }
193
+ }
194
+ }
195
+ }
196
+ }
197
+ ```
198
+
199
+ | Field | Meaning |
200
+ |---|---|
201
+ | `enforce.status` | `confirmed` (instant), `pending` (business approves), `held` (pay / confirm next). Default `pending`. The caller can't override it. |
202
+ | `enforce.visibility` | Default: `owner` for signed-in, `admin` for anonymous |
203
+ | `limits.maxQuantity` | Max seats / claims per booking |
204
+ | `limits.holdMinutes` | Hold length for public `held` bookings (default 15, max 60) |
205
+ | `rules.targets` | `slots` (only your published slots) and/or `resources` (free-form time). Default `['slots']` |
206
+ | `rules.schedule` | **Required for `resources`.** The platform checks the requested time against the resource's schedule: an app record of **your app** with `recordType: 'availability'`, `parentType` / `parentId` = the resource, `data` in the standard shape above |
207
+ | `rules.resourceTypes` | Which resource types the public may book |
208
+ | `rules.durations` | Allowed lengths in minutes |
209
+ | `rules.minNoticeMinutes`, `rules.horizonDays` | How soon / how far ahead |
210
+ | `rules.bufferBefore`, `rules.bufferAfter` | Applied to every public booking (the caller can't set buffers) |
211
+ | `edit.editToken` | Anonymous only: the create response carries `editToken` **once** — store it so the guest can manage the booking. `edit.windowMinutes` limits how long it works |
212
+
213
+ Public callers can't set `contactId` (signed-in callers get their own contact; guests none), the
214
+ admin zone, buffers, `customId` or `sourceSystem`.
215
+
216
+ ### `ownerActions.bookings` — what the booker may do afterwards
217
+
218
+ ```json
219
+ {
220
+ "ownerActions": {
221
+ "bookings": {
222
+ "cancel": { "allow": true, "cutoffMinutes": 1440 },
223
+ "move": { "allow": true, "cutoffMinutes": 1440 },
224
+ "confirm": { "allow": true }
225
+ }
226
+ }
227
+ }
228
+ ```
229
+
230
+ Default: nothing. `cutoffMinutes` = not within that time of the start (`CUTOFF_PASSED`). `move`
231
+ re-checks the create rules for the new time. `confirm` turns the booker's own **held** booking into
232
+ `confirmed` — only for apps that take no payment (a hold waiting for its payment answers
233
+ `PAYMENT_REQUIRED`); `pending` and `waitlisted` are the business's to confirm.
234
+
235
+ ```ts
236
+ // Signed-in booker
237
+ await bookings.cancel(collectionId, appId, bookingId)
238
+ const mine = await bookings.mine(collectionId, appId, { from: new Date() })
239
+
240
+ // Guest, with the token from create
241
+ const b = await bookings.get(collectionId, appId, bookingId, false, { editToken })
242
+ await bookings.move(collectionId, appId, bookingId, { slotId: other.id }, false, { editToken })
243
+ ```
244
+
245
+ ### `publicRead.bookings.freebusy`
246
+
247
+ `{ "publicRead": { "bookings": { "freebusy": true } } }` lets public pages call `bookings.freebusy`.
248
+ Off by default — most apps serve free times through their own function.
249
+
250
+ ---
251
+
252
+ ## In a server function — `ctx.sl.bookings`
253
+
254
+ When public booking is off, your app books through its own server function. `ctx.sl.bookings` is
255
+ the same API, admin-side, for **your app's** bookings only (`sl:bookings:read` / `sl:bookings:write`):
256
+
257
+ ```ts
258
+ // manifest: { name: 'book', trigger: { type: 'http' }, visibility: 'public', authority: 'collection',
259
+ // capabilities: ['sl:bookings:write', 'sl:contacts:write'] }
260
+ export async function book(ctx, req) {
261
+ const me = await ctx.sl.contacts.forCaller() // null when signed out
262
+ // … your rules: hours (utils.withinSchedule), a queue token, a member level, a price …
263
+ const b = await ctx.sl.bookings.create({
264
+ resourceType: 'record', resourceId: req.body.staffId,
265
+ startsAt: req.body.startsAt, endsAt: req.body.endsAt, bufferAfter: 10,
266
+ contactId: me?.contactId, status: 'confirmed', idempotencyKey: req.body.requestId,
267
+ })
268
+ return Response.json({ id: b.id, startsAt: b.startsAt })
269
+ }
270
+ ```
271
+
272
+ `create`, `get`, `query`, `mine` (the caller's own), `update`, `confirm`, `cancel`, `move`,
273
+ `extendHold`, `complete`, `noShow`, `freebusy`, `checkout`, `refund`, `slots.*`, `blocks.*`. Errors carry `code`,
274
+ `status` and `details` exactly as over HTTP. The local test harness
275
+ (`@proveanything/smartlinks/testing`) runs bookings in memory with the same rules.
276
+
277
+ ---
278
+
279
+ ## Paid bookings
280
+
281
+ The platform can take the payment for you: on the business's own Stripe account (connected once in
282
+ Studio → Payments), with our fee for your app, and refunds when bookings are cancelled. Your app
283
+ names prices; it never handles card details, Stripe keys or webhooks.
284
+
285
+ **1. Prices, set by admins only.** On a slot, ticket types in `data.prices`; for appointments, the
286
+ app's price list in its config, `bookingPayments.prices`. Amounts are minor units (pence).
287
+
288
+ ```ts
289
+ await bookings.slots.create(collectionId, appId, {
290
+ startsAt, endsAt, capacity: 40,
291
+ data: { title: 'Santa\'s grotto', prices: [{ id: 'adult', label: 'Adult', amount: 1200 }, { id: 'child', label: 'Child', amount: 600 }] },
292
+ })
293
+ ```
294
+
295
+ ```json
296
+ {
297
+ "bookingPayments": {
298
+ "required": true,
299
+ "prices": [{ "id": "cut", "label": "Haircut", "amount": 2500, "durationMinutes": 30, "resourceIds": ["staff-1"] }],
300
+ "ownerCancelRefund": "full",
301
+ "successUrl": "https://example.com/booked",
302
+ "cancelUrl": "https://example.com/book"
303
+ }
304
+ }
305
+ ```
306
+
307
+ - `required: true` closes the free way in: a plain `bookings.create` of a priced booking fails with
308
+ `PAYMENT_REQUIRED`, so nobody skips the payment by calling the API.
309
+ - An appointment price is tied to what's booked: the booked length must be its `durationMinutes`, the
310
+ resource one of its `resourceIds` (`PRICE_MISMATCH` otherwise), and the booking's `data.service`
311
+ is set from the price.
312
+ - `sessionMinutes` (30–120, default 30): time on Stripe's page; the place is held 10 minutes longer.
313
+ `payWithinHours` (1–168, default 48): for requests, see below. `allowedHosts`: other hosts a page may
314
+ pass as `successUrl` / `cancelUrl` (the business's own hosts only).
315
+
316
+ **2. Book and pay.**
317
+
318
+ ```ts
319
+ const r = await bookings.checkout(collectionId, appId, {
320
+ slotId, lines: [{ priceId: 'adult', quantity: 2 }, { priceId: 'child', quantity: 1 }], // 3 places
321
+ email, customer: { name, email },
322
+ })
323
+ if (r.checkoutUrl) location.href = r.checkoutUrl // pay on Stripe's page
324
+ else if (r.request) showRequestSent() // approval first: a pay link follows
325
+ else showBooked(r.booking) // free
326
+ // Appointments: { resourceType, resourceId, startsAt, endsAt, priceId: 'cut' }
327
+ ```
328
+
329
+ The booking is **held** while the person pays; Stripe's webhook confirms it (`booking.paid`, then
330
+ `booking.confirmed` as usual, so your confirmation emails don't change). Not paid in time: cancelled
331
+ (`payment_not_completed`) and the places go back at once. On the success page:
332
+
333
+ ```ts
334
+ const b = await bookings.bySession(collectionId, appId, new URLSearchParams(location.search).get('session_id')!)
335
+ if (b.confirming) setTimeout(reload, 2000) // the webhook is a moment behind
336
+ ```
337
+
338
+ Every booking response carries a read-only `payment`: `{ status: 'awaiting' | 'paid' |
339
+ 'partially_refunded' | 'refunded' | 'waived', total, currency, refunded, lines }`, and emails get it
340
+ formatted as `{{ booking.payment.totalText }}`, `{{ booking.payment.lines }}`.
341
+
342
+ **3. Bookings that need approval** (the rules book as `pending`): nobody pays for a booking they don't
343
+ have yet. `checkout` keeps the place and fixes the price, `checkoutUrl: null, request: true`. When
344
+ staff confirm it (`bookings.confirm(…, true)`), it becomes a hold until the pay-by time and
345
+ `booking.payment_requested` fires: put `{{ booking.payment.link }}` and `{{ booking.payment.payByText }}`
346
+ in that flow's email. The link goes straight to Stripe; an app with its own pay page calls
347
+ `bookings.pay(collectionId, appId, bookingId, token)`. Unpaid by then, the place goes back. Staff can
348
+ confirm without payment with `{ payment: 'waive' }` (paid in cash).
349
+
350
+ **4. Cancelling and refunds.** The booker cancelling (per `ownerActions.bookings.cancel`) is refunded
351
+ by `bookingPayments.ownerCancelRefund` (`'full'`, default, or `'none'`). Staff choose:
352
+ `bookings.cancel(…, true, { refund: 'full' | 'none' | 500 })`. A refund without cancelling:
353
+ `bookings.refund(collectionId, appId, bookingId, { amount })`. A refund Stripe can't take right away is
354
+ retried by the platform; the booking is flagged `refund_failed` after three tries. A paid booking
355
+ moves only to a place at the same price.
356
+
357
+ Events: `booking.paid`, `booking.refunded`, `booking.payment_requested`, `booking.payment_refunded` (paid
358
+ after the place had gone: refunded in full and flagged `refunded_no_place`). Flags on the booking:
359
+ `paid_late`, `payment_mismatch`, `refunded_no_place`, `refund_failed`.
360
+
361
+ In a server function, `ctx.sl.bookings.checkout({ …, status: 'held' | 'pending' })` does the same
362
+ without the public rules; `ctx.sl.bookings.refund(id, { amount })`. In the local test harness there is
363
+ no Stripe: `checkoutUrl` is pretend and `ctx.sl.bookings.payWith(bookingId)` stands in for the payment.
364
+
365
+ **Your own payments instead.** Nothing here is required: an app that takes payment its own way (its own
366
+ Stripe keys, credits, vouchers) uses holds and confirm as below.
367
+
368
+ ## Payments your app takes itself, and high-demand sales
369
+
370
+ The platform gives you what your own payment or credits flow needs:
371
+
372
+ 1. Create the booking **`held`** (claims the place; `holdMinutes`).
373
+ 2. Take payment. Slow step? `bookings.extendHold(…, minutes)` (admin; capped at 24h from creation).
374
+ 3. **Confirm after payment** — from your function or payment webhook handler. Confirm is idempotent, so
375
+ a repeated webhook is harmless. A run-out hold fails with `HOLD_EXPIRED`.
376
+ 4. If it's never confirmed, the hold expires within a minute: the booking becomes `cancelled`
377
+ (`cancelReason: 'hold_expired'`) and the place goes back. Void the payment intent on the
378
+ `booking.hold_expired` event.
379
+
380
+ Keep payment references, amounts, credits and refunds in the booking's `admin` / `owner` zones.
381
+
382
+ **High demand** (queues, lotteries, bot checks): turn public booking **off** so the only way in is
383
+ your server function; it checks the queue token / per-person limit / throttle, then creates a short
384
+ `held` booking. The platform guarantees nothing is oversold however many requests arrive.
385
+
386
+ ---
387
+
388
+ ## Errors
389
+
390
+ Booking calls fail with HTTP 409 and an `errorCode` you can show or act on:
391
+
392
+ | Code | When |
393
+ |---|---|
394
+ | `SLOT_FULL` | Not enough places left (`details.remaining`) |
395
+ | `SLOT_CLOSED` | The slot isn't open |
396
+ | `RESOURCE_TAKEN` | The time isn't free on that resource (`details` names it) |
397
+ | `PER_CONTACT_LIMIT` / `QUANTITY_LIMIT` | Per-person / per-booking limit |
398
+ | `HOLD_EXPIRED` | The hold ran out before confirm / move |
399
+ | `INVALID_STATE` | e.g. confirming a cancelled booking |
400
+ | `SLOT_OVERBOOKED` / `SLOT_HAS_BOOKINGS` | Lowering capacity below what's booked / changing a booked slot's time or deleting it |
401
+ | `TOO_SOON` / `TOO_FAR_AHEAD` / `IN_THE_PAST` / `DURATION_NOT_ALLOWED` | Public time rules |
402
+ | `OUTSIDE_SCHEDULE` / `NO_SCHEDULE` / `SCHEDULE_INVALID` | Public schedule check |
403
+ | `CUTOFF_PASSED` | Owner action inside its cutoff |
404
+ | `PAYMENT_REQUIRED` | A priced booking made without `checkout`, or confirming one that isn't paid |
405
+ | `PAYMENTS_NOT_READY` | The business hasn't connected Stripe yet (Studio → Payments) |
406
+ | `PRICE_MISMATCH` | The price doesn't fit what's booked (length, staff), or a paid move to another price |
407
+ | `NOT_PAID` | Refunding a booking with no payment |
408
+ | `PRICE_NOT_FOUND` (400) | Unknown `priceId`, or several ticket types and no `lines` |
409
+
410
+ `403 FORBIDDEN` when the app's rules don't allow the call; `404` for unknown ids.
411
+
412
+ ---
413
+
414
+ ## Events
415
+
416
+ Recorded after each write commits, for flows and app functions (`trigger: { type: 'event', eventTypes: [...] }`):
417
+
418
+ `booking.created`, `booking.confirmed`, `booking.cancelled`, `booking.moved`, `booking.completed`,
419
+ `booking.no_show`, `booking.hold_expired`, `slot.full`, `slot.place_freed` (for waitlist promotion);
420
+ paid bookings add `booking.paid`, `booking.refunded`, `booking.payment_requested`,
421
+ `booking.payment_refunded`.
422
+ Context: `{ appId, status, slotIds }` (bookings) / `{ appId, remaining }` (slots).
423
+
424
+ Reminders before a booking (`booking.starts_in`) are coming; until then, send a reminder template to
425
+ tomorrow's bookers with `bookings.message` (below) from a cron function.
426
+
427
+ ---
428
+
429
+ ## Confirmations and messages
430
+
431
+ Nothing is emailed by default: your app decides what goes out, in **flows on booking events**, with
432
+ **templates the business can reword in Studio** (Comms → Templates). The platform does the sending,
433
+ the hydration and the consent.
434
+
435
+ ### Flows on booking events
436
+
437
+ A site, or an app on behalf of a business, sets them up through the cloud blueprint
438
+ (`cloud/flows.json` in a site; `POST /admin/collection/:cId/blueprint/apply` with
439
+ `{ appId, blueprint: { templates, flows } }` from an app's admin screen). Additive: re-applying never
440
+ removes what is there, and a template edited in Studio keeps its edits unless the blueprint sends new
441
+ wording.
442
+
443
+ ```json
444
+ {
445
+ "templates": {
446
+ "booking-confirmed": { "name": "You're booked", "email": { "subject": "{{ booking.serviceName }} on {{ booking.when.date }}", "body": "<p>Hi {{ contact.firstName }}, see you at {{ booking.when.time }}.</p>" }, "sms": { "body": "Booked: {{ booking.when.shortDate }} {{ booking.when.time }}" } },
447
+ "booking-requested": { "name": "Request received", "email": { "subject": "We got your request", "body": "<p>We'll confirm shortly.</p>" } },
448
+ "staff-new-booking": { "name": "You've been booked", "email": { "subject": "New appointment", "body": "<p>{{ booking.customer.name }}, {{ booking.when.dateTime }}</p>" } }
449
+ },
450
+ "flows": [
451
+ { "when": { "event": "booking.confirmed" }, "do": [{ "send": "booking-confirmed", "to": "contact" }, { "send": "staff-new-booking", "to": "resource" }, { "send": "team-new-booking", "to": "team" }] },
452
+ { "when": { "event": "booking.created", "status": "pending" }, "do": [{ "send": "booking-requested", "to": "contact" }] }
453
+ ]
454
+ }
455
+ ```
456
+
457
+ - `when.event`: `booking.created` / `confirmed` / `cancelled` / `moved` / `completed` / `no_show` /
458
+ `hold_expired`, `slot.full` / `slot.place_freed`; `when.status` narrows to the booking's status at the
459
+ time (`"pending"` for "request received").
460
+ - `to`: `contact` — the booker, by their preferred channel (`channel` to force one; a template needs an
461
+ `sms` part to go by text); `team` — the collection's team addresses; an **address** (`"hello@bloom.com"`,
462
+ or a list of up to 10) — a particular inbox, written out: never built from what someone sent
463
+ (`{{ … }}` is refused), at most 200 a day per template; `resource` — the booked
464
+ person or room: a resource that is a contact, or a record with `data.email` / `data.contactId`.
465
+ A **public** resource record (a staff profile the booking page lists) keeps its address on a
466
+ **private child record** instead (`visibility: 'admin'`, `parentType: 'record'`, `parentId` = the
467
+ resource) — the platform looks there too, and the address never ships with the public listing.
468
+ - Any step can also take `replyTo` — an address, or `"contact"` (replies go to the person the event is
469
+ about: a team notification answered straight to the booker) — and `cc` / `bcc` (written-out addresses,
470
+ same rules as `to`, counted in the same daily cap; over it the person still gets their email, without the
471
+ copies). A site's `cloud/email.json` (`{ "fromName", "replyTo" }`) sets the name the business's emails come
472
+ from and their default reply-to; the From address is the business's verified domain.
473
+ - `attach` on a step adds files (at most 5, 10 MB in all): `"calendar"` — the booking as an `.ics` invite
474
+ that drops straight into the person's calendar (a cancelled booking's invite cancels it there);
475
+ `{ "asset": "<assetId>" }` — a file in the collection's assets (terms, a price list);
476
+ `{ "function": "<name>" }` — your app's own function makes it (a receipt PDF: server-functions.md,
477
+ "Making an email attachment"). E.g. `{ "send": "booking-confirmed", "to": "contact", "attach": ["calendar"] }`.
478
+ One that can't be made is left out; the email still goes.
479
+ - Who gets what, in templates: `{{ booking }}` is the booking **ready-formatted**: its fields and
480
+ `data`, plus `serviceName`, `staffName`, `customer`, `durationMinutes`, `when` (`date`,
481
+ `shortDate`, `time`, `endTime`, `dateTime`, `timezone` — in the business's timezone) and, when the
482
+ recipient's timezone is known and differs, `whenFor` (the same in theirs); `editToken` only when the
483
+ recipient is the booker (a guest's manage link). `{{ contact }}` is the recipient; `{{ appConfig }}`
484
+ the app's public config (a booking page's address, the business name) for sends to the contact.
485
+
486
+ ### Who is reachable
487
+
488
+ A **guest** who books with an email or phone gets a **contact** (found by that identity or made,
489
+ filling only empty fields: a form's details never overwrite a known contact), and so does a customer
490
+ **staff book in by hand** (`customer: { name, email, phone }` on the body or in `data`). Admin
491
+ creates may pass `contactId` instead. A booking with no contact gets no messages: show the booker why
492
+ an email is worth giving.
493
+
494
+ ### Messaging everyone booked — `bookings.message`
495
+
496
+ No list to build, no segment to save: send a template to everyone on a slot, or everyone booked in a
497
+ window (optionally with one resource), each hydrated with **their own** booking.
498
+
499
+ ```ts
500
+ // Everyone on tomorrow's 10:00 class
501
+ await SL.bookings.message(collectionId, appId, { templateId, slotId })
502
+ // Everyone booked with Sam next week, by email even if they prefer texts
503
+ await SL.bookings.message(collectionId, appId, { templateId, channel: 'email', from, to, resourceType: 'record', resourceId: samId })
504
+ // Everyone on the class, each with their own calendar invite
505
+ await SL.bookings.message(collectionId, appId, { templateId, slotId, attach: ['calendar'] })
506
+ // → { matched, sent, skipped: { noContact, duplicate, failed }, failures: [{ bookingId, reason }] }
507
+ ```
508
+
509
+ `attach` takes the same files as `comms.sendTransactional` (comms.md, "Attachments"); `'calendar'` is
510
+ each person's own booking.
511
+
512
+ Statuses default to held, pending and confirmed; at most 500 recipients per call (narrow the window
513
+ for more). One message per contact on a slot, one per booking in a window. Also
514
+ `ctx.sl.bookings.message(input)` in a server function (`sl:bookings:write`) — a cron function that
515
+ messages tomorrow's bookers is a reminder system in five lines.
516
+
517
+ ---
518
+
519
+ ## API reference
520
+
521
+ All take `(collectionId, appId, …)`; `admin` is the last parameter where both exist.
522
+
523
+ | Call | Admin | Public |
524
+ |---|---|---|
525
+ | `bookings.create(input, admin?)` | any status, any field | per `publicCreate.bookings` |
526
+ | `bookings.list(params?)` | ✓ | — (use `mine`) |
527
+ | `bookings.mine(params?)` | — | signed-in booker |
528
+ | `bookings.get(id, admin?, { editToken }?)` | ✓ | booker / token |
529
+ | `bookings.update(id, input)` | ✓ | — |
530
+ | `bookings.confirm / cancel / move(…, admin?, { editToken }?)` | ✓ | per `ownerActions.bookings` |
531
+ | `bookings.extendHold / complete / noShow` | ✓ | — |
532
+ | `bookings.freebusy(q, admin?)` | ✓ | if `publicRead.bookings.freebusy` |
533
+ | `bookings.message(input)` | ✓ | — |
534
+ | `bookings.slots.create / createMany / update / remove` | ✓ | — |
535
+ | `bookings.slots.list / get(…, admin?)` | ✓ | open, public slots |
536
+ | `bookings.blocks.create / list / remove` | ✓ | — |
537
+ | `utils.freeTimes / withinSchedule / openIntervals / subtractIntervals / validateSchedule` | pure helpers | |
538
+
539
+ REST: `/{admin|public}/collection/:cId/app/:appId/bookings[/slots|/blocks|/freebusy|/mine|/:id[/confirm|/cancel|/move|/extend-hold|/complete|/no-show]]`.