@ordinatio/scheduling 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 (2026-10-29)
4
+
5
+ - **Security fix: booking analytics and group-class lists no longer rely on the database handle being limited to one business.**
6
+ `getBookingAnalytics` and `getGroupSessions` take an optional `organizationId`; given one, nothing from another organization is
7
+ counted or listed, even when several businesses share one database. A new exported helper, `withOrganization(where, organizationId)`,
8
+ does the same for any appointment query, and `scopeToOrganization(db, organizationId)` limits every query a handle makes.
9
+ `getAppointmentDashboard`, `getAppointmentsForRange` (new 4th argument `{ organizationId }`), `getUserDayAppointments`,
10
+ `listAppointments` and `getAppointment` take the same optional `organizationId`; an appointment of another organization is reported
11
+ as not found. Left out, behavior is unchanged (for a host that gives each business its own database).
12
+ If you keep several businesses in one database, upgrade to this version and `@ordinatio/scheduling-api` 0.3.0 together: engine 0.4.0
13
+ and API 0.2.0 (and earlier) return other businesses' appointments and revenue totals to staff. If your own code calls
14
+ `getBookingAnalytics` or `getGroupSessions`, pass `organizationId` from now on.
15
+
16
+ ## 0.4.0 (2026-10-28)
17
+
18
+ - **Organization brand.** `saveBrand`, `getBrand`, `getPublicBrand` and `deleteBrand` keep a name, logo, colours, font, footer and
19
+ sender identity per organization (new table `OrganizationBrand`, migration `20261027400000_organization_brand`). Everything is
20
+ checked when saved and all problems are reported together (`SCHED_1400`); a sending address is accepted only for a domain the host
21
+ confirms. Messages can use `{{brandName}}`, `{{brandLogoUrl}}`, `{{brandColor}}`, `{{brandFooter}}` when `scheduleNotifications`,
22
+ `queueImmediateNotification` or `queueStaffNotification` get `{ brand: true }`, and `processPendingNotifications({ brand: true })`
23
+ hands each message's sender identity to the sender as `context.from` (and to a notification adapter as `message.from`). New exports:
24
+ `validateBrand`, `senderIdentity`, `brandTemplateFields`, `toPublicBrand`, `BRAND_FIELDS`, and the `SenderIdentity` type.
25
+ - Video-meeting rooms for new virtual bookings are now named `ordinatio-<id>` instead of carrying the name of the business the package
26
+ was first built for; rooms already created keep their link.
27
+ - **Data export and erasure.** `exportSubject` returns everything held about one person (by email, client id, or both) as one
28
+ document, without the links that would let someone act as them. `eraseSubject` anonymizes their bookings, package purchases and
29
+ recurring series and deletes their messages, waitlist entries and queued webhook events, all in one transaction; it refuses
30
+ (`SCHED_1301`) while they have an upcoming booking or an open waitlist offer. `previewErase` shows the effect first. Each
31
+ request is recorded in the new `DataSubjectRequest` table (migration `20261027300000_privacy_requests`) as counts and
32
+ digests, never the address. New functions: `exportSubject`, `previewErase`, `eraseSubject`, `listPrivacyRequests`,
33
+ `parseSubject`, `resolveSubject`, `subjectHashes`. New error codes `SCHED_1300` and `SCHED_1301`.
34
+ - **Routing forms.** An admin defines a short form (questions, ordered rules, a fallback) that sends a client to the right
35
+ appointment type or calendar. Everything is checked when the form is saved: rules must name questions that exist, use an
36
+ operator that fits the question and a value that is one of its options, and send the client to a type and calendar that are
37
+ live in the organization and belong together. All problems are reported at once with their place in the form. New table
38
+ `RoutingForm` (migration `20261027200000_routing_forms`). New functions: `createRoutingForm`, `updateRoutingForm`,
39
+ `getRoutingForm`, `listRoutingForms`, `deleteRoutingForm`, `getPublicRoutingForm`, `routeClient`, `testRoutingForm`,
40
+ `validateRoutingStructure`, `validateRoutingDestinations`, `checkAnswers`, `matchingRules`, `resolveDestination`,
41
+ `OPERATORS_BY_TYPE`, `ROUTING_LIMITS`. A slug is unique across organizations in one database. New error codes
42
+ `SCHED_1200` to `SCHED_1204`.
43
+ - **Waitlist.** A client can wait for a full slot or day. When a booking is cancelled or moved, the slot it held
44
+ is offered to the longest-waiting person it fits, for 30 minutes by default and never past the start of the slot.
45
+ New table `WaitlistEntry` (migration `20261027100000_waitlist`, which also adds a database rule that lets one live
46
+ offer hold a slot, so two cancellations cannot offer the same slot twice). New functions: `joinWaitlist`,
47
+ `offerFreedSlot`, `tryOfferFreedSlot`, `expireWaitlistOffers`, `getWaitlistOffer`, `beginWaitlistAccept`,
48
+ `completeWaitlistAccept`, `releaseWaitlistAccept`, `listWaitlist`, `removeWaitlistEntry`, `leaveWaitlist`.
49
+ `leaveWaitlist` and `removeWaitlistEntry` return the slot a held offer occupied, and `releaseWaitlistAccept` takes an
50
+ outcome, `settleBookedAccept` recognises an accept whose booking was saved even though the request failed, so a host can pass a freed slot on. `expireWaitlistOffers` also settles an accept that never finished: booked
51
+ if the booking was saved, otherwise back in line with its slot returned. New error codes `SCHED_1100` to `SCHED_1110`.
52
+ - New webhook event `waitlist.offered`.
53
+
3
54
  ## 0.3.0
4
55
 
5
56
  - **Outbound webhooks.** An organization can register web addresses that are told when a booking is made,
package/README.md CHANGED
@@ -257,8 +257,8 @@ credentials as the second argument to `checkAuthContract`, or it cannot check th
257
257
  ## Webhooks
258
258
 
259
259
  An organization can register web addresses that are told when something happens to a booking. The events are
260
- `appointment.booked`, `appointment.rescheduled`, `appointment.cancelled`, `appointment.no_show` and
261
- `reminder.sent`. Run `prisma migrate deploy` after updating: webhooks need the `WebhookEndpoint`,
260
+ `appointment.booked`, `appointment.rescheduled`, `appointment.cancelled`, `appointment.no_show`,
261
+ `reminder.sent` and `waitlist.offered`. Run `prisma migrate deploy` after updating: webhooks need the `WebhookEndpoint`,
262
262
  `WebhookDelivery` and `WebhookAttempt` tables.
263
263
 
264
264
  ```ts
@@ -307,3 +307,180 @@ because signing needs it; protect database backups as you would any key. To rota
307
307
  and remove the old one.
308
308
 
309
309
  To also queue `reminder.sent`, call `processPendingNotifications(db, sender, { webhooks: true })`.
310
+
311
+ ## Waitlist
312
+
313
+ A client can wait for a slot or day that is full. When a booking is cancelled or moved, the slot it held is offered to
314
+ the person who has waited longest and whose appointment type fits it. Run `prisma migrate deploy` after updating:
315
+ the waitlist needs the `WaitlistEntry` table.
316
+
317
+ ```ts
318
+ import { joinWaitlist, offerFreedSlot, expireWaitlistOffers, beginWaitlistAccept, completeWaitlistAccept, releaseWaitlistAccept } from '@ordinatio/scheduling';
319
+
320
+ // 1. A client joins a full day (or one full slot). Joining is refused while the day still has room: they should book.
321
+ const { token } = await joinWaitlist(db, { organizationId, typeId, day: '2026-11-03', clientName: 'Jane', clientEmail: 'jane@example.com' });
322
+
323
+ // 2. A booking was cancelled: offer its slot to the first person in line. Returns null when nobody fits.
324
+ const offer = await offerFreedSlot(db, { organizationId, calendarId, startTime: cancelledStart });
325
+ if (offer) await sendEmail(offer.entry.clientEmail, `https://example.com/offer?token=${offer.token}`);
326
+
327
+ // 3. On a timer: end offers whose time ran out, and offer each freed slot to the next person.
328
+ const { lapsed } = await expireWaitlistOffers(db);
329
+ for (const slot of lapsed) await offerFreedSlot(db, slot);
330
+ ```
331
+
332
+ When the client opens their link, take the slot in three steps so the booking runs through your normal booking path:
333
+ `beginWaitlistAccept(db, token)` claims the offer (two clicks at once: one wins), you book, then
334
+ `completeWaitlistAccept(db, entryId, appointmentId)`. If the booking did not happen, call
335
+ `releaseWaitlistAccept(db, entryId, outcome)`: `'KEEP_OFFER'` for a temporary failure (the offer stays open),
336
+ `'BACK_IN_LINE'` when the slot was taken (the client keeps their place), or `'DROP'` when a booking rule refuses them
337
+ (they come off the list). `'DROP'` returns the slot.
338
+
339
+ **Pass freed slots on.** Three calls return a `FreedSlot` (or `null`) that you must hand to `offerFreedSlot`, or the
340
+ next person never hears about it: `leaveWaitlist` and `removeWaitlistEntry` (when the entry held an offer) and
341
+ `releaseWaitlistAccept(..., 'DROP')`. `expireWaitlistOffers` returns its `lapsed` list for the same reason; it also settles
342
+ an accept that started more than five minutes ago and never finished (booked if the booking was saved, otherwise back in
343
+ line with its slot added to `lapsed`). If an accept looks like it failed, call `settleBookedAccept(db, entryId)` before releasing it: a booking can be saved and a later step fail, and it marks the entry booked and returns the booking when the client already holds the slot.
344
+
345
+ **What an offer is.** First dibs, not a hold: until the client accepts, the slot is still open to anyone who books it,
346
+ and if someone does, accepting fails and the client keeps their place. One live offer holds a slot at a time (a database
347
+ rule), and one person is never offered two slots at once. A waitlist is not available for a type that needs payment or has required intake questions (an accepted offer books with
348
+ no answers); `joinWaitlist` refuses both. Joining checks no one owns the email address, so offer messages can reach a person
349
+ who did not ask for them; put your own check (or a CAPTCHA) in front of it for a public page.
350
+ `token` is the client's own handle (it opens the offer and leaves the list); send it only to them.
351
+
352
+ ## Routing forms
353
+
354
+ A routing form asks a client a few questions and sends them to the right appointment type or calendar ("What do you need?
355
+ Suit, shirt, repair"). Run `prisma migrate deploy` after updating: routing forms need the `RoutingForm` table.
356
+
357
+ ```ts
358
+ import { createRoutingForm, routeClient } from '@ordinatio/scheduling';
359
+
360
+ // An admin saves a form. Nothing is stored unless the whole form is valid.
361
+ await createRoutingForm(db, organizationId, {
362
+ name: 'Fitting finder',
363
+ slug: 'fitting-finder',
364
+ questions: [
365
+ { id: 'service', label: 'What do you need?', type: 'select', required: true, options: ['Suit', 'Shirt', 'Repair'] },
366
+ { id: 'budget', label: 'Budget', type: 'number' },
367
+ ],
368
+ rules: [
369
+ // Rules run in order; the first whose conditions hold wins.
370
+ { id: 'big-suit', match: 'all',
371
+ conditions: [{ questionId: 'service', operator: 'equals', value: 'Suit' }, { questionId: 'budget', operator: 'gte', value: 2000 }],
372
+ destination: { typeId: premiumTypeId, calendarId: seniorCalendarId } },
373
+ { id: 'suit', conditions: [{ questionId: 'service', operator: 'equals', value: 'Suit' }], destination: { typeId: suitTypeId } },
374
+ ],
375
+ // Required: what happens when no rule matches.
376
+ fallback: { kind: 'MESSAGE', message: 'Please call the shop and we will find a time.' },
377
+ });
378
+
379
+ // A client's answers decide where they go.
380
+ const outcome = await routeClient(db, { organizationId, slug: 'fitting-finder', answers: { service: 'Suit', budget: 2500 } });
381
+ // { destination: { typeId, typeSlug, typeName, calendarId, calendarSlug, calendarName }, message: null, matchedRuleId: 'big-suit', usedFallback: false }
382
+ ```
383
+
384
+ **Question types** are `select`, `radio` (one of the options), `checkbox` (a list of options), `text` and `number`.
385
+ **Operators** depend on the type: choice questions allow `equals`, `not_equals`, `in`; checkbox allows `contains`,
386
+ `not_contains`; text allows `equals`, `not_equals`, `contains` (ignoring case, whereas `equals` is exact), `not_contains`; number allows `equals`,
387
+ `not_equals`, `gt`, `gte`, `lt`, `lte`; every type allows `is_answered` and `is_empty`. A rule's `match` is `all` (default) or
388
+ `any`. A question the client left unanswered satisfies only `is_empty`, so "not equal to X" does not match someone who skipped it.
389
+
390
+ **Checked when saved.** `createRoutingForm` and `updateRoutingForm` refuse a form that has a rule naming a question that does
391
+ not exist, an operator that does not fit the question, a value that is not one of its options, a form with no question, no
392
+ rule or no fallback, or a destination that is not live in the organization (the type or calendar is missing, switched off, or
393
+ the type is not offered on that calendar). They throw `SCHED_1200` with every problem, each with its place such as
394
+ `rules[2].conditions[0].value`, in `error.context.errors`. An update checks the whole merged form again, destinations
395
+ included, when it changes the questions, rules or fallback; a change that leaves those alone (a rename, switching the form
396
+ off) is always allowed, even if a destination has been switched off since. A slug is unique within the organization and also
397
+ may not be used by another organization's form in the same database, so a public link by slug alone is never ambiguous (a
398
+ host with a database per organization names the organization instead).
399
+
400
+ **Checked when used.** Destinations are looked up again at the moment a client is routed: a rule whose type or calendar was
401
+ switched off since saving is skipped, and the next matching rule (or the fallback) is used. If the fallback destination is gone
402
+ too, the client is told to get in touch. `getPublicRoutingForm` returns the questions only; the rules stay on the server.
403
+ `testRoutingForm` tries sample answers, even on a form that is switched off, and lists every rule that matched.
404
+
405
+ **Limits.** 20 questions, 50 rules, 10 conditions per rule, 50 options per question, 50 forms per organization. Answers are not
406
+ stored: routing a client leaves no record.
407
+
408
+ ## Organization brand
409
+
410
+ Each organization can have a brand: a name, logo, colours, font and footer for the booking page and its messages, and an identity
411
+ its messages are sent as. Run `prisma migrate deploy` after updating: it needs the `OrganizationBrand` table.
412
+
413
+ ```ts
414
+ import { saveBrand, getBrand, getPublicBrand } from '@ordinatio/scheduling';
415
+
416
+ await saveBrand(db, organizationId, {
417
+ displayName: 'Acme Fittings',
418
+ logoUrl: 'https://cdn.acme.example/logo.png',
419
+ primaryColor: '#112233',
420
+ footerText: 'Acme, 1 Main St',
421
+ replyToEmail: 'help@acme.example',
422
+ fromName: 'Acme Bookings',
423
+ fromEmail: 'bookings@mail.acme.example',
424
+ }, { isSendingDomainVerified: async (domain) => myMailProvider.isVerified(domain) });
425
+ ```
426
+
427
+ `saveBrand` replaces the whole brand and refuses (`SCHED_1400`) one with any problem, listing every problem with its field.
428
+ Colours must be hex (`#1a2b3c`), the logo an `https` address, font names plain words, and addresses single plain addresses.
429
+ **A sending address (`fromEmail`) is accepted only for a domain `isSendingDomainVerified` confirms.** Without that function no
430
+ organization can set one, so an organization can never send as a domain it does not control; `replyToEmail` needs no check.
431
+ The package does not verify domains itself: confirming that your mail provider will send for the domain (SPF, DKIM) is the host's job.
432
+
433
+ **On the booking page.** `getPublicBrand` returns what a visitor may see (never an email address). The API package serves it at
434
+ `GET /brand` and the booking widget applies it.
435
+
436
+ **In messages.** Pass `{ brand: true }` to `scheduleNotifications`, `queueImmediateNotification` or `queueStaffNotification` and a
437
+ template can use `{{brandName}}`, `{{brandLogoUrl}}`, `{{brandColor}}` and `{{brandFooter}}` (empty text when the organization has
438
+ no brand; HTML-escaped in email bodies). Pass `brand: true` to `processPendingNotifications` and each message reaches your sender with
439
+ `context.from` set to its organization's identity (`{ name, email?, replyTo? }`); a notification adapter receives the same as
440
+ `message.from`. **Your sender decides what to do with it**: use `email` as the From address (it is on a domain you confirmed),
441
+ `name` as the display name and `replyTo` as Reply-To, or ignore `from` and send from your own address.
442
+
443
+ Without those options nothing changes and the brand table is never read. The brand fields in a message are filled in when it is
444
+ queued, so a message queued before the brand was saved or changed keeps the text it was rendered with. The sender identity is read when
445
+ the message is sent, so it follows the brand as it is at that moment, and a domain the host stops confirming keeps being used until the
446
+ brand is saved again. A sender name may not contain quotes, angle brackets, commas, semicolons, `@` or backslashes.
447
+
448
+ ## Data export and erasure
449
+
450
+ Answers a person's request to see, or to be forgotten. Run `prisma migrate deploy` after updating: it needs the
451
+ `DataSubjectRequest` table. A person is named by an email address (any letter case), a client id, or both; a client id also
452
+ covers every address that client booked with in the organization.
453
+
454
+ ```ts
455
+ import { exportSubject, previewErase, eraseSubject } from '@ordinatio/scheduling';
456
+
457
+ const file = await exportSubject(db, { organizationId, requestedBy: staff.userId, email: 'jane@example.com' });
458
+ const preview = await previewErase(db, { organizationId, email: 'jane@example.com' }); // changes nothing
459
+ if (preview.canErase) await eraseSubject(db, { organizationId, requestedBy: staff.userId, email: 'jane@example.com' });
460
+ ```
461
+
462
+ **Export** returns one document with the person's bookings, the messages sent about them, waitlist entries, package purchases,
463
+ recurring series, and the queued webhook events that carry their details. The links and tokens that let someone act as the person
464
+ are left out: the self-service link and waitlist link are not exported, and the self-service and calendar links inside message
465
+ bodies, and the offer link inside a waitlist event, are replaced with `[removed]`.
466
+
467
+ **Erase** keeps what the business needs to keep its books and removes the person from it. Bookings, package purchases and recurring
468
+ series stay as records with the name "Erased client" and the address `erased@erased.invalid`; the phone, client id, notes, staff notes,
469
+ intake answers and cancellation reason are cleared, and every booking gets a new self-service link so old links stop working. Times,
470
+ types, calendars, status, payment amounts and ids, and the meeting link, location and outside-calendar event ids stay (a host that
471
+ puts a name in a location or meeting link should clear it itself). Messages, waitlist entries and webhook events that mention the person are
472
+ deleted. It runs in one transaction: it all happens or none of it does.
473
+
474
+ **Erase is refused (`SCHED_1301`) while the person has an upcoming pending or confirmed booking, or a waitlist entry that holds or is
475
+ taking an offer.** Cancel those first; the refusal says how many there are. `previewErase` also warns when an active package still has
476
+ unused sessions, because after erasure it can no longer be matched to the person.
477
+
478
+ **Every export and erase is recorded** in `DataSubjectRequest` with who asked, the counts, and a SHA-256 digest of each identifier
479
+ (tied to the organization), never the address or name. A digest can be recomputed by anyone who already knows the address, so it shows
480
+ that a request was made for that address; it is not anonymous. If the record cannot be written, an export returns nothing.
481
+
482
+ **Not covered**, because the package does not hold it: the host's own client record, events already created in Google or Outlook
483
+ calendars (they carry the client's name), the payment provider's records, webhook events already delivered to a receiver, database
484
+ backups, and logs. Queued webhook events are found by the person's email address in the event text, so an event that names someone
485
+ without their address is not found. A booking made in another organization under the same address is a different business's record
486
+ and is never touched.