@composable-os/pack-bookings 0.1.0-beta.10 → 0.1.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automations.d.ts +146 -0
- package/dist/automations.js +612 -0
- package/dist/blocks/bookings-class-list/class-list.d.ts +16 -0
- package/dist/blocks/bookings-class-list/class-list.js +62 -0
- package/dist/blocks/bookings-desk/desk.d.ts +7 -0
- package/dist/blocks/bookings-desk/desk.js +17 -1
- package/dist/blocks/bookings-drop-in/drop-in.d.ts +28 -0
- package/dist/blocks/bookings-drop-in/drop-in.js +137 -0
- package/dist/blocks/bookings-native-class-list/class-list-screen.d.ts +12 -0
- package/dist/blocks/bookings-native-class-list/class-list-screen.js +59 -0
- package/dist/blocks/bookings-native-timetable/timetable-screen.d.ts +7 -2
- package/dist/blocks/bookings-native-timetable/timetable-screen.js +90 -18
- package/dist/blocks/bookings-timetable/timetable.d.ts +9 -2
- package/dist/blocks/bookings-timetable/timetable.js +100 -11
- package/dist/client/index.d.ts +1270 -182
- package/dist/client/index.js +102 -3
- package/dist/dashboards.d.ts +5 -0
- package/dist/dashboards.js +157 -0
- package/dist/index.d.ts +2617 -407
- package/dist/index.js +1133 -68
- package/dist/routine-mail.d.ts +577 -0
- package/dist/routine-mail.js +443 -0
- package/dist/tools.d.ts +597 -0
- package/dist/tools.js +1628 -102
- package/package.json +3 -3
package/dist/tools.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The Bookings tools (stage 31a
|
|
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
|
|
@@ -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
|
|
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)
|
|
@@ -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("
|
|
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). " +
|
|
@@ -119,12 +127,36 @@ const refused = z.object({
|
|
|
119
127
|
.optional()
|
|
120
128
|
.describe("For person_exists and possible_duplicates: who is already on file"),
|
|
121
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
|
+
});
|
|
122
148
|
/** A host refusal as a member can be told it, or the error itself when it is not one. */
|
|
123
149
|
function refusalOf(error, what, expect) {
|
|
124
150
|
if (!(error instanceof OpsCallError))
|
|
125
151
|
throw error;
|
|
126
|
-
const details = (error
|
|
152
|
+
const details = detailsOf(error);
|
|
127
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;
|
|
128
160
|
const times = {
|
|
129
161
|
opensAt: text(details.opensAt),
|
|
130
162
|
closesAt: text(details.closesAt),
|
|
@@ -137,6 +169,11 @@ function refusalOf(error, what, expect) {
|
|
|
137
169
|
...times,
|
|
138
170
|
});
|
|
139
171
|
if (error.code === "not_found") {
|
|
172
|
+
// A Person they may not book for (not a child linked to them, or a link that has ended) is
|
|
173
|
+
// answered as one that does not exist (ADR 0540).
|
|
174
|
+
if (details.object === "person") {
|
|
175
|
+
return out("not_found", "You cannot book for that person.");
|
|
176
|
+
}
|
|
140
177
|
return out("not_found", what === "book" ? "That class cannot be booked." : "No such booking.");
|
|
141
178
|
}
|
|
142
179
|
if (rule === "state_window_not_open") {
|
|
@@ -181,10 +218,21 @@ function refusalOf(error, what, expect) {
|
|
|
181
218
|
? "There are no classes left on your membership or pass for that week or period."
|
|
182
219
|
: "Nothing you hold can pay for this class.", reason);
|
|
183
220
|
}
|
|
184
|
-
if (rule === "
|
|
185
|
-
return
|
|
221
|
+
if (rule === "waitlist") {
|
|
222
|
+
return details.reason === "closed"
|
|
223
|
+
? out("waitlist_closed", "This class is full, and it is too close to the start to join its waitlist.")
|
|
224
|
+
: out("changed", "A place came free meanwhile. Try booking again.");
|
|
225
|
+
}
|
|
226
|
+
if (rule === "unique") {
|
|
227
|
+
return out("already_booked", "You already have a place in this class, or are waiting for one.");
|
|
228
|
+
}
|
|
186
229
|
if (rule === "capacity")
|
|
187
230
|
return out("full", "This class is full.");
|
|
231
|
+
// A cancel that found the booking already in a final state: another write moved it first (a
|
|
232
|
+
// race). Any other undeclared move is a fault and is not dressed up as one.
|
|
233
|
+
if (what === "cancel" && rule === "state_final") {
|
|
234
|
+
return out("changed", "It changed meanwhile: it is no longer booked. Look again.");
|
|
235
|
+
}
|
|
188
236
|
if (error.code === "conflict") {
|
|
189
237
|
return out("changed", "It changed while you were booking. Look again and try once more.");
|
|
190
238
|
}
|
|
@@ -244,7 +292,35 @@ export const classGet = defineTool({
|
|
|
244
292
|
return { class: described };
|
|
245
293
|
},
|
|
246
294
|
});
|
|
247
|
-
|
|
295
|
+
/** The member and the children staff linked to them, as the host says (ADR 0540). */
|
|
296
|
+
const familyOf = (ctx) => ctx.ops.call("me.family", {});
|
|
297
|
+
const forPerson = z
|
|
298
|
+
.string()
|
|
299
|
+
.min(1)
|
|
300
|
+
.max(64)
|
|
301
|
+
.optional()
|
|
302
|
+
.describe("A child of theirs to book for instead (a dependant the gym linked to them; see family). " +
|
|
303
|
+
"The child's own membership or pass pays, never the parent's.");
|
|
304
|
+
export const family = defineTool({
|
|
305
|
+
description: "Who the signed-in member may book for: themselves, and the children (dependants) the gym " +
|
|
306
|
+
"has linked to them, each with their name and id. Pass a child's id as book's forPersonId " +
|
|
307
|
+
"and mine's personId. Only the gym's staff link a parent to a child. Read-only.",
|
|
308
|
+
input: z.object({}),
|
|
309
|
+
output: z.object({
|
|
310
|
+
people: z.array(z.object({ personId: z.string(), name: z.string(), self: z.boolean() })),
|
|
311
|
+
}),
|
|
312
|
+
risk: "read",
|
|
313
|
+
audiences: ["customer"],
|
|
314
|
+
async handler(_input, ctx) {
|
|
315
|
+
const found = await familyOf(ctx);
|
|
316
|
+
return {
|
|
317
|
+
people: [
|
|
318
|
+
{ ...found.self, self: true },
|
|
319
|
+
...found.dependants.map((d) => ({ ...d, self: false })),
|
|
320
|
+
],
|
|
321
|
+
};
|
|
322
|
+
},
|
|
323
|
+
});
|
|
248
324
|
const booked = z.object({
|
|
249
325
|
result: z.literal("booked"),
|
|
250
326
|
bookingId: z.string(),
|
|
@@ -254,47 +330,306 @@ const booked = z.object({
|
|
|
254
330
|
.nullable()
|
|
255
331
|
.describe("The membership or pass a use was spent from; null when paid at the desk"),
|
|
256
332
|
});
|
|
333
|
+
const waiting = z.object({
|
|
334
|
+
result: z.literal("waiting"),
|
|
335
|
+
bookingId: z.string(),
|
|
336
|
+
classId: z.string(),
|
|
337
|
+
position: z.number().nullable().describe("Their place in the queue: 1 is next"),
|
|
338
|
+
waiting: z.number().nullable().describe("How many are waiting, them included"),
|
|
339
|
+
message: z.string(),
|
|
340
|
+
});
|
|
341
|
+
/** Where a waiting booking stands, as the host says (their own only, for a member). */
|
|
342
|
+
async function positionOf(ctx, bookingId) {
|
|
343
|
+
const at = await ctx.ops.call("waitlist.position", { object: BOOKING, id: bookingId });
|
|
344
|
+
return { position: at.position, waiting: at.waiting };
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Makes a booking through `operation` (my.create for a member, record.create for staff): booked
|
|
348
|
+
* if a place is free, else, when asked, on the class's waitlist. Both are the host's to allow:
|
|
349
|
+
* the places, and joining only while the class is full and before its cut-off. Joining spends
|
|
350
|
+
* nothing, so someone whose booking was refused for want of a use may still wait on a full class
|
|
351
|
+
* (decision 7: they are passed over at promotion if they still cannot pay). A place that came
|
|
352
|
+
* free between the two is booked (once).
|
|
353
|
+
*/
|
|
354
|
+
async function bookOrWait(ctx, operation, values, wait, forPersonId) {
|
|
355
|
+
// For a member's dependant (ADR 0540): the host checks the link in the write.
|
|
356
|
+
const whose = operation === "my.create" && forPersonId ? { forPersonId } : {};
|
|
357
|
+
for (let attempt = 0;; attempt++) {
|
|
358
|
+
let refusal;
|
|
359
|
+
try {
|
|
360
|
+
const made = await ctx.ops.call(operation, {
|
|
361
|
+
object: BOOKING,
|
|
362
|
+
values,
|
|
363
|
+
...whose,
|
|
364
|
+
});
|
|
365
|
+
return { made, waiting: false };
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
const rule = detailsOf(error).rule;
|
|
369
|
+
if (!wait || (rule !== "capacity" && rule !== "allowance"))
|
|
370
|
+
throw error;
|
|
371
|
+
refusal = error;
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
const made = await ctx.ops.call(operation, {
|
|
375
|
+
object: BOOKING,
|
|
376
|
+
values: { ...values, state: "waiting" },
|
|
377
|
+
...whose,
|
|
378
|
+
});
|
|
379
|
+
return { made, waiting: true };
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
const join = detailsOf(error);
|
|
383
|
+
const first = detailsOf(refusal).rule;
|
|
384
|
+
// Full a moment ago, and a place came free: book it (once).
|
|
385
|
+
if (join.reason === "not_full" && first === "capacity" && attempt === 0) {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
// Nothing to pay with, and no waitlist to join (it is not full, or has closed): that is the
|
|
389
|
+
// answer. Any other refusal of the join (already booked or waiting…) is the true reason.
|
|
390
|
+
if (first === "allowance" && join.rule === "waitlist")
|
|
391
|
+
throw refusal;
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* A member already waiting on the class asked to book it: when a place is free (after the
|
|
398
|
+
* cut-off, after the queue was passed over, or more places), they take it themselves, spending
|
|
399
|
+
* then; a place held for the queue is the host's to give (ADR 0520). Null when they are not
|
|
400
|
+
* waiting on it; otherwise booked, or still waiting with where they stand.
|
|
401
|
+
*/
|
|
402
|
+
async function takeFreePlace(ctx, classId, personId) {
|
|
403
|
+
const mine = await ctx.ops.call("my.list", {
|
|
404
|
+
object: BOOKING,
|
|
405
|
+
filter: {
|
|
406
|
+
and: [
|
|
407
|
+
{ field: "class", op: "eq", value: classId },
|
|
408
|
+
{ field: "person", op: "eq", value: personId },
|
|
409
|
+
{ field: "state", op: "eq", value: "waiting" },
|
|
410
|
+
],
|
|
411
|
+
},
|
|
412
|
+
limit: 1,
|
|
413
|
+
});
|
|
414
|
+
const queued = mine.items[0];
|
|
415
|
+
if (!queued)
|
|
416
|
+
return null;
|
|
417
|
+
try {
|
|
418
|
+
const after = await ctx.ops.call("my.update", {
|
|
419
|
+
object: BOOKING,
|
|
420
|
+
id: queued.id,
|
|
421
|
+
from: "waiting",
|
|
422
|
+
values: { state: "booked" },
|
|
423
|
+
});
|
|
424
|
+
return {
|
|
425
|
+
result: "booked",
|
|
426
|
+
bookingId: queued.id,
|
|
427
|
+
classId,
|
|
428
|
+
holderId: text(after.values.holder),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
if (detailsOf(error).rule !== "capacity")
|
|
433
|
+
throw error;
|
|
434
|
+
const at = await positionOf(ctx, queued.id);
|
|
435
|
+
return {
|
|
436
|
+
result: "waiting",
|
|
437
|
+
bookingId: queued.id,
|
|
438
|
+
classId,
|
|
439
|
+
...at,
|
|
440
|
+
message: `You are already on this class's waitlist${at.position === null ? "" : `, number ${at.position}`}: no place is free for you yet.`,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
const waitingMessage = (position) => position === null
|
|
445
|
+
? "The class is full: you are on its waitlist."
|
|
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
|
+
}
|
|
257
466
|
export const book = defineTool({
|
|
258
467
|
description: "Book the signed-in member into a class with what they already hold (a membership or a " +
|
|
259
468
|
"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.
|
|
261
|
-
"
|
|
262
|
-
"
|
|
469
|
+
"when they name one. No money moves. When the class is full they join its waitlist " +
|
|
470
|
+
"(unless `waitlist` is false): that spends nothing, and if a place frees before the class " +
|
|
471
|
+
"type's cut-off the host moves the first waiter in and spends their use then. Asked again " +
|
|
472
|
+
"by a member already waiting, it books them if a place is free to them (never one held for " +
|
|
473
|
+
"the queue), else says where they stand. Answers " +
|
|
474
|
+
"booked, waiting (with their position), or refused with the reason the host gave: booking " +
|
|
475
|
+
"not open yet (with when it opens), closed, booked by the gym only, nothing to pay with, " +
|
|
476
|
+
"already booked or waiting, full, or too close to the start to wait. A parent books a " +
|
|
477
|
+
"child the gym linked to them with forPersonId (see family): the same rules, and the " +
|
|
478
|
+
"child's own membership or pass pays.",
|
|
263
479
|
input: z.object({
|
|
264
480
|
classId: z.string().min(1).max(64),
|
|
481
|
+
forPersonId: forPerson,
|
|
265
482
|
holderId: z
|
|
266
483
|
.string()
|
|
267
484
|
.min(1)
|
|
268
485
|
.max(64)
|
|
269
486
|
.optional()
|
|
270
487
|
.describe("A membership or pass of theirs to spend, when they hold several"),
|
|
488
|
+
waitlist: z
|
|
489
|
+
.boolean()
|
|
490
|
+
.default(true)
|
|
491
|
+
.describe("When the class is full, join its waitlist (default) rather than be refused"),
|
|
271
492
|
}),
|
|
272
|
-
output: z.union([booked, refused]),
|
|
493
|
+
output: z.union([booked, waiting, refused]),
|
|
273
494
|
risk: "write",
|
|
274
495
|
audiences: ["customer"],
|
|
275
496
|
async handler(input, ctx) {
|
|
276
497
|
try {
|
|
277
498
|
// 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
|
|
279
|
-
|
|
499
|
+
// the windows, the staff-only rule, the place, the one-per-class rule, the spend and when
|
|
500
|
+
// a waitlist may be joined.
|
|
501
|
+
const made = await bookOrWait(ctx, "my.create", {
|
|
502
|
+
class: input.classId,
|
|
503
|
+
...(input.holderId ? { holder: input.holderId } : {}),
|
|
504
|
+
}, input.waitlist, input.forPersonId);
|
|
505
|
+
return await answerOf(ctx, input.classId, made);
|
|
506
|
+
}
|
|
507
|
+
catch (error) {
|
|
508
|
+
if (detailsOf(error).rule === "unique") {
|
|
509
|
+
// Already waiting on it: take a free place if there is one (finding 5, ADR 0520).
|
|
510
|
+
try {
|
|
511
|
+
const whose = input.forPersonId ?? (await familyOf(ctx)).self.personId;
|
|
512
|
+
const taken = await takeFreePlace(ctx, input.classId, whose);
|
|
513
|
+
if (taken)
|
|
514
|
+
return taken;
|
|
515
|
+
}
|
|
516
|
+
catch (inner) {
|
|
517
|
+
return refusalOf(inner, "book");
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return refusalOf(error, "book");
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
});
|
|
524
|
+
// --- A drop-in: one class paid for on the website (decision 8, ADR 0560) --------------------------
|
|
525
|
+
export const buy = defineTool({
|
|
526
|
+
description: "Pay for one class (a drop-in), on the website: for a visitor, or a member with nothing to " +
|
|
527
|
+
"spend on it. The host makes the booking held while it is paid for (a place kept), prices it " +
|
|
528
|
+
"from the class's drop-in price, and starts its order; nothing is paid here. The buyer then " +
|
|
529
|
+
"calls order.checkout with the order's id (and a guest's token) to pay on the provider's " +
|
|
530
|
+
"page: the verified payment books them; an order left unpaid expires after a few minutes and " +
|
|
531
|
+
"the place goes back. The same rules as booking hold (when booking opens and closes, booked " +
|
|
532
|
+
"by the gym only, one booking per person per class); a full class is refused (only members " +
|
|
533
|
+
"with a membership or pass wait for a place). A signed-in member buys as themselves, or for a " +
|
|
534
|
+
"child the gym linked to them (forPersonId; they pay, it is the child's booking); a guest " +
|
|
535
|
+
"gives their email address. Cancelled in time, or by the gym, the money goes back to the " +
|
|
536
|
+
"card once a member of staff approves the refund; cancelled late, it is kept. Amounts in the " +
|
|
537
|
+
"currency's minor unit.",
|
|
538
|
+
input: z.object({
|
|
539
|
+
classId: z.string().min(1).max(64),
|
|
540
|
+
forPersonId: forPerson,
|
|
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."),
|
|
549
|
+
}),
|
|
550
|
+
output: z.union([
|
|
551
|
+
z.object({
|
|
552
|
+
result: z.literal("pending"),
|
|
553
|
+
bookingId: z.string(),
|
|
554
|
+
classId: z.string(),
|
|
555
|
+
orderId: z.string(),
|
|
556
|
+
total: z.number(),
|
|
557
|
+
currency: z.string(),
|
|
558
|
+
expiresAt: z.string().nullable().describe("When the held place goes back if unpaid"),
|
|
559
|
+
token: z.string().nullable().describe("A guest's key to this order, shown once"),
|
|
560
|
+
}),
|
|
561
|
+
refused,
|
|
562
|
+
]),
|
|
563
|
+
risk: "write",
|
|
564
|
+
audiences: ["customer", "public"],
|
|
565
|
+
async handler(input, ctx) {
|
|
566
|
+
try {
|
|
567
|
+
// The host makes the booking, held, as the caller's own (or their child's), prices it, and
|
|
568
|
+
// holds every rule: the class's windows and staff-only rule, its places, one per person.
|
|
569
|
+
const order = await ctx.ops.call("order.startHeld", {
|
|
280
570
|
object: BOOKING,
|
|
281
|
-
values: {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
},
|
|
571
|
+
values: { class: input.classId },
|
|
572
|
+
...(input.forPersonId ? { forPersonId: input.forPersonId } : {}),
|
|
573
|
+
...(input.email === undefined ? {} : { email: input.email }),
|
|
574
|
+
...(input.agreements === undefined ? {} : { agreements: input.agreements }),
|
|
285
575
|
});
|
|
286
576
|
return {
|
|
287
|
-
result: "
|
|
288
|
-
bookingId:
|
|
577
|
+
result: "pending",
|
|
578
|
+
bookingId: order.recordId,
|
|
289
579
|
classId: input.classId,
|
|
290
|
-
|
|
580
|
+
orderId: order.id,
|
|
581
|
+
total: order.total,
|
|
582
|
+
currency: order.currency,
|
|
583
|
+
expiresAt: order.expiresAt,
|
|
584
|
+
token: order.token ?? null,
|
|
291
585
|
};
|
|
292
586
|
}
|
|
293
587
|
catch (error) {
|
|
588
|
+
if (error instanceof OpsCallError) {
|
|
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.");
|
|
592
|
+
}
|
|
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.");
|
|
595
|
+
}
|
|
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.");
|
|
598
|
+
}
|
|
599
|
+
if (details.field === "email")
|
|
600
|
+
return refuse("ask_desk", error.message);
|
|
601
|
+
}
|
|
294
602
|
return refusalOf(error, "book");
|
|
295
603
|
}
|
|
296
604
|
},
|
|
297
605
|
});
|
|
606
|
+
export const leaveWaitlist = defineTool({
|
|
607
|
+
description: "Take the signed-in member off a class's waitlist (one of their bookings that is waiting). " +
|
|
608
|
+
"Nothing was spent, so nothing is given back. Refused when it is no longer waiting (they " +
|
|
609
|
+
"were moved in meanwhile: cancel that booking instead).",
|
|
610
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
611
|
+
output: z.union([z.object({ result: z.literal("left"), bookingId: z.string() }), refused]),
|
|
612
|
+
risk: "write",
|
|
613
|
+
audiences: ["customer"],
|
|
614
|
+
async handler(input, ctx) {
|
|
615
|
+
try {
|
|
616
|
+
// From waiting, or not at all (ADR 0437): a promotion and a leave at once, one wins.
|
|
617
|
+
await ctx.ops.call("my.update", {
|
|
618
|
+
object: BOOKING,
|
|
619
|
+
id: input.bookingId,
|
|
620
|
+
from: "waiting",
|
|
621
|
+
values: { state: "left" },
|
|
622
|
+
});
|
|
623
|
+
return { result: "left", bookingId: input.bookingId };
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
if (error instanceof OpsCallError && error.code === "conflict") {
|
|
627
|
+
return refuse("changed", "This booking is no longer waiting: look at it again (you may have been moved in).");
|
|
628
|
+
}
|
|
629
|
+
return refusalOf(error, "cancel");
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
});
|
|
298
633
|
export const cancel = defineTool({
|
|
299
634
|
description: "Cancel one of the signed-in member's bookings. First without `confirm`: the host says " +
|
|
300
635
|
"whether a cancel now is in time (`cancelled`, the class's use given back) or late " +
|
|
@@ -315,6 +650,9 @@ export const cancel = defineTool({
|
|
|
315
650
|
result: z.enum(["preview", "cancelled", "late_cancelled"]),
|
|
316
651
|
state: z.enum(["cancelled", "late_cancelled"]),
|
|
317
652
|
late: z.boolean().describe("A late cancel keeps the use the booking spent"),
|
|
653
|
+
dropIn: z
|
|
654
|
+
.boolean()
|
|
655
|
+
.describe("Paid for on its own: in time, the money goes back once staff approve it"),
|
|
318
656
|
message: z.string(),
|
|
319
657
|
}),
|
|
320
658
|
refused,
|
|
@@ -322,19 +660,35 @@ export const cancel = defineTool({
|
|
|
322
660
|
risk: "write",
|
|
323
661
|
audiences: ["customer"],
|
|
324
662
|
async handler(input, ctx) {
|
|
663
|
+
// A drop-in (ADR 0560) gets its money back, not a use: read which this booking is.
|
|
664
|
+
let dropIn = false;
|
|
325
665
|
const say = (state, done) => ({
|
|
326
666
|
result: done ? state : "preview",
|
|
327
667
|
state,
|
|
328
668
|
late: state === "late_cancelled",
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
:
|
|
669
|
+
dropIn,
|
|
670
|
+
message: dropIn
|
|
671
|
+
? state === "cancelled"
|
|
672
|
+
? done
|
|
673
|
+
? "Cancelled. Your payment is refunded to your card once the gym approves it."
|
|
674
|
+
: "Cancelling now is in time: your payment is refunded to your card once the gym approves it."
|
|
675
|
+
: done
|
|
676
|
+
? "Cancelled late. The payment is kept."
|
|
677
|
+
: "Cancelling now is late: the payment is kept."
|
|
678
|
+
: state === "cancelled"
|
|
679
|
+
? done
|
|
680
|
+
? "Cancelled. The class is back on your membership or pass."
|
|
681
|
+
: "Cancelling now is in time: the class goes back on your membership or pass."
|
|
682
|
+
: done
|
|
683
|
+
? "Cancelled late. The class stays used."
|
|
684
|
+
: "Cancelling now is late: the class stays used.",
|
|
336
685
|
});
|
|
337
686
|
try {
|
|
687
|
+
const own = await ctx.ops.call("my.get", {
|
|
688
|
+
object: BOOKING,
|
|
689
|
+
id: input.bookingId,
|
|
690
|
+
});
|
|
691
|
+
dropIn = text(own.values.dropInOrder) !== null;
|
|
338
692
|
if (!input.confirm) {
|
|
339
693
|
// The host's dry run: the state "cancel" would enter now (ADR 0503).
|
|
340
694
|
const resolved = await ctx.ops.call("state.resolve", {
|
|
@@ -369,19 +723,38 @@ export const cancel = defineTool({
|
|
|
369
723
|
});
|
|
370
724
|
export const mine = defineTool({
|
|
371
725
|
description: "The signed-in member's own bookings, soonest class first: each with its state (booked, " +
|
|
372
|
-
"cancelled, cancelled late…),
|
|
373
|
-
"
|
|
374
|
-
"
|
|
726
|
+
"waiting, cancelled, cancelled late…), for one waiting its place on the waitlist, the " +
|
|
727
|
+
"membership or pass it spent from, and its class (name, start and end in its own time " +
|
|
728
|
+
"zone, coach, room, whether it still runs). With personId, a child's the gym linked to " +
|
|
729
|
+
"them instead (see family). Only their own and their children's bookings exist here. " +
|
|
730
|
+
"Read-only.",
|
|
375
731
|
input: z.object({
|
|
376
|
-
|
|
732
|
+
personId: z
|
|
733
|
+
.string()
|
|
734
|
+
.min(1)
|
|
735
|
+
.max(64)
|
|
736
|
+
.optional()
|
|
737
|
+
.describe("A child of theirs (see family); left out, their own"),
|
|
738
|
+
state: z
|
|
739
|
+
.enum(["booked", "pending", "waiting", "cancelled", "late_cancelled", "left"])
|
|
740
|
+
.optional(),
|
|
377
741
|
upcoming: z.boolean().default(true).describe("Only classes that have not started"),
|
|
378
742
|
limit: z.number().int().min(1).max(100).default(50),
|
|
379
743
|
}),
|
|
380
744
|
output: z.object({
|
|
381
745
|
bookings: z.array(z.object({
|
|
382
746
|
id: z.string(),
|
|
747
|
+
personId: z.string().nullable().describe("Whose booking it is: theirs, or their child's"),
|
|
383
748
|
state: z.string().nullable(),
|
|
749
|
+
position: z
|
|
750
|
+
.number()
|
|
751
|
+
.nullable()
|
|
752
|
+
.describe("While waiting: their place on the waitlist (1 is next); otherwise null"),
|
|
384
753
|
holderId: z.string().nullable(),
|
|
754
|
+
dropInOrderId: z
|
|
755
|
+
.string()
|
|
756
|
+
.nullable()
|
|
757
|
+
.describe("A drop-in's order (pending: pay it with order.checkout); null otherwise"),
|
|
385
758
|
classId: z.string().nullable(),
|
|
386
759
|
title: z.string().nullable(),
|
|
387
760
|
startsAt: z.string().nullable(),
|
|
@@ -395,17 +768,29 @@ export const mine = defineTool({
|
|
|
395
768
|
risk: "read",
|
|
396
769
|
audiences: ["customer"],
|
|
397
770
|
async handler(input, ctx) {
|
|
398
|
-
// The seam gives a member their own bookings only;
|
|
771
|
+
// The seam gives a member their own bookings and their children's only; the filter picks
|
|
772
|
+
// whose of those (a Person they may not read gives nothing, as one that does not exist).
|
|
773
|
+
const whose = input.personId ?? (await familyOf(ctx)).self.personId;
|
|
399
774
|
const page = await ctx.ops.call("my.list", {
|
|
400
775
|
object: BOOKING,
|
|
401
|
-
|
|
776
|
+
filter: {
|
|
777
|
+
and: [
|
|
778
|
+
{ field: "person", op: "eq", value: whose },
|
|
779
|
+
...(input.state ? [{ field: "state", op: "eq", value: input.state }] : []),
|
|
780
|
+
],
|
|
781
|
+
},
|
|
402
782
|
limit: input.limit,
|
|
403
783
|
});
|
|
404
784
|
// Their bookings' classes, whatever the class's state (customerVia), and only those.
|
|
405
785
|
const classes = await byIds(ctx, "my.list", CLASS, page.items.map((b) => text(b.values.class)));
|
|
406
|
-
const
|
|
407
|
-
const rooms = await
|
|
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
|
+
]);
|
|
408
792
|
const now = Date.now();
|
|
793
|
+
const positions = new Map(waitingIds.map((id, i) => [id, waitingAt[i]?.position ?? null]));
|
|
409
794
|
const bookings = page.items
|
|
410
795
|
.map((booking) => {
|
|
411
796
|
const classId = text(booking.values.class);
|
|
@@ -414,8 +799,11 @@ export const mine = defineTool({
|
|
|
414
799
|
const roomId = text(klass.room);
|
|
415
800
|
return {
|
|
416
801
|
id: booking.id,
|
|
802
|
+
personId: text(booking.values.person),
|
|
417
803
|
state: text(booking.values.state),
|
|
804
|
+
position: positions.get(booking.id) ?? null,
|
|
418
805
|
holderId: text(booking.values.holder),
|
|
806
|
+
dropInOrderId: text(booking.values.dropInOrder),
|
|
419
807
|
classId,
|
|
420
808
|
title: text(klass.title),
|
|
421
809
|
startsAt: text(klass.startsAt),
|
|
@@ -441,6 +829,8 @@ export const findPeople = defineTool({
|
|
|
441
829
|
people: z.array(z.object({ id: z.string(), name: z.string().nullable(), email: z.string().nullable() })),
|
|
442
830
|
}),
|
|
443
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",
|
|
444
834
|
async handler(input, ctx) {
|
|
445
835
|
const found = new Map();
|
|
446
836
|
for (const filter of [
|
|
@@ -465,7 +855,9 @@ export const bookFor = defineTool({
|
|
|
465
855
|
"rather than made twice: book them, or pass confirmNew when you checked it is someone else. " +
|
|
466
856
|
"Staff are not bound by the booking windows or by 'booked by staff only'; a class that was " +
|
|
467
857
|
"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).
|
|
858
|
+
"still hold. With `paidAtDesk` it spends no use (they paid at the desk). With `waitlist`, " +
|
|
859
|
+
"a person on file is put on a full class's waitlist instead of being refused (it spends " +
|
|
860
|
+
"nothing until the host moves them in). Audited.",
|
|
469
861
|
input: z.object({
|
|
470
862
|
classId: z.string().min(1).max(64),
|
|
471
863
|
personId: z.string().min(1).max(64).optional(),
|
|
@@ -483,14 +875,29 @@ export const bookFor = defineTool({
|
|
|
483
875
|
.describe("The possible duplicates were checked: this is someone new"),
|
|
484
876
|
holderId: z.string().min(1).max(64).optional(),
|
|
485
877
|
paidAtDesk: z.boolean().default(false),
|
|
878
|
+
waitlist: z
|
|
879
|
+
.boolean()
|
|
880
|
+
.default(false)
|
|
881
|
+
.describe("A person on file, a full class: put them on its waitlist instead"),
|
|
486
882
|
note: z.string().max(2000).optional(),
|
|
487
883
|
}),
|
|
488
|
-
output: z.union([
|
|
884
|
+
output: z.union([
|
|
885
|
+
booked.extend({ personId: z.string() }),
|
|
886
|
+
waiting.extend({ personId: z.string() }),
|
|
887
|
+
refused,
|
|
888
|
+
]),
|
|
489
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",
|
|
490
892
|
async handler(input, ctx) {
|
|
491
893
|
if (!input.personId && !input.newPerson) {
|
|
492
894
|
throw new OpsCallError("invalid_input", "Give personId, or newPerson for a walk-in");
|
|
493
895
|
}
|
|
896
|
+
// Paid at the desk is for a place they take now: nobody pays at the desk for a place they
|
|
897
|
+
// may never get, and a promotion later would then spend nothing (ADR 0520).
|
|
898
|
+
if (input.paidAtDesk && input.waitlist) {
|
|
899
|
+
throw new OpsCallError("invalid_input", "paidAtDesk is for a free place taken now; put them on the waitlist without it");
|
|
900
|
+
}
|
|
494
901
|
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
495
902
|
const values = {
|
|
496
903
|
class: input.classId,
|
|
@@ -501,17 +908,8 @@ export const bookFor = defineTool({
|
|
|
501
908
|
};
|
|
502
909
|
try {
|
|
503
910
|
if (input.personId) {
|
|
504
|
-
const made = await ctx
|
|
505
|
-
|
|
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
|
-
};
|
|
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 };
|
|
515
913
|
}
|
|
516
914
|
const walkIn = input.newPerson;
|
|
517
915
|
// The person and the booking in one batch, after the duplicate check (ADR 0507).
|
|
@@ -562,6 +960,8 @@ export const cancelFor = defineTool({
|
|
|
562
960
|
}),
|
|
563
961
|
output: z.union([cancelled, refused]),
|
|
564
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",
|
|
565
965
|
async handler(input, ctx) {
|
|
566
966
|
try {
|
|
567
967
|
// `cancel` is resolved by the host: this tool's calls are never a person's (ADR 0507).
|
|
@@ -597,9 +997,9 @@ export const returnUse = defineTool({
|
|
|
597
997
|
]),
|
|
598
998
|
risk: "destructive",
|
|
599
999
|
// Only a person calls it, with the pack's permission (ADR 0513); the move it makes is open to
|
|
600
|
-
// no other staff write.
|
|
1000
|
+
// no other staff write. The desk's (ADR 0600; it was `bookings:returns`, which nothing held).
|
|
601
1001
|
humanOnly: true,
|
|
602
|
-
permission: "bookings:
|
|
1002
|
+
permission: "bookings:desk",
|
|
603
1003
|
async handler(input, ctx) {
|
|
604
1004
|
try {
|
|
605
1005
|
await ctx.ops.call("record.update", {
|
|
@@ -654,30 +1054,11 @@ const staffClass = z.object({
|
|
|
654
1054
|
staffOnly: z.boolean().describe("Its class type is booked by staff only"),
|
|
655
1055
|
});
|
|
656
1056
|
async function staffClasses(ctx, classes) {
|
|
657
|
-
const
|
|
658
|
-
const
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
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");
|
|
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);
|
|
681
1062
|
return classes.map((klass) => {
|
|
682
1063
|
const v = klass.values;
|
|
683
1064
|
const typeId = text(v.classType);
|
|
@@ -689,8 +1070,8 @@ async function staffClasses(ctx, classes) {
|
|
|
689
1070
|
startsAt: text(v.startsAt),
|
|
690
1071
|
endsAt: text(v.endsAt),
|
|
691
1072
|
timeZone: text(v.timezone),
|
|
692
|
-
coach: coaches
|
|
693
|
-
room: rooms
|
|
1073
|
+
coach: name(coaches, v.coach),
|
|
1074
|
+
room: name(rooms, v.room),
|
|
694
1075
|
places: num(v.places),
|
|
695
1076
|
booked: num(v.taken) ?? 0,
|
|
696
1077
|
held: num(v.held) ?? 0,
|
|
@@ -719,6 +1100,11 @@ export const day = defineTool({
|
|
|
719
1100
|
}),
|
|
720
1101
|
output: z.object({ date: z.string(), classes: z.array(staffClass) }),
|
|
721
1102
|
risk: "read",
|
|
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,
|
|
722
1108
|
async handler(input, ctx) {
|
|
723
1109
|
const from = localMidnight(input.date, input.timeZone);
|
|
724
1110
|
const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
|
|
@@ -737,10 +1123,17 @@ export const day = defineTool({
|
|
|
737
1123
|
return { date: input.date, classes: await staffClasses(ctx, page.items) };
|
|
738
1124
|
},
|
|
739
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.");
|
|
740
1131
|
export const classList = defineTool({
|
|
741
1132
|
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…),
|
|
743
|
-
"paid at the desk, the membership or pass it spent from
|
|
1133
|
+
"it with the person's name, its state (booked, waiting, cancelled, cancelled late…), " +
|
|
1134
|
+
"whether they paid at the desk, the membership or pass it spent from, who booked it, and " +
|
|
1135
|
+
"for the waitlist when they were moved in or why they were passed over. Waiters are in " +
|
|
1136
|
+
"the order they joined. Read-only.",
|
|
744
1137
|
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
745
1138
|
output: z.object({
|
|
746
1139
|
class: staffClass,
|
|
@@ -751,48 +1144,1181 @@ export const classList = defineTool({
|
|
|
751
1144
|
paidAtDesk: z.boolean(),
|
|
752
1145
|
holderId: z.string().nullable(),
|
|
753
1146
|
bookedBy: z.string().nullable(),
|
|
1147
|
+
promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
|
|
1148
|
+
healthNote,
|
|
1149
|
+
passedOver: z
|
|
1150
|
+
.string()
|
|
1151
|
+
.nullable()
|
|
1152
|
+
.describe("While waiting: why a free place could not be theirs (what they hold)"),
|
|
754
1153
|
})),
|
|
755
1154
|
}),
|
|
756
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",
|
|
1158
|
+
async handler(input, ctx) {
|
|
1159
|
+
const { klass, bookings, names } = await listOf(ctx, input.classId);
|
|
1160
|
+
const notes = await healthNotesOf(ctx, klass.id, names);
|
|
1161
|
+
return {
|
|
1162
|
+
class: klass,
|
|
1163
|
+
bookings: bookings.map((booking) => {
|
|
1164
|
+
const personId = text(booking.values.person);
|
|
1165
|
+
return {
|
|
1166
|
+
id: booking.id,
|
|
1167
|
+
person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
|
|
1168
|
+
state: text(booking.values.state),
|
|
1169
|
+
healthNote: notes && personId ? notes.has(personId) : null,
|
|
1170
|
+
paidAtDesk: flag(booking.values.paidOtherwise),
|
|
1171
|
+
holderId: text(booking.values.holder),
|
|
1172
|
+
bookedBy: text(booking.values.bookedBy),
|
|
1173
|
+
promotedAt: text(booking.values.promotedAt),
|
|
1174
|
+
passedOver: text(booking.values.passedOverReason),
|
|
1175
|
+
};
|
|
1176
|
+
}),
|
|
1177
|
+
};
|
|
1178
|
+
},
|
|
1179
|
+
});
|
|
1180
|
+
// --- Attendance, the coach's list (step 7) --------------------------------------------------------
|
|
1181
|
+
/** Who is marking a list: the staff member who called the tool (never from the input). */
|
|
1182
|
+
function marker(ctx) {
|
|
1183
|
+
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
1184
|
+
return { markedBy: staff?.userId ?? null, markedByName: staff?.name || null };
|
|
1185
|
+
}
|
|
1186
|
+
const marked = z.object({
|
|
1187
|
+
result: z.enum(["attended", "no_show", "booked"]),
|
|
1188
|
+
bookingId: z.string(),
|
|
1189
|
+
message: z.string(),
|
|
1190
|
+
});
|
|
1191
|
+
const alreadyMarked = z.object({
|
|
1192
|
+
result: z.literal("already"),
|
|
1193
|
+
bookingId: z.string(),
|
|
1194
|
+
state: z.string().nullable().describe("What the booking is now"),
|
|
1195
|
+
markedAt: z.string().nullable(),
|
|
1196
|
+
markedBy: z.string().nullable().describe("The name of who marked it first"),
|
|
1197
|
+
message: z.string(),
|
|
1198
|
+
});
|
|
1199
|
+
const listRefused = z.object({
|
|
1200
|
+
result: z.literal("refused"),
|
|
1201
|
+
reason: z
|
|
1202
|
+
.enum(["not_found", "not_started", "not_booked", "changed"])
|
|
1203
|
+
.describe("not_started: the list opens an hour before the class (see opensAt). not_booked: the " +
|
|
1204
|
+
"booking is not one that can be marked (cancelled, waiting, moved…; see state). changed: " +
|
|
1205
|
+
"it changed meanwhile; look again."),
|
|
1206
|
+
state: z.string().nullable(),
|
|
1207
|
+
opensAt: z.string().nullable(),
|
|
1208
|
+
message: z.string(),
|
|
1209
|
+
});
|
|
1210
|
+
const STATE_WORDS = {
|
|
1211
|
+
booked: "booked",
|
|
1212
|
+
attended: "ticked as come",
|
|
1213
|
+
no_show: "marked as not come",
|
|
1214
|
+
waiting: "on the waitlist",
|
|
1215
|
+
cancelled: "cancelled",
|
|
1216
|
+
late_cancelled: "cancelled late",
|
|
1217
|
+
excused: "cancelled with the class given back",
|
|
1218
|
+
cancelled_by_us: "cancelled with the class",
|
|
1219
|
+
moved: "moved to another class",
|
|
1220
|
+
left: "off the waitlist",
|
|
1221
|
+
pending: "held while paying",
|
|
1222
|
+
expired: "expired",
|
|
1223
|
+
};
|
|
1224
|
+
const words = (state) => STATE_WORDS[state ?? ""] ?? state ?? "unknown";
|
|
1225
|
+
/**
|
|
1226
|
+
* Marks one booking as `to` from where it is (one of `from`), from that position or not at all
|
|
1227
|
+
* (ADR 0437): of two coaches marking one name at once, one is made and the other is told who was
|
|
1228
|
+
* first. The host holds when a list may be marked (from an hour before the class) and which moves
|
|
1229
|
+
* a booking may make.
|
|
1230
|
+
*/
|
|
1231
|
+
async function markBooking(ctx, bookingId, to, from) {
|
|
1232
|
+
const no = (reason, message, state = null, opensAt = null) => ({ result: "refused", reason, state, opensAt, message });
|
|
1233
|
+
let record;
|
|
1234
|
+
try {
|
|
1235
|
+
record = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
|
|
1236
|
+
}
|
|
1237
|
+
catch (error) {
|
|
1238
|
+
if (error instanceof OpsCallError && error.code === "not_found") {
|
|
1239
|
+
return no("not_found", "No such booking.");
|
|
1240
|
+
}
|
|
1241
|
+
throw error;
|
|
1242
|
+
}
|
|
1243
|
+
const already = (now) => {
|
|
1244
|
+
const state = text(now.values.state);
|
|
1245
|
+
const by = text(now.values.markedByName);
|
|
1246
|
+
return {
|
|
1247
|
+
result: "already",
|
|
1248
|
+
bookingId,
|
|
1249
|
+
state,
|
|
1250
|
+
markedAt: text(now.values.markedAt),
|
|
1251
|
+
markedBy: by,
|
|
1252
|
+
message: `Already ${words(state)}${by ? ` by ${by}` : ""}.`,
|
|
1253
|
+
};
|
|
1254
|
+
};
|
|
1255
|
+
const state = text(record.values.state) ?? "";
|
|
1256
|
+
if (state === to)
|
|
1257
|
+
return already(record);
|
|
1258
|
+
if (!from.includes(state)) {
|
|
1259
|
+
return no("not_booked", `This booking is ${words(state)}: it cannot be marked.`, state);
|
|
1260
|
+
}
|
|
1261
|
+
const values = to === "booked"
|
|
1262
|
+
? { state: to, markedAt: null, markedBy: null, markedByName: null }
|
|
1263
|
+
: { state: to, markedAt: new Date().toISOString(), ...marker(ctx) };
|
|
1264
|
+
try {
|
|
1265
|
+
await ctx.ops.call("record.update", { object: BOOKING, id: bookingId, from: state, values });
|
|
1266
|
+
}
|
|
1267
|
+
catch (error) {
|
|
1268
|
+
if (!(error instanceof OpsCallError))
|
|
1269
|
+
throw error;
|
|
1270
|
+
const details = detailsOf(error);
|
|
1271
|
+
if (details.rule === "state_window_not_open") {
|
|
1272
|
+
return no("not_started", to === "no_show"
|
|
1273
|
+
? "A no-show is marked once the class has started."
|
|
1274
|
+
: "The class's list opens an hour before it starts.", state, text(details.opensAt));
|
|
1275
|
+
}
|
|
1276
|
+
if (error.code === "conflict") {
|
|
1277
|
+
// Someone marked it first (or it moved): say who, from what it is now.
|
|
1278
|
+
const now = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
|
|
1279
|
+
if (text(now.values.state) === to)
|
|
1280
|
+
return already(now);
|
|
1281
|
+
const is = text(now.values.state);
|
|
1282
|
+
return no("changed", `It changed meanwhile: it is now ${words(is)}.`, is);
|
|
1283
|
+
}
|
|
1284
|
+
if (details.rule === "state_move_not_declared" || details.rule === "state_final") {
|
|
1285
|
+
return no("not_booked", "This booking cannot be marked.", state);
|
|
1286
|
+
}
|
|
1287
|
+
throw error;
|
|
1288
|
+
}
|
|
1289
|
+
return {
|
|
1290
|
+
result: to,
|
|
1291
|
+
bookingId,
|
|
1292
|
+
message: to === "attended"
|
|
1293
|
+
? "Ticked: they came."
|
|
1294
|
+
: to === "no_show"
|
|
1295
|
+
? "Marked: they did not come. The class stays used."
|
|
1296
|
+
: "Unticked: booked again.",
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
const markOutput = z.union([marked, alreadyMarked, listRefused]);
|
|
1300
|
+
export const markAttended = defineTool({
|
|
1301
|
+
description: "Tick a booking on a class's list: they came. From an hour before the class, and any time " +
|
|
1302
|
+
"after it (a late correction: a no-show ticked becomes attended). Of two coaches ticking one " +
|
|
1303
|
+
"name at once, one tick is made and the other is told who was first. A booking that is " +
|
|
1304
|
+
"cancelled, waiting or moved cannot be ticked. The use it spent stays spent.",
|
|
1305
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1306
|
+
output: markOutput,
|
|
1307
|
+
risk: "write",
|
|
1308
|
+
permission: "bookings:coach",
|
|
1309
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "attended", ["booked", "no_show"]),
|
|
1310
|
+
});
|
|
1311
|
+
export const undoAttended = defineTool({
|
|
1312
|
+
description: "Untick a booking ticked by mistake: it is booked again (and, once the class is 30 minutes " +
|
|
1313
|
+
"over with others ticked, the host makes it a no-show). Who ticked it and when are cleared.",
|
|
1314
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1315
|
+
output: markOutput,
|
|
1316
|
+
risk: "write",
|
|
1317
|
+
permission: "bookings:coach",
|
|
1318
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "booked", ["attended"]),
|
|
1319
|
+
});
|
|
1320
|
+
export const markNoShow = defineTool({
|
|
1321
|
+
description: "Mark a booked booking as not come (a no-show), once the class has started. The class stays " +
|
|
1322
|
+
"used (no money, nothing else follows). The host does this itself for everyone still booked " +
|
|
1323
|
+
"30 minutes after the class ends, if anyone on the list was marked.",
|
|
1324
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1325
|
+
output: markOutput,
|
|
1326
|
+
risk: "write",
|
|
1327
|
+
permission: "bookings:coach",
|
|
1328
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "no_show", ["booked"]),
|
|
1329
|
+
});
|
|
1330
|
+
export const markAll = defineTool({
|
|
1331
|
+
description: "Tick everyone still booked on a class's list at once (from an hour before the class). Each " +
|
|
1332
|
+
"name is ticked from where it is or not at all, so a name another coach ticked meanwhile is " +
|
|
1333
|
+
"counted as already ticked, not twice.",
|
|
1334
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
1335
|
+
output: z.union([
|
|
1336
|
+
z.object({
|
|
1337
|
+
result: z.literal("marked"),
|
|
1338
|
+
classId: z.string(),
|
|
1339
|
+
ticked: z.number().describe("Names ticked now"),
|
|
1340
|
+
already: z.number().describe("Names someone else ticked meanwhile"),
|
|
1341
|
+
skipped: z.number().describe("Names that changed meanwhile (cancelled, moved…)"),
|
|
1342
|
+
}),
|
|
1343
|
+
listRefused,
|
|
1344
|
+
]),
|
|
1345
|
+
risk: "write",
|
|
1346
|
+
permission: "bookings:coach",
|
|
757
1347
|
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
1348
|
const page = await ctx.ops.call("record.list", {
|
|
764
1349
|
object: BOOKING,
|
|
765
|
-
filter: {
|
|
1350
|
+
filter: {
|
|
1351
|
+
and: [
|
|
1352
|
+
{ field: "class", op: "eq", value: input.classId },
|
|
1353
|
+
{ field: "state", op: "eq", value: "booked" },
|
|
1354
|
+
],
|
|
1355
|
+
},
|
|
766
1356
|
sort: { field: "createdAt", direction: "asc" },
|
|
767
1357
|
limit: 200,
|
|
768
1358
|
});
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
1359
|
+
let ticked = 0;
|
|
1360
|
+
let already = 0;
|
|
1361
|
+
let skipped = 0;
|
|
1362
|
+
for (const booking of page.items) {
|
|
1363
|
+
const out = await markBooking(ctx, booking.id, "attended", ["booked"]);
|
|
1364
|
+
if (out.result === "attended")
|
|
1365
|
+
ticked += 1;
|
|
1366
|
+
else if (out.result === "already")
|
|
1367
|
+
already += 1;
|
|
1368
|
+
else if (out.result === "refused" && out.reason === "not_started")
|
|
1369
|
+
return out;
|
|
1370
|
+
else
|
|
1371
|
+
skipped += 1;
|
|
1372
|
+
}
|
|
1373
|
+
return { result: "marked", classId: input.classId, ticked, already, skipped };
|
|
1374
|
+
},
|
|
1375
|
+
});
|
|
1376
|
+
/** A class as staff see it, its bookings in the order they were made, and their people's names. */
|
|
1377
|
+
async function listOf(ctx, classId) {
|
|
1378
|
+
const record = await ctx.ops.call("record.get", { object: CLASS, id: classId });
|
|
1379
|
+
const [klass] = await staffClasses(ctx, [record]);
|
|
1380
|
+
const page = await ctx.ops.call("record.list", {
|
|
1381
|
+
object: BOOKING,
|
|
1382
|
+
filter: { field: "class", op: "eq", value: record.id },
|
|
1383
|
+
sort: { field: "createdAt", direction: "asc" },
|
|
1384
|
+
limit: 200,
|
|
1385
|
+
});
|
|
1386
|
+
const names = new Map();
|
|
1387
|
+
for (const id of new Set(page.items.map((b) => text(b.values.person)).filter(Boolean))) {
|
|
1388
|
+
try {
|
|
1389
|
+
const person = await ctx.ops.call("person.get", {
|
|
1390
|
+
id,
|
|
1391
|
+
});
|
|
1392
|
+
names.set(id, person?.displayName ?? null);
|
|
1393
|
+
}
|
|
1394
|
+
catch (error) {
|
|
1395
|
+
if (!(error instanceof OpsCallError) || error.code !== "not_found")
|
|
1396
|
+
throw error;
|
|
1397
|
+
names.set(id, null);
|
|
782
1398
|
}
|
|
1399
|
+
}
|
|
1400
|
+
return { klass: klass, bookings: page.items, names };
|
|
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
|
+
}
|
|
1420
|
+
export const roster = defineTool({
|
|
1421
|
+
description: "A class's list for its coach: the class (as on the day view) and every booking of it with " +
|
|
1422
|
+
"the person's name and its state (booked, ticked, not come, waiting in the order they " +
|
|
1423
|
+
"joined, cancelled…), who marked it and when. Nothing about what anyone paid with. Read-only.",
|
|
1424
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
1425
|
+
output: z.object({
|
|
1426
|
+
class: staffClass,
|
|
1427
|
+
bookings: z.array(z.object({
|
|
1428
|
+
id: z.string(),
|
|
1429
|
+
person: named,
|
|
1430
|
+
state: z.string().nullable(),
|
|
1431
|
+
markedAt: z.string().nullable(),
|
|
1432
|
+
markedBy: z.string().nullable().describe("The name of who marked it"),
|
|
1433
|
+
promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
|
|
1434
|
+
healthNote,
|
|
1435
|
+
})),
|
|
1436
|
+
}),
|
|
1437
|
+
risk: "read",
|
|
1438
|
+
permission: "bookings:coach",
|
|
1439
|
+
async handler(input, ctx) {
|
|
1440
|
+
const { klass, bookings, names } = await listOf(ctx, input.classId);
|
|
1441
|
+
const notes = await healthNotesOf(ctx, klass.id, names);
|
|
783
1442
|
return {
|
|
784
|
-
class:
|
|
785
|
-
bookings:
|
|
1443
|
+
class: klass,
|
|
1444
|
+
bookings: bookings.map((booking) => {
|
|
786
1445
|
const personId = text(booking.values.person);
|
|
787
1446
|
return {
|
|
788
1447
|
id: booking.id,
|
|
789
1448
|
person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
|
|
790
1449
|
state: text(booking.values.state),
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1450
|
+
markedAt: text(booking.values.markedAt),
|
|
1451
|
+
markedBy: text(booking.values.markedByName),
|
|
1452
|
+
promotedAt: text(booking.values.promotedAt),
|
|
1453
|
+
healthNote: notes && personId ? notes.has(personId) : null,
|
|
794
1454
|
};
|
|
795
1455
|
}),
|
|
796
1456
|
};
|
|
797
1457
|
},
|
|
798
1458
|
});
|
|
1459
|
+
// --- Moving people and cancelling a class (step 7) ------------------------------------------------
|
|
1460
|
+
const moveRefusal = z
|
|
1461
|
+
.enum(["not_booked", "same_class", "started"])
|
|
1462
|
+
.describe("not_booked: only a booked booking moves. same_class: it is already on that class. started: " +
|
|
1463
|
+
"its class has started; giving its use back is returnUse's.");
|
|
1464
|
+
export const move = defineTool({
|
|
1465
|
+
description: "Staff move a member's booking to another class, with the use it spent, in one batch: the " +
|
|
1466
|
+
"old booking is moved (its place given back, to the waitlist first before its cut-off), a " +
|
|
1467
|
+
"new booking is made on the other class, and the use is spent again on it from the same " +
|
|
1468
|
+
"membership or pass. Refused whole, with nothing changed, when the other class is full " +
|
|
1469
|
+
"(places held for its waitlist included: raise its places first), was cancelled or is over, " +
|
|
1470
|
+
"they are already booked on it, or the use cannot be spent in that class's week or period. " +
|
|
1471
|
+
"Only a booked booking, before its class starts. A booking paid at the desk moves paid at " +
|
|
1472
|
+
"the desk. Audited.",
|
|
1473
|
+
input: z.object({
|
|
1474
|
+
bookingId: z.string().min(1).max(64),
|
|
1475
|
+
toClassId: z.string().min(1).max(64),
|
|
1476
|
+
note: z.string().max(2000).optional(),
|
|
1477
|
+
}),
|
|
1478
|
+
output: z.union([
|
|
1479
|
+
z.object({
|
|
1480
|
+
result: z.literal("moved"),
|
|
1481
|
+
fromBookingId: z.string(),
|
|
1482
|
+
bookingId: z.string().describe("The new booking"),
|
|
1483
|
+
classId: z.string(),
|
|
1484
|
+
holderId: z.string().nullable().describe("The membership or pass the use is spent from"),
|
|
1485
|
+
}),
|
|
1486
|
+
refused,
|
|
1487
|
+
refused.extend({ reason: moveRefusal }),
|
|
1488
|
+
]),
|
|
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",
|
|
1492
|
+
async handler(input, ctx) {
|
|
1493
|
+
const no = (reason, message) => refuse(reason, message);
|
|
1494
|
+
let old;
|
|
1495
|
+
try {
|
|
1496
|
+
old = await ctx.ops.call("record.get", { object: BOOKING, id: input.bookingId });
|
|
1497
|
+
}
|
|
1498
|
+
catch (error) {
|
|
1499
|
+
if (error instanceof OpsCallError && error.code === "not_found") {
|
|
1500
|
+
return refusalOf(error, "cancel");
|
|
1501
|
+
}
|
|
1502
|
+
throw error;
|
|
1503
|
+
}
|
|
1504
|
+
const state = text(old.values.state);
|
|
1505
|
+
if (state !== "booked") {
|
|
1506
|
+
return no("not_booked", `This booking is ${words(state)}: only a booked one moves.`);
|
|
1507
|
+
}
|
|
1508
|
+
if (text(old.values.class) === input.toClassId) {
|
|
1509
|
+
return no("same_class", "It is already booked on that class.");
|
|
1510
|
+
}
|
|
1511
|
+
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
1512
|
+
try {
|
|
1513
|
+
// The host moves the old booking in this create's batch (the allowance's `movedFrom`): its
|
|
1514
|
+
// place given back, the use spent again here from the same holder; or nothing at all.
|
|
1515
|
+
const made = await ctx.ops.call("record.create", {
|
|
1516
|
+
object: BOOKING,
|
|
1517
|
+
values: {
|
|
1518
|
+
class: input.toClassId,
|
|
1519
|
+
person: text(old.values.person),
|
|
1520
|
+
movedFrom: old.id,
|
|
1521
|
+
...(staff?.userId ? { bookedBy: staff.userId } : {}),
|
|
1522
|
+
...(input.note ? { note: input.note } : {}),
|
|
1523
|
+
},
|
|
1524
|
+
});
|
|
1525
|
+
return {
|
|
1526
|
+
result: "moved",
|
|
1527
|
+
fromBookingId: old.id,
|
|
1528
|
+
bookingId: made.id,
|
|
1529
|
+
classId: input.toClassId,
|
|
1530
|
+
holderId: text(made.values.holder),
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
catch (error) {
|
|
1534
|
+
const { rule } = detailsOf(error);
|
|
1535
|
+
// The old booking moved to a final state meanwhile (the member cancelled it): a race.
|
|
1536
|
+
if (rule === "state_final") {
|
|
1537
|
+
return refuse("changed", "It changed meanwhile: it is no longer booked. Look again.");
|
|
1538
|
+
}
|
|
1539
|
+
// The old booking's own move has a window: until its class starts.
|
|
1540
|
+
if (rule === "state_window_closed") {
|
|
1541
|
+
return no("started", "Its class has started: it can no longer be moved. A person can give its use back (returnUse).");
|
|
1542
|
+
}
|
|
1543
|
+
return refusalOf(error, "book");
|
|
1544
|
+
}
|
|
1545
|
+
},
|
|
1546
|
+
});
|
|
1547
|
+
export const cancelClass = defineTool({
|
|
1548
|
+
description: "Cancel a scheduled class that has not ended, with a reason: in the same batch every booking " +
|
|
1549
|
+
"of it holding a place or a use (booked, waiting, held while paying, ticked as come, marked " +
|
|
1550
|
+
"not come, cancelled late) is cancelled by the gym, each place given back and each use " +
|
|
1551
|
+
"returned once. A person's act: the assistant, MCP clients and automations may ask, and it " +
|
|
1552
|
+
"waits for a person to approve it. When it cannot be done (no such class, not scheduled, " +
|
|
1553
|
+
"already ended, or it changed twice while being done) it fails with the reason, so an " +
|
|
1554
|
+
"approved request shows it did not apply. (Emails to the members, and refunds of paid " +
|
|
1555
|
+
"drop-ins, come in a later release.)",
|
|
1556
|
+
input: z.object({
|
|
1557
|
+
classId: z.string().min(1).max(64),
|
|
1558
|
+
reason: z.string().trim().min(3).max(2000),
|
|
1559
|
+
}),
|
|
1560
|
+
output: z.object({
|
|
1561
|
+
result: z.literal("cancelled"),
|
|
1562
|
+
classId: z.string(),
|
|
1563
|
+
bookingsCancelled: z.number().describe("Bookings cancelled with the class"),
|
|
1564
|
+
}),
|
|
1565
|
+
risk: "destructive",
|
|
1566
|
+
// Anyone but a person waits for a person's approval (ADR 0552); the class's move into
|
|
1567
|
+
// cancelled is made by this tool and the host only.
|
|
1568
|
+
personApproves: true,
|
|
1569
|
+
permission: "bookings:cancelClasses",
|
|
1570
|
+
async handler(input, ctx) {
|
|
1571
|
+
// A refusal is an error, never an answer: an approved request that cannot apply must show
|
|
1572
|
+
// that it did not (ADR 0553).
|
|
1573
|
+
const fail = (code, reason, message) => {
|
|
1574
|
+
throw new OpsCallError(code, message, { reason });
|
|
1575
|
+
};
|
|
1576
|
+
// A race (a booking landing under the cancel, another write moving the class) is tried once
|
|
1577
|
+
// more from a fresh read; anything else is the answer.
|
|
1578
|
+
for (let attempt = 0;; attempt++) {
|
|
1579
|
+
try {
|
|
1580
|
+
await ctx.ops.call("record.update", {
|
|
1581
|
+
object: CLASS,
|
|
1582
|
+
id: input.classId,
|
|
1583
|
+
from: "scheduled",
|
|
1584
|
+
values: { state: "cancelled", cancelledReason: input.reason },
|
|
1585
|
+
});
|
|
1586
|
+
break;
|
|
1587
|
+
}
|
|
1588
|
+
catch (error) {
|
|
1589
|
+
if (!(error instanceof OpsCallError))
|
|
1590
|
+
throw error;
|
|
1591
|
+
if (error.code === "not_found")
|
|
1592
|
+
fail("not_found", "not_found", "No such class.");
|
|
1593
|
+
const details = detailsOf(error);
|
|
1594
|
+
if (details.reason === "not_in_position") {
|
|
1595
|
+
fail("conflict", "not_scheduled", "This class is not scheduled (it was cancelled or is over).");
|
|
1596
|
+
}
|
|
1597
|
+
if (details.rule === "state_window_closed") {
|
|
1598
|
+
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).");
|
|
1599
|
+
}
|
|
1600
|
+
if (details.rule === "state_window_unknown") {
|
|
1601
|
+
fail("invalid_input", "no_end", "This class has no end time, so whether it has ended cannot be told: give it one first.");
|
|
1602
|
+
}
|
|
1603
|
+
if (error.code === "conflict" && attempt === 0)
|
|
1604
|
+
continue;
|
|
1605
|
+
if (error.code === "conflict") {
|
|
1606
|
+
fail("conflict", "changed", "The class or its bookings changed while it was being cancelled. Look again.");
|
|
1607
|
+
}
|
|
1608
|
+
throw error;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
const page = await ctx.ops.call("record.list", {
|
|
1612
|
+
object: BOOKING,
|
|
1613
|
+
filter: {
|
|
1614
|
+
and: [
|
|
1615
|
+
{ field: "class", op: "eq", value: input.classId },
|
|
1616
|
+
{ field: "state", op: "eq", value: "cancelled_by_us" },
|
|
1617
|
+
],
|
|
1618
|
+
},
|
|
1619
|
+
limit: 200,
|
|
1620
|
+
});
|
|
1621
|
+
return {
|
|
1622
|
+
result: "cancelled",
|
|
1623
|
+
classId: input.classId,
|
|
1624
|
+
bookingsCancelled: page.items.length,
|
|
1625
|
+
};
|
|
1626
|
+
},
|
|
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
|
+
});
|