@composable-os/pack-bookings 0.1.0-beta.11 → 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.
package/dist/tools.js CHANGED
@@ -34,7 +34,7 @@ const classOutput = z.object({
34
34
  notes: z.string().nullable(),
35
35
  places,
36
36
  });
37
- /** Records of `object` by id, through a read operation the caller may use (public or my). */
37
+ /** Records of `object` by id, through a read operation the caller may use (public, my or staff's). */
38
38
  async function byIds(ctx, operation, object, ids) {
39
39
  const wanted = [...new Set(ids.filter((id) => Boolean(id)))];
40
40
  if (!wanted.length)
@@ -127,12 +127,36 @@ const refused = z.object({
127
127
  .optional()
128
128
  .describe("For person_exists and possible_duplicates: who is already on file"),
129
129
  });
130
+ /** What a host refusal says of itself (its rule, reason…); nothing for any other error. */
131
+ function detailsOf(error) {
132
+ if (!(error instanceof OpsCallError))
133
+ return {};
134
+ const { details } = error;
135
+ return typeof details === "object" && details !== null
136
+ ? details
137
+ : {};
138
+ }
139
+ /** A refusal answered with no booking times (a refusal the host gave times for is refusalOf's). */
140
+ const refuse = (reason, message) => ({
141
+ result: "refused",
142
+ reason,
143
+ message,
144
+ detail: null,
145
+ opensAt: null,
146
+ closesAt: null,
147
+ });
130
148
  /** A host refusal as a member can be told it, or the error itself when it is not one. */
131
149
  function refusalOf(error, what, expect) {
132
150
  if (!(error instanceof OpsCallError))
133
151
  throw error;
134
- const details = (error.details ?? {});
152
+ const details = detailsOf(error);
135
153
  const rule = typeof details.rule === "string" ? details.rule : "";
154
+ // Something must be agreed to first, or what is due changed while booking (stage 44, ADR
155
+ // 0644): the host's own refusal goes back as it is, with its documents, so the block shows
156
+ // what is due inline (the agreements entry in @composable-os/client reads it) and, for a
157
+ // change, asks again and tries once more. Never dressed up as "changed".
158
+ if (rule === "agreements_due" || rule === "agreements_changed")
159
+ throw error;
136
160
  const times = {
137
161
  opensAt: text(details.opensAt),
138
162
  closesAt: text(details.closesAt),
@@ -330,9 +354,6 @@ async function positionOf(ctx, bookingId) {
330
354
  async function bookOrWait(ctx, operation, values, wait, forPersonId) {
331
355
  // For a member's dependant (ADR 0540): the host checks the link in the write.
332
356
  const whose = operation === "my.create" && forPersonId ? { forPersonId } : {};
333
- const ruleOf = (error) => error instanceof OpsCallError
334
- ? (error.details ?? {})
335
- : {};
336
357
  for (let attempt = 0;; attempt++) {
337
358
  let refusal;
338
359
  try {
@@ -344,7 +365,7 @@ async function bookOrWait(ctx, operation, values, wait, forPersonId) {
344
365
  return { made, waiting: false };
345
366
  }
346
367
  catch (error) {
347
- const rule = ruleOf(error).rule;
368
+ const rule = detailsOf(error).rule;
348
369
  if (!wait || (rule !== "capacity" && rule !== "allowance"))
349
370
  throw error;
350
371
  refusal = error;
@@ -358,14 +379,15 @@ async function bookOrWait(ctx, operation, values, wait, forPersonId) {
358
379
  return { made, waiting: true };
359
380
  }
360
381
  catch (error) {
361
- const join = ruleOf(error);
382
+ const join = detailsOf(error);
383
+ const first = detailsOf(refusal).rule;
362
384
  // Full a moment ago, and a place came free: book it (once).
363
- if (join.reason === "not_full" && ruleOf(refusal).rule === "capacity" && attempt === 0) {
385
+ if (join.reason === "not_full" && first === "capacity" && attempt === 0) {
364
386
  continue;
365
387
  }
366
388
  // Nothing to pay with, and no waitlist to join (it is not full, or has closed): that is the
367
389
  // answer. Any other refusal of the join (already booked or waiting…) is the true reason.
368
- if (ruleOf(refusal).rule === "allowance" && join.rule === "waitlist")
390
+ if (first === "allowance" && join.rule === "waitlist")
369
391
  throw refusal;
370
392
  throw error;
371
393
  }
@@ -407,8 +429,7 @@ async function takeFreePlace(ctx, classId, personId) {
407
429
  };
408
430
  }
409
431
  catch (error) {
410
- const rule = error instanceof OpsCallError ? error.details?.rule : null;
411
- if (rule !== "capacity")
432
+ if (detailsOf(error).rule !== "capacity")
412
433
  throw error;
413
434
  const at = await positionOf(ctx, queued.id);
414
435
  return {
@@ -423,6 +444,25 @@ async function takeFreePlace(ctx, classId, personId) {
423
444
  const waitingMessage = (position) => position === null
424
445
  ? "The class is full: you are on its waitlist."
425
446
  : `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.`;
447
+ /** What bookOrWait made, as book and bookFor answer it: booked, or waiting with where they stand. */
448
+ async function answerOf(ctx, classId, { made, waiting: queued }) {
449
+ if (!queued) {
450
+ return {
451
+ result: "booked",
452
+ bookingId: made.id,
453
+ classId,
454
+ holderId: text(made.values.holder),
455
+ };
456
+ }
457
+ const at = await positionOf(ctx, made.id);
458
+ return {
459
+ result: "waiting",
460
+ bookingId: made.id,
461
+ classId,
462
+ ...at,
463
+ message: waitingMessage(at.position),
464
+ };
465
+ }
426
466
  export const book = defineTool({
427
467
  description: "Book the signed-in member into a class with what they already hold (a membership or a " +
428
468
  "pass): the host spends one use of the one whose use would lapse first, or of `holderId` " +
@@ -458,31 +498,14 @@ export const book = defineTool({
458
498
  // The host sets whose it is (the caller), checks the class is one they may see, and holds
459
499
  // the windows, the staff-only rule, the place, the one-per-class rule, the spend and when
460
500
  // a waitlist may be joined.
461
- const { made, waiting: queued } = await bookOrWait(ctx, "my.create", {
501
+ const made = await bookOrWait(ctx, "my.create", {
462
502
  class: input.classId,
463
503
  ...(input.holderId ? { holder: input.holderId } : {}),
464
504
  }, 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
- }
475
- return {
476
- result: "booked",
477
- bookingId: made.id,
478
- classId: input.classId,
479
- holderId: text(made.values.holder),
480
- };
505
+ return await answerOf(ctx, input.classId, made);
481
506
  }
482
507
  catch (error) {
483
- const unique = error instanceof OpsCallError &&
484
- error.details?.rule === "unique";
485
- if (unique) {
508
+ if (detailsOf(error).rule === "unique") {
486
509
  // Already waiting on it: take a free place if there is one (finding 5, ADR 0520).
487
510
  try {
488
511
  const whose = input.forPersonId ?? (await familyOf(ctx)).self.personId;
@@ -516,6 +539,13 @@ export const buy = defineTool({
516
539
  classId: z.string().min(1).max(64),
517
540
  forPersonId: forPerson,
518
541
  email: z.string().trim().max(320).optional().describe("A guest's email address"),
542
+ agreements: z
543
+ .array(z.record(z.string(), z.unknown()))
544
+ .max(20)
545
+ .optional()
546
+ .describe("A guest only: their acceptances of what is due, passed on to the host as they are (each " +
547
+ "{ versionId, typedName, signature?, answers? }); the host checks and records them. A " +
548
+ "signed-in member agrees first."),
519
549
  }),
520
550
  output: z.union([
521
551
  z.object({
@@ -541,6 +571,7 @@ export const buy = defineTool({
541
571
  values: { class: input.classId },
542
572
  ...(input.forPersonId ? { forPersonId: input.forPersonId } : {}),
543
573
  ...(input.email === undefined ? {} : { email: input.email }),
574
+ ...(input.agreements === undefined ? {} : { agreements: input.agreements }),
544
575
  });
545
576
  return {
546
577
  result: "pending",
@@ -555,27 +586,18 @@ export const buy = defineTool({
555
586
  }
556
587
  catch (error) {
557
588
  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.");
589
+ const details = detailsOf(error);
590
+ if (details.rule === "no_price" || details.rule === "not_for_sale") {
591
+ return refuse("no_drop_in", "This class cannot be paid for online. Ask at the desk.");
569
592
  }
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.");
593
+ if (details.rule === "try_later" || error.code === "rate_limited") {
594
+ return refuse("try_later", "Too many places are being held for payment just now: try again shortly.");
572
595
  }
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);
596
+ if (details.rule === "buyer_unclear") {
597
+ return refuse("ask_desk", "We could not tell who you are from that address. Ask at the desk.");
578
598
  }
599
+ if (details.field === "email")
600
+ return refuse("ask_desk", error.message);
579
601
  }
580
602
  return refusalOf(error, "book");
581
603
  }
@@ -602,14 +624,7 @@ export const leaveWaitlist = defineTool({
602
624
  }
603
625
  catch (error) {
604
626
  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
- };
627
+ return refuse("changed", "This booking is no longer waiting: look at it again (you may have been moved in).");
613
628
  }
614
629
  return refusalOf(error, "cancel");
615
630
  }
@@ -768,15 +783,14 @@ export const mine = defineTool({
768
783
  });
769
784
  // Their bookings' classes, whatever the class's state (customerVia), and only those.
770
785
  const classes = await byIds(ctx, "my.list", CLASS, page.items.map((b) => text(b.values.class)));
771
- const coaches = await byIds(ctx, "public.list", COACH, [...classes.values()].map((c) => text(c.coach)));
772
- const rooms = await byIds(ctx, "public.list", ROOM, [...classes.values()].map((c) => text(c.room)));
786
+ const waitingIds = page.items.filter((b) => b.values.state === "waiting").map((b) => b.id);
787
+ const [coaches, rooms, waitingAt] = await Promise.all([
788
+ byIds(ctx, "public.list", COACH, [...classes.values()].map((c) => text(c.coach))),
789
+ byIds(ctx, "public.list", ROOM, [...classes.values()].map((c) => text(c.room))),
790
+ Promise.all(waitingIds.map((id) => positionOf(ctx, id))),
791
+ ]);
773
792
  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
- }
793
+ const positions = new Map(waitingIds.map((id, i) => [id, waitingAt[i]?.position ?? null]));
780
794
  const bookings = page.items
781
795
  .map((booking) => {
782
796
  const classId = text(booking.values.class);
@@ -815,6 +829,8 @@ export const findPeople = defineTool({
815
829
  people: z.array(z.object({ id: z.string(), name: z.string().nullable(), email: z.string().nullable() })),
816
830
  }),
817
831
  risk: "read",
832
+ // The front desk (ADR 0600): any staff member holds it as any tool; a coach is granted it.
833
+ permission: "bookings:desk",
818
834
  async handler(input, ctx) {
819
835
  const found = new Map();
820
836
  for (const filter of [
@@ -871,6 +887,8 @@ export const bookFor = defineTool({
871
887
  refused,
872
888
  ]),
873
889
  risk: "write",
890
+ // The front desk (ADR 0600): any staff member holds it as any tool; a coach is granted it.
891
+ permission: "bookings:desk",
874
892
  async handler(input, ctx) {
875
893
  if (!input.personId && !input.newPerson) {
876
894
  throw new OpsCallError("invalid_input", "Give personId, or newPerson for a walk-in");
@@ -890,25 +908,8 @@ export const bookFor = defineTool({
890
908
  };
891
909
  try {
892
910
  if (input.personId) {
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
- }
905
- return {
906
- result: "booked",
907
- bookingId: made.id,
908
- classId: input.classId,
909
- personId: input.personId,
910
- holderId: text(made.values.holder),
911
- };
911
+ const made = await bookOrWait(ctx, "record.create", { ...values, person: input.personId }, input.waitlist);
912
+ return { ...(await answerOf(ctx, input.classId, made)), personId: input.personId };
912
913
  }
913
914
  const walkIn = input.newPerson;
914
915
  // The person and the booking in one batch, after the duplicate check (ADR 0507).
@@ -959,6 +960,8 @@ export const cancelFor = defineTool({
959
960
  }),
960
961
  output: z.union([cancelled, refused]),
961
962
  risk: "write",
963
+ // The front desk (ADR 0600): any staff member holds it as any tool; a coach is granted it.
964
+ permission: "bookings:desk",
962
965
  async handler(input, ctx) {
963
966
  try {
964
967
  // `cancel` is resolved by the host: this tool's calls are never a person's (ADR 0507).
@@ -994,9 +997,9 @@ export const returnUse = defineTool({
994
997
  ]),
995
998
  risk: "destructive",
996
999
  // Only a person calls it, with the pack's permission (ADR 0513); the move it makes is open to
997
- // no other staff write.
1000
+ // no other staff write. The desk's (ADR 0600; it was `bookings:returns`, which nothing held).
998
1001
  humanOnly: true,
999
- permission: "bookings:returns",
1002
+ permission: "bookings:desk",
1000
1003
  async handler(input, ctx) {
1001
1004
  try {
1002
1005
  await ctx.ops.call("record.update", {
@@ -1051,30 +1054,11 @@ const staffClass = z.object({
1051
1054
  staffOnly: z.boolean().describe("Its class type is booked by staff only"),
1052
1055
  });
1053
1056
  async function staffClasses(ctx, classes) {
1054
- const types = new Map();
1055
- const typeIds = [...new Set(classes.map((c) => text(c.values.classType)).filter(Boolean))];
1056
- if (typeIds.length) {
1057
- const found = await ctx.ops.call("record.list", {
1058
- object: CLASS_TYPE,
1059
- filter: { field: "id", op: "in", value: typeIds },
1060
- limit: typeIds.length,
1061
- });
1062
- for (const item of found.items)
1063
- types.set(item.id, item.values);
1064
- }
1065
- const names = async (object, field) => {
1066
- const ids = [...new Set(classes.map((c) => text(c.values[field])).filter(Boolean))];
1067
- if (!ids.length)
1068
- return new Map();
1069
- const found = await ctx.ops.call("record.list", {
1070
- object,
1071
- filter: { field: "id", op: "in", value: ids },
1072
- limit: ids.length,
1073
- });
1074
- return new Map(found.items.map((item) => [item.id, text(item.values.name)]));
1075
- };
1076
- const coaches = await names(COACH, "coach");
1077
- const rooms = await names(ROOM, "room");
1057
+ const of = (object, field) => byIds(ctx, "record.list", object, classes.map((c) => text(c.values[field])));
1058
+ const types = await of(CLASS_TYPE, "classType");
1059
+ const coaches = await of(COACH, "coach");
1060
+ const rooms = await of(ROOM, "room");
1061
+ const name = (found, id) => text(found.get(text(id) ?? "")?.name);
1078
1062
  return classes.map((klass) => {
1079
1063
  const v = klass.values;
1080
1064
  const typeId = text(v.classType);
@@ -1086,8 +1070,8 @@ async function staffClasses(ctx, classes) {
1086
1070
  startsAt: text(v.startsAt),
1087
1071
  endsAt: text(v.endsAt),
1088
1072
  timeZone: text(v.timezone),
1089
- coach: coaches.get(text(v.coach) ?? "") ?? null,
1090
- room: rooms.get(text(v.room) ?? "") ?? null,
1073
+ coach: name(coaches, v.coach),
1074
+ room: name(rooms, v.room),
1091
1075
  places: num(v.places),
1092
1076
  booked: num(v.taken) ?? 0,
1093
1077
  held: num(v.held) ?? 0,
@@ -1116,8 +1100,11 @@ export const day = defineTool({
1116
1100
  }),
1117
1101
  output: z.object({ date: z.string(), classes: z.array(staffClass) }),
1118
1102
  risk: "read",
1119
- // The coach role holds it (ADR 0436); staff hold it as any read tool.
1120
- permission: "bookings:coach",
1103
+ // The coach role holds it (ADR 0436), today's only; the desk any day, so a coach granted the
1104
+ // desk reaches it through the grant (ADR 0600); staff hold it as any read tool.
1105
+ permission: ["bookings:coach", "bookings:desk"],
1106
+ // On purpose: a coach granted the desk sees any day's classes here (ADR 0600).
1107
+ grantLiftsRoleLimits: true,
1121
1108
  async handler(input, ctx) {
1122
1109
  const from = localMidnight(input.date, input.timeZone);
1123
1110
  const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
@@ -1136,6 +1123,11 @@ export const day = defineTool({
1136
1123
  return { date: input.date, classes: await staffClasses(ctx, page.items) };
1137
1124
  },
1138
1125
  });
1126
+ const healthNote = z
1127
+ .boolean()
1128
+ .nullable()
1129
+ .describe("A yes on their current health form: a mark only (staff who may read health answers open " +
1130
+ "it from the Person page). Null when not shown.");
1139
1131
  export const classList = defineTool({
1140
1132
  description: "A class's list for staff and coaches: the class (as on the day view) and every booking of " +
1141
1133
  "it with the person's name, its state (booked, waiting, cancelled, cancelled late…), " +
@@ -1153,6 +1145,7 @@ export const classList = defineTool({
1153
1145
  holderId: z.string().nullable(),
1154
1146
  bookedBy: z.string().nullable(),
1155
1147
  promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
1148
+ healthNote,
1156
1149
  passedOver: z
1157
1150
  .string()
1158
1151
  .nullable()
@@ -1160,8 +1153,11 @@ export const classList = defineTool({
1160
1153
  })),
1161
1154
  }),
1162
1155
  risk: "read",
1156
+ // The front desk (ADR 0600): any staff member holds it as any tool; a coach is granted it.
1157
+ permission: "bookings:desk",
1163
1158
  async handler(input, ctx) {
1164
1159
  const { klass, bookings, names } = await listOf(ctx, input.classId);
1160
+ const notes = await healthNotesOf(ctx, klass.id, names);
1165
1161
  return {
1166
1162
  class: klass,
1167
1163
  bookings: bookings.map((booking) => {
@@ -1170,6 +1166,7 @@ export const classList = defineTool({
1170
1166
  id: booking.id,
1171
1167
  person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
1172
1168
  state: text(booking.values.state),
1169
+ healthNote: notes && personId ? notes.has(personId) : null,
1173
1170
  paidAtDesk: flag(booking.values.paidOtherwise),
1174
1171
  holderId: text(booking.values.holder),
1175
1172
  bookedBy: text(booking.values.bookedBy),
@@ -1270,7 +1267,7 @@ async function markBooking(ctx, bookingId, to, from) {
1270
1267
  catch (error) {
1271
1268
  if (!(error instanceof OpsCallError))
1272
1269
  throw error;
1273
- const details = (error.details ?? {});
1270
+ const details = detailsOf(error);
1274
1271
  if (details.rule === "state_window_not_open") {
1275
1272
  return no("not_started", to === "no_show"
1276
1273
  ? "A no-show is marked once the class has started."
@@ -1402,6 +1399,24 @@ async function listOf(ctx, classId) {
1402
1399
  }
1403
1400
  return { klass: klass, bookings: page.items, names };
1404
1401
  }
1402
+ /**
1403
+ * Who on a class's list answered yes on their current health form (stage 44, decision 18): a
1404
+ * mark, no content. The host reads the People from the class's bookings itself (never ids from
1405
+ * here). Null when the host gives none: a list the assistant reads, or an approved AI's call.
1406
+ */
1407
+ async function healthNotesOf(ctx, classId, names) {
1408
+ if (!names.size)
1409
+ return null;
1410
+ try {
1411
+ const { notes } = await ctx.ops.call("agreement.listHealthNotes", { records: BOOKING, value: classId });
1412
+ return new Set(notes.filter((n) => n.healthNote).map((n) => n.personId));
1413
+ }
1414
+ catch (error) {
1415
+ if (error instanceof OpsCallError && error.code === "forbidden")
1416
+ return null;
1417
+ throw error;
1418
+ }
1419
+ }
1405
1420
  export const roster = defineTool({
1406
1421
  description: "A class's list for its coach: the class (as on the day view) and every booking of it with " +
1407
1422
  "the person's name and its state (booked, ticked, not come, waiting in the order they " +
@@ -1416,12 +1431,14 @@ export const roster = defineTool({
1416
1431
  markedAt: z.string().nullable(),
1417
1432
  markedBy: z.string().nullable().describe("The name of who marked it"),
1418
1433
  promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
1434
+ healthNote,
1419
1435
  })),
1420
1436
  }),
1421
1437
  risk: "read",
1422
1438
  permission: "bookings:coach",
1423
1439
  async handler(input, ctx) {
1424
1440
  const { klass, bookings, names } = await listOf(ctx, input.classId);
1441
+ const notes = await healthNotesOf(ctx, klass.id, names);
1425
1442
  return {
1426
1443
  class: klass,
1427
1444
  bookings: bookings.map((booking) => {
@@ -1433,6 +1450,7 @@ export const roster = defineTool({
1433
1450
  markedAt: text(booking.values.markedAt),
1434
1451
  markedBy: text(booking.values.markedByName),
1435
1452
  promotedAt: text(booking.values.promotedAt),
1453
+ healthNote: notes && personId ? notes.has(personId) : null,
1436
1454
  };
1437
1455
  }),
1438
1456
  };
@@ -1469,15 +1487,10 @@ export const move = defineTool({
1469
1487
  refused.extend({ reason: moveRefusal }),
1470
1488
  ]),
1471
1489
  risk: "write",
1490
+ // The front desk (ADR 0600): any staff member holds it as any tool; a coach is granted it.
1491
+ permission: "bookings:desk",
1472
1492
  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
- });
1493
+ const no = (reason, message) => refuse(reason, message);
1481
1494
  let old;
1482
1495
  try {
1483
1496
  old = await ctx.ops.call("record.get", { object: BOOKING, id: input.bookingId });
@@ -1518,19 +1531,10 @@ export const move = defineTool({
1518
1531
  };
1519
1532
  }
1520
1533
  catch (error) {
1521
- const rule = error instanceof OpsCallError
1522
- ? error.details?.rule
1523
- : undefined;
1534
+ const { rule } = detailsOf(error);
1524
1535
  // The old booking moved to a final state meanwhile (the member cancelled it): a race.
1525
1536
  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
- };
1537
+ return refuse("changed", "It changed meanwhile: it is no longer booked. Look again.");
1534
1538
  }
1535
1539
  // The old booking's own move has a window: until its class starts.
1536
1540
  if (rule === "state_window_closed") {
@@ -1586,7 +1590,7 @@ export const cancelClass = defineTool({
1586
1590
  throw error;
1587
1591
  if (error.code === "not_found")
1588
1592
  fail("not_found", "not_found", "No such class.");
1589
- const details = (error.details ?? {});
1593
+ const details = detailsOf(error);
1590
1594
  if (details.reason === "not_in_position") {
1591
1595
  fail("conflict", "not_scheduled", "This class is not scheduled (it was cancelled or is over).");
1592
1596
  }
@@ -1621,3 +1625,700 @@ export const cancelClass = defineTool({
1621
1625
  };
1622
1626
  },
1623
1627
  });
1628
+ // --- Appointments, booked by staff (stage 49 step 5, ADR 0764) -------------------------------------
1629
+ //
1630
+ // One-to-one sessions. Every rule is the host's (index.ts): one coach never on two things at once
1631
+ // (classes, duties, appointments) with the service's buffer, a private room taken once, a coach
1632
+ // with an account, the session a pass or membership pays for and when it is given back, when a
1633
+ // cancel is late, who may give a session back or cancel for the business. These tools ask, and say
1634
+ // what the host answered.
1635
+ const APPOINTMENT = "bookings.appointment";
1636
+ const SERVICE = "bookings.service";
1637
+ const MINUTE = 60_000;
1638
+ const appointmentRefusal = z
1639
+ .enum([
1640
+ "not_found",
1641
+ "double_booked",
1642
+ "room_taken",
1643
+ "no_account",
1644
+ "no_coach_free",
1645
+ "no_use",
1646
+ "not_offered",
1647
+ "not_booked",
1648
+ "too_late",
1649
+ "started",
1650
+ "not_started",
1651
+ "same_time",
1652
+ "changed",
1653
+ ])
1654
+ .describe("double_booked: the coach is on something else then (a class, a duty or another session, " +
1655
+ "buffers included; see message). room_taken: no room the service may use is free then. " +
1656
+ "no_account: the coach has no staff account, so cannot be booked. no_coach_free: nobody " +
1657
+ "qualified is free at that time (any coach). no_use: nothing the client holds pays for this " +
1658
+ "service (see detail): book it paid at the desk. not_offered: the service is no longer " +
1659
+ "offered. not_booked: it is not booked (see state). too_late: it has started. started: it " +
1660
+ "has started, so it cannot be moved. not_started: it can be marked once it has started. " +
1661
+ "same_time: it is already at that time with that coach. changed: it changed meanwhile.");
1662
+ const appointmentRefused = z.object({
1663
+ result: z.literal("refused"),
1664
+ reason: appointmentRefusal,
1665
+ message: z.string(),
1666
+ detail: z
1667
+ .string()
1668
+ .nullable()
1669
+ .describe("The host's reason for an allowance refusal (no_uses_left, not_covered…)"),
1670
+ state: z.string().nullable().describe("What the appointment is now, when that is the reason"),
1671
+ });
1672
+ const noAppointment = (reason, message, detail = null, state = null) => ({ result: "refused", reason, message, detail, state });
1673
+ /** A host refusal of an appointment write, as staff can be told it; any other error is thrown. */
1674
+ function appointmentRefusalOf(error, what) {
1675
+ if (!(error instanceof OpsCallError))
1676
+ throw error;
1677
+ const details = detailsOf(error);
1678
+ const rule = typeof details.rule === "string" ? details.rule : "";
1679
+ // What must be agreed first goes back as it is (stage 44, ADR 0644), as for a class.
1680
+ if (rule === "agreements_due" || rule === "agreements_changed")
1681
+ throw error;
1682
+ if (error.code === "not_found")
1683
+ return noAppointment("not_found", "No such appointment, service or coach.");
1684
+ if (rule === "double_booked")
1685
+ return noAppointment("double_booked", error.message);
1686
+ if (rule === "room_taken")
1687
+ return noAppointment("room_taken", error.message);
1688
+ if (rule === "staffed_account")
1689
+ return noAppointment("no_account", error.message);
1690
+ if (rule === "state_closed") {
1691
+ return noAppointment("not_offered", "This service is no longer offered: it cannot be booked.");
1692
+ }
1693
+ if (rule === "allowance") {
1694
+ const reason = text(details.reason);
1695
+ return noAppointment("no_use", reason === "no_uses_left"
1696
+ ? "There are no sessions left on their pass or membership for that period."
1697
+ : "Nothing they hold pays for this service. Book it paid at the desk instead.", reason);
1698
+ }
1699
+ if (rule === "state_window_not_open" && what === "mark") {
1700
+ return noAppointment("not_started", "It can be marked once it has started.");
1701
+ }
1702
+ if (rule === "state_window_closed" || rule === "state_window_unknown") {
1703
+ return what === "mark"
1704
+ ? noAppointment("too_late", "It is more than 7 days since it ended: it can no longer be changed.")
1705
+ : noAppointment("too_late", "It has started: it can no longer be cancelled or moved.");
1706
+ }
1707
+ if (rule === "state_request_refused") {
1708
+ return noAppointment("too_late", "It can no longer be cancelled.");
1709
+ }
1710
+ if (rule === "state_final" || rule === "state_move_not_declared" || error.code === "conflict") {
1711
+ return noAppointment("changed", "It changed meanwhile. Look again.");
1712
+ }
1713
+ throw error;
1714
+ }
1715
+ const appointmentWarning = z.object({
1716
+ code: z.string().describe("unavailable, not_qualified, outside_hours, client_busy, uncovered"),
1717
+ message: z.string(),
1718
+ });
1719
+ /** The warnings the host made a staff write with (ADRs 0622, 0763): made anyway, and said so. */
1720
+ function warningsIn(record) {
1721
+ return Array.isArray(record.warnings)
1722
+ ? record.warnings.map((w) => ({
1723
+ code: String(w.code ?? ""),
1724
+ message: String(w.message ?? ""),
1725
+ }))
1726
+ : [];
1727
+ }
1728
+ const appointmentBooked = z.object({
1729
+ result: z.literal("booked"),
1730
+ appointmentId: z.string(),
1731
+ coachId: z.string().nullable(),
1732
+ roomId: z.string().nullable().describe("The room it takes: the first of the service's free"),
1733
+ startsAt: z.string().nullable(),
1734
+ endsAt: z.string().nullable(),
1735
+ holderId: z
1736
+ .string()
1737
+ .nullable()
1738
+ .describe("The pass or membership a session was spent from; null when paid at the desk"),
1739
+ paidAtDesk: z.boolean(),
1740
+ warnings: z
1741
+ .array(appointmentWarning)
1742
+ .describe("Made anyway: the coach away, not qualified, outside their open hours, client busy"),
1743
+ });
1744
+ /** How an appointment's write is answered: its time, coach, room, how it was paid, warnings. */
1745
+ function bookedAnswer(made) {
1746
+ const v = made.values;
1747
+ return {
1748
+ result: "booked",
1749
+ appointmentId: made.id,
1750
+ coachId: text(v.coach),
1751
+ roomId: text(v.room),
1752
+ startsAt: text(v.startsAt),
1753
+ endsAt: text(v.endsAt),
1754
+ holderId: text(v.holder),
1755
+ paidAtDesk: flag(v.paidOtherwise),
1756
+ warnings: warningsIn(made),
1757
+ };
1758
+ }
1759
+ /** A service, as staff may read it, with its length in minutes (or a refusal). */
1760
+ async function serviceOf(ctx, id) {
1761
+ const service = await ctx.ops.call("record.get", { object: SERVICE, id });
1762
+ return { service, length: num(service.values.length) ?? 0 };
1763
+ }
1764
+ /**
1765
+ * "Any coach": the first qualified coach the host says is free for the service at exactly that
1766
+ * start (open hours, time off, their other shifts with buffers, a room), or null.
1767
+ */
1768
+ async function firstFreeCoach(ctx, serviceId, startsAt, personId) {
1769
+ const free = await ctx.ops.call("staffing.free", {
1770
+ object: APPOINTMENT,
1771
+ kind: serviceId,
1772
+ from: new Date(startsAt).toISOString(),
1773
+ to: new Date(startsAt + MINUTE).toISOString(),
1774
+ client: personId,
1775
+ });
1776
+ const at = free.times.find((t) => Date.parse(t.startsAt) === startsAt);
1777
+ return at?.providers[0] ?? null;
1778
+ }
1779
+ /** The staff member calling (never from the input). */
1780
+ const staffCaller = (ctx) => (ctx.caller?.kind === "staff" ? ctx.caller : null);
1781
+ export const bookAppointment = defineTool({
1782
+ description: "Staff book a one-to-one session (an appointment) for a client: a service, a start time, " +
1783
+ "a coach (or none: the first qualified coach free then), and the client (personId; look " +
1784
+ "them up with findPeople). It ends after the service's length. The host refuses it when the " +
1785
+ "coach is on anything else then (a class, a duty or another session, the service's buffer " +
1786
+ "included), when no room the service needs is free, when the coach has no staff account, " +
1787
+ "or when nothing the client holds pays for the service; staff may book any time, outside " +
1788
+ "the booking windows and the coach's open hours, and are told what it was made with " +
1789
+ "(warnings: the coach away, not qualified, outside open hours, the client busy). It spends " +
1790
+ "one session of a pass or membership covering the service, unless paidAtDesk. The room is " +
1791
+ "the first of the service's rooms free then unless roomId names one. Audited.",
1792
+ input: z.object({
1793
+ serviceId: z.string().min(1).max(64),
1794
+ startsAt: z.string().datetime().describe("When it starts (ISO 8601)"),
1795
+ personId: z.string().min(1).max(64).describe("The client"),
1796
+ coachId: z.string().min(1).max(64).optional().describe("Left out: any coach free then"),
1797
+ roomId: z.string().min(1).max(64).optional(),
1798
+ holderId: z.string().min(1).max(64).optional().describe("A pass or membership to spend"),
1799
+ paidAtDesk: z.boolean().default(false).describe("Paid at the desk: it spends no session"),
1800
+ note: z.string().max(2000).optional().describe("A staff note, never shown to the client"),
1801
+ }),
1802
+ output: z.union([appointmentBooked, appointmentRefused]),
1803
+ risk: "write",
1804
+ // The desk books them (ADR 0600), as a manager of the coaches does (ADR 0764).
1805
+ permission: ["bookings:desk", "bookings:appointments"],
1806
+ async handler(input, ctx) {
1807
+ try {
1808
+ const { length } = await serviceOf(ctx, input.serviceId);
1809
+ const starts = Date.parse(input.startsAt);
1810
+ const coach = input.coachId ?? (await firstFreeCoach(ctx, input.serviceId, starts, input.personId));
1811
+ if (!coach) {
1812
+ return noAppointment("no_coach_free", "No qualified coach is free for this service at that time. Pick a coach to book them anyway.");
1813
+ }
1814
+ const staff = staffCaller(ctx);
1815
+ const made = await ctx.ops.call("record.create", {
1816
+ object: APPOINTMENT,
1817
+ values: {
1818
+ service: input.serviceId,
1819
+ person: input.personId,
1820
+ coach,
1821
+ startsAt: new Date(starts).toISOString(),
1822
+ endsAt: new Date(starts + length * MINUTE).toISOString(),
1823
+ ...(input.roomId ? { room: input.roomId } : {}),
1824
+ ...(input.holderId ? { holder: input.holderId } : {}),
1825
+ ...(input.paidAtDesk ? { paidOtherwise: true } : {}),
1826
+ ...(staff?.userId ? { bookedBy: staff.userId } : {}),
1827
+ ...(input.note ? { note: input.note } : {}),
1828
+ },
1829
+ });
1830
+ return bookedAnswer(made);
1831
+ }
1832
+ catch (error) {
1833
+ return appointmentRefusalOf(error, "book");
1834
+ }
1835
+ },
1836
+ });
1837
+ /** An appointment as staff read it, or a refusal when there is none. */
1838
+ async function appointmentOf(ctx, id) {
1839
+ try {
1840
+ return await ctx.ops.call("record.get", { object: APPOINTMENT, id });
1841
+ }
1842
+ catch (error) {
1843
+ if (error instanceof OpsCallError && error.code === "not_found") {
1844
+ return noAppointment("not_found", "No such appointment.");
1845
+ }
1846
+ throw error;
1847
+ }
1848
+ }
1849
+ const isRefusal = (v) => v.result === "refused";
1850
+ const APPOINTMENT_WORDS = {
1851
+ booked: "booked",
1852
+ pending: "held while paying",
1853
+ unpaid: "not paid yet",
1854
+ cancelled: "cancelled",
1855
+ late_cancelled: "cancelled late",
1856
+ excused: "cancelled with the session given back",
1857
+ attended: "attended",
1858
+ no_show: "a no-show",
1859
+ cancelled_by_us: "cancelled by the business",
1860
+ moved: "moved",
1861
+ expired: "expired",
1862
+ };
1863
+ const appointmentWords = (state) => APPOINTMENT_WORDS[state ?? ""] ?? state ?? "unknown";
1864
+ export const moveAppointment = defineTool({
1865
+ description: "Staff move a booked appointment to another start time, or another coach, or both, in one " +
1866
+ "batch: a new appointment is made at the new time and the old one is moved, the session it " +
1867
+ "spent moving with it (a session paid at the desk stays paid). The host refuses it whole, " +
1868
+ "nothing changed, when the coach is on anything else then, no room is free, or it has " +
1869
+ "started. Same warnings as booking. Only a booked appointment, before it starts.",
1870
+ input: z.object({
1871
+ appointmentId: z.string().min(1).max(64),
1872
+ startsAt: z.string().datetime().describe("The new start (ISO 8601)"),
1873
+ coachId: z.string().min(1).max(64).optional().describe("Left out: the same coach"),
1874
+ note: z.string().max(2000).optional(),
1875
+ }),
1876
+ output: z.union([
1877
+ appointmentBooked.extend({ fromAppointmentId: z.string() }),
1878
+ appointmentRefused,
1879
+ ]),
1880
+ risk: "write",
1881
+ permission: ["bookings:desk", "bookings:appointments"],
1882
+ async handler(input, ctx) {
1883
+ const old = await appointmentOf(ctx, input.appointmentId);
1884
+ if (isRefusal(old))
1885
+ return old;
1886
+ const state = text(old.values.state);
1887
+ if (state !== "booked") {
1888
+ return noAppointment("not_booked", `This appointment is ${appointmentWords(state)}: only a booked one moves.`, null, state);
1889
+ }
1890
+ const serviceId = text(old.values.service);
1891
+ const coach = input.coachId ?? text(old.values.coach);
1892
+ const starts = Date.parse(input.startsAt);
1893
+ if (starts === Date.parse(text(old.values.startsAt) ?? "") &&
1894
+ coach === text(old.values.coach)) {
1895
+ return noAppointment("same_time", "It is already at that time with that coach.");
1896
+ }
1897
+ const staff = staffCaller(ctx);
1898
+ try {
1899
+ const { length } = await serviceOf(ctx, serviceId);
1900
+ const values = {
1901
+ service: serviceId,
1902
+ person: text(old.values.person),
1903
+ coach,
1904
+ startsAt: new Date(starts).toISOString(),
1905
+ endsAt: new Date(starts + length * MINUTE).toISOString(),
1906
+ movedFrom: old.id,
1907
+ ...(staff?.userId ? { bookedBy: staff.userId } : {}),
1908
+ ...(input.note ? { note: input.note } : {}),
1909
+ };
1910
+ const room = text(old.values.room);
1911
+ let made;
1912
+ try {
1913
+ // Its own room first (the old claim goes in the same batch); if that is taken then, the
1914
+ // host gives it the first of the service's rooms that is free.
1915
+ made = await ctx.ops.call("record.create", {
1916
+ object: APPOINTMENT,
1917
+ values: { ...values, ...(room ? { room } : {}) },
1918
+ });
1919
+ }
1920
+ catch (error) {
1921
+ if (!room || detailsOf(error).rule !== "room_taken")
1922
+ throw error;
1923
+ made = await ctx.ops.call("record.create", { object: APPOINTMENT, values });
1924
+ }
1925
+ return { ...bookedAnswer(made), fromAppointmentId: old.id };
1926
+ }
1927
+ catch (error) {
1928
+ const refusal = appointmentRefusalOf(error, "book");
1929
+ if (refusal.reason === "too_late") {
1930
+ return noAppointment("started", "It has started: it can no longer be moved.");
1931
+ }
1932
+ return refusal;
1933
+ }
1934
+ },
1935
+ });
1936
+ export const cancelAppointment = defineTool({
1937
+ description: "Staff cancel a booked appointment, in time or late by the host's clock: before the " +
1938
+ "service's late-cancel point (24 hours before unless the service sets its own) it is " +
1939
+ "cancelled and its session given back; from then until it starts it is cancelled late and " +
1940
+ "the session is used, with no fee. With keepUse it is cancelled late whatever the time. " +
1941
+ "After it starts it cannot be cancelled. To give a session back after the late point a " +
1942
+ "person excuses it (excuseAppointment); the business cancelling its own appointment is " +
1943
+ "cancelAppointmentByUs. Without confirm it only says which it would be.",
1944
+ input: z.object({
1945
+ appointmentId: z.string().min(1).max(64),
1946
+ confirm: z.boolean().default(false),
1947
+ keepUse: z.boolean().default(false),
1948
+ note: z.string().max(2000).optional(),
1949
+ }),
1950
+ output: z.union([
1951
+ z.object({
1952
+ result: z.enum(["preview", "cancelled", "late_cancelled"]),
1953
+ appointmentId: z.string(),
1954
+ state: z.enum(["cancelled", "late_cancelled"]),
1955
+ late: z.boolean().describe("A late cancel keeps the session it spent"),
1956
+ }),
1957
+ appointmentRefused,
1958
+ ]),
1959
+ risk: "write",
1960
+ permission: ["bookings:desk", "bookings:appointments"],
1961
+ async handler(input, ctx) {
1962
+ const say = (state, done) => ({
1963
+ result: done ? state : "preview",
1964
+ appointmentId: input.appointmentId,
1965
+ state,
1966
+ late: state === "late_cancelled",
1967
+ });
1968
+ try {
1969
+ if (!input.confirm) {
1970
+ if (input.keepUse)
1971
+ return say("late_cancelled", false);
1972
+ // The host's dry run: the state "cancel" would enter now (ADR 0503).
1973
+ const resolved = await ctx.ops.call("state.resolve", {
1974
+ object: APPOINTMENT,
1975
+ id: input.appointmentId,
1976
+ request: "cancel",
1977
+ });
1978
+ return say(resolved.state === "late_cancelled" ? "late_cancelled" : "cancelled", false);
1979
+ }
1980
+ const after = await ctx.ops.call("record.update", {
1981
+ object: APPOINTMENT,
1982
+ id: input.appointmentId,
1983
+ from: "booked",
1984
+ values: {
1985
+ state: input.keepUse ? "late_cancelled" : "cancel",
1986
+ ...(input.note ? { note: input.note } : {}),
1987
+ },
1988
+ });
1989
+ return say(after.values.state === "late_cancelled" ? "late_cancelled" : "cancelled", true);
1990
+ }
1991
+ catch (error) {
1992
+ return appointmentRefusalOf(error, "cancel");
1993
+ }
1994
+ },
1995
+ });
1996
+ export const cancelAppointmentByUs = defineTool({
1997
+ description: "The business cancels an appointment that is booked, held while paying or not paid yet " +
1998
+ "(the coach is ill, the room is closed): it is cancelled by the business and the session " +
1999
+ "it spent is given back, whatever the time, with the reason kept. A person's act: the " +
2000
+ "assistant, MCP clients and automations may ask, and it waits for a person to approve it. " +
2001
+ "Fails with the reason when it cannot be done, so an approved request shows it did not " +
2002
+ "apply. (The client's email comes in a later release.)",
2003
+ input: z.object({
2004
+ appointmentId: z.string().min(1).max(64),
2005
+ reason: z.string().trim().min(3).max(2000),
2006
+ }),
2007
+ output: z.object({ result: z.literal("cancelled_by_us"), appointmentId: z.string() }),
2008
+ risk: "destructive",
2009
+ personApproves: true,
2010
+ permission: "bookings:appointments",
2011
+ async handler(input, ctx) {
2012
+ const old = await appointmentOf(ctx, input.appointmentId);
2013
+ if (isRefusal(old))
2014
+ throw new OpsCallError("not_found", old.message, { reason: "not_found" });
2015
+ const state = text(old.values.state) ?? "";
2016
+ if (!["booked", "pending", "unpaid"].includes(state)) {
2017
+ throw new OpsCallError("conflict", `This appointment is ${appointmentWords(state)}: only one still to come is cancelled by the business.`, { reason: "not_live", state });
2018
+ }
2019
+ await ctx.ops.call("record.update", {
2020
+ object: APPOINTMENT,
2021
+ id: input.appointmentId,
2022
+ from: state,
2023
+ values: { state: "cancelled_by_us", cancelledReason: input.reason },
2024
+ });
2025
+ return { result: "cancelled_by_us", appointmentId: input.appointmentId };
2026
+ },
2027
+ });
2028
+ export const markAppointment = defineTool({
2029
+ description: "Mark an appointment once it has started: attended (they came) or no_show (they did not; " +
2030
+ "the session is used, with no fee). Either may be corrected into the other for 7 days " +
2031
+ "after it ends. The host marks one nobody marked as attended 30 minutes after it ends. " +
2032
+ "Who marked it and when are kept. To give a no-show's session back a person excuses it.",
2033
+ input: z.object({
2034
+ appointmentId: z.string().min(1).max(64),
2035
+ mark: z.enum(["attended", "no_show"]),
2036
+ }),
2037
+ output: z.union([
2038
+ z.object({
2039
+ result: z.enum(["attended", "no_show"]),
2040
+ appointmentId: z.string(),
2041
+ message: z.string(),
2042
+ }),
2043
+ appointmentRefused,
2044
+ ]),
2045
+ risk: "write",
2046
+ permission: ["bookings:desk", "bookings:appointments"],
2047
+ async handler(input, ctx) {
2048
+ const record = await appointmentOf(ctx, input.appointmentId);
2049
+ if (isRefusal(record))
2050
+ return record;
2051
+ const state = text(record.values.state) ?? "";
2052
+ const from = input.mark === "attended" ? ["booked", "no_show"] : ["booked", "attended"];
2053
+ if (state === input.mark) {
2054
+ return {
2055
+ result: input.mark,
2056
+ appointmentId: record.id,
2057
+ message: `Already marked ${appointmentWords(state)}.`,
2058
+ };
2059
+ }
2060
+ if (!from.includes(state)) {
2061
+ return noAppointment("not_booked", `This appointment is ${appointmentWords(state)}: it cannot be marked.`, null, state);
2062
+ }
2063
+ const staff = staffCaller(ctx);
2064
+ try {
2065
+ await ctx.ops.call("record.update", {
2066
+ object: APPOINTMENT,
2067
+ id: record.id,
2068
+ from: state,
2069
+ values: {
2070
+ state: input.mark,
2071
+ markedAt: new Date().toISOString(),
2072
+ markedBy: staff?.userId ?? null,
2073
+ markedByName: staff?.name || null,
2074
+ },
2075
+ });
2076
+ }
2077
+ catch (error) {
2078
+ return appointmentRefusalOf(error, "mark");
2079
+ }
2080
+ return {
2081
+ result: input.mark,
2082
+ appointmentId: record.id,
2083
+ message: input.mark === "attended"
2084
+ ? "Marked: they came."
2085
+ : "Marked: they did not come. The session stays used, with no fee.",
2086
+ };
2087
+ },
2088
+ });
2089
+ export const excuseAppointment = defineTool({
2090
+ description: "A person on the staff gives the session back for a late cancel or a no-show (a client " +
2091
+ "who was ill): it becomes excused and the pass or membership gets its session back. A " +
2092
+ "person's own act: the assistant, MCP clients, automations and other code cannot call it. " +
2093
+ "The reason is kept on the appointment and in the audit log.",
2094
+ input: z.object({
2095
+ appointmentId: z.string().min(1).max(64),
2096
+ reason: z.string().trim().min(3).max(2000),
2097
+ }),
2098
+ output: z.union([
2099
+ z.object({ result: z.literal("excused"), appointmentId: z.string() }),
2100
+ appointmentRefused,
2101
+ ]),
2102
+ risk: "destructive",
2103
+ humanOnly: true,
2104
+ permission: ["bookings:desk", "bookings:appointments"],
2105
+ async handler(input, ctx) {
2106
+ const record = await appointmentOf(ctx, input.appointmentId);
2107
+ if (isRefusal(record))
2108
+ return record;
2109
+ const state = text(record.values.state) ?? "";
2110
+ if (state !== "late_cancelled" && state !== "no_show") {
2111
+ return noAppointment("not_booked", `This appointment is ${appointmentWords(state)}: only a late cancel or a no-show is excused.`, null, state);
2112
+ }
2113
+ try {
2114
+ await ctx.ops.call("record.update", {
2115
+ object: APPOINTMENT,
2116
+ id: record.id,
2117
+ from: state,
2118
+ values: { state: "excused", cancelledReason: `Session given back: ${input.reason}` },
2119
+ });
2120
+ return { result: "excused", appointmentId: record.id };
2121
+ }
2122
+ catch (error) {
2123
+ return appointmentRefusalOf(error, "cancel");
2124
+ }
2125
+ },
2126
+ });
2127
+ export const reassignAppointment = defineTool({
2128
+ description: "Give an appointment still to come to another coach (decision 7: the coach is off or " +
2129
+ "away), keeping its time, room and how it was paid. The host refuses it when that coach is " +
2130
+ "on anything else then (buffers included) or has no staff account, and says what it was " +
2131
+ "made with (warnings: not qualified for the service, away, outside their open hours). " +
2132
+ "(The client's email comes in a later release.)",
2133
+ input: z.object({
2134
+ appointmentId: z.string().min(1).max(64),
2135
+ coachId: z.string().min(1).max(64),
2136
+ }),
2137
+ output: z.union([appointmentBooked, appointmentRefused]),
2138
+ risk: "write",
2139
+ // Who works a session is a person's to change (ADR 0626): an AI's call waits for a person.
2140
+ personApproves: true,
2141
+ permission: "bookings:appointments",
2142
+ async handler(input, ctx) {
2143
+ const record = await appointmentOf(ctx, input.appointmentId);
2144
+ if (isRefusal(record))
2145
+ return record;
2146
+ const state = text(record.values.state) ?? "";
2147
+ if (!["booked", "pending", "unpaid"].includes(state)) {
2148
+ return noAppointment("not_booked", `This appointment is ${appointmentWords(state)}: only one still to come is reassigned.`, null, state);
2149
+ }
2150
+ if (Date.parse(text(record.values.startsAt) ?? "") <= Date.now()) {
2151
+ return noAppointment("started", "It has started: it can no longer be reassigned.");
2152
+ }
2153
+ if (text(record.values.coach) === input.coachId) {
2154
+ return noAppointment("same_time", "It is already with that coach.");
2155
+ }
2156
+ try {
2157
+ const after = await ctx.ops.call("record.update", {
2158
+ object: APPOINTMENT,
2159
+ id: record.id,
2160
+ values: { coach: input.coachId },
2161
+ });
2162
+ return bookedAnswer(after);
2163
+ }
2164
+ catch (error) {
2165
+ return appointmentRefusalOf(error, "book");
2166
+ }
2167
+ },
2168
+ });
2169
+ // --- The coach's day ------------------------------------------------------------------------------
2170
+ const dayItem = z.object({
2171
+ kind: z.enum(["class", "appointment", "shift"]),
2172
+ object: z.string(),
2173
+ id: z.string(),
2174
+ title: z.string().nullable(),
2175
+ startsAt: z.string().nullable(),
2176
+ endsAt: z.string().nullable(),
2177
+ room: z.string().nullable(),
2178
+ state: z.string().nullable(),
2179
+ service: z.string().nullable().describe("An appointment's service"),
2180
+ client: named.describe("An appointment's client"),
2181
+ });
2182
+ export const coachDay = defineTool({
2183
+ description: "The coaches' day for staff: for each coach (or one, with coachId), their classes, " +
2184
+ "appointments (service, client, room, state) and other shifts (duties) on one local date " +
2185
+ "of the organisation, in start order. Classes and appointments cancelled, moved or done " +
2186
+ "are left out but for attended and no-show sessions. Read-only.",
2187
+ input: z.object({
2188
+ date: z
2189
+ .string()
2190
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
2191
+ .describe("The local date, YYYY-MM-DD"),
2192
+ coachId: z.string().min(1).max(64).optional(),
2193
+ }),
2194
+ output: z.object({
2195
+ date: z.string(),
2196
+ timeZone: z.string(),
2197
+ coaches: z.array(z.object({
2198
+ coachId: z.string(),
2199
+ name: z.string().nullable(),
2200
+ items: z.array(dayItem),
2201
+ })),
2202
+ }),
2203
+ risk: "read",
2204
+ permission: ["bookings:desk", "bookings:appointments"],
2205
+ async handler(input, ctx) {
2206
+ const coachFilter = input.coachId ? [{ field: "id", op: "eq", value: input.coachId }] : [];
2207
+ const coaches = await ctx.ops.call("record.list", {
2208
+ object: COACH,
2209
+ filter: input.coachId ? { and: coachFilter } : { field: "active", op: "eq", value: true },
2210
+ sort: { field: "name", direction: "asc" },
2211
+ limit: 100,
2212
+ });
2213
+ const account = input.coachId ? text(coaches.items[0]?.values.user) : null;
2214
+ // The roster (ADR 0626): every live shift of the day, whatever object, in the org's zone. A
2215
+ // coach's duties come from it; its appointments show their service, never the client.
2216
+ const roster = await ctx.ops.call("staffing.week", {
2217
+ from: input.date,
2218
+ to: input.date,
2219
+ ...(account ? { account } : {}),
2220
+ });
2221
+ const zone = roster.zone;
2222
+ const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
2223
+ const range = [
2224
+ {
2225
+ field: "startsAt",
2226
+ op: "gte",
2227
+ value: new Date(localMidnight(input.date, zone)).toISOString(),
2228
+ },
2229
+ { field: "startsAt", op: "lt", value: new Date(localMidnight(next, zone)).toISOString() },
2230
+ ];
2231
+ const ids = coaches.items.map((c) => c.id);
2232
+ const byCoach = ids.length ? [{ field: "coach", op: "in", value: ids }] : [];
2233
+ const [classes, appointments] = ids.length
2234
+ ? await Promise.all([CLASS, APPOINTMENT].map((object) => ctx.ops.call("record.list", {
2235
+ object,
2236
+ filter: { and: [...range, ...byCoach] },
2237
+ sort: { field: "startsAt", direction: "asc" },
2238
+ limit: 200,
2239
+ })))
2240
+ : [{ items: [] }, { items: [] }];
2241
+ const rooms = await byIds(ctx, "record.list", ROOM, [...(classes?.items ?? []), ...(appointments?.items ?? [])].map((r) => text(r.values.room)));
2242
+ const services = await byIds(ctx, "record.list", SERVICE, (appointments?.items ?? []).map((a) => text(a.values.service)));
2243
+ const names = new Map();
2244
+ for (const id of new Set((appointments?.items ?? []).map((a) => text(a.values.person)))) {
2245
+ if (!id)
2246
+ continue;
2247
+ try {
2248
+ const person = await ctx.ops.call("person.get", {
2249
+ id,
2250
+ });
2251
+ names.set(id, person?.displayName ?? null);
2252
+ }
2253
+ catch (error) {
2254
+ if (!(error instanceof OpsCallError) || error.code !== "not_found")
2255
+ throw error;
2256
+ names.set(id, null);
2257
+ }
2258
+ }
2259
+ const roomName = (id) => text(rooms.get(text(id) ?? "")?.name);
2260
+ const shown = (object, state) => object === CLASS
2261
+ ? state !== "cancelled"
2262
+ : ["booked", "pending", "unpaid", "attended", "no_show"].includes(state ?? "");
2263
+ const items = new Map(ids.map((id) => [id, []]));
2264
+ for (const [object, page] of [
2265
+ [CLASS, classes],
2266
+ [APPOINTMENT, appointments],
2267
+ ]) {
2268
+ for (const r of page?.items ?? []) {
2269
+ const v = r.values;
2270
+ const coachId = text(v.coach);
2271
+ const state = text(v.state);
2272
+ if (!coachId || !shown(object, state))
2273
+ continue;
2274
+ const personId = text(v.person);
2275
+ items.get(coachId)?.push({
2276
+ kind: object === CLASS ? "class" : "appointment",
2277
+ object,
2278
+ id: r.id,
2279
+ title: text(v.title) ?? text(r.title),
2280
+ startsAt: text(v.startsAt),
2281
+ endsAt: text(v.endsAt),
2282
+ room: roomName(v.room),
2283
+ state,
2284
+ service: object === APPOINTMENT ? text(services.get(text(v.service) ?? "")?.title) : null,
2285
+ client: object === APPOINTMENT && personId
2286
+ ? { id: personId, name: names.get(personId) ?? null }
2287
+ : null,
2288
+ });
2289
+ }
2290
+ }
2291
+ // Other packs' shifts (a duty), by the coach profile's staff account.
2292
+ const byAccount = new Map(coaches.items
2293
+ .map((c) => [text(c.values.user), c.id])
2294
+ .filter((pair) => pair[0] !== null));
2295
+ for (const s of roster.shifts) {
2296
+ if (s.object.startsWith("bookings.") || !s.account)
2297
+ continue;
2298
+ const coachId = byAccount.get(s.account);
2299
+ if (!coachId)
2300
+ continue;
2301
+ items.get(coachId)?.push({
2302
+ kind: "shift",
2303
+ object: s.object,
2304
+ id: s.id,
2305
+ title: s.title,
2306
+ startsAt: s.startsAt,
2307
+ endsAt: s.endsAt,
2308
+ room: s.place,
2309
+ state: null,
2310
+ service: null,
2311
+ client: null,
2312
+ });
2313
+ }
2314
+ return {
2315
+ date: input.date,
2316
+ timeZone: zone,
2317
+ coaches: coaches.items.map((c) => ({
2318
+ coachId: c.id,
2319
+ name: text(c.values.name),
2320
+ items: (items.get(c.id) ?? []).sort((a, b) => (a.startsAt ?? "").localeCompare(b.startsAt ?? "")),
2321
+ })),
2322
+ };
2323
+ },
2324
+ });