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

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/dist/tools.js CHANGED
@@ -1,4 +1,4 @@
1
- // The Bookings tools (stage 31a step 3). They become operations x.bookings.<tool>, run in the
1
+ // The Bookings tools (stage 31a steps 3 to 7). They become operations x.bookings.<tool>, run in the
2
2
  // sandbox, and reach the host only through ctx.ops. None of them holds a rule: when booking opens
3
3
  // and closes, whether a cancel is late, which class types only staff book, the places left, one
4
4
  // booking per person per class and the use a booking spends are all the host's (index.ts). A tool
@@ -95,8 +95,16 @@ const refusalReason = z
95
95
  "not_running",
96
96
  "person_exists",
97
97
  "possible_duplicates",
98
+ "waitlist_closed",
99
+ "no_drop_in",
100
+ "ask_desk",
101
+ "try_later",
98
102
  ])
99
- .describe("not_open: booking has not opened yet (see opensAt). closed: booking has closed. " +
103
+ .describe("no_drop_in: the class cannot be paid for online (no drop-in price). ask_desk: the address " +
104
+ "given cannot be used. try_later: too many places are held for payment just now. " +
105
+ "waitlist_closed: the class is full and it is too close to the start to wait for a place " +
106
+ "(nobody is moved in from the waitlist then). " +
107
+ "not_open: booking has not opened yet (see opensAt). closed: booking has closed. " +
100
108
  "not_running: the class was cancelled or is over. person_exists: someone on file has that " +
101
109
  "email (see people). possible_duplicates: people on file may be this person (see people; " +
102
110
  "book one of them, or ask again with confirmNew). " +
@@ -137,6 +145,11 @@ function refusalOf(error, what, expect) {
137
145
  ...times,
138
146
  });
139
147
  if (error.code === "not_found") {
148
+ // A Person they may not book for (not a child linked to them, or a link that has ended) is
149
+ // answered as one that does not exist (ADR 0540).
150
+ if (details.object === "person") {
151
+ return out("not_found", "You cannot book for that person.");
152
+ }
140
153
  return out("not_found", what === "book" ? "That class cannot be booked." : "No such booking.");
141
154
  }
142
155
  if (rule === "state_window_not_open") {
@@ -181,10 +194,21 @@ function refusalOf(error, what, expect) {
181
194
  ? "There are no classes left on your membership or pass for that week or period."
182
195
  : "Nothing you hold can pay for this class.", reason);
183
196
  }
184
- if (rule === "unique")
185
- return out("already_booked", "You already have a place in this class.");
197
+ if (rule === "waitlist") {
198
+ return details.reason === "closed"
199
+ ? out("waitlist_closed", "This class is full, and it is too close to the start to join its waitlist.")
200
+ : out("changed", "A place came free meanwhile. Try booking again.");
201
+ }
202
+ if (rule === "unique") {
203
+ return out("already_booked", "You already have a place in this class, or are waiting for one.");
204
+ }
186
205
  if (rule === "capacity")
187
206
  return out("full", "This class is full.");
207
+ // A cancel that found the booking already in a final state: another write moved it first (a
208
+ // race). Any other undeclared move is a fault and is not dressed up as one.
209
+ if (what === "cancel" && rule === "state_final") {
210
+ return out("changed", "It changed meanwhile: it is no longer booked. Look again.");
211
+ }
188
212
  if (error.code === "conflict") {
189
213
  return out("changed", "It changed while you were booking. Look again and try once more.");
190
214
  }
@@ -244,7 +268,35 @@ export const classGet = defineTool({
244
268
  return { class: described };
245
269
  },
246
270
  });
247
- // --- Booking and cancelling (a signed-in member) ----------------------------------------------------
271
+ /** The member and the children staff linked to them, as the host says (ADR 0540). */
272
+ const familyOf = (ctx) => ctx.ops.call("me.family", {});
273
+ const forPerson = z
274
+ .string()
275
+ .min(1)
276
+ .max(64)
277
+ .optional()
278
+ .describe("A child of theirs to book for instead (a dependant the gym linked to them; see family). " +
279
+ "The child's own membership or pass pays, never the parent's.");
280
+ export const family = defineTool({
281
+ description: "Who the signed-in member may book for: themselves, and the children (dependants) the gym " +
282
+ "has linked to them, each with their name and id. Pass a child's id as book's forPersonId " +
283
+ "and mine's personId. Only the gym's staff link a parent to a child. Read-only.",
284
+ input: z.object({}),
285
+ output: z.object({
286
+ people: z.array(z.object({ personId: z.string(), name: z.string(), self: z.boolean() })),
287
+ }),
288
+ risk: "read",
289
+ audiences: ["customer"],
290
+ async handler(_input, ctx) {
291
+ const found = await familyOf(ctx);
292
+ return {
293
+ people: [
294
+ { ...found.self, self: true },
295
+ ...found.dependants.map((d) => ({ ...d, self: false })),
296
+ ],
297
+ };
298
+ },
299
+ });
248
300
  const booked = z.object({
249
301
  result: z.literal("booked"),
250
302
  bookingId: z.string(),
@@ -254,35 +306,172 @@ const booked = z.object({
254
306
  .nullable()
255
307
  .describe("The membership or pass a use was spent from; null when paid at the desk"),
256
308
  });
309
+ const waiting = z.object({
310
+ result: z.literal("waiting"),
311
+ bookingId: z.string(),
312
+ classId: z.string(),
313
+ position: z.number().nullable().describe("Their place in the queue: 1 is next"),
314
+ waiting: z.number().nullable().describe("How many are waiting, them included"),
315
+ message: z.string(),
316
+ });
317
+ /** Where a waiting booking stands, as the host says (their own only, for a member). */
318
+ async function positionOf(ctx, bookingId) {
319
+ const at = await ctx.ops.call("waitlist.position", { object: BOOKING, id: bookingId });
320
+ return { position: at.position, waiting: at.waiting };
321
+ }
322
+ /**
323
+ * Makes a booking through `operation` (my.create for a member, record.create for staff): booked
324
+ * if a place is free, else, when asked, on the class's waitlist. Both are the host's to allow:
325
+ * the places, and joining only while the class is full and before its cut-off. Joining spends
326
+ * nothing, so someone whose booking was refused for want of a use may still wait on a full class
327
+ * (decision 7: they are passed over at promotion if they still cannot pay). A place that came
328
+ * free between the two is booked (once).
329
+ */
330
+ async function bookOrWait(ctx, operation, values, wait, forPersonId) {
331
+ // For a member's dependant (ADR 0540): the host checks the link in the write.
332
+ const whose = operation === "my.create" && forPersonId ? { forPersonId } : {};
333
+ const ruleOf = (error) => error instanceof OpsCallError
334
+ ? (error.details ?? {})
335
+ : {};
336
+ for (let attempt = 0;; attempt++) {
337
+ let refusal;
338
+ try {
339
+ const made = await ctx.ops.call(operation, {
340
+ object: BOOKING,
341
+ values,
342
+ ...whose,
343
+ });
344
+ return { made, waiting: false };
345
+ }
346
+ catch (error) {
347
+ const rule = ruleOf(error).rule;
348
+ if (!wait || (rule !== "capacity" && rule !== "allowance"))
349
+ throw error;
350
+ refusal = error;
351
+ }
352
+ try {
353
+ const made = await ctx.ops.call(operation, {
354
+ object: BOOKING,
355
+ values: { ...values, state: "waiting" },
356
+ ...whose,
357
+ });
358
+ return { made, waiting: true };
359
+ }
360
+ catch (error) {
361
+ const join = ruleOf(error);
362
+ // Full a moment ago, and a place came free: book it (once).
363
+ if (join.reason === "not_full" && ruleOf(refusal).rule === "capacity" && attempt === 0) {
364
+ continue;
365
+ }
366
+ // Nothing to pay with, and no waitlist to join (it is not full, or has closed): that is the
367
+ // answer. Any other refusal of the join (already booked or waiting…) is the true reason.
368
+ if (ruleOf(refusal).rule === "allowance" && join.rule === "waitlist")
369
+ throw refusal;
370
+ throw error;
371
+ }
372
+ }
373
+ }
374
+ /**
375
+ * A member already waiting on the class asked to book it: when a place is free (after the
376
+ * cut-off, after the queue was passed over, or more places), they take it themselves, spending
377
+ * then; a place held for the queue is the host's to give (ADR 0520). Null when they are not
378
+ * waiting on it; otherwise booked, or still waiting with where they stand.
379
+ */
380
+ async function takeFreePlace(ctx, classId, personId) {
381
+ const mine = await ctx.ops.call("my.list", {
382
+ object: BOOKING,
383
+ filter: {
384
+ and: [
385
+ { field: "class", op: "eq", value: classId },
386
+ { field: "person", op: "eq", value: personId },
387
+ { field: "state", op: "eq", value: "waiting" },
388
+ ],
389
+ },
390
+ limit: 1,
391
+ });
392
+ const queued = mine.items[0];
393
+ if (!queued)
394
+ return null;
395
+ try {
396
+ const after = await ctx.ops.call("my.update", {
397
+ object: BOOKING,
398
+ id: queued.id,
399
+ from: "waiting",
400
+ values: { state: "booked" },
401
+ });
402
+ return {
403
+ result: "booked",
404
+ bookingId: queued.id,
405
+ classId,
406
+ holderId: text(after.values.holder),
407
+ };
408
+ }
409
+ catch (error) {
410
+ const rule = error instanceof OpsCallError ? error.details?.rule : null;
411
+ if (rule !== "capacity")
412
+ throw error;
413
+ const at = await positionOf(ctx, queued.id);
414
+ return {
415
+ result: "waiting",
416
+ bookingId: queued.id,
417
+ classId,
418
+ ...at,
419
+ message: `You are already on this class's waitlist${at.position === null ? "" : `, number ${at.position}`}: no place is free for you yet.`,
420
+ };
421
+ }
422
+ }
423
+ const waitingMessage = (position) => position === null
424
+ ? "The class is full: you are on its waitlist."
425
+ : `The class is full: you are number ${position} on its waitlist. If a place frees in time, you are moved in and it is paid from your membership or pass then.`;
257
426
  export const book = defineTool({
258
427
  description: "Book the signed-in member into a class with what they already hold (a membership or a " +
259
428
  "pass): the host spends one use of the one whose use would lapse first, or of `holderId` " +
260
- "when they name one. No money moves. Answers booked, or refused with the reason the host " +
261
- "gave: booking not open yet (with when it opens), closed, booked by the gym only, nothing " +
262
- "to pay with, already booked, or full.",
429
+ "when they name one. No money moves. When the class is full they join its waitlist " +
430
+ "(unless `waitlist` is false): that spends nothing, and if a place frees before the class " +
431
+ "type's cut-off the host moves the first waiter in and spends their use then. Asked again " +
432
+ "by a member already waiting, it books them if a place is free to them (never one held for " +
433
+ "the queue), else says where they stand. Answers " +
434
+ "booked, waiting (with their position), or refused with the reason the host gave: booking " +
435
+ "not open yet (with when it opens), closed, booked by the gym only, nothing to pay with, " +
436
+ "already booked or waiting, full, or too close to the start to wait. A parent books a " +
437
+ "child the gym linked to them with forPersonId (see family): the same rules, and the " +
438
+ "child's own membership or pass pays.",
263
439
  input: z.object({
264
440
  classId: z.string().min(1).max(64),
441
+ forPersonId: forPerson,
265
442
  holderId: z
266
443
  .string()
267
444
  .min(1)
268
445
  .max(64)
269
446
  .optional()
270
447
  .describe("A membership or pass of theirs to spend, when they hold several"),
448
+ waitlist: z
449
+ .boolean()
450
+ .default(true)
451
+ .describe("When the class is full, join its waitlist (default) rather than be refused"),
271
452
  }),
272
- output: z.union([booked, refused]),
453
+ output: z.union([booked, waiting, refused]),
273
454
  risk: "write",
274
455
  audiences: ["customer"],
275
456
  async handler(input, ctx) {
276
457
  try {
277
458
  // The host sets whose it is (the caller), checks the class is one they may see, and holds
278
- // the windows, the staff-only rule, the place, the one-per-class rule and the spend.
279
- const made = await ctx.ops.call("my.create", {
280
- object: BOOKING,
281
- values: {
282
- class: input.classId,
283
- ...(input.holderId ? { holder: input.holderId } : {}),
284
- },
285
- });
459
+ // the windows, the staff-only rule, the place, the one-per-class rule, the spend and when
460
+ // a waitlist may be joined.
461
+ const { made, waiting: queued } = await bookOrWait(ctx, "my.create", {
462
+ class: input.classId,
463
+ ...(input.holderId ? { holder: input.holderId } : {}),
464
+ }, input.waitlist, input.forPersonId);
465
+ if (queued) {
466
+ const at = await positionOf(ctx, made.id);
467
+ return {
468
+ result: "waiting",
469
+ bookingId: made.id,
470
+ classId: input.classId,
471
+ ...at,
472
+ message: waitingMessage(at.position),
473
+ };
474
+ }
286
475
  return {
287
476
  result: "booked",
288
477
  bookingId: made.id,
@@ -291,10 +480,141 @@ export const book = defineTool({
291
480
  };
292
481
  }
293
482
  catch (error) {
483
+ const unique = error instanceof OpsCallError &&
484
+ error.details?.rule === "unique";
485
+ if (unique) {
486
+ // Already waiting on it: take a free place if there is one (finding 5, ADR 0520).
487
+ try {
488
+ const whose = input.forPersonId ?? (await familyOf(ctx)).self.personId;
489
+ const taken = await takeFreePlace(ctx, input.classId, whose);
490
+ if (taken)
491
+ return taken;
492
+ }
493
+ catch (inner) {
494
+ return refusalOf(inner, "book");
495
+ }
496
+ }
294
497
  return refusalOf(error, "book");
295
498
  }
296
499
  },
297
500
  });
501
+ // --- A drop-in: one class paid for on the website (decision 8, ADR 0560) --------------------------
502
+ export const buy = defineTool({
503
+ description: "Pay for one class (a drop-in), on the website: for a visitor, or a member with nothing to " +
504
+ "spend on it. The host makes the booking held while it is paid for (a place kept), prices it " +
505
+ "from the class's drop-in price, and starts its order; nothing is paid here. The buyer then " +
506
+ "calls order.checkout with the order's id (and a guest's token) to pay on the provider's " +
507
+ "page: the verified payment books them; an order left unpaid expires after a few minutes and " +
508
+ "the place goes back. The same rules as booking hold (when booking opens and closes, booked " +
509
+ "by the gym only, one booking per person per class); a full class is refused (only members " +
510
+ "with a membership or pass wait for a place). A signed-in member buys as themselves, or for a " +
511
+ "child the gym linked to them (forPersonId; they pay, it is the child's booking); a guest " +
512
+ "gives their email address. Cancelled in time, or by the gym, the money goes back to the " +
513
+ "card once a member of staff approves the refund; cancelled late, it is kept. Amounts in the " +
514
+ "currency's minor unit.",
515
+ input: z.object({
516
+ classId: z.string().min(1).max(64),
517
+ forPersonId: forPerson,
518
+ email: z.string().trim().max(320).optional().describe("A guest's email address"),
519
+ }),
520
+ output: z.union([
521
+ z.object({
522
+ result: z.literal("pending"),
523
+ bookingId: z.string(),
524
+ classId: z.string(),
525
+ orderId: z.string(),
526
+ total: z.number(),
527
+ currency: z.string(),
528
+ expiresAt: z.string().nullable().describe("When the held place goes back if unpaid"),
529
+ token: z.string().nullable().describe("A guest's key to this order, shown once"),
530
+ }),
531
+ refused,
532
+ ]),
533
+ risk: "write",
534
+ audiences: ["customer", "public"],
535
+ async handler(input, ctx) {
536
+ try {
537
+ // The host makes the booking, held, as the caller's own (or their child's), prices it, and
538
+ // holds every rule: the class's windows and staff-only rule, its places, one per person.
539
+ const order = await ctx.ops.call("order.startHeld", {
540
+ object: BOOKING,
541
+ values: { class: input.classId },
542
+ ...(input.forPersonId ? { forPersonId: input.forPersonId } : {}),
543
+ ...(input.email === undefined ? {} : { email: input.email }),
544
+ });
545
+ return {
546
+ result: "pending",
547
+ bookingId: order.recordId,
548
+ classId: input.classId,
549
+ orderId: order.id,
550
+ total: order.total,
551
+ currency: order.currency,
552
+ expiresAt: order.expiresAt,
553
+ token: order.token ?? null,
554
+ };
555
+ }
556
+ catch (error) {
557
+ if (error instanceof OpsCallError) {
558
+ const rule = error.details?.rule;
559
+ const out = (reason, message) => ({
560
+ result: "refused",
561
+ reason,
562
+ message,
563
+ detail: null,
564
+ opensAt: null,
565
+ closesAt: null,
566
+ });
567
+ if (rule === "no_price" || rule === "not_for_sale") {
568
+ return out("no_drop_in", "This class cannot be paid for online. Ask at the desk.");
569
+ }
570
+ if (rule === "try_later" || error.code === "rate_limited") {
571
+ return out("try_later", "Too many places are being held for payment just now: try again shortly.");
572
+ }
573
+ if (rule === "buyer_unclear") {
574
+ return out("ask_desk", "We could not tell who you are from that address. Ask at the desk.");
575
+ }
576
+ if (error.details?.field === "email") {
577
+ return out("ask_desk", error.message);
578
+ }
579
+ }
580
+ return refusalOf(error, "book");
581
+ }
582
+ },
583
+ });
584
+ export const leaveWaitlist = defineTool({
585
+ description: "Take the signed-in member off a class's waitlist (one of their bookings that is waiting). " +
586
+ "Nothing was spent, so nothing is given back. Refused when it is no longer waiting (they " +
587
+ "were moved in meanwhile: cancel that booking instead).",
588
+ input: z.object({ bookingId: z.string().min(1).max(64) }),
589
+ output: z.union([z.object({ result: z.literal("left"), bookingId: z.string() }), refused]),
590
+ risk: "write",
591
+ audiences: ["customer"],
592
+ async handler(input, ctx) {
593
+ try {
594
+ // From waiting, or not at all (ADR 0437): a promotion and a leave at once, one wins.
595
+ await ctx.ops.call("my.update", {
596
+ object: BOOKING,
597
+ id: input.bookingId,
598
+ from: "waiting",
599
+ values: { state: "left" },
600
+ });
601
+ return { result: "left", bookingId: input.bookingId };
602
+ }
603
+ catch (error) {
604
+ if (error instanceof OpsCallError && error.code === "conflict") {
605
+ return {
606
+ result: "refused",
607
+ reason: "changed",
608
+ message: "This booking is no longer waiting: look at it again (you may have been moved in).",
609
+ detail: null,
610
+ opensAt: null,
611
+ closesAt: null,
612
+ };
613
+ }
614
+ return refusalOf(error, "cancel");
615
+ }
616
+ },
617
+ });
298
618
  export const cancel = defineTool({
299
619
  description: "Cancel one of the signed-in member's bookings. First without `confirm`: the host says " +
300
620
  "whether a cancel now is in time (`cancelled`, the class's use given back) or late " +
@@ -315,6 +635,9 @@ export const cancel = defineTool({
315
635
  result: z.enum(["preview", "cancelled", "late_cancelled"]),
316
636
  state: z.enum(["cancelled", "late_cancelled"]),
317
637
  late: z.boolean().describe("A late cancel keeps the use the booking spent"),
638
+ dropIn: z
639
+ .boolean()
640
+ .describe("Paid for on its own: in time, the money goes back once staff approve it"),
318
641
  message: z.string(),
319
642
  }),
320
643
  refused,
@@ -322,19 +645,35 @@ export const cancel = defineTool({
322
645
  risk: "write",
323
646
  audiences: ["customer"],
324
647
  async handler(input, ctx) {
648
+ // A drop-in (ADR 0560) gets its money back, not a use: read which this booking is.
649
+ let dropIn = false;
325
650
  const say = (state, done) => ({
326
651
  result: done ? state : "preview",
327
652
  state,
328
653
  late: state === "late_cancelled",
329
- message: state === "cancelled"
330
- ? done
331
- ? "Cancelled. The class is back on your membership or pass."
332
- : "Cancelling now is in time: the class goes back on your membership or pass."
333
- : done
334
- ? "Cancelled late. The class stays used."
335
- : "Cancelling now is late: the class stays used.",
654
+ dropIn,
655
+ message: dropIn
656
+ ? state === "cancelled"
657
+ ? done
658
+ ? "Cancelled. Your payment is refunded to your card once the gym approves it."
659
+ : "Cancelling now is in time: your payment is refunded to your card once the gym approves it."
660
+ : done
661
+ ? "Cancelled late. The payment is kept."
662
+ : "Cancelling now is late: the payment is kept."
663
+ : state === "cancelled"
664
+ ? done
665
+ ? "Cancelled. The class is back on your membership or pass."
666
+ : "Cancelling now is in time: the class goes back on your membership or pass."
667
+ : done
668
+ ? "Cancelled late. The class stays used."
669
+ : "Cancelling now is late: the class stays used.",
336
670
  });
337
671
  try {
672
+ const own = await ctx.ops.call("my.get", {
673
+ object: BOOKING,
674
+ id: input.bookingId,
675
+ });
676
+ dropIn = text(own.values.dropInOrder) !== null;
338
677
  if (!input.confirm) {
339
678
  // The host's dry run: the state "cancel" would enter now (ADR 0503).
340
679
  const resolved = await ctx.ops.call("state.resolve", {
@@ -369,19 +708,38 @@ export const cancel = defineTool({
369
708
  });
370
709
  export const mine = defineTool({
371
710
  description: "The signed-in member's own bookings, soonest class first: each with its state (booked, " +
372
- "cancelled, cancelled late…), the membership or pass it spent from, and its class (name, " +
373
- "start and end in its own time zone, coach, room, whether it still runs). Only their own " +
374
- "bookings exist here. Read-only.",
711
+ "waiting, cancelled, cancelled late…), for one waiting its place on the waitlist, the " +
712
+ "membership or pass it spent from, and its class (name, start and end in its own time " +
713
+ "zone, coach, room, whether it still runs). With personId, a child's the gym linked to " +
714
+ "them instead (see family). Only their own and their children's bookings exist here. " +
715
+ "Read-only.",
375
716
  input: z.object({
376
- state: z.enum(["booked", "cancelled", "late_cancelled"]).optional(),
717
+ personId: z
718
+ .string()
719
+ .min(1)
720
+ .max(64)
721
+ .optional()
722
+ .describe("A child of theirs (see family); left out, their own"),
723
+ state: z
724
+ .enum(["booked", "pending", "waiting", "cancelled", "late_cancelled", "left"])
725
+ .optional(),
377
726
  upcoming: z.boolean().default(true).describe("Only classes that have not started"),
378
727
  limit: z.number().int().min(1).max(100).default(50),
379
728
  }),
380
729
  output: z.object({
381
730
  bookings: z.array(z.object({
382
731
  id: z.string(),
732
+ personId: z.string().nullable().describe("Whose booking it is: theirs, or their child's"),
383
733
  state: z.string().nullable(),
734
+ position: z
735
+ .number()
736
+ .nullable()
737
+ .describe("While waiting: their place on the waitlist (1 is next); otherwise null"),
384
738
  holderId: z.string().nullable(),
739
+ dropInOrderId: z
740
+ .string()
741
+ .nullable()
742
+ .describe("A drop-in's order (pending: pay it with order.checkout); null otherwise"),
385
743
  classId: z.string().nullable(),
386
744
  title: z.string().nullable(),
387
745
  startsAt: z.string().nullable(),
@@ -395,10 +753,17 @@ export const mine = defineTool({
395
753
  risk: "read",
396
754
  audiences: ["customer"],
397
755
  async handler(input, ctx) {
398
- // The seam gives a member their own bookings only; no filter here decides whose they are.
756
+ // The seam gives a member their own bookings and their children's only; the filter picks
757
+ // whose of those (a Person they may not read gives nothing, as one that does not exist).
758
+ const whose = input.personId ?? (await familyOf(ctx)).self.personId;
399
759
  const page = await ctx.ops.call("my.list", {
400
760
  object: BOOKING,
401
- ...(input.state ? { filter: { field: "state", op: "eq", value: input.state } } : {}),
761
+ filter: {
762
+ and: [
763
+ { field: "person", op: "eq", value: whose },
764
+ ...(input.state ? [{ field: "state", op: "eq", value: input.state }] : []),
765
+ ],
766
+ },
402
767
  limit: input.limit,
403
768
  });
404
769
  // Their bookings' classes, whatever the class's state (customerVia), and only those.
@@ -406,6 +771,12 @@ export const mine = defineTool({
406
771
  const coaches = await byIds(ctx, "public.list", COACH, [...classes.values()].map((c) => text(c.coach)));
407
772
  const rooms = await byIds(ctx, "public.list", ROOM, [...classes.values()].map((c) => text(c.room)));
408
773
  const now = Date.now();
774
+ const positions = new Map();
775
+ for (const booking of page.items) {
776
+ if (booking.values.state === "waiting") {
777
+ positions.set(booking.id, (await positionOf(ctx, booking.id)).position);
778
+ }
779
+ }
409
780
  const bookings = page.items
410
781
  .map((booking) => {
411
782
  const classId = text(booking.values.class);
@@ -414,8 +785,11 @@ export const mine = defineTool({
414
785
  const roomId = text(klass.room);
415
786
  return {
416
787
  id: booking.id,
788
+ personId: text(booking.values.person),
417
789
  state: text(booking.values.state),
790
+ position: positions.get(booking.id) ?? null,
418
791
  holderId: text(booking.values.holder),
792
+ dropInOrderId: text(booking.values.dropInOrder),
419
793
  classId,
420
794
  title: text(klass.title),
421
795
  startsAt: text(klass.startsAt),
@@ -465,7 +839,9 @@ export const bookFor = defineTool({
465
839
  "rather than made twice: book them, or pass confirmNew when you checked it is someone else. " +
466
840
  "Staff are not bound by the booking windows or by 'booked by staff only'; a class that was " +
467
841
  "cancelled or is over, the places, one booking per person per class and the use it spends " +
468
- "still hold. With `paidAtDesk` it spends no use (they paid at the desk). Audited.",
842
+ "still hold. With `paidAtDesk` it spends no use (they paid at the desk). With `waitlist`, " +
843
+ "a person on file is put on a full class's waitlist instead of being refused (it spends " +
844
+ "nothing until the host moves them in). Audited.",
469
845
  input: z.object({
470
846
  classId: z.string().min(1).max(64),
471
847
  personId: z.string().min(1).max(64).optional(),
@@ -483,14 +859,27 @@ export const bookFor = defineTool({
483
859
  .describe("The possible duplicates were checked: this is someone new"),
484
860
  holderId: z.string().min(1).max(64).optional(),
485
861
  paidAtDesk: z.boolean().default(false),
862
+ waitlist: z
863
+ .boolean()
864
+ .default(false)
865
+ .describe("A person on file, a full class: put them on its waitlist instead"),
486
866
  note: z.string().max(2000).optional(),
487
867
  }),
488
- output: z.union([booked.extend({ personId: z.string() }), refused]),
868
+ output: z.union([
869
+ booked.extend({ personId: z.string() }),
870
+ waiting.extend({ personId: z.string() }),
871
+ refused,
872
+ ]),
489
873
  risk: "write",
490
874
  async handler(input, ctx) {
491
875
  if (!input.personId && !input.newPerson) {
492
876
  throw new OpsCallError("invalid_input", "Give personId, or newPerson for a walk-in");
493
877
  }
878
+ // Paid at the desk is for a place they take now: nobody pays at the desk for a place they
879
+ // may never get, and a promotion later would then spend nothing (ADR 0520).
880
+ if (input.paidAtDesk && input.waitlist) {
881
+ throw new OpsCallError("invalid_input", "paidAtDesk is for a free place taken now; put them on the waitlist without it");
882
+ }
494
883
  const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
495
884
  const values = {
496
885
  class: input.classId,
@@ -501,10 +890,18 @@ export const bookFor = defineTool({
501
890
  };
502
891
  try {
503
892
  if (input.personId) {
504
- const made = await ctx.ops.call("record.create", {
505
- object: BOOKING,
506
- values: { ...values, person: input.personId },
507
- });
893
+ const { made, waiting: queued } = await bookOrWait(ctx, "record.create", { ...values, person: input.personId }, input.waitlist);
894
+ if (queued) {
895
+ const at = await positionOf(ctx, made.id);
896
+ return {
897
+ result: "waiting",
898
+ bookingId: made.id,
899
+ classId: input.classId,
900
+ personId: input.personId,
901
+ ...at,
902
+ message: waitingMessage(at.position),
903
+ };
904
+ }
508
905
  return {
509
906
  result: "booked",
510
907
  bookingId: made.id,
@@ -719,6 +1116,8 @@ export const day = defineTool({
719
1116
  }),
720
1117
  output: z.object({ date: z.string(), classes: z.array(staffClass) }),
721
1118
  risk: "read",
1119
+ // The coach role holds it (ADR 0436); staff hold it as any read tool.
1120
+ permission: "bookings:coach",
722
1121
  async handler(input, ctx) {
723
1122
  const from = localMidnight(input.date, input.timeZone);
724
1123
  const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
@@ -739,8 +1138,10 @@ export const day = defineTool({
739
1138
  });
740
1139
  export const classList = defineTool({
741
1140
  description: "A class's list for staff and coaches: the class (as on the day view) and every booking of " +
742
- "it with the person's name, its state (booked, cancelled, cancelled late…), whether they " +
743
- "paid at the desk, the membership or pass it spent from and who booked it. Read-only.",
1141
+ "it with the person's name, its state (booked, waiting, cancelled, cancelled late…), " +
1142
+ "whether they paid at the desk, the membership or pass it spent from, who booked it, and " +
1143
+ "for the waitlist when they were moved in or why they were passed over. Waiters are in " +
1144
+ "the order they joined. Read-only.",
744
1145
  input: z.object({ classId: z.string().min(1).max(64) }),
745
1146
  output: z.object({
746
1147
  class: staffClass,
@@ -751,48 +1152,472 @@ export const classList = defineTool({
751
1152
  paidAtDesk: z.boolean(),
752
1153
  holderId: z.string().nullable(),
753
1154
  bookedBy: z.string().nullable(),
1155
+ promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
1156
+ passedOver: z
1157
+ .string()
1158
+ .nullable()
1159
+ .describe("While waiting: why a free place could not be theirs (what they hold)"),
754
1160
  })),
755
1161
  }),
756
1162
  risk: "read",
757
1163
  async handler(input, ctx) {
758
- const klass = await ctx.ops.call("record.get", {
759
- object: CLASS,
760
- id: input.classId,
761
- });
762
- const [described] = await staffClasses(ctx, [klass]);
1164
+ const { klass, bookings, names } = await listOf(ctx, input.classId);
1165
+ return {
1166
+ class: klass,
1167
+ bookings: bookings.map((booking) => {
1168
+ const personId = text(booking.values.person);
1169
+ return {
1170
+ id: booking.id,
1171
+ person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
1172
+ state: text(booking.values.state),
1173
+ paidAtDesk: flag(booking.values.paidOtherwise),
1174
+ holderId: text(booking.values.holder),
1175
+ bookedBy: text(booking.values.bookedBy),
1176
+ promotedAt: text(booking.values.promotedAt),
1177
+ passedOver: text(booking.values.passedOverReason),
1178
+ };
1179
+ }),
1180
+ };
1181
+ },
1182
+ });
1183
+ // --- Attendance, the coach's list (step 7) --------------------------------------------------------
1184
+ /** Who is marking a list: the staff member who called the tool (never from the input). */
1185
+ function marker(ctx) {
1186
+ const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
1187
+ return { markedBy: staff?.userId ?? null, markedByName: staff?.name || null };
1188
+ }
1189
+ const marked = z.object({
1190
+ result: z.enum(["attended", "no_show", "booked"]),
1191
+ bookingId: z.string(),
1192
+ message: z.string(),
1193
+ });
1194
+ const alreadyMarked = z.object({
1195
+ result: z.literal("already"),
1196
+ bookingId: z.string(),
1197
+ state: z.string().nullable().describe("What the booking is now"),
1198
+ markedAt: z.string().nullable(),
1199
+ markedBy: z.string().nullable().describe("The name of who marked it first"),
1200
+ message: z.string(),
1201
+ });
1202
+ const listRefused = z.object({
1203
+ result: z.literal("refused"),
1204
+ reason: z
1205
+ .enum(["not_found", "not_started", "not_booked", "changed"])
1206
+ .describe("not_started: the list opens an hour before the class (see opensAt). not_booked: the " +
1207
+ "booking is not one that can be marked (cancelled, waiting, moved…; see state). changed: " +
1208
+ "it changed meanwhile; look again."),
1209
+ state: z.string().nullable(),
1210
+ opensAt: z.string().nullable(),
1211
+ message: z.string(),
1212
+ });
1213
+ const STATE_WORDS = {
1214
+ booked: "booked",
1215
+ attended: "ticked as come",
1216
+ no_show: "marked as not come",
1217
+ waiting: "on the waitlist",
1218
+ cancelled: "cancelled",
1219
+ late_cancelled: "cancelled late",
1220
+ excused: "cancelled with the class given back",
1221
+ cancelled_by_us: "cancelled with the class",
1222
+ moved: "moved to another class",
1223
+ left: "off the waitlist",
1224
+ pending: "held while paying",
1225
+ expired: "expired",
1226
+ };
1227
+ const words = (state) => STATE_WORDS[state ?? ""] ?? state ?? "unknown";
1228
+ /**
1229
+ * Marks one booking as `to` from where it is (one of `from`), from that position or not at all
1230
+ * (ADR 0437): of two coaches marking one name at once, one is made and the other is told who was
1231
+ * first. The host holds when a list may be marked (from an hour before the class) and which moves
1232
+ * a booking may make.
1233
+ */
1234
+ async function markBooking(ctx, bookingId, to, from) {
1235
+ const no = (reason, message, state = null, opensAt = null) => ({ result: "refused", reason, state, opensAt, message });
1236
+ let record;
1237
+ try {
1238
+ record = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
1239
+ }
1240
+ catch (error) {
1241
+ if (error instanceof OpsCallError && error.code === "not_found") {
1242
+ return no("not_found", "No such booking.");
1243
+ }
1244
+ throw error;
1245
+ }
1246
+ const already = (now) => {
1247
+ const state = text(now.values.state);
1248
+ const by = text(now.values.markedByName);
1249
+ return {
1250
+ result: "already",
1251
+ bookingId,
1252
+ state,
1253
+ markedAt: text(now.values.markedAt),
1254
+ markedBy: by,
1255
+ message: `Already ${words(state)}${by ? ` by ${by}` : ""}.`,
1256
+ };
1257
+ };
1258
+ const state = text(record.values.state) ?? "";
1259
+ if (state === to)
1260
+ return already(record);
1261
+ if (!from.includes(state)) {
1262
+ return no("not_booked", `This booking is ${words(state)}: it cannot be marked.`, state);
1263
+ }
1264
+ const values = to === "booked"
1265
+ ? { state: to, markedAt: null, markedBy: null, markedByName: null }
1266
+ : { state: to, markedAt: new Date().toISOString(), ...marker(ctx) };
1267
+ try {
1268
+ await ctx.ops.call("record.update", { object: BOOKING, id: bookingId, from: state, values });
1269
+ }
1270
+ catch (error) {
1271
+ if (!(error instanceof OpsCallError))
1272
+ throw error;
1273
+ const details = (error.details ?? {});
1274
+ if (details.rule === "state_window_not_open") {
1275
+ return no("not_started", to === "no_show"
1276
+ ? "A no-show is marked once the class has started."
1277
+ : "The class's list opens an hour before it starts.", state, text(details.opensAt));
1278
+ }
1279
+ if (error.code === "conflict") {
1280
+ // Someone marked it first (or it moved): say who, from what it is now.
1281
+ const now = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
1282
+ if (text(now.values.state) === to)
1283
+ return already(now);
1284
+ const is = text(now.values.state);
1285
+ return no("changed", `It changed meanwhile: it is now ${words(is)}.`, is);
1286
+ }
1287
+ if (details.rule === "state_move_not_declared" || details.rule === "state_final") {
1288
+ return no("not_booked", "This booking cannot be marked.", state);
1289
+ }
1290
+ throw error;
1291
+ }
1292
+ return {
1293
+ result: to,
1294
+ bookingId,
1295
+ message: to === "attended"
1296
+ ? "Ticked: they came."
1297
+ : to === "no_show"
1298
+ ? "Marked: they did not come. The class stays used."
1299
+ : "Unticked: booked again.",
1300
+ };
1301
+ }
1302
+ const markOutput = z.union([marked, alreadyMarked, listRefused]);
1303
+ export const markAttended = defineTool({
1304
+ description: "Tick a booking on a class's list: they came. From an hour before the class, and any time " +
1305
+ "after it (a late correction: a no-show ticked becomes attended). Of two coaches ticking one " +
1306
+ "name at once, one tick is made and the other is told who was first. A booking that is " +
1307
+ "cancelled, waiting or moved cannot be ticked. The use it spent stays spent.",
1308
+ input: z.object({ bookingId: z.string().min(1).max(64) }),
1309
+ output: markOutput,
1310
+ risk: "write",
1311
+ permission: "bookings:coach",
1312
+ handler: (input, ctx) => markBooking(ctx, input.bookingId, "attended", ["booked", "no_show"]),
1313
+ });
1314
+ export const undoAttended = defineTool({
1315
+ description: "Untick a booking ticked by mistake: it is booked again (and, once the class is 30 minutes " +
1316
+ "over with others ticked, the host makes it a no-show). Who ticked it and when are cleared.",
1317
+ input: z.object({ bookingId: z.string().min(1).max(64) }),
1318
+ output: markOutput,
1319
+ risk: "write",
1320
+ permission: "bookings:coach",
1321
+ handler: (input, ctx) => markBooking(ctx, input.bookingId, "booked", ["attended"]),
1322
+ });
1323
+ export const markNoShow = defineTool({
1324
+ description: "Mark a booked booking as not come (a no-show), once the class has started. The class stays " +
1325
+ "used (no money, nothing else follows). The host does this itself for everyone still booked " +
1326
+ "30 minutes after the class ends, if anyone on the list was marked.",
1327
+ input: z.object({ bookingId: z.string().min(1).max(64) }),
1328
+ output: markOutput,
1329
+ risk: "write",
1330
+ permission: "bookings:coach",
1331
+ handler: (input, ctx) => markBooking(ctx, input.bookingId, "no_show", ["booked"]),
1332
+ });
1333
+ export const markAll = defineTool({
1334
+ description: "Tick everyone still booked on a class's list at once (from an hour before the class). Each " +
1335
+ "name is ticked from where it is or not at all, so a name another coach ticked meanwhile is " +
1336
+ "counted as already ticked, not twice.",
1337
+ input: z.object({ classId: z.string().min(1).max(64) }),
1338
+ output: z.union([
1339
+ z.object({
1340
+ result: z.literal("marked"),
1341
+ classId: z.string(),
1342
+ ticked: z.number().describe("Names ticked now"),
1343
+ already: z.number().describe("Names someone else ticked meanwhile"),
1344
+ skipped: z.number().describe("Names that changed meanwhile (cancelled, moved…)"),
1345
+ }),
1346
+ listRefused,
1347
+ ]),
1348
+ risk: "write",
1349
+ permission: "bookings:coach",
1350
+ async handler(input, ctx) {
763
1351
  const page = await ctx.ops.call("record.list", {
764
1352
  object: BOOKING,
765
- filter: { field: "class", op: "eq", value: klass.id },
1353
+ filter: {
1354
+ and: [
1355
+ { field: "class", op: "eq", value: input.classId },
1356
+ { field: "state", op: "eq", value: "booked" },
1357
+ ],
1358
+ },
766
1359
  sort: { field: "createdAt", direction: "asc" },
767
1360
  limit: 200,
768
1361
  });
769
- const names = new Map();
770
- for (const id of new Set(page.items.map((b) => text(b.values.person)).filter(Boolean))) {
771
- try {
772
- const person = await ctx.ops.call("person.get", {
773
- id,
774
- });
775
- names.set(id, person?.displayName ?? null);
776
- }
777
- catch (error) {
778
- if (!(error instanceof OpsCallError) || error.code !== "not_found")
779
- throw error;
780
- names.set(id, null);
781
- }
1362
+ let ticked = 0;
1363
+ let already = 0;
1364
+ let skipped = 0;
1365
+ for (const booking of page.items) {
1366
+ const out = await markBooking(ctx, booking.id, "attended", ["booked"]);
1367
+ if (out.result === "attended")
1368
+ ticked += 1;
1369
+ else if (out.result === "already")
1370
+ already += 1;
1371
+ else if (out.result === "refused" && out.reason === "not_started")
1372
+ return out;
1373
+ else
1374
+ skipped += 1;
1375
+ }
1376
+ return { result: "marked", classId: input.classId, ticked, already, skipped };
1377
+ },
1378
+ });
1379
+ /** A class as staff see it, its bookings in the order they were made, and their people's names. */
1380
+ async function listOf(ctx, classId) {
1381
+ const record = await ctx.ops.call("record.get", { object: CLASS, id: classId });
1382
+ const [klass] = await staffClasses(ctx, [record]);
1383
+ const page = await ctx.ops.call("record.list", {
1384
+ object: BOOKING,
1385
+ filter: { field: "class", op: "eq", value: record.id },
1386
+ sort: { field: "createdAt", direction: "asc" },
1387
+ limit: 200,
1388
+ });
1389
+ const names = new Map();
1390
+ for (const id of new Set(page.items.map((b) => text(b.values.person)).filter(Boolean))) {
1391
+ try {
1392
+ const person = await ctx.ops.call("person.get", {
1393
+ id,
1394
+ });
1395
+ names.set(id, person?.displayName ?? null);
782
1396
  }
1397
+ catch (error) {
1398
+ if (!(error instanceof OpsCallError) || error.code !== "not_found")
1399
+ throw error;
1400
+ names.set(id, null);
1401
+ }
1402
+ }
1403
+ return { klass: klass, bookings: page.items, names };
1404
+ }
1405
+ export const roster = defineTool({
1406
+ description: "A class's list for its coach: the class (as on the day view) and every booking of it with " +
1407
+ "the person's name and its state (booked, ticked, not come, waiting in the order they " +
1408
+ "joined, cancelled…), who marked it and when. Nothing about what anyone paid with. Read-only.",
1409
+ input: z.object({ classId: z.string().min(1).max(64) }),
1410
+ output: z.object({
1411
+ class: staffClass,
1412
+ bookings: z.array(z.object({
1413
+ id: z.string(),
1414
+ person: named,
1415
+ state: z.string().nullable(),
1416
+ markedAt: z.string().nullable(),
1417
+ markedBy: z.string().nullable().describe("The name of who marked it"),
1418
+ promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
1419
+ })),
1420
+ }),
1421
+ risk: "read",
1422
+ permission: "bookings:coach",
1423
+ async handler(input, ctx) {
1424
+ const { klass, bookings, names } = await listOf(ctx, input.classId);
783
1425
  return {
784
- class: described,
785
- bookings: page.items.map((booking) => {
1426
+ class: klass,
1427
+ bookings: bookings.map((booking) => {
786
1428
  const personId = text(booking.values.person);
787
1429
  return {
788
1430
  id: booking.id,
789
1431
  person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
790
1432
  state: text(booking.values.state),
791
- paidAtDesk: flag(booking.values.paidOtherwise),
792
- holderId: text(booking.values.holder),
793
- bookedBy: text(booking.values.bookedBy),
1433
+ markedAt: text(booking.values.markedAt),
1434
+ markedBy: text(booking.values.markedByName),
1435
+ promotedAt: text(booking.values.promotedAt),
794
1436
  };
795
1437
  }),
796
1438
  };
797
1439
  },
798
1440
  });
1441
+ // --- Moving people and cancelling a class (step 7) ------------------------------------------------
1442
+ const moveRefusal = z
1443
+ .enum(["not_booked", "same_class", "started"])
1444
+ .describe("not_booked: only a booked booking moves. same_class: it is already on that class. started: " +
1445
+ "its class has started; giving its use back is returnUse's.");
1446
+ export const move = defineTool({
1447
+ description: "Staff move a member's booking to another class, with the use it spent, in one batch: the " +
1448
+ "old booking is moved (its place given back, to the waitlist first before its cut-off), a " +
1449
+ "new booking is made on the other class, and the use is spent again on it from the same " +
1450
+ "membership or pass. Refused whole, with nothing changed, when the other class is full " +
1451
+ "(places held for its waitlist included: raise its places first), was cancelled or is over, " +
1452
+ "they are already booked on it, or the use cannot be spent in that class's week or period. " +
1453
+ "Only a booked booking, before its class starts. A booking paid at the desk moves paid at " +
1454
+ "the desk. Audited.",
1455
+ input: z.object({
1456
+ bookingId: z.string().min(1).max(64),
1457
+ toClassId: z.string().min(1).max(64),
1458
+ note: z.string().max(2000).optional(),
1459
+ }),
1460
+ output: z.union([
1461
+ z.object({
1462
+ result: z.literal("moved"),
1463
+ fromBookingId: z.string(),
1464
+ bookingId: z.string().describe("The new booking"),
1465
+ classId: z.string(),
1466
+ holderId: z.string().nullable().describe("The membership or pass the use is spent from"),
1467
+ }),
1468
+ refused,
1469
+ refused.extend({ reason: moveRefusal }),
1470
+ ]),
1471
+ risk: "write",
1472
+ async handler(input, ctx) {
1473
+ const no = (reason, message) => ({
1474
+ result: "refused",
1475
+ reason,
1476
+ message,
1477
+ detail: null,
1478
+ opensAt: null,
1479
+ closesAt: null,
1480
+ });
1481
+ let old;
1482
+ try {
1483
+ old = await ctx.ops.call("record.get", { object: BOOKING, id: input.bookingId });
1484
+ }
1485
+ catch (error) {
1486
+ if (error instanceof OpsCallError && error.code === "not_found") {
1487
+ return refusalOf(error, "cancel");
1488
+ }
1489
+ throw error;
1490
+ }
1491
+ const state = text(old.values.state);
1492
+ if (state !== "booked") {
1493
+ return no("not_booked", `This booking is ${words(state)}: only a booked one moves.`);
1494
+ }
1495
+ if (text(old.values.class) === input.toClassId) {
1496
+ return no("same_class", "It is already booked on that class.");
1497
+ }
1498
+ const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
1499
+ try {
1500
+ // The host moves the old booking in this create's batch (the allowance's `movedFrom`): its
1501
+ // place given back, the use spent again here from the same holder; or nothing at all.
1502
+ const made = await ctx.ops.call("record.create", {
1503
+ object: BOOKING,
1504
+ values: {
1505
+ class: input.toClassId,
1506
+ person: text(old.values.person),
1507
+ movedFrom: old.id,
1508
+ ...(staff?.userId ? { bookedBy: staff.userId } : {}),
1509
+ ...(input.note ? { note: input.note } : {}),
1510
+ },
1511
+ });
1512
+ return {
1513
+ result: "moved",
1514
+ fromBookingId: old.id,
1515
+ bookingId: made.id,
1516
+ classId: input.toClassId,
1517
+ holderId: text(made.values.holder),
1518
+ };
1519
+ }
1520
+ catch (error) {
1521
+ const rule = error instanceof OpsCallError
1522
+ ? error.details?.rule
1523
+ : undefined;
1524
+ // The old booking moved to a final state meanwhile (the member cancelled it): a race.
1525
+ if (rule === "state_final") {
1526
+ return {
1527
+ result: "refused",
1528
+ reason: "changed",
1529
+ message: "It changed meanwhile: it is no longer booked. Look again.",
1530
+ detail: null,
1531
+ opensAt: null,
1532
+ closesAt: null,
1533
+ };
1534
+ }
1535
+ // The old booking's own move has a window: until its class starts.
1536
+ if (rule === "state_window_closed") {
1537
+ return no("started", "Its class has started: it can no longer be moved. A person can give its use back (returnUse).");
1538
+ }
1539
+ return refusalOf(error, "book");
1540
+ }
1541
+ },
1542
+ });
1543
+ export const cancelClass = defineTool({
1544
+ description: "Cancel a scheduled class that has not ended, with a reason: in the same batch every booking " +
1545
+ "of it holding a place or a use (booked, waiting, held while paying, ticked as come, marked " +
1546
+ "not come, cancelled late) is cancelled by the gym, each place given back and each use " +
1547
+ "returned once. A person's act: the assistant, MCP clients and automations may ask, and it " +
1548
+ "waits for a person to approve it. When it cannot be done (no such class, not scheduled, " +
1549
+ "already ended, or it changed twice while being done) it fails with the reason, so an " +
1550
+ "approved request shows it did not apply. (Emails to the members, and refunds of paid " +
1551
+ "drop-ins, come in a later release.)",
1552
+ input: z.object({
1553
+ classId: z.string().min(1).max(64),
1554
+ reason: z.string().trim().min(3).max(2000),
1555
+ }),
1556
+ output: z.object({
1557
+ result: z.literal("cancelled"),
1558
+ classId: z.string(),
1559
+ bookingsCancelled: z.number().describe("Bookings cancelled with the class"),
1560
+ }),
1561
+ risk: "destructive",
1562
+ // Anyone but a person waits for a person's approval (ADR 0552); the class's move into
1563
+ // cancelled is made by this tool and the host only.
1564
+ personApproves: true,
1565
+ permission: "bookings:cancelClasses",
1566
+ async handler(input, ctx) {
1567
+ // A refusal is an error, never an answer: an approved request that cannot apply must show
1568
+ // that it did not (ADR 0553).
1569
+ const fail = (code, reason, message) => {
1570
+ throw new OpsCallError(code, message, { reason });
1571
+ };
1572
+ // A race (a booking landing under the cancel, another write moving the class) is tried once
1573
+ // more from a fresh read; anything else is the answer.
1574
+ for (let attempt = 0;; attempt++) {
1575
+ try {
1576
+ await ctx.ops.call("record.update", {
1577
+ object: CLASS,
1578
+ id: input.classId,
1579
+ from: "scheduled",
1580
+ values: { state: "cancelled", cancelledReason: input.reason },
1581
+ });
1582
+ break;
1583
+ }
1584
+ catch (error) {
1585
+ if (!(error instanceof OpsCallError))
1586
+ throw error;
1587
+ if (error.code === "not_found")
1588
+ fail("not_found", "not_found", "No such class.");
1589
+ const details = (error.details ?? {});
1590
+ if (details.reason === "not_in_position") {
1591
+ fail("conflict", "not_scheduled", "This class is not scheduled (it was cancelled or is over).");
1592
+ }
1593
+ if (details.rule === "state_window_closed") {
1594
+ fail("invalid_input", "ended", "This class has ended: a class that happened is not cancelled. A person can give a booking's use back (returnUse).");
1595
+ }
1596
+ if (details.rule === "state_window_unknown") {
1597
+ fail("invalid_input", "no_end", "This class has no end time, so whether it has ended cannot be told: give it one first.");
1598
+ }
1599
+ if (error.code === "conflict" && attempt === 0)
1600
+ continue;
1601
+ if (error.code === "conflict") {
1602
+ fail("conflict", "changed", "The class or its bookings changed while it was being cancelled. Look again.");
1603
+ }
1604
+ throw error;
1605
+ }
1606
+ }
1607
+ const page = await ctx.ops.call("record.list", {
1608
+ object: BOOKING,
1609
+ filter: {
1610
+ and: [
1611
+ { field: "class", op: "eq", value: input.classId },
1612
+ { field: "state", op: "eq", value: "cancelled_by_us" },
1613
+ ],
1614
+ },
1615
+ limit: 200,
1616
+ });
1617
+ return {
1618
+ result: "cancelled",
1619
+ classId: input.classId,
1620
+ bookingsCancelled: page.items.length,
1621
+ };
1622
+ },
1623
+ });