@composable-os/pack-bookings 0.0.0-stage → 0.1.0-beta.9

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 ADDED
@@ -0,0 +1,798 @@
1
+ // The Bookings tools (stage 31a step 3). They become operations x.bookings.<tool>, run in the
2
+ // sandbox, and reach the host only through ctx.ops. None of them holds a rule: when booking opens
3
+ // and closes, whether a cancel is late, which class types only staff book, the places left, one
4
+ // booking per person per class and the use a booking spends are all the host's (index.ts). A tool
5
+ // asks, and reports what the host answered, in words a member can be shown.
6
+ import { defineTool, OpsCallError, z } from "@composable-os/sdk";
7
+ const CLASS = "bookings.class";
8
+ const BOOKING = "bookings.booking";
9
+ const COACH = "bookings.coach";
10
+ const ROOM = "bookings.room";
11
+ const CLASS_TYPE = "programs.classtype";
12
+ const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
13
+ const num = (value) => typeof value === "number" ? value : value == null || value === "" ? null : Number(value);
14
+ const flag = (value) => value === true || value === 1 || value === "1";
15
+ /** A class's own time zone: its times are this zone's (ADR 0460). */
16
+ const timeZone = z
17
+ .string()
18
+ .nullable()
19
+ .describe("The class's IANA time zone: show its times in this zone.");
20
+ const places = z.object({
21
+ status: z.enum(["available", "low", "sold_out"]),
22
+ available: z.number().nullable().optional().describe("Places left; null when unlimited"),
23
+ });
24
+ const named = z.object({ id: z.string(), name: z.string().nullable() }).nullable();
25
+ const classOutput = z.object({
26
+ id: z.string(),
27
+ title: z.string().nullable().describe("The class's name (its class type's, unless renamed)"),
28
+ classType: z.string().nullable(),
29
+ startsAt: z.string().nullable().describe("When it starts (ISO 8601, UTC)"),
30
+ endsAt: z.string().nullable(),
31
+ timeZone,
32
+ room: named,
33
+ coach: named.and(z.object({ photo: z.string().nullable() }).partial()).nullable(),
34
+ notes: z.string().nullable(),
35
+ places,
36
+ });
37
+ /** Records of `object` by id, through a read operation the caller may use (public or my). */
38
+ async function byIds(ctx, operation, object, ids) {
39
+ const wanted = [...new Set(ids.filter((id) => Boolean(id)))];
40
+ if (!wanted.length)
41
+ return new Map();
42
+ const found = await ctx.ops.call(operation, {
43
+ object,
44
+ filter: { field: "id", op: "in", value: wanted },
45
+ limit: Math.min(wanted.length, 200),
46
+ });
47
+ return new Map(found.items.map((item) => [item.id, item.values]));
48
+ }
49
+ /** What the host says of a class's places, as an outsider may be told (`show: "exact"`). */
50
+ async function placesOf(ctx, id) {
51
+ const view = await ctx.ops.call("capacity.get", { object: CLASS, id });
52
+ return {
53
+ status: view.status,
54
+ ...(view.available === undefined ? {} : { available: view.available }),
55
+ };
56
+ }
57
+ async function describeClasses(ctx, classes) {
58
+ // Coaches and rooms are public (their names); a class's other people are never read here.
59
+ const coaches = await byIds(ctx, "public.list", COACH, classes.map((c) => text(c.values.coach)));
60
+ const rooms = await byIds(ctx, "public.list", ROOM, classes.map((c) => text(c.values.room)));
61
+ const out = [];
62
+ for (const klass of classes) {
63
+ const v = klass.values;
64
+ const coachId = text(v.coach);
65
+ const roomId = text(v.room);
66
+ const coach = coachId ? coaches.get(coachId) : undefined;
67
+ const room = roomId ? rooms.get(roomId) : undefined;
68
+ out.push({
69
+ id: klass.id,
70
+ title: text(v.title) ?? text(klass.title),
71
+ classType: text(v.classType),
72
+ startsAt: text(v.startsAt),
73
+ endsAt: text(v.endsAt),
74
+ timeZone: text(v.timezone),
75
+ room: roomId ? { id: roomId, name: text(room?.name) } : null,
76
+ coach: coachId ? { id: coachId, name: text(coach?.name), photo: text(coach?.photo) } : null,
77
+ notes: text(v.notes),
78
+ places: await placesOf(ctx, klass.id),
79
+ });
80
+ }
81
+ return out;
82
+ }
83
+ // --- Why the host refused -------------------------------------------------------------------------
84
+ const refusalReason = z
85
+ .enum([
86
+ "not_open",
87
+ "closed",
88
+ "staff_only",
89
+ "no_use",
90
+ "already_booked",
91
+ "full",
92
+ "too_late",
93
+ "not_found",
94
+ "changed",
95
+ "not_running",
96
+ "person_exists",
97
+ "possible_duplicates",
98
+ ])
99
+ .describe("not_open: booking has not opened yet (see opensAt). closed: booking has closed. " +
100
+ "not_running: the class was cancelled or is over. person_exists: someone on file has that " +
101
+ "email (see people). possible_duplicates: people on file may be this person (see people; " +
102
+ "book one of them, or ask again with confirmNew). " +
103
+ "staff_only: this class is booked by the gym. no_use: nothing the " +
104
+ "member holds can pay for it (see detail). already_booked: they already have a place. " +
105
+ "full: no places left. too_late: the class has started, so it cannot be cancelled. " +
106
+ "not_found: no such class or booking of theirs. changed: it changed meanwhile; try again.");
107
+ const refused = z.object({
108
+ result: z.literal("refused"),
109
+ reason: refusalReason,
110
+ message: z.string(),
111
+ detail: z
112
+ .string()
113
+ .nullable()
114
+ .describe("The host's reason for an allowance refusal (no_uses_left, ended, not_covered…)"),
115
+ opensAt: z.string().nullable(),
116
+ closesAt: z.string().nullable(),
117
+ people: z
118
+ .array(z.object({ id: z.string(), name: z.string(), reasons: z.array(z.string()) }))
119
+ .optional()
120
+ .describe("For person_exists and possible_duplicates: who is already on file"),
121
+ });
122
+ /** A host refusal as a member can be told it, or the error itself when it is not one. */
123
+ function refusalOf(error, what, expect) {
124
+ if (!(error instanceof OpsCallError))
125
+ throw error;
126
+ const details = (error.details ?? {});
127
+ const rule = typeof details.rule === "string" ? details.rule : "";
128
+ const times = {
129
+ opensAt: text(details.opensAt),
130
+ closesAt: text(details.closesAt),
131
+ };
132
+ const out = (reason, message, detail = null) => ({
133
+ result: "refused",
134
+ reason,
135
+ message,
136
+ detail,
137
+ ...times,
138
+ });
139
+ if (error.code === "not_found") {
140
+ return out("not_found", what === "book" ? "That class cannot be booked." : "No such booking.");
141
+ }
142
+ if (rule === "state_window_not_open") {
143
+ // A cancel asked for as late, before the late point: it is in time, say so (not "opens").
144
+ if (what === "cancel" && expect === "late_cancelled") {
145
+ return out("changed", "It is not late yet: cancelling now is in time and gives the class back. Look again.");
146
+ }
147
+ return out("not_open", "Booking for this class has not opened yet.");
148
+ }
149
+ if (rule === "state_closed") {
150
+ return out("not_running", "This class was cancelled or is over: it cannot be booked.");
151
+ }
152
+ if (rule === "person_exists" || rule === "possible_duplicates") {
153
+ const people = Array.isArray(details.people)
154
+ ? details.people.map((p) => ({
155
+ id: String(p.id ?? ""),
156
+ name: String(p.title ?? ""),
157
+ reasons: Array.isArray(p.reasons) ? p.reasons.map(String) : [],
158
+ }))
159
+ : [];
160
+ return {
161
+ ...out(rule, rule === "person_exists"
162
+ ? "Someone on file already has that email address: book them instead."
163
+ : "This may be someone already on file: book them, or confirm this is someone new."),
164
+ people,
165
+ };
166
+ }
167
+ if (rule === "state_window_closed" || rule === "state_window_unknown") {
168
+ return what === "book"
169
+ ? out("closed", "Booking for this class has closed.")
170
+ : out("too_late", "The class has started: it can no longer be cancelled.");
171
+ }
172
+ if (rule === "state_request_refused") {
173
+ return out("too_late", "This booking can no longer be cancelled.");
174
+ }
175
+ if (rule === "state_staff_only") {
176
+ return out("staff_only", "This class is booked by the gym. Ask at the desk.");
177
+ }
178
+ if (rule === "allowance") {
179
+ const reason = text(details.reason);
180
+ return out("no_use", reason === "no_uses_left"
181
+ ? "There are no classes left on your membership or pass for that week or period."
182
+ : "Nothing you hold can pay for this class.", reason);
183
+ }
184
+ if (rule === "unique")
185
+ return out("already_booked", "You already have a place in this class.");
186
+ if (rule === "capacity")
187
+ return out("full", "This class is full.");
188
+ if (error.code === "conflict") {
189
+ return out("changed", "It changed while you were booking. Look again and try once more.");
190
+ }
191
+ throw error;
192
+ }
193
+ // --- The timetable (members and the public) --------------------------------------------------------
194
+ const DAY = 86_400_000;
195
+ export const timetable = defineTool({
196
+ description: "The gym's timetable: its scheduled classes between two times (default: the next 7 days), " +
197
+ "soonest first, each with its name, class type, start and end in its own time zone, coach, " +
198
+ "room, notes for members and how many places are left. Filter by class type or coach. Only " +
199
+ "what the public may read: never who is booked. Booking rules (when booking opens, whether " +
200
+ "the gym books it) are the host's: book answers with them. Read-only.",
201
+ input: z.object({
202
+ from: z.string().datetime().optional().describe("From this time (ISO 8601). Default: now"),
203
+ to: z.string().datetime().optional().describe("Until this time. Default: 7 days after from"),
204
+ classType: z.string().min(1).max(64).optional(),
205
+ coach: z.string().min(1).max(64).optional(),
206
+ limit: z.number().int().min(1).max(100).default(50),
207
+ }),
208
+ output: z.object({ classes: z.array(classOutput) }),
209
+ risk: "read",
210
+ audiences: ["customer", "public"],
211
+ async handler(input, ctx) {
212
+ const from = input.from ?? new Date().toISOString();
213
+ const to = input.to ?? new Date(Date.parse(from) + 7 * DAY).toISOString();
214
+ const conditions = [
215
+ { field: "startsAt", op: "gte", value: from },
216
+ { field: "startsAt", op: "lt", value: to },
217
+ ...(input.classType ? [{ field: "classType", op: "eq", value: input.classType }] : []),
218
+ ...(input.coach ? [{ field: "coach", op: "eq", value: input.coach }] : []),
219
+ ];
220
+ // The seam decides which classes: the public reads a class only while it is scheduled.
221
+ const page = await ctx.ops.call("public.list", {
222
+ object: CLASS,
223
+ filter: { and: conditions },
224
+ sort: { field: "startsAt", direction: "asc" },
225
+ limit: input.limit,
226
+ });
227
+ return { classes: await describeClasses(ctx, page.items) };
228
+ },
229
+ });
230
+ export const classGet = defineTool({
231
+ description: "One scheduled class of the timetable: its name, class type, start and end in its own time " +
232
+ "zone, coach, room, notes for members and how many places are left. Not found once it is " +
233
+ "not scheduled. Never who is booked. Read-only.",
234
+ input: z.object({ classId: z.string().min(1).max(64) }),
235
+ output: z.object({ class: classOutput }),
236
+ risk: "read",
237
+ audiences: ["customer", "public"],
238
+ async handler(input, ctx) {
239
+ const klass = await ctx.ops.call("public.get", {
240
+ object: CLASS,
241
+ id: input.classId,
242
+ });
243
+ const [described] = await describeClasses(ctx, [klass]);
244
+ return { class: described };
245
+ },
246
+ });
247
+ // --- Booking and cancelling (a signed-in member) ----------------------------------------------------
248
+ const booked = z.object({
249
+ result: z.literal("booked"),
250
+ bookingId: z.string(),
251
+ classId: z.string(),
252
+ holderId: z
253
+ .string()
254
+ .nullable()
255
+ .describe("The membership or pass a use was spent from; null when paid at the desk"),
256
+ });
257
+ export const book = defineTool({
258
+ description: "Book the signed-in member into a class with what they already hold (a membership or a " +
259
+ "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.",
263
+ input: z.object({
264
+ classId: z.string().min(1).max(64),
265
+ holderId: z
266
+ .string()
267
+ .min(1)
268
+ .max(64)
269
+ .optional()
270
+ .describe("A membership or pass of theirs to spend, when they hold several"),
271
+ }),
272
+ output: z.union([booked, refused]),
273
+ risk: "write",
274
+ audiences: ["customer"],
275
+ async handler(input, ctx) {
276
+ try {
277
+ // 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
+ });
286
+ return {
287
+ result: "booked",
288
+ bookingId: made.id,
289
+ classId: input.classId,
290
+ holderId: text(made.values.holder),
291
+ };
292
+ }
293
+ catch (error) {
294
+ return refusalOf(error, "book");
295
+ }
296
+ },
297
+ });
298
+ export const cancel = defineTool({
299
+ description: "Cancel one of the signed-in member's bookings. First without `confirm`: the host says " +
300
+ "whether a cancel now is in time (`cancelled`, the class's use given back) or late " +
301
+ "(`late_cancelled`, the use kept), by its clock. Then with `confirm: true` and `expect` set " +
302
+ "to that answer: cancelled as said, or refused if it has become late meanwhile, so a member " +
303
+ "never loses a use they were told they would keep. After the class starts it cannot be " +
304
+ "cancelled.",
305
+ input: z.object({
306
+ bookingId: z.string().min(1).max(64),
307
+ confirm: z.boolean().default(false),
308
+ expect: z
309
+ .enum(["cancelled", "late_cancelled"])
310
+ .optional()
311
+ .describe("What the preview said; with confirm, cancel only into this state"),
312
+ }),
313
+ output: z.union([
314
+ z.object({
315
+ result: z.enum(["preview", "cancelled", "late_cancelled"]),
316
+ state: z.enum(["cancelled", "late_cancelled"]),
317
+ late: z.boolean().describe("A late cancel keeps the use the booking spent"),
318
+ message: z.string(),
319
+ }),
320
+ refused,
321
+ ]),
322
+ risk: "write",
323
+ audiences: ["customer"],
324
+ async handler(input, ctx) {
325
+ const say = (state, done) => ({
326
+ result: done ? state : "preview",
327
+ state,
328
+ 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.",
336
+ });
337
+ try {
338
+ if (!input.confirm) {
339
+ // The host's dry run: the state "cancel" would enter now (ADR 0503).
340
+ const resolved = await ctx.ops.call("state.resolve", {
341
+ object: BOOKING,
342
+ id: input.bookingId,
343
+ request: "cancel",
344
+ });
345
+ return say(resolved.state === "late_cancelled" ? "late_cancelled" : "cancelled", false);
346
+ }
347
+ // From booked, or not at all (ADR 0437); into the state they were told, or the host's pick.
348
+ const after = await ctx.ops.call("my.update", {
349
+ object: BOOKING,
350
+ id: input.bookingId,
351
+ from: "booked",
352
+ values: { state: input.expect ?? "cancel" },
353
+ });
354
+ return say(after.values.state === "late_cancelled" ? "late_cancelled" : "cancelled", true);
355
+ }
356
+ catch (error) {
357
+ const refusal = refusalOf(error, "cancel", input.expect);
358
+ // Asked for "in time" and it is now late: say so, so they can confirm the late cancel.
359
+ if (refusal.reason === "too_late" && input.expect === "cancelled") {
360
+ return {
361
+ ...refusal,
362
+ reason: "changed",
363
+ message: "It is now too late to cancel in time. Cancelling now keeps the class used.",
364
+ };
365
+ }
366
+ return refusal;
367
+ }
368
+ },
369
+ });
370
+ export const mine = defineTool({
371
+ 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.",
375
+ input: z.object({
376
+ state: z.enum(["booked", "cancelled", "late_cancelled"]).optional(),
377
+ upcoming: z.boolean().default(true).describe("Only classes that have not started"),
378
+ limit: z.number().int().min(1).max(100).default(50),
379
+ }),
380
+ output: z.object({
381
+ bookings: z.array(z.object({
382
+ id: z.string(),
383
+ state: z.string().nullable(),
384
+ holderId: z.string().nullable(),
385
+ classId: z.string().nullable(),
386
+ title: z.string().nullable(),
387
+ startsAt: z.string().nullable(),
388
+ endsAt: z.string().nullable(),
389
+ timeZone,
390
+ classState: z.string().nullable().describe("scheduled, cancelled or done"),
391
+ coach: z.string().nullable(),
392
+ room: z.string().nullable(),
393
+ })),
394
+ }),
395
+ risk: "read",
396
+ audiences: ["customer"],
397
+ async handler(input, ctx) {
398
+ // The seam gives a member their own bookings only; no filter here decides whose they are.
399
+ const page = await ctx.ops.call("my.list", {
400
+ object: BOOKING,
401
+ ...(input.state ? { filter: { field: "state", op: "eq", value: input.state } } : {}),
402
+ limit: input.limit,
403
+ });
404
+ // Their bookings' classes, whatever the class's state (customerVia), and only those.
405
+ const classes = await byIds(ctx, "my.list", CLASS, page.items.map((b) => text(b.values.class)));
406
+ const coaches = await byIds(ctx, "public.list", COACH, [...classes.values()].map((c) => text(c.coach)));
407
+ const rooms = await byIds(ctx, "public.list", ROOM, [...classes.values()].map((c) => text(c.room)));
408
+ const now = Date.now();
409
+ const bookings = page.items
410
+ .map((booking) => {
411
+ const classId = text(booking.values.class);
412
+ const klass = (classId && classes.get(classId)) || {};
413
+ const coachId = text(klass.coach);
414
+ const roomId = text(klass.room);
415
+ return {
416
+ id: booking.id,
417
+ state: text(booking.values.state),
418
+ holderId: text(booking.values.holder),
419
+ classId,
420
+ title: text(klass.title),
421
+ startsAt: text(klass.startsAt),
422
+ endsAt: text(klass.endsAt),
423
+ timeZone: text(klass.timezone),
424
+ classState: text(klass.state),
425
+ coach: coachId ? text(coaches.get(coachId)?.name) : null,
426
+ room: roomId ? text(rooms.get(roomId)?.name) : null,
427
+ };
428
+ })
429
+ .filter((b) => !input.upcoming || (b.startsAt !== null && Date.parse(b.startsAt) > now))
430
+ .sort((a, b) => (a.startsAt ?? "").localeCompare(b.startsAt ?? ""));
431
+ return { bookings };
432
+ },
433
+ });
434
+ // --- Staff ----------------------------------------------------------------------------------------
435
+ export const findPeople = defineTool({
436
+ description: "Staff look a person up before booking them: People on file whose name or email contains " +
437
+ "the text, at most 10, with their email. Use it at the desk before adding a walk-in, so a " +
438
+ "member is booked as themselves. Read-only.",
439
+ input: z.object({ query: z.string().trim().min(2).max(100) }),
440
+ output: z.object({
441
+ people: z.array(z.object({ id: z.string(), name: z.string().nullable(), email: z.string().nullable() })),
442
+ }),
443
+ risk: "read",
444
+ async handler(input, ctx) {
445
+ const found = new Map();
446
+ for (const filter of [
447
+ { field: "displayName", op: "contains", value: input.query },
448
+ { field: "emails", op: "contains", value: input.query.toLowerCase() },
449
+ ]) {
450
+ const page = await ctx.ops.call("person.list", { filter, limit: 10 });
451
+ for (const p of page.items) {
452
+ if (found.size >= 10)
453
+ break;
454
+ found.set(p.id, { id: p.id, name: p.displayName ?? null, email: p.primaryEmail ?? null });
455
+ }
456
+ }
457
+ return { people: [...found.values()] };
458
+ },
459
+ });
460
+ export const bookFor = defineTool({
461
+ description: "Staff book a person into a class: someone on file (`personId`; look them up with " +
462
+ "findPeople first), or a walk-in not on file yet (`newPerson`). A walk-in and their booking " +
463
+ "are made in one batch, so a refused booking leaves nobody behind; the platform's duplicate " +
464
+ "check runs first, and a match is answered (person_exists or possible_duplicates, with who) " +
465
+ "rather than made twice: book them, or pass confirmNew when you checked it is someone else. " +
466
+ "Staff are not bound by the booking windows or by 'booked by staff only'; a class that was " +
467
+ "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.",
469
+ input: z.object({
470
+ classId: z.string().min(1).max(64),
471
+ personId: z.string().min(1).max(64).optional(),
472
+ newPerson: z
473
+ .object({
474
+ givenName: z.string().trim().min(1).max(100),
475
+ familyName: z.string().trim().max(100).optional(),
476
+ email: z.string().trim().email().max(320).optional(),
477
+ })
478
+ .optional()
479
+ .describe("A walk-in who is not on file yet"),
480
+ confirmNew: z
481
+ .boolean()
482
+ .default(false)
483
+ .describe("The possible duplicates were checked: this is someone new"),
484
+ holderId: z.string().min(1).max(64).optional(),
485
+ paidAtDesk: z.boolean().default(false),
486
+ note: z.string().max(2000).optional(),
487
+ }),
488
+ output: z.union([booked.extend({ personId: z.string() }), refused]),
489
+ risk: "write",
490
+ async handler(input, ctx) {
491
+ if (!input.personId && !input.newPerson) {
492
+ throw new OpsCallError("invalid_input", "Give personId, or newPerson for a walk-in");
493
+ }
494
+ const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
495
+ const values = {
496
+ class: input.classId,
497
+ ...(input.holderId ? { holder: input.holderId } : {}),
498
+ ...(input.paidAtDesk ? { paidOtherwise: true } : {}),
499
+ ...(staff?.userId ? { bookedBy: staff.userId } : {}),
500
+ ...(input.note ? { note: input.note } : {}),
501
+ };
502
+ try {
503
+ if (input.personId) {
504
+ const made = await ctx.ops.call("record.create", {
505
+ object: BOOKING,
506
+ values: { ...values, person: input.personId },
507
+ });
508
+ return {
509
+ result: "booked",
510
+ bookingId: made.id,
511
+ classId: input.classId,
512
+ personId: input.personId,
513
+ holderId: text(made.values.holder),
514
+ };
515
+ }
516
+ const walkIn = input.newPerson;
517
+ // The person and the booking in one batch, after the duplicate check (ADR 0507).
518
+ const made = await ctx.ops.call("person.createWith", {
519
+ person: {
520
+ givenName: walkIn.givenName,
521
+ ...(walkIn.familyName ? { familyName: walkIn.familyName } : {}),
522
+ ...(walkIn.email ? { emails: [{ email: walkIn.email }] } : {}),
523
+ },
524
+ object: BOOKING,
525
+ field: "person",
526
+ values,
527
+ allowDuplicates: input.confirmNew,
528
+ });
529
+ const booking = await ctx.ops.call("record.get", {
530
+ object: BOOKING,
531
+ id: made.id,
532
+ });
533
+ return {
534
+ result: "booked",
535
+ bookingId: made.id,
536
+ classId: input.classId,
537
+ personId: made.personId,
538
+ holderId: text(booking.values.holder),
539
+ };
540
+ }
541
+ catch (error) {
542
+ return refusalOf(error, "book");
543
+ }
544
+ },
545
+ });
546
+ const cancelled = z.object({
547
+ result: z.enum(["cancelled", "late_cancelled"]),
548
+ bookingId: z.string(),
549
+ late: z.boolean().describe("A late cancel keeps the use the booking spent"),
550
+ });
551
+ export const cancelFor = defineTool({
552
+ description: "Staff cancel a booking, decided by the host's clock as a member's own cancel is: in time " +
553
+ "(`cancelled`, the use given back) until the class type's late-cancel time, late " +
554
+ "(`late_cancelled`, the use kept) after it, not at all once the class has started. With " +
555
+ "`keepUse` it is cancelled late whatever the time. To give a use back after the late point, a " +
556
+ "person uses returnUse. The place is given back either way. Only a booked booking can be " +
557
+ "cancelled; one that has moved on is reported as changed.",
558
+ input: z.object({
559
+ bookingId: z.string().min(1).max(64),
560
+ keepUse: z.boolean().default(false),
561
+ note: z.string().max(2000).optional(),
562
+ }),
563
+ output: z.union([cancelled, refused]),
564
+ risk: "write",
565
+ async handler(input, ctx) {
566
+ try {
567
+ // `cancel` is resolved by the host: this tool's calls are never a person's (ADR 0507).
568
+ const after = await ctx.ops.call("record.update", {
569
+ object: BOOKING,
570
+ id: input.bookingId,
571
+ from: "booked",
572
+ values: {
573
+ state: input.keepUse ? "late_cancelled" : "cancel",
574
+ ...(input.note ? { note: input.note } : {}),
575
+ },
576
+ });
577
+ const state = after.values.state === "late_cancelled" ? "late_cancelled" : "cancelled";
578
+ return { result: state, bookingId: input.bookingId, late: state === "late_cancelled" };
579
+ }
580
+ catch (error) {
581
+ return refusalOf(error, "cancel");
582
+ }
583
+ },
584
+ });
585
+ export const returnUse = defineTool({
586
+ description: "A person on the staff cancels a booking and gives its use back whatever the time: after " +
587
+ "the late-cancel point, or after the class (a member who was ill, a class the coach missed). " +
588
+ "A person's own act: the assistant, MCP clients, automations and other code cannot call it. " +
589
+ "The reason is kept on the booking and in the audit log. Only a booked booking.",
590
+ input: z.object({
591
+ bookingId: z.string().min(1).max(64),
592
+ reason: z.string().trim().min(3).max(2000),
593
+ }),
594
+ output: z.union([
595
+ z.object({ result: z.literal("excused"), bookingId: z.string(), late: z.literal(false) }),
596
+ refused,
597
+ ]),
598
+ risk: "destructive",
599
+ // Only a person calls it, with the pack's permission (ADR 0513); the move it makes is open to
600
+ // no other staff write.
601
+ humanOnly: true,
602
+ permission: "bookings:returns",
603
+ async handler(input, ctx) {
604
+ try {
605
+ await ctx.ops.call("record.update", {
606
+ object: BOOKING,
607
+ id: input.bookingId,
608
+ from: "booked",
609
+ values: { state: "excused", note: `Use given back: ${input.reason}` },
610
+ });
611
+ return { result: "excused", bookingId: input.bookingId, late: false };
612
+ }
613
+ catch (error) {
614
+ return refusalOf(error, "cancel");
615
+ }
616
+ },
617
+ });
618
+ /** The instant a local date's midnight is in `zone` (display only: which classes a day lists). */
619
+ export function localMidnight(date, zone) {
620
+ const [y, m, d] = date.split("-").map(Number);
621
+ const guess = Date.UTC(y, m - 1, d);
622
+ const offsetAt = (instant) => {
623
+ const parts = new Intl.DateTimeFormat("en-GB", {
624
+ timeZone: zone,
625
+ hourCycle: "h23",
626
+ year: "numeric",
627
+ month: "2-digit",
628
+ day: "2-digit",
629
+ hour: "2-digit",
630
+ minute: "2-digit",
631
+ second: "2-digit",
632
+ }).formatToParts(new Date(instant));
633
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value);
634
+ const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
635
+ return asUtc - instant;
636
+ };
637
+ const first = guess - offsetAt(guess);
638
+ return guess - offsetAt(first);
639
+ }
640
+ const staffClass = z.object({
641
+ id: z.string(),
642
+ title: z.string().nullable(),
643
+ classType: named,
644
+ startsAt: z.string().nullable(),
645
+ endsAt: z.string().nullable(),
646
+ timeZone,
647
+ coach: z.string().nullable(),
648
+ room: z.string().nullable(),
649
+ places: z.number().nullable(),
650
+ booked: z.number().describe("Places taken"),
651
+ held: z.number(),
652
+ available: z.number().nullable(),
653
+ state: z.string().nullable(),
654
+ staffOnly: z.boolean().describe("Its class type is booked by staff only"),
655
+ });
656
+ async function staffClasses(ctx, classes) {
657
+ const types = new Map();
658
+ const typeIds = [...new Set(classes.map((c) => text(c.values.classType)).filter(Boolean))];
659
+ if (typeIds.length) {
660
+ const found = await ctx.ops.call("record.list", {
661
+ object: CLASS_TYPE,
662
+ filter: { field: "id", op: "in", value: typeIds },
663
+ limit: typeIds.length,
664
+ });
665
+ for (const item of found.items)
666
+ types.set(item.id, item.values);
667
+ }
668
+ const names = async (object, field) => {
669
+ const ids = [...new Set(classes.map((c) => text(c.values[field])).filter(Boolean))];
670
+ if (!ids.length)
671
+ return new Map();
672
+ const found = await ctx.ops.call("record.list", {
673
+ object,
674
+ filter: { field: "id", op: "in", value: ids },
675
+ limit: ids.length,
676
+ });
677
+ return new Map(found.items.map((item) => [item.id, text(item.values.name)]));
678
+ };
679
+ const coaches = await names(COACH, "coach");
680
+ const rooms = await names(ROOM, "room");
681
+ return classes.map((klass) => {
682
+ const v = klass.values;
683
+ const typeId = text(v.classType);
684
+ const type = typeId ? types.get(typeId) : undefined;
685
+ return {
686
+ id: klass.id,
687
+ title: text(v.title) ?? text(klass.title),
688
+ classType: typeId ? { id: typeId, name: text(type?.name) } : null,
689
+ startsAt: text(v.startsAt),
690
+ endsAt: text(v.endsAt),
691
+ timeZone: text(v.timezone),
692
+ coach: coaches.get(text(v.coach) ?? "") ?? null,
693
+ room: rooms.get(text(v.room) ?? "") ?? null,
694
+ places: num(v.places),
695
+ booked: num(v.taken) ?? 0,
696
+ held: num(v.held) ?? 0,
697
+ available: num(v.available),
698
+ state: text(v.state),
699
+ // Bookings' own field on Programs' class type (registry name `bookings.staffOnly`).
700
+ staffOnly: flag(type?.["bookings.staffOnly"] ?? type?.staffOnly),
701
+ };
702
+ });
703
+ }
704
+ export const day = defineTool({
705
+ description: "Staff's day view: every class on one local date (scheduled, cancelled or done), in start " +
706
+ "order, with its class type, coach, room, places, how many are booked and held, and whether " +
707
+ "its class type is booked by staff only. For the front desk and coaches. Read-only.",
708
+ input: z.object({
709
+ date: z
710
+ .string()
711
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
712
+ .describe("The local date, YYYY-MM-DD"),
713
+ timeZone: z
714
+ .string()
715
+ .min(1)
716
+ .max(64)
717
+ .default("UTC")
718
+ .describe("The zone the date is in (the gym's, e.g. Australia/Sydney)"),
719
+ }),
720
+ output: z.object({ date: z.string(), classes: z.array(staffClass) }),
721
+ risk: "read",
722
+ async handler(input, ctx) {
723
+ const from = localMidnight(input.date, input.timeZone);
724
+ const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
725
+ const to = localMidnight(next, input.timeZone);
726
+ const page = await ctx.ops.call("record.list", {
727
+ object: CLASS,
728
+ filter: {
729
+ and: [
730
+ { field: "startsAt", op: "gte", value: new Date(from).toISOString() },
731
+ { field: "startsAt", op: "lt", value: new Date(to).toISOString() },
732
+ ],
733
+ },
734
+ sort: { field: "startsAt", direction: "asc" },
735
+ limit: 200,
736
+ });
737
+ return { date: input.date, classes: await staffClasses(ctx, page.items) };
738
+ },
739
+ });
740
+ export const classList = defineTool({
741
+ 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.",
744
+ input: z.object({ classId: z.string().min(1).max(64) }),
745
+ output: z.object({
746
+ class: staffClass,
747
+ bookings: z.array(z.object({
748
+ id: z.string(),
749
+ person: named,
750
+ state: z.string().nullable(),
751
+ paidAtDesk: z.boolean(),
752
+ holderId: z.string().nullable(),
753
+ bookedBy: z.string().nullable(),
754
+ })),
755
+ }),
756
+ risk: "read",
757
+ 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]);
763
+ const page = await ctx.ops.call("record.list", {
764
+ object: BOOKING,
765
+ filter: { field: "class", op: "eq", value: klass.id },
766
+ sort: { field: "createdAt", direction: "asc" },
767
+ limit: 200,
768
+ });
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
+ }
782
+ }
783
+ return {
784
+ class: described,
785
+ bookings: page.items.map((booking) => {
786
+ const personId = text(booking.values.person);
787
+ return {
788
+ id: booking.id,
789
+ person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
790
+ state: text(booking.values.state),
791
+ paidAtDesk: flag(booking.values.paidOtherwise),
792
+ holderId: text(booking.values.holder),
793
+ bookedBy: text(booking.values.bookedBy),
794
+ };
795
+ }),
796
+ };
797
+ },
798
+ });