@composable-os/pack-bookings 0.1.0-beta.10 → 0.1.0-beta.13

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.
@@ -0,0 +1,612 @@
1
+ // The Bookings messages (stage 31a step 9, decision 16; ADR 0572). Members' email is routine mail
2
+ // (ADR 0590): fixed emails this pack declares (routine-mail.ts), which the host composes, sends
3
+ // to whoever the booking belongs to and sends without a person's approval, unless an admin turned
4
+ // the kind off or the host holds one for a person. These automations only decide which message,
5
+ // about which booking, with which declared choices; they add no rule of their own: every state
6
+ // they read was written by the host's behaviours, and they write no record (the pack's own storage
7
+ // holds which class changes are still to be told). One notice to staff goes in the app.
8
+ //
9
+ // Who is written to is the host's rule, the same for every message: the booking's Person, each of
10
+ // their live guardians (ADR 0540), or for a visitor's paid drop-in with no Person the order's own
11
+ // address (ADR 0560); nobody else, one recipient per email, so no email names another member.
12
+ // Not emailed (spec 31): a coach swap, and a booking the member cancelled themselves (the screen
13
+ // says so). Nothing here sends a push or a text.
14
+ //
15
+ // A send step retried after a failure part way sends nothing twice: the host keys each email by
16
+ // the run its chain began with, the kind, the message, the booking and the recipient.
17
+ import { defineAutomation, } from "@composable-os/sdk";
18
+ const CLASS = "bookings.class";
19
+ const BOOKING = "bookings.booking";
20
+ const CLASS_TYPE = "programs.classtype";
21
+ /**
22
+ * The email-send connection the host sends from: a person binds it to each automation, which is
23
+ * their consent to the pack's mail going out from that address.
24
+ */
25
+ const MAIL = {
26
+ id: "mail",
27
+ gatekeeper: "email-send",
28
+ purpose: "Email members about their bookings",
29
+ };
30
+ /** How long a change to a class settles before it is told, so several edits make one email. */
31
+ const SETTLE = "2 minutes";
32
+ const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
33
+ const PAGE = 200;
34
+ /** The pack's settings (the booking rules), stored or default. */
35
+ async function settings(ctx) {
36
+ // Each item names its extension as `extension` (extensionSettings.list's output): reading `id`
37
+ // found none, so every setting read here was its default (found building stage 29 step 5).
38
+ const { items } = await ctx.ops.call("extensionSettings.list", { extension: "bookings" });
39
+ return items.find((item) => item.extension === "bookings")?.values ?? {};
40
+ }
41
+ /** Which declared words say why the host passed a waiter over (ADR 0520's reasons). */
42
+ export function passedOverChoice(reason) {
43
+ switch (reason) {
44
+ case "no_uses_left":
45
+ return "noUsesLeft";
46
+ case "ended":
47
+ case "not_live":
48
+ return "notLive";
49
+ case "not_covered":
50
+ return "notCovered";
51
+ default:
52
+ return "other";
53
+ }
54
+ }
55
+ async function classFacts(ctx, id) {
56
+ const found = await ctx.ops
57
+ .call("record.get", { object: CLASS, id })
58
+ .catch(() => null);
59
+ if (!found)
60
+ return null;
61
+ const v = found.values;
62
+ return {
63
+ id,
64
+ startsAt: text(v.startsAt),
65
+ state: text(v.state),
66
+ classType: text(v.classType),
67
+ };
68
+ }
69
+ /** Asks the host for each email of `kind`, in order. */
70
+ async function sendAll(ctx, kind, sends) {
71
+ let sent = 0;
72
+ let held = 0;
73
+ let off = false;
74
+ for (const send of sends) {
75
+ const result = await ctx.routineMail.send({ kind, ...send });
76
+ sent += result.sent;
77
+ held += result.held;
78
+ off ||= result.off;
79
+ }
80
+ return { sent, held, off };
81
+ }
82
+ /** Every booking of a class in some states, page by page. */
83
+ async function bookingsOf(ctx, classId, states) {
84
+ const out = [];
85
+ let cursor = null;
86
+ do {
87
+ const page = await ctx.ops.call("record.list", {
88
+ object: BOOKING,
89
+ filter: {
90
+ and: [
91
+ { field: "class", op: "eq", value: classId },
92
+ { field: "state", op: "in", value: states },
93
+ ],
94
+ },
95
+ sort: { field: "createdAt", direction: "asc" },
96
+ limit: PAGE,
97
+ ...(cursor ? { cursor } : {}),
98
+ });
99
+ out.push(...page.items);
100
+ cursor = page.nextCursor;
101
+ } while (cursor);
102
+ return out;
103
+ }
104
+ /** The run a chain of retries began with (ADR 0574): what a class's turn is held by. */
105
+ const chainOf = (event) => event.originalRunId ?? event.runId;
106
+ // --- Booked -------------------------------------------------------------------------------------
107
+ /**
108
+ * Which booked message a change into `booked` is, or none. The record is read when the run starts,
109
+ * which may be after later changes: a waiter created and then moved in, or a drop-in held and then
110
+ * paid for, is booked by the time its creation's run reads it. Those are told by their own move's
111
+ * run (`promoted`, `paid`), never by the creation's, so each booking gets one booked message. None
112
+ * for a correction (ticked as come, then unticked).
113
+ */
114
+ export function bookedKind(change, values) {
115
+ if (!change || change.action === "created") {
116
+ if (text(values.movedFrom))
117
+ return "moved";
118
+ // Made waiting and moved in since (the host records when), or held while its order was paid.
119
+ if (text(values.promotedAt) || text(values.dropInOrder))
120
+ return null;
121
+ return "booked";
122
+ }
123
+ const state = change.diff.state;
124
+ if (state?.after !== "booked")
125
+ return null;
126
+ if (state.before === "pending")
127
+ return "paid";
128
+ if (state.before === "waiting")
129
+ return "promoted";
130
+ return null;
131
+ }
132
+ export const bookingConfirmed = defineAutomation({
133
+ label: "Booking confirmed",
134
+ description: "When a booking becomes booked (made by the member, a parent or staff; a drop-in paid for; " +
135
+ "moved in from the waiting list; or moved by staff to another class), emails the member and " +
136
+ "their parents or guardians the class, its time and room, with an add-to-calendar file (a " +
137
+ "move also takes the old class off the calendar). Routine email: Booking confirmations.",
138
+ trigger: { type: "record", object: BOOKING, on: ["created", "updated"] },
139
+ conditions: { field: "state", op: "eq", value: "booked" },
140
+ // Each change its own run: the message is read from the change (a waiter moved in, a drop-in
141
+ // paid), which coalescing a record's updates into one run would lose.
142
+ rails: { debounceSeconds: 0 },
143
+ connections: [MAIL],
144
+ steps: [
145
+ { name: "compose", label: "Check the booking is still booked", reads: [BOOKING] },
146
+ { name: "send", label: "Email the member (and their guardians)" },
147
+ ],
148
+ async run(event, step, ctx) {
149
+ const id = event.record?.id;
150
+ const values = event.record?.data ?? {};
151
+ const kind = bookedKind(event.change, values);
152
+ if (!id || !kind)
153
+ return { skipped: "not a new booking" };
154
+ const sends = await step.do("compose", async () => {
155
+ const booking = await ctx.ops.call("record.get", { object: BOOKING, id });
156
+ if (text(booking.values.state) !== "booked")
157
+ return [];
158
+ return [{ record: id, message: kind }];
159
+ });
160
+ if (!sends.length)
161
+ return { sent: 0, kind };
162
+ return { ...(await step.do("send", () => sendAll(ctx, "confirmation", sends))), kind };
163
+ },
164
+ });
165
+ // --- The waiting list ---------------------------------------------------------------------------
166
+ export const waitlistPassedOver = defineAutomation({
167
+ label: "Passed over on the waiting list",
168
+ description: "When a place came free but the first person waiting could not be moved in (nothing they " +
169
+ "hold could pay for it), emails them why; they stay first on the waiting list. Routine " +
170
+ "email: Waiting list news.",
171
+ trigger: { type: "fieldChanged", object: BOOKING, field: "passedOverReason" },
172
+ conditions: { field: "state", op: "eq", value: "waiting" },
173
+ connections: [MAIL],
174
+ steps: [
175
+ { name: "compose", label: "Read why they were passed over", reads: [BOOKING] },
176
+ { name: "send", label: "Email the member (and their guardians)" },
177
+ ],
178
+ async run(event, step, ctx) {
179
+ const id = event.record?.id;
180
+ if (!id)
181
+ return { skipped: "no booking" };
182
+ const sends = await step.do("compose", async () => {
183
+ const booking = await ctx.ops.call("record.get", { object: BOOKING, id });
184
+ const reason = text(booking.values.passedOverReason);
185
+ if (text(booking.values.state) !== "waiting" || !reason)
186
+ return [];
187
+ return [{ record: id, message: "passedOver", values: { why: passedOverChoice(reason) } }];
188
+ });
189
+ if (!sends.length)
190
+ return { sent: 0 };
191
+ return step.do("send", () => sendAll(ctx, "waitingList", sends));
192
+ },
193
+ });
194
+ /** The moment nobody is moved in from the waiting list any more: the class type's, else the org's. */
195
+ async function cutOff(ctx, cls) {
196
+ if (!cls.startsAt)
197
+ return null;
198
+ let minutes = null;
199
+ if (cls.classType) {
200
+ const type = await ctx.ops
201
+ .call("record.get", { object: CLASS_TYPE, id: cls.classType })
202
+ .catch(() => null);
203
+ const own = type?.values["bookings.promotionMinutes"] ?? type?.values.promotionMinutes;
204
+ if (typeof own === "number")
205
+ minutes = own;
206
+ }
207
+ if (minutes === null) {
208
+ const org = (await settings(ctx)).promotionMinutes;
209
+ minutes = typeof org === "number" ? org : 120;
210
+ }
211
+ return Date.parse(cls.startsAt) - minutes * 60_000;
212
+ }
213
+ /**
214
+ * Several runs for one class within a moment are told once (ADR 0572): each run takes the class's
215
+ * turn in the pack's storage (`claimTurn`), waits for things to settle, and only the run that took
216
+ * the turn last tells, with what is true then. A run never loses the turn without a later run
217
+ * holding it, so the last change is always told. The turn is given up only after the send
218
+ * (`releaseTurn`, its own step): a compose or send step retried after a failure still holds it.
219
+ */
220
+ async function claimTurn(ctx, key, runId, merge) {
221
+ const before = await ctx.storage.get(key);
222
+ await ctx.storage.set(key, { ...merge(before), turn: runId });
223
+ }
224
+ /** What this run noted, while it still holds the turn; null when a later run took it. */
225
+ async function heldTurn(ctx, key, runId) {
226
+ const held = await ctx.storage.get(key);
227
+ return held?.turn === runId ? held : null;
228
+ }
229
+ /** Gives the turn up after telling, unless a later run has taken it meanwhile. */
230
+ async function releaseTurn(ctx, key, runId) {
231
+ if (await heldTurn(ctx, key, runId))
232
+ await ctx.storage.delete(key);
233
+ }
234
+ export const placeFree = defineAutomation({
235
+ label: "A place free after the waiting list stops",
236
+ description: "When someone gives a place back after the class's waiting list has stopped (2 hours before " +
237
+ "by default), emails everyone still waiting that a place is free: whoever books it first " +
238
+ "gets it. Several places given back within two minutes make one email. Routine email: " +
239
+ "Waiting list news.",
240
+ trigger: {
241
+ type: "fieldChanged",
242
+ object: BOOKING,
243
+ field: "state",
244
+ from: "booked",
245
+ to: { in: ["cancelled", "late_cancelled", "excused"] },
246
+ },
247
+ connections: [MAIL],
248
+ steps: [
249
+ { name: "note", label: "Note the class has a place to tell of" },
250
+ { name: "settle", kind: "sleep", duration: SETTLE },
251
+ {
252
+ name: "compose",
253
+ label: "Check the place is free and read who is waiting",
254
+ reads: [BOOKING, CLASS, CLASS_TYPE],
255
+ calls: ["capacity.get", "extensionSettings.list"],
256
+ },
257
+ { name: "send", label: "Email each person waiting" },
258
+ { name: "release", label: "Give up the class's turn" },
259
+ ],
260
+ async run(event, step, ctx) {
261
+ const classId = text(event.record?.data?.class);
262
+ if (!classId)
263
+ return { skipped: "no class" };
264
+ const key = `free:${classId}`;
265
+ await step.do("note", () => claimTurn(ctx, key, chainOf(event), () => ({ classId })));
266
+ await step.sleep("settle", SETTLE);
267
+ const sends = await step.do("compose", async () => {
268
+ if (!(await heldTurn(ctx, key, chainOf(event))))
269
+ return [];
270
+ const cls = await classFacts(ctx, classId);
271
+ if (cls?.state !== "scheduled" || !cls.startsAt)
272
+ return [];
273
+ const now = Date.now();
274
+ const stops = await cutOff(ctx, cls);
275
+ // Before the cut-off the place went to the waiting list (the host's): nothing to tell.
276
+ if (stops === null || now < stops || now >= Date.parse(cls.startsAt))
277
+ return [];
278
+ const places = await ctx.ops
279
+ .call("capacity.get", { object: CLASS, id: classId })
280
+ .catch(() => null);
281
+ if (!places?.available || places.available < 1)
282
+ return [];
283
+ const waiting = await bookingsOf(ctx, classId, ["waiting"]);
284
+ return waiting.map((b) => ({ record: b.id, message: "placeFree" }));
285
+ });
286
+ const sent = sends.length
287
+ ? await step.do("send", () => sendAll(ctx, "waitingList", sends))
288
+ : { sent: 0 };
289
+ await step.do("release", () => releaseTurn(ctx, key, chainOf(event)));
290
+ return sent;
291
+ },
292
+ });
293
+ // --- A change or a cancellation by the gym ------------------------------------------------------
294
+ /** Bookings that a change to their class concerns: with a place, held while paying, or waiting. */
295
+ const LIVE = ["booked", "pending", "waiting"];
296
+ export const classChanged = defineAutomation({
297
+ label: "Class time or room changed",
298
+ description: "When staff change a scheduled class's time, day, end or room (one class, or a series from a " +
299
+ "date), emails everyone booked or waiting what it is now, with an updated add-to-calendar " +
300
+ "file; several changes within two minutes make one email. A change of coach sends nothing. " +
301
+ "Routine email: Class changes.",
302
+ trigger: { type: "record", object: CLASS, on: ["updated"], includeBulk: true },
303
+ conditions: { field: "state", op: "eq", value: "scheduled" },
304
+ // Each change its own run: a coach swap then a new time a moment later must not coalesce into
305
+ // one run that sees only the swap. The runs then agree among themselves which tells (claimTurn).
306
+ rails: { debounceSeconds: 0 },
307
+ connections: [MAIL],
308
+ steps: [
309
+ { name: "note", label: "Note what changed" },
310
+ { name: "settle", kind: "sleep", duration: SETTLE },
311
+ { name: "compose", label: "Read who is booked or waiting", reads: [BOOKING, CLASS] },
312
+ { name: "send", label: "Email each member (and their guardians)" },
313
+ { name: "release", label: "Give up the class's turn" },
314
+ ],
315
+ async run(event, step, ctx) {
316
+ const classId = event.record?.id;
317
+ const diff = event.change?.diff ?? {};
318
+ const changed = { time: "startsAt" in diff, end: "endsAt" in diff, room: "room" in diff };
319
+ // A coach swap (decision 16), the places or the notes: nothing to tell.
320
+ if (!classId || (!changed.time && !changed.end && !changed.room)) {
321
+ return { skipped: "no time or room change" };
322
+ }
323
+ const key = `changed:${classId}`;
324
+ await step.do("note", () => claimTurn(ctx, key, chainOf(event), (before) => ({
325
+ startsBefore: before ? before.startsBefore : text(diff.startsAt?.before),
326
+ time: Boolean(before?.time) || changed.time,
327
+ end: Boolean(before?.end) || changed.end,
328
+ room: Boolean(before?.room) || changed.room,
329
+ })));
330
+ await step.sleep("settle", SETTLE);
331
+ const sends = await step.do("compose", async () => {
332
+ // A later change took the turn: it tells, with everything changed since.
333
+ const told = await heldTurn(ctx, key, chainOf(event));
334
+ if (!told)
335
+ return [];
336
+ const cls = await classFacts(ctx, classId);
337
+ if (cls?.state !== "scheduled")
338
+ return [];
339
+ const before = told.startsBefore;
340
+ const moved = told.time && (!before || Date.parse(before) !== Date.parse(cls.startsAt ?? ""));
341
+ // Changed and changed back: nothing to tell.
342
+ if (!moved && !told.end && !told.room)
343
+ return [];
344
+ const bookings = await bookingsOf(ctx, classId, LIVE);
345
+ return bookings.map((booking) => {
346
+ const waiting = text(booking.values.state) === "waiting";
347
+ return {
348
+ record: booking.id,
349
+ message: "changed",
350
+ values: {
351
+ moved,
352
+ notMoved: !moved,
353
+ ...(moved && before ? { before } : {}),
354
+ endChanged: told.end,
355
+ roomChanged: told.room,
356
+ stays: waiting ? "waiting" : "booking",
357
+ keep: !waiting,
358
+ },
359
+ };
360
+ });
361
+ });
362
+ const sent = sends.length
363
+ ? await step.do("send", () => sendAll(ctx, "change", sends))
364
+ : { sent: 0 };
365
+ await step.do("release", () => releaseTurn(ctx, key, chainOf(event)));
366
+ return sent;
367
+ },
368
+ });
369
+ export const classCancelled = defineAutomation({
370
+ label: "Class cancelled by the gym",
371
+ description: "When the gym cancels a class (staff, a closure, or a series ended), emails everyone whose " +
372
+ "booking it cancelled: the class, the reason, that nothing was used from their membership or " +
373
+ "pass, and for a paid drop-in that the money goes back to their card once approved. Routine " +
374
+ "email: Class cancellations.",
375
+ trigger: {
376
+ type: "fieldChanged",
377
+ object: CLASS,
378
+ field: "state",
379
+ from: "scheduled",
380
+ to: "cancelled",
381
+ includeBulk: true,
382
+ },
383
+ connections: [MAIL],
384
+ steps: [
385
+ {
386
+ name: "compose",
387
+ label: "Read the bookings the cancel cancelled",
388
+ reads: [BOOKING, CLASS],
389
+ calls: ["order.get"],
390
+ },
391
+ { name: "send", label: "Email each member (and their guardians)" },
392
+ ],
393
+ async run(event, step, ctx) {
394
+ const classId = event.record?.id;
395
+ if (!classId)
396
+ return { skipped: "no class" };
397
+ const sends = await step.do("compose", async () => {
398
+ const cls = await classFacts(ctx, classId);
399
+ if (cls?.state !== "cancelled")
400
+ return [];
401
+ const bookings = await bookingsOf(ctx, classId, ["cancelled_by_us"]);
402
+ // Whether each drop-in's money was taken (its order paid), read once per order.
403
+ const paid = new Map();
404
+ for (const booking of bookings) {
405
+ const order = text(booking.values.dropInOrder);
406
+ if (order && !paid.has(order)) {
407
+ const found = await ctx.ops
408
+ .call("order.get", { id: order })
409
+ .catch(() => null);
410
+ paid.set(order, (found?.paid ?? 0) > 0);
411
+ }
412
+ }
413
+ return bookings.map((booking) => {
414
+ const order = text(booking.values.dropInOrder);
415
+ const money = order ? (paid.get(order) ? "refund" : "unpaid") : "membership";
416
+ return { record: booking.id, message: "cancelled", values: { money } };
417
+ });
418
+ });
419
+ if (!sends.length)
420
+ return { sent: 0 };
421
+ return step.do("send", () => sendAll(ctx, "cancellation", sends));
422
+ },
423
+ });
424
+ // --- The reminder -------------------------------------------------------------------------------
425
+ export const classReminder = defineAutomation({
426
+ label: "Class reminder",
427
+ description: "Before each scheduled class (3 hours by default: the class type's reminder, else the " +
428
+ "organisation's), emails everyone booked into it a reminder of the time and room, and a " +
429
+ "visitor who paid for a place that staff have not yet confirmed. Routine email: Class " +
430
+ "reminders.",
431
+ trigger: {
432
+ type: "dateRelative",
433
+ object: CLASS,
434
+ field: "startsAt",
435
+ minutesBefore: { field: "classType.reminderMinutes", setting: "reminderMinutes" },
436
+ },
437
+ conditions: { field: "state", op: "eq", value: "scheduled" },
438
+ connections: [MAIL],
439
+ steps: [
440
+ { name: "compose", label: "Read who is booked", reads: [BOOKING, CLASS] },
441
+ { name: "send", label: "Email each member (and their guardians)" },
442
+ ],
443
+ async run(event, step, ctx) {
444
+ const classId = event.record?.id;
445
+ if (!classId)
446
+ return { skipped: "no class" };
447
+ const sends = await step.do("compose", async () => {
448
+ const cls = await classFacts(ctx, classId);
449
+ // Cancelled (or done) since the run began: no reminder.
450
+ if (cls?.state !== "scheduled")
451
+ return [];
452
+ // Run late for a class already started: no reminder.
453
+ if (cls.startsAt && Date.parse(cls.startsAt) <= Date.now())
454
+ return [];
455
+ // Booked; and a visitor's paid place held for staff to settle (the host sends nothing
456
+ // about a hold nobody paid for).
457
+ const bookings = (await bookingsOf(ctx, classId, ["booked", "pending"])).filter((b) => text(b.values.state) === "booked" || !text(b.values.person));
458
+ return bookings.map((b) => ({ record: b.id, message: "reminder" }));
459
+ });
460
+ if (!sends.length)
461
+ return { sent: 0 };
462
+ return step.do("send", () => sendAll(ctx, "reminder", sends));
463
+ },
464
+ });
465
+ // --- A drop-in's payment and refund --------------------------------------------------------------
466
+ export const dropInOrder = defineAutomation({
467
+ label: "Drop-in paid or refunded",
468
+ description: "When a visitor pays for a class that staff still have to confirm (their address matches " +
469
+ "several people on file), emails them at the order's address that their place is held; when " +
470
+ "the refund of a paid drop-in has been made, emails the person who paid that their money is " +
471
+ "back. Routine email: Drop-in payments and refunds.",
472
+ trigger: {
473
+ type: "fieldChanged",
474
+ object: "order",
475
+ field: "state",
476
+ to: { in: ["paid", "refunded"] },
477
+ },
478
+ connections: [MAIL],
479
+ steps: [
480
+ {
481
+ name: "compose",
482
+ label: "Find the drop-in the order paid for",
483
+ reads: [BOOKING],
484
+ calls: ["order.get"],
485
+ },
486
+ { name: "send", label: "Email the person who paid" },
487
+ ],
488
+ async run(event, step, ctx) {
489
+ const orderId = event.record?.id;
490
+ if (!orderId)
491
+ return { skipped: "no order" };
492
+ const sends = await step.do("compose", async () => {
493
+ const found = await ctx.ops.call("record.list", {
494
+ object: BOOKING,
495
+ filter: { field: "dropInOrder", op: "eq", value: orderId },
496
+ limit: 10,
497
+ });
498
+ // An order of something else: not ours to tell.
499
+ const booking = found.items[0];
500
+ if (!booking)
501
+ return [];
502
+ const order = await ctx.ops.call("order.get", { id: orderId });
503
+ // About the order (D3): the host sends it to the address that paid.
504
+ if (order.state === "refunded")
505
+ return [{ record: orderId, message: "refunded" }];
506
+ // Paid, and still held with no Person: staff settle whose it is (ADR 0560). A booking
507
+ // that became booked with its Person is told by bookingConfirmed instead.
508
+ if (text(booking.values.state) !== "pending" || text(booking.values.person))
509
+ return [];
510
+ return [{ record: orderId, message: "held" }];
511
+ });
512
+ if (!sends.length)
513
+ return { sent: 0 };
514
+ return step.do("send", () => sendAll(ctx, "dropIn", sends));
515
+ },
516
+ });
517
+ // --- Staff: classes with no attendance taken ----------------------------------------------------
518
+ export const noAttendanceTaken = defineAutomation({
519
+ label: "No attendance taken",
520
+ description: "An hour after a class ends, when people were booked but nobody on it was ticked as come or " +
521
+ "marked as not come, tells the admins in the app, so someone takes the list (no-shows are " +
522
+ "only written for a class whose list was taken).",
523
+ trigger: { type: "dateRelative", object: CLASS, field: "endsAt", minutesAfter: 60 },
524
+ conditions: { field: "state", op: "eq", value: "scheduled" },
525
+ steps: [
526
+ { name: "check", label: "Count who was booked and who was marked", reads: [BOOKING] },
527
+ {
528
+ name: "notify",
529
+ label: "Tell the admins",
530
+ notifies: [
531
+ {
532
+ to: "admins",
533
+ message: "No attendance taken: {record}",
534
+ body: "Nobody on this class was ticked as come or marked as not come.",
535
+ },
536
+ ],
537
+ },
538
+ ],
539
+ async run(event, step, ctx) {
540
+ const classId = event.record?.id;
541
+ if (!classId)
542
+ return { skipped: "no class" };
543
+ const counts = await step.do("check", async () => {
544
+ const marked = await bookingsOf(ctx, classId, ["attended", "no_show"]);
545
+ if (marked.length)
546
+ return { booked: 0, marked: marked.length };
547
+ const booked = await bookingsOf(ctx, classId, ["booked"]);
548
+ return { booked: booked.length, marked: 0 };
549
+ });
550
+ if (counts.marked || !counts.booked)
551
+ return { notified: false, ...counts };
552
+ await step.do("notify", () => ctx.notify("admins", {
553
+ title: "No attendance taken: {record}",
554
+ body: `${counts.booked} booked, nobody ticked as come or marked as not come.`,
555
+ link: "record",
556
+ }));
557
+ return { notified: true, ...counts };
558
+ },
559
+ });
560
+ // --- Feedback after a class (stage 29 step 5, decision 4) ---------------------------------------
561
+ export const feedbackAfterClass = defineAutomation({
562
+ label: "Feedback after a class",
563
+ description: "A few hours after a member is ticked as come (the feedback setting, 3 hours by default), " +
564
+ "when a feedback form is chosen, emails them (or a child's parents or guardians) a link to " +
565
+ "it that works once and for a week. The host makes the link, sends it at most once a month " +
566
+ "to a member, and never to someone who stopped these emails. Routine email: Feedback after " +
567
+ "a class.",
568
+ trigger: {
569
+ type: "dateRelative",
570
+ object: BOOKING,
571
+ field: "markedAt",
572
+ minutesAfter: { setting: "feedbackMinutes" },
573
+ },
574
+ conditions: { field: "state", op: "eq", value: "attended" },
575
+ connections: [MAIL],
576
+ steps: [
577
+ { name: "compose", label: "Check a feedback form is chosen and they came", reads: [BOOKING] },
578
+ { name: "send", label: "Email the member (or their guardians) the form's link" },
579
+ ],
580
+ async run(event, step, ctx) {
581
+ const bookingId = event.record?.id;
582
+ if (!bookingId)
583
+ return { skipped: "no booking" };
584
+ const sends = await step.do("compose", async () => {
585
+ // No form chosen: nobody is asked. Which form, and whether the member may be asked, is the
586
+ // host's to read again when it makes the link.
587
+ if (!text((await settings(ctx)).feedbackForm))
588
+ return [];
589
+ const booking = await ctx.ops
590
+ .call("record.get", { object: BOOKING, id: bookingId })
591
+ .catch(() => null);
592
+ // Unticked since: not asked.
593
+ if (text(booking?.values.state) !== "attended")
594
+ return [];
595
+ return [{ record: bookingId, message: "ask" }];
596
+ });
597
+ if (!sends.length)
598
+ return { sent: 0 };
599
+ return step.do("send", () => sendAll(ctx, "feedback", sends));
600
+ },
601
+ });
602
+ export const bookingsAutomations = {
603
+ bookingConfirmed,
604
+ waitlistPassedOver,
605
+ placeFree,
606
+ classChanged,
607
+ classCancelled,
608
+ classReminder,
609
+ dropInOrder,
610
+ noAttendanceTaken,
611
+ feedbackAfterClass,
612
+ };
@@ -0,0 +1,16 @@
1
+ import type { BookingsHooks } from "@composable-os/pack-bookings/client";
2
+ type Hooks = Pick<BookingsHooks, "useRoster" | "useMarkAttended" | "useUndoAttended">;
3
+ /**
4
+ * A class's list as the product's admin shows it (stage 47): on a class's page, that class's
5
+ * list; opened from the navigation (a coach), today's classes in this browser's zone to choose
6
+ * one from. Which classes a coach may open (today's only) is the host's: it lists no others.
7
+ */
8
+ export declare function TodayClassList({ bookings, classId, }: {
9
+ bookings: Hooks & Pick<BookingsHooks, "useDay">;
10
+ classId?: string;
11
+ }): import("react").JSX.Element;
12
+ export declare function ClassList({ bookings, classId }: {
13
+ bookings: Hooks;
14
+ classId: string;
15
+ }): import("react").JSX.Element;
16
+ export {};