@composable-os/pack-bookings 0.0.0-stage → 0.1.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +109 -0
- package/dist/blocks/bookings-class-list/class-list.d.ts +7 -0
- package/dist/blocks/bookings-class-list/class-list.js +37 -0
- package/dist/blocks/bookings-desk/desk.d.ts +10 -0
- package/dist/blocks/bookings-desk/desk.js +62 -0
- package/dist/blocks/bookings-drop-in/drop-in.d.ts +22 -0
- package/dist/blocks/bookings-drop-in/drop-in.js +54 -0
- package/dist/blocks/bookings-native-timetable/timetable-screen.d.ts +6 -0
- package/dist/blocks/bookings-native-timetable/timetable-screen.js +61 -0
- package/dist/blocks/bookings-timetable/timetable.d.ts +11 -0
- package/dist/blocks/bookings-timetable/timetable.js +83 -0
- package/dist/client/index.d.ts +2039 -0
- package/dist/client/index.js +209 -0
- package/dist/index.d.ts +1745 -0
- package/dist/index.js +974 -0
- package/dist/tools.d.ts +691 -0
- package/dist/tools.js +1623 -0
- package/package.json +36 -4
- package/README.md +0 -3
package/dist/tools.js
ADDED
|
@@ -0,0 +1,1623 @@
|
|
|
1
|
+
// The Bookings tools (stage 31a steps 3 to 7). They become operations x.bookings.<tool>, run in the
|
|
2
|
+
// sandbox, and reach the host only through ctx.ops. None of them holds a rule: when booking opens
|
|
3
|
+
// and closes, whether a cancel is late, which class types only staff book, the places left, one
|
|
4
|
+
// booking per person per class and the use a booking spends are all the host's (index.ts). A tool
|
|
5
|
+
// asks, and reports what the host answered, in words a member can be shown.
|
|
6
|
+
import { defineTool, OpsCallError, z } from "@composable-os/sdk";
|
|
7
|
+
const CLASS = "bookings.class";
|
|
8
|
+
const BOOKING = "bookings.booking";
|
|
9
|
+
const COACH = "bookings.coach";
|
|
10
|
+
const ROOM = "bookings.room";
|
|
11
|
+
const CLASS_TYPE = "programs.classtype";
|
|
12
|
+
const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
|
|
13
|
+
const num = (value) => typeof value === "number" ? value : value == null || value === "" ? null : Number(value);
|
|
14
|
+
const flag = (value) => value === true || value === 1 || value === "1";
|
|
15
|
+
/** A class's own time zone: its times are this zone's (ADR 0460). */
|
|
16
|
+
const timeZone = z
|
|
17
|
+
.string()
|
|
18
|
+
.nullable()
|
|
19
|
+
.describe("The class's IANA time zone: show its times in this zone.");
|
|
20
|
+
const places = z.object({
|
|
21
|
+
status: z.enum(["available", "low", "sold_out"]),
|
|
22
|
+
available: z.number().nullable().optional().describe("Places left; null when unlimited"),
|
|
23
|
+
});
|
|
24
|
+
const named = z.object({ id: z.string(), name: z.string().nullable() }).nullable();
|
|
25
|
+
const classOutput = z.object({
|
|
26
|
+
id: z.string(),
|
|
27
|
+
title: z.string().nullable().describe("The class's name (its class type's, unless renamed)"),
|
|
28
|
+
classType: z.string().nullable(),
|
|
29
|
+
startsAt: z.string().nullable().describe("When it starts (ISO 8601, UTC)"),
|
|
30
|
+
endsAt: z.string().nullable(),
|
|
31
|
+
timeZone,
|
|
32
|
+
room: named,
|
|
33
|
+
coach: named.and(z.object({ photo: z.string().nullable() }).partial()).nullable(),
|
|
34
|
+
notes: z.string().nullable(),
|
|
35
|
+
places,
|
|
36
|
+
});
|
|
37
|
+
/** Records of `object` by id, through a read operation the caller may use (public or my). */
|
|
38
|
+
async function byIds(ctx, operation, object, ids) {
|
|
39
|
+
const wanted = [...new Set(ids.filter((id) => Boolean(id)))];
|
|
40
|
+
if (!wanted.length)
|
|
41
|
+
return new Map();
|
|
42
|
+
const found = await ctx.ops.call(operation, {
|
|
43
|
+
object,
|
|
44
|
+
filter: { field: "id", op: "in", value: wanted },
|
|
45
|
+
limit: Math.min(wanted.length, 200),
|
|
46
|
+
});
|
|
47
|
+
return new Map(found.items.map((item) => [item.id, item.values]));
|
|
48
|
+
}
|
|
49
|
+
/** What the host says of a class's places, as an outsider may be told (`show: "exact"`). */
|
|
50
|
+
async function placesOf(ctx, id) {
|
|
51
|
+
const view = await ctx.ops.call("capacity.get", { object: CLASS, id });
|
|
52
|
+
return {
|
|
53
|
+
status: view.status,
|
|
54
|
+
...(view.available === undefined ? {} : { available: view.available }),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
async function describeClasses(ctx, classes) {
|
|
58
|
+
// Coaches and rooms are public (their names); a class's other people are never read here.
|
|
59
|
+
const coaches = await byIds(ctx, "public.list", COACH, classes.map((c) => text(c.values.coach)));
|
|
60
|
+
const rooms = await byIds(ctx, "public.list", ROOM, classes.map((c) => text(c.values.room)));
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const klass of classes) {
|
|
63
|
+
const v = klass.values;
|
|
64
|
+
const coachId = text(v.coach);
|
|
65
|
+
const roomId = text(v.room);
|
|
66
|
+
const coach = coachId ? coaches.get(coachId) : undefined;
|
|
67
|
+
const room = roomId ? rooms.get(roomId) : undefined;
|
|
68
|
+
out.push({
|
|
69
|
+
id: klass.id,
|
|
70
|
+
title: text(v.title) ?? text(klass.title),
|
|
71
|
+
classType: text(v.classType),
|
|
72
|
+
startsAt: text(v.startsAt),
|
|
73
|
+
endsAt: text(v.endsAt),
|
|
74
|
+
timeZone: text(v.timezone),
|
|
75
|
+
room: roomId ? { id: roomId, name: text(room?.name) } : null,
|
|
76
|
+
coach: coachId ? { id: coachId, name: text(coach?.name), photo: text(coach?.photo) } : null,
|
|
77
|
+
notes: text(v.notes),
|
|
78
|
+
places: await placesOf(ctx, klass.id),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
// --- Why the host refused -------------------------------------------------------------------------
|
|
84
|
+
const refusalReason = z
|
|
85
|
+
.enum([
|
|
86
|
+
"not_open",
|
|
87
|
+
"closed",
|
|
88
|
+
"staff_only",
|
|
89
|
+
"no_use",
|
|
90
|
+
"already_booked",
|
|
91
|
+
"full",
|
|
92
|
+
"too_late",
|
|
93
|
+
"not_found",
|
|
94
|
+
"changed",
|
|
95
|
+
"not_running",
|
|
96
|
+
"person_exists",
|
|
97
|
+
"possible_duplicates",
|
|
98
|
+
"waitlist_closed",
|
|
99
|
+
"no_drop_in",
|
|
100
|
+
"ask_desk",
|
|
101
|
+
"try_later",
|
|
102
|
+
])
|
|
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. " +
|
|
108
|
+
"not_running: the class was cancelled or is over. person_exists: someone on file has that " +
|
|
109
|
+
"email (see people). possible_duplicates: people on file may be this person (see people; " +
|
|
110
|
+
"book one of them, or ask again with confirmNew). " +
|
|
111
|
+
"staff_only: this class is booked by the gym. no_use: nothing the " +
|
|
112
|
+
"member holds can pay for it (see detail). already_booked: they already have a place. " +
|
|
113
|
+
"full: no places left. too_late: the class has started, so it cannot be cancelled. " +
|
|
114
|
+
"not_found: no such class or booking of theirs. changed: it changed meanwhile; try again.");
|
|
115
|
+
const refused = z.object({
|
|
116
|
+
result: z.literal("refused"),
|
|
117
|
+
reason: refusalReason,
|
|
118
|
+
message: z.string(),
|
|
119
|
+
detail: z
|
|
120
|
+
.string()
|
|
121
|
+
.nullable()
|
|
122
|
+
.describe("The host's reason for an allowance refusal (no_uses_left, ended, not_covered…)"),
|
|
123
|
+
opensAt: z.string().nullable(),
|
|
124
|
+
closesAt: z.string().nullable(),
|
|
125
|
+
people: z
|
|
126
|
+
.array(z.object({ id: z.string(), name: z.string(), reasons: z.array(z.string()) }))
|
|
127
|
+
.optional()
|
|
128
|
+
.describe("For person_exists and possible_duplicates: who is already on file"),
|
|
129
|
+
});
|
|
130
|
+
/** A host refusal as a member can be told it, or the error itself when it is not one. */
|
|
131
|
+
function refusalOf(error, what, expect) {
|
|
132
|
+
if (!(error instanceof OpsCallError))
|
|
133
|
+
throw error;
|
|
134
|
+
const details = (error.details ?? {});
|
|
135
|
+
const rule = typeof details.rule === "string" ? details.rule : "";
|
|
136
|
+
const times = {
|
|
137
|
+
opensAt: text(details.opensAt),
|
|
138
|
+
closesAt: text(details.closesAt),
|
|
139
|
+
};
|
|
140
|
+
const out = (reason, message, detail = null) => ({
|
|
141
|
+
result: "refused",
|
|
142
|
+
reason,
|
|
143
|
+
message,
|
|
144
|
+
detail,
|
|
145
|
+
...times,
|
|
146
|
+
});
|
|
147
|
+
if (error.code === "not_found") {
|
|
148
|
+
// A Person they may not book for (not a child linked to them, or a link that has ended) is
|
|
149
|
+
// answered as one that does not exist (ADR 0540).
|
|
150
|
+
if (details.object === "person") {
|
|
151
|
+
return out("not_found", "You cannot book for that person.");
|
|
152
|
+
}
|
|
153
|
+
return out("not_found", what === "book" ? "That class cannot be booked." : "No such booking.");
|
|
154
|
+
}
|
|
155
|
+
if (rule === "state_window_not_open") {
|
|
156
|
+
// A cancel asked for as late, before the late point: it is in time, say so (not "opens").
|
|
157
|
+
if (what === "cancel" && expect === "late_cancelled") {
|
|
158
|
+
return out("changed", "It is not late yet: cancelling now is in time and gives the class back. Look again.");
|
|
159
|
+
}
|
|
160
|
+
return out("not_open", "Booking for this class has not opened yet.");
|
|
161
|
+
}
|
|
162
|
+
if (rule === "state_closed") {
|
|
163
|
+
return out("not_running", "This class was cancelled or is over: it cannot be booked.");
|
|
164
|
+
}
|
|
165
|
+
if (rule === "person_exists" || rule === "possible_duplicates") {
|
|
166
|
+
const people = Array.isArray(details.people)
|
|
167
|
+
? details.people.map((p) => ({
|
|
168
|
+
id: String(p.id ?? ""),
|
|
169
|
+
name: String(p.title ?? ""),
|
|
170
|
+
reasons: Array.isArray(p.reasons) ? p.reasons.map(String) : [],
|
|
171
|
+
}))
|
|
172
|
+
: [];
|
|
173
|
+
return {
|
|
174
|
+
...out(rule, rule === "person_exists"
|
|
175
|
+
? "Someone on file already has that email address: book them instead."
|
|
176
|
+
: "This may be someone already on file: book them, or confirm this is someone new."),
|
|
177
|
+
people,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (rule === "state_window_closed" || rule === "state_window_unknown") {
|
|
181
|
+
return what === "book"
|
|
182
|
+
? out("closed", "Booking for this class has closed.")
|
|
183
|
+
: out("too_late", "The class has started: it can no longer be cancelled.");
|
|
184
|
+
}
|
|
185
|
+
if (rule === "state_request_refused") {
|
|
186
|
+
return out("too_late", "This booking can no longer be cancelled.");
|
|
187
|
+
}
|
|
188
|
+
if (rule === "state_staff_only") {
|
|
189
|
+
return out("staff_only", "This class is booked by the gym. Ask at the desk.");
|
|
190
|
+
}
|
|
191
|
+
if (rule === "allowance") {
|
|
192
|
+
const reason = text(details.reason);
|
|
193
|
+
return out("no_use", reason === "no_uses_left"
|
|
194
|
+
? "There are no classes left on your membership or pass for that week or period."
|
|
195
|
+
: "Nothing you hold can pay for this class.", reason);
|
|
196
|
+
}
|
|
197
|
+
if (rule === "waitlist") {
|
|
198
|
+
return details.reason === "closed"
|
|
199
|
+
? out("waitlist_closed", "This class is full, and it is too close to the start to join its waitlist.")
|
|
200
|
+
: out("changed", "A place came free meanwhile. Try booking again.");
|
|
201
|
+
}
|
|
202
|
+
if (rule === "unique") {
|
|
203
|
+
return out("already_booked", "You already have a place in this class, or are waiting for one.");
|
|
204
|
+
}
|
|
205
|
+
if (rule === "capacity")
|
|
206
|
+
return out("full", "This class is full.");
|
|
207
|
+
// A cancel that found the booking already in a final state: another write moved it first (a
|
|
208
|
+
// race). Any other undeclared move is a fault and is not dressed up as one.
|
|
209
|
+
if (what === "cancel" && rule === "state_final") {
|
|
210
|
+
return out("changed", "It changed meanwhile: it is no longer booked. Look again.");
|
|
211
|
+
}
|
|
212
|
+
if (error.code === "conflict") {
|
|
213
|
+
return out("changed", "It changed while you were booking. Look again and try once more.");
|
|
214
|
+
}
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
// --- The timetable (members and the public) --------------------------------------------------------
|
|
218
|
+
const DAY = 86_400_000;
|
|
219
|
+
export const timetable = defineTool({
|
|
220
|
+
description: "The gym's timetable: its scheduled classes between two times (default: the next 7 days), " +
|
|
221
|
+
"soonest first, each with its name, class type, start and end in its own time zone, coach, " +
|
|
222
|
+
"room, notes for members and how many places are left. Filter by class type or coach. Only " +
|
|
223
|
+
"what the public may read: never who is booked. Booking rules (when booking opens, whether " +
|
|
224
|
+
"the gym books it) are the host's: book answers with them. Read-only.",
|
|
225
|
+
input: z.object({
|
|
226
|
+
from: z.string().datetime().optional().describe("From this time (ISO 8601). Default: now"),
|
|
227
|
+
to: z.string().datetime().optional().describe("Until this time. Default: 7 days after from"),
|
|
228
|
+
classType: z.string().min(1).max(64).optional(),
|
|
229
|
+
coach: z.string().min(1).max(64).optional(),
|
|
230
|
+
limit: z.number().int().min(1).max(100).default(50),
|
|
231
|
+
}),
|
|
232
|
+
output: z.object({ classes: z.array(classOutput) }),
|
|
233
|
+
risk: "read",
|
|
234
|
+
audiences: ["customer", "public"],
|
|
235
|
+
async handler(input, ctx) {
|
|
236
|
+
const from = input.from ?? new Date().toISOString();
|
|
237
|
+
const to = input.to ?? new Date(Date.parse(from) + 7 * DAY).toISOString();
|
|
238
|
+
const conditions = [
|
|
239
|
+
{ field: "startsAt", op: "gte", value: from },
|
|
240
|
+
{ field: "startsAt", op: "lt", value: to },
|
|
241
|
+
...(input.classType ? [{ field: "classType", op: "eq", value: input.classType }] : []),
|
|
242
|
+
...(input.coach ? [{ field: "coach", op: "eq", value: input.coach }] : []),
|
|
243
|
+
];
|
|
244
|
+
// The seam decides which classes: the public reads a class only while it is scheduled.
|
|
245
|
+
const page = await ctx.ops.call("public.list", {
|
|
246
|
+
object: CLASS,
|
|
247
|
+
filter: { and: conditions },
|
|
248
|
+
sort: { field: "startsAt", direction: "asc" },
|
|
249
|
+
limit: input.limit,
|
|
250
|
+
});
|
|
251
|
+
return { classes: await describeClasses(ctx, page.items) };
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
export const classGet = defineTool({
|
|
255
|
+
description: "One scheduled class of the timetable: its name, class type, start and end in its own time " +
|
|
256
|
+
"zone, coach, room, notes for members and how many places are left. Not found once it is " +
|
|
257
|
+
"not scheduled. Never who is booked. Read-only.",
|
|
258
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
259
|
+
output: z.object({ class: classOutput }),
|
|
260
|
+
risk: "read",
|
|
261
|
+
audiences: ["customer", "public"],
|
|
262
|
+
async handler(input, ctx) {
|
|
263
|
+
const klass = await ctx.ops.call("public.get", {
|
|
264
|
+
object: CLASS,
|
|
265
|
+
id: input.classId,
|
|
266
|
+
});
|
|
267
|
+
const [described] = await describeClasses(ctx, [klass]);
|
|
268
|
+
return { class: described };
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
/** The member and the children staff linked to them, as the host says (ADR 0540). */
|
|
272
|
+
const familyOf = (ctx) => ctx.ops.call("me.family", {});
|
|
273
|
+
const forPerson = z
|
|
274
|
+
.string()
|
|
275
|
+
.min(1)
|
|
276
|
+
.max(64)
|
|
277
|
+
.optional()
|
|
278
|
+
.describe("A child of theirs to book for instead (a dependant the gym linked to them; see family). " +
|
|
279
|
+
"The child's own membership or pass pays, never the parent's.");
|
|
280
|
+
export const family = defineTool({
|
|
281
|
+
description: "Who the signed-in member may book for: themselves, and the children (dependants) the gym " +
|
|
282
|
+
"has linked to them, each with their name and id. Pass a child's id as book's forPersonId " +
|
|
283
|
+
"and mine's personId. Only the gym's staff link a parent to a child. Read-only.",
|
|
284
|
+
input: z.object({}),
|
|
285
|
+
output: z.object({
|
|
286
|
+
people: z.array(z.object({ personId: z.string(), name: z.string(), self: z.boolean() })),
|
|
287
|
+
}),
|
|
288
|
+
risk: "read",
|
|
289
|
+
audiences: ["customer"],
|
|
290
|
+
async handler(_input, ctx) {
|
|
291
|
+
const found = await familyOf(ctx);
|
|
292
|
+
return {
|
|
293
|
+
people: [
|
|
294
|
+
{ ...found.self, self: true },
|
|
295
|
+
...found.dependants.map((d) => ({ ...d, self: false })),
|
|
296
|
+
],
|
|
297
|
+
};
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
const booked = z.object({
|
|
301
|
+
result: z.literal("booked"),
|
|
302
|
+
bookingId: z.string(),
|
|
303
|
+
classId: z.string(),
|
|
304
|
+
holderId: z
|
|
305
|
+
.string()
|
|
306
|
+
.nullable()
|
|
307
|
+
.describe("The membership or pass a use was spent from; null when paid at the desk"),
|
|
308
|
+
});
|
|
309
|
+
const waiting = z.object({
|
|
310
|
+
result: z.literal("waiting"),
|
|
311
|
+
bookingId: z.string(),
|
|
312
|
+
classId: z.string(),
|
|
313
|
+
position: z.number().nullable().describe("Their place in the queue: 1 is next"),
|
|
314
|
+
waiting: z.number().nullable().describe("How many are waiting, them included"),
|
|
315
|
+
message: z.string(),
|
|
316
|
+
});
|
|
317
|
+
/** Where a waiting booking stands, as the host says (their own only, for a member). */
|
|
318
|
+
async function positionOf(ctx, bookingId) {
|
|
319
|
+
const at = await ctx.ops.call("waitlist.position", { object: BOOKING, id: bookingId });
|
|
320
|
+
return { position: at.position, waiting: at.waiting };
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Makes a booking through `operation` (my.create for a member, record.create for staff): booked
|
|
324
|
+
* if a place is free, else, when asked, on the class's waitlist. Both are the host's to allow:
|
|
325
|
+
* the places, and joining only while the class is full and before its cut-off. Joining spends
|
|
326
|
+
* nothing, so someone whose booking was refused for want of a use may still wait on a full class
|
|
327
|
+
* (decision 7: they are passed over at promotion if they still cannot pay). A place that came
|
|
328
|
+
* free between the two is booked (once).
|
|
329
|
+
*/
|
|
330
|
+
async function bookOrWait(ctx, operation, values, wait, forPersonId) {
|
|
331
|
+
// For a member's dependant (ADR 0540): the host checks the link in the write.
|
|
332
|
+
const whose = operation === "my.create" && forPersonId ? { forPersonId } : {};
|
|
333
|
+
const ruleOf = (error) => error instanceof OpsCallError
|
|
334
|
+
? (error.details ?? {})
|
|
335
|
+
: {};
|
|
336
|
+
for (let attempt = 0;; attempt++) {
|
|
337
|
+
let refusal;
|
|
338
|
+
try {
|
|
339
|
+
const made = await ctx.ops.call(operation, {
|
|
340
|
+
object: BOOKING,
|
|
341
|
+
values,
|
|
342
|
+
...whose,
|
|
343
|
+
});
|
|
344
|
+
return { made, waiting: false };
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
const rule = ruleOf(error).rule;
|
|
348
|
+
if (!wait || (rule !== "capacity" && rule !== "allowance"))
|
|
349
|
+
throw error;
|
|
350
|
+
refusal = error;
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
const made = await ctx.ops.call(operation, {
|
|
354
|
+
object: BOOKING,
|
|
355
|
+
values: { ...values, state: "waiting" },
|
|
356
|
+
...whose,
|
|
357
|
+
});
|
|
358
|
+
return { made, waiting: true };
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
const join = ruleOf(error);
|
|
362
|
+
// Full a moment ago, and a place came free: book it (once).
|
|
363
|
+
if (join.reason === "not_full" && ruleOf(refusal).rule === "capacity" && attempt === 0) {
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
// Nothing to pay with, and no waitlist to join (it is not full, or has closed): that is the
|
|
367
|
+
// answer. Any other refusal of the join (already booked or waiting…) is the true reason.
|
|
368
|
+
if (ruleOf(refusal).rule === "allowance" && join.rule === "waitlist")
|
|
369
|
+
throw refusal;
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* A member already waiting on the class asked to book it: when a place is free (after the
|
|
376
|
+
* cut-off, after the queue was passed over, or more places), they take it themselves, spending
|
|
377
|
+
* then; a place held for the queue is the host's to give (ADR 0520). Null when they are not
|
|
378
|
+
* waiting on it; otherwise booked, or still waiting with where they stand.
|
|
379
|
+
*/
|
|
380
|
+
async function takeFreePlace(ctx, classId, personId) {
|
|
381
|
+
const mine = await ctx.ops.call("my.list", {
|
|
382
|
+
object: BOOKING,
|
|
383
|
+
filter: {
|
|
384
|
+
and: [
|
|
385
|
+
{ field: "class", op: "eq", value: classId },
|
|
386
|
+
{ field: "person", op: "eq", value: personId },
|
|
387
|
+
{ field: "state", op: "eq", value: "waiting" },
|
|
388
|
+
],
|
|
389
|
+
},
|
|
390
|
+
limit: 1,
|
|
391
|
+
});
|
|
392
|
+
const queued = mine.items[0];
|
|
393
|
+
if (!queued)
|
|
394
|
+
return null;
|
|
395
|
+
try {
|
|
396
|
+
const after = await ctx.ops.call("my.update", {
|
|
397
|
+
object: BOOKING,
|
|
398
|
+
id: queued.id,
|
|
399
|
+
from: "waiting",
|
|
400
|
+
values: { state: "booked" },
|
|
401
|
+
});
|
|
402
|
+
return {
|
|
403
|
+
result: "booked",
|
|
404
|
+
bookingId: queued.id,
|
|
405
|
+
classId,
|
|
406
|
+
holderId: text(after.values.holder),
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
const rule = error instanceof OpsCallError ? error.details?.rule : null;
|
|
411
|
+
if (rule !== "capacity")
|
|
412
|
+
throw error;
|
|
413
|
+
const at = await positionOf(ctx, queued.id);
|
|
414
|
+
return {
|
|
415
|
+
result: "waiting",
|
|
416
|
+
bookingId: queued.id,
|
|
417
|
+
classId,
|
|
418
|
+
...at,
|
|
419
|
+
message: `You are already on this class's waitlist${at.position === null ? "" : `, number ${at.position}`}: no place is free for you yet.`,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const waitingMessage = (position) => position === null
|
|
424
|
+
? "The class is full: you are on its waitlist."
|
|
425
|
+
: `The class is full: you are number ${position} on its waitlist. If a place frees in time, you are moved in and it is paid from your membership or pass then.`;
|
|
426
|
+
export const book = defineTool({
|
|
427
|
+
description: "Book the signed-in member into a class with what they already hold (a membership or a " +
|
|
428
|
+
"pass): the host spends one use of the one whose use would lapse first, or of `holderId` " +
|
|
429
|
+
"when they name one. No money moves. When the class is full they join its waitlist " +
|
|
430
|
+
"(unless `waitlist` is false): that spends nothing, and if a place frees before the class " +
|
|
431
|
+
"type's cut-off the host moves the first waiter in and spends their use then. Asked again " +
|
|
432
|
+
"by a member already waiting, it books them if a place is free to them (never one held for " +
|
|
433
|
+
"the queue), else says where they stand. Answers " +
|
|
434
|
+
"booked, waiting (with their position), or refused with the reason the host gave: booking " +
|
|
435
|
+
"not open yet (with when it opens), closed, booked by the gym only, nothing to pay with, " +
|
|
436
|
+
"already booked or waiting, full, or too close to the start to wait. A parent books a " +
|
|
437
|
+
"child the gym linked to them with forPersonId (see family): the same rules, and the " +
|
|
438
|
+
"child's own membership or pass pays.",
|
|
439
|
+
input: z.object({
|
|
440
|
+
classId: z.string().min(1).max(64),
|
|
441
|
+
forPersonId: forPerson,
|
|
442
|
+
holderId: z
|
|
443
|
+
.string()
|
|
444
|
+
.min(1)
|
|
445
|
+
.max(64)
|
|
446
|
+
.optional()
|
|
447
|
+
.describe("A membership or pass of theirs to spend, when they hold several"),
|
|
448
|
+
waitlist: z
|
|
449
|
+
.boolean()
|
|
450
|
+
.default(true)
|
|
451
|
+
.describe("When the class is full, join its waitlist (default) rather than be refused"),
|
|
452
|
+
}),
|
|
453
|
+
output: z.union([booked, waiting, refused]),
|
|
454
|
+
risk: "write",
|
|
455
|
+
audiences: ["customer"],
|
|
456
|
+
async handler(input, ctx) {
|
|
457
|
+
try {
|
|
458
|
+
// The host sets whose it is (the caller), checks the class is one they may see, and holds
|
|
459
|
+
// the windows, the staff-only rule, the place, the one-per-class rule, the spend and when
|
|
460
|
+
// a waitlist may be joined.
|
|
461
|
+
const { made, waiting: queued } = await bookOrWait(ctx, "my.create", {
|
|
462
|
+
class: input.classId,
|
|
463
|
+
...(input.holderId ? { holder: input.holderId } : {}),
|
|
464
|
+
}, input.waitlist, input.forPersonId);
|
|
465
|
+
if (queued) {
|
|
466
|
+
const at = await positionOf(ctx, made.id);
|
|
467
|
+
return {
|
|
468
|
+
result: "waiting",
|
|
469
|
+
bookingId: made.id,
|
|
470
|
+
classId: input.classId,
|
|
471
|
+
...at,
|
|
472
|
+
message: waitingMessage(at.position),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
return {
|
|
476
|
+
result: "booked",
|
|
477
|
+
bookingId: made.id,
|
|
478
|
+
classId: input.classId,
|
|
479
|
+
holderId: text(made.values.holder),
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
const unique = error instanceof OpsCallError &&
|
|
484
|
+
error.details?.rule === "unique";
|
|
485
|
+
if (unique) {
|
|
486
|
+
// Already waiting on it: take a free place if there is one (finding 5, ADR 0520).
|
|
487
|
+
try {
|
|
488
|
+
const whose = input.forPersonId ?? (await familyOf(ctx)).self.personId;
|
|
489
|
+
const taken = await takeFreePlace(ctx, input.classId, whose);
|
|
490
|
+
if (taken)
|
|
491
|
+
return taken;
|
|
492
|
+
}
|
|
493
|
+
catch (inner) {
|
|
494
|
+
return refusalOf(inner, "book");
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return refusalOf(error, "book");
|
|
498
|
+
}
|
|
499
|
+
},
|
|
500
|
+
});
|
|
501
|
+
// --- A drop-in: one class paid for on the website (decision 8, ADR 0560) --------------------------
|
|
502
|
+
export const buy = defineTool({
|
|
503
|
+
description: "Pay for one class (a drop-in), on the website: for a visitor, or a member with nothing to " +
|
|
504
|
+
"spend on it. The host makes the booking held while it is paid for (a place kept), prices it " +
|
|
505
|
+
"from the class's drop-in price, and starts its order; nothing is paid here. The buyer then " +
|
|
506
|
+
"calls order.checkout with the order's id (and a guest's token) to pay on the provider's " +
|
|
507
|
+
"page: the verified payment books them; an order left unpaid expires after a few minutes and " +
|
|
508
|
+
"the place goes back. The same rules as booking hold (when booking opens and closes, booked " +
|
|
509
|
+
"by the gym only, one booking per person per class); a full class is refused (only members " +
|
|
510
|
+
"with a membership or pass wait for a place). A signed-in member buys as themselves, or for a " +
|
|
511
|
+
"child the gym linked to them (forPersonId; they pay, it is the child's booking); a guest " +
|
|
512
|
+
"gives their email address. Cancelled in time, or by the gym, the money goes back to the " +
|
|
513
|
+
"card once a member of staff approves the refund; cancelled late, it is kept. Amounts in the " +
|
|
514
|
+
"currency's minor unit.",
|
|
515
|
+
input: z.object({
|
|
516
|
+
classId: z.string().min(1).max(64),
|
|
517
|
+
forPersonId: forPerson,
|
|
518
|
+
email: z.string().trim().max(320).optional().describe("A guest's email address"),
|
|
519
|
+
}),
|
|
520
|
+
output: z.union([
|
|
521
|
+
z.object({
|
|
522
|
+
result: z.literal("pending"),
|
|
523
|
+
bookingId: z.string(),
|
|
524
|
+
classId: z.string(),
|
|
525
|
+
orderId: z.string(),
|
|
526
|
+
total: z.number(),
|
|
527
|
+
currency: z.string(),
|
|
528
|
+
expiresAt: z.string().nullable().describe("When the held place goes back if unpaid"),
|
|
529
|
+
token: z.string().nullable().describe("A guest's key to this order, shown once"),
|
|
530
|
+
}),
|
|
531
|
+
refused,
|
|
532
|
+
]),
|
|
533
|
+
risk: "write",
|
|
534
|
+
audiences: ["customer", "public"],
|
|
535
|
+
async handler(input, ctx) {
|
|
536
|
+
try {
|
|
537
|
+
// The host makes the booking, held, as the caller's own (or their child's), prices it, and
|
|
538
|
+
// holds every rule: the class's windows and staff-only rule, its places, one per person.
|
|
539
|
+
const order = await ctx.ops.call("order.startHeld", {
|
|
540
|
+
object: BOOKING,
|
|
541
|
+
values: { class: input.classId },
|
|
542
|
+
...(input.forPersonId ? { forPersonId: input.forPersonId } : {}),
|
|
543
|
+
...(input.email === undefined ? {} : { email: input.email }),
|
|
544
|
+
});
|
|
545
|
+
return {
|
|
546
|
+
result: "pending",
|
|
547
|
+
bookingId: order.recordId,
|
|
548
|
+
classId: input.classId,
|
|
549
|
+
orderId: order.id,
|
|
550
|
+
total: order.total,
|
|
551
|
+
currency: order.currency,
|
|
552
|
+
expiresAt: order.expiresAt,
|
|
553
|
+
token: order.token ?? null,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
catch (error) {
|
|
557
|
+
if (error instanceof OpsCallError) {
|
|
558
|
+
const rule = error.details?.rule;
|
|
559
|
+
const out = (reason, message) => ({
|
|
560
|
+
result: "refused",
|
|
561
|
+
reason,
|
|
562
|
+
message,
|
|
563
|
+
detail: null,
|
|
564
|
+
opensAt: null,
|
|
565
|
+
closesAt: null,
|
|
566
|
+
});
|
|
567
|
+
if (rule === "no_price" || rule === "not_for_sale") {
|
|
568
|
+
return out("no_drop_in", "This class cannot be paid for online. Ask at the desk.");
|
|
569
|
+
}
|
|
570
|
+
if (rule === "try_later" || error.code === "rate_limited") {
|
|
571
|
+
return out("try_later", "Too many places are being held for payment just now: try again shortly.");
|
|
572
|
+
}
|
|
573
|
+
if (rule === "buyer_unclear") {
|
|
574
|
+
return out("ask_desk", "We could not tell who you are from that address. Ask at the desk.");
|
|
575
|
+
}
|
|
576
|
+
if (error.details?.field === "email") {
|
|
577
|
+
return out("ask_desk", error.message);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return refusalOf(error, "book");
|
|
581
|
+
}
|
|
582
|
+
},
|
|
583
|
+
});
|
|
584
|
+
export const leaveWaitlist = defineTool({
|
|
585
|
+
description: "Take the signed-in member off a class's waitlist (one of their bookings that is waiting). " +
|
|
586
|
+
"Nothing was spent, so nothing is given back. Refused when it is no longer waiting (they " +
|
|
587
|
+
"were moved in meanwhile: cancel that booking instead).",
|
|
588
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
589
|
+
output: z.union([z.object({ result: z.literal("left"), bookingId: z.string() }), refused]),
|
|
590
|
+
risk: "write",
|
|
591
|
+
audiences: ["customer"],
|
|
592
|
+
async handler(input, ctx) {
|
|
593
|
+
try {
|
|
594
|
+
// From waiting, or not at all (ADR 0437): a promotion and a leave at once, one wins.
|
|
595
|
+
await ctx.ops.call("my.update", {
|
|
596
|
+
object: BOOKING,
|
|
597
|
+
id: input.bookingId,
|
|
598
|
+
from: "waiting",
|
|
599
|
+
values: { state: "left" },
|
|
600
|
+
});
|
|
601
|
+
return { result: "left", bookingId: input.bookingId };
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
if (error instanceof OpsCallError && error.code === "conflict") {
|
|
605
|
+
return {
|
|
606
|
+
result: "refused",
|
|
607
|
+
reason: "changed",
|
|
608
|
+
message: "This booking is no longer waiting: look at it again (you may have been moved in).",
|
|
609
|
+
detail: null,
|
|
610
|
+
opensAt: null,
|
|
611
|
+
closesAt: null,
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
return refusalOf(error, "cancel");
|
|
615
|
+
}
|
|
616
|
+
},
|
|
617
|
+
});
|
|
618
|
+
export const cancel = defineTool({
|
|
619
|
+
description: "Cancel one of the signed-in member's bookings. First without `confirm`: the host says " +
|
|
620
|
+
"whether a cancel now is in time (`cancelled`, the class's use given back) or late " +
|
|
621
|
+
"(`late_cancelled`, the use kept), by its clock. Then with `confirm: true` and `expect` set " +
|
|
622
|
+
"to that answer: cancelled as said, or refused if it has become late meanwhile, so a member " +
|
|
623
|
+
"never loses a use they were told they would keep. After the class starts it cannot be " +
|
|
624
|
+
"cancelled.",
|
|
625
|
+
input: z.object({
|
|
626
|
+
bookingId: z.string().min(1).max(64),
|
|
627
|
+
confirm: z.boolean().default(false),
|
|
628
|
+
expect: z
|
|
629
|
+
.enum(["cancelled", "late_cancelled"])
|
|
630
|
+
.optional()
|
|
631
|
+
.describe("What the preview said; with confirm, cancel only into this state"),
|
|
632
|
+
}),
|
|
633
|
+
output: z.union([
|
|
634
|
+
z.object({
|
|
635
|
+
result: z.enum(["preview", "cancelled", "late_cancelled"]),
|
|
636
|
+
state: z.enum(["cancelled", "late_cancelled"]),
|
|
637
|
+
late: z.boolean().describe("A late cancel keeps the use the booking spent"),
|
|
638
|
+
dropIn: z
|
|
639
|
+
.boolean()
|
|
640
|
+
.describe("Paid for on its own: in time, the money goes back once staff approve it"),
|
|
641
|
+
message: z.string(),
|
|
642
|
+
}),
|
|
643
|
+
refused,
|
|
644
|
+
]),
|
|
645
|
+
risk: "write",
|
|
646
|
+
audiences: ["customer"],
|
|
647
|
+
async handler(input, ctx) {
|
|
648
|
+
// A drop-in (ADR 0560) gets its money back, not a use: read which this booking is.
|
|
649
|
+
let dropIn = false;
|
|
650
|
+
const say = (state, done) => ({
|
|
651
|
+
result: done ? state : "preview",
|
|
652
|
+
state,
|
|
653
|
+
late: state === "late_cancelled",
|
|
654
|
+
dropIn,
|
|
655
|
+
message: dropIn
|
|
656
|
+
? state === "cancelled"
|
|
657
|
+
? done
|
|
658
|
+
? "Cancelled. Your payment is refunded to your card once the gym approves it."
|
|
659
|
+
: "Cancelling now is in time: your payment is refunded to your card once the gym approves it."
|
|
660
|
+
: done
|
|
661
|
+
? "Cancelled late. The payment is kept."
|
|
662
|
+
: "Cancelling now is late: the payment is kept."
|
|
663
|
+
: state === "cancelled"
|
|
664
|
+
? done
|
|
665
|
+
? "Cancelled. The class is back on your membership or pass."
|
|
666
|
+
: "Cancelling now is in time: the class goes back on your membership or pass."
|
|
667
|
+
: done
|
|
668
|
+
? "Cancelled late. The class stays used."
|
|
669
|
+
: "Cancelling now is late: the class stays used.",
|
|
670
|
+
});
|
|
671
|
+
try {
|
|
672
|
+
const own = await ctx.ops.call("my.get", {
|
|
673
|
+
object: BOOKING,
|
|
674
|
+
id: input.bookingId,
|
|
675
|
+
});
|
|
676
|
+
dropIn = text(own.values.dropInOrder) !== null;
|
|
677
|
+
if (!input.confirm) {
|
|
678
|
+
// The host's dry run: the state "cancel" would enter now (ADR 0503).
|
|
679
|
+
const resolved = await ctx.ops.call("state.resolve", {
|
|
680
|
+
object: BOOKING,
|
|
681
|
+
id: input.bookingId,
|
|
682
|
+
request: "cancel",
|
|
683
|
+
});
|
|
684
|
+
return say(resolved.state === "late_cancelled" ? "late_cancelled" : "cancelled", false);
|
|
685
|
+
}
|
|
686
|
+
// From booked, or not at all (ADR 0437); into the state they were told, or the host's pick.
|
|
687
|
+
const after = await ctx.ops.call("my.update", {
|
|
688
|
+
object: BOOKING,
|
|
689
|
+
id: input.bookingId,
|
|
690
|
+
from: "booked",
|
|
691
|
+
values: { state: input.expect ?? "cancel" },
|
|
692
|
+
});
|
|
693
|
+
return say(after.values.state === "late_cancelled" ? "late_cancelled" : "cancelled", true);
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
const refusal = refusalOf(error, "cancel", input.expect);
|
|
697
|
+
// Asked for "in time" and it is now late: say so, so they can confirm the late cancel.
|
|
698
|
+
if (refusal.reason === "too_late" && input.expect === "cancelled") {
|
|
699
|
+
return {
|
|
700
|
+
...refusal,
|
|
701
|
+
reason: "changed",
|
|
702
|
+
message: "It is now too late to cancel in time. Cancelling now keeps the class used.",
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
return refusal;
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
});
|
|
709
|
+
export const mine = defineTool({
|
|
710
|
+
description: "The signed-in member's own bookings, soonest class first: each with its state (booked, " +
|
|
711
|
+
"waiting, cancelled, cancelled late…), for one waiting its place on the waitlist, the " +
|
|
712
|
+
"membership or pass it spent from, and its class (name, start and end in its own time " +
|
|
713
|
+
"zone, coach, room, whether it still runs). With personId, a child's the gym linked to " +
|
|
714
|
+
"them instead (see family). Only their own and their children's bookings exist here. " +
|
|
715
|
+
"Read-only.",
|
|
716
|
+
input: z.object({
|
|
717
|
+
personId: z
|
|
718
|
+
.string()
|
|
719
|
+
.min(1)
|
|
720
|
+
.max(64)
|
|
721
|
+
.optional()
|
|
722
|
+
.describe("A child of theirs (see family); left out, their own"),
|
|
723
|
+
state: z
|
|
724
|
+
.enum(["booked", "pending", "waiting", "cancelled", "late_cancelled", "left"])
|
|
725
|
+
.optional(),
|
|
726
|
+
upcoming: z.boolean().default(true).describe("Only classes that have not started"),
|
|
727
|
+
limit: z.number().int().min(1).max(100).default(50),
|
|
728
|
+
}),
|
|
729
|
+
output: z.object({
|
|
730
|
+
bookings: z.array(z.object({
|
|
731
|
+
id: z.string(),
|
|
732
|
+
personId: z.string().nullable().describe("Whose booking it is: theirs, or their child's"),
|
|
733
|
+
state: z.string().nullable(),
|
|
734
|
+
position: z
|
|
735
|
+
.number()
|
|
736
|
+
.nullable()
|
|
737
|
+
.describe("While waiting: their place on the waitlist (1 is next); otherwise null"),
|
|
738
|
+
holderId: z.string().nullable(),
|
|
739
|
+
dropInOrderId: z
|
|
740
|
+
.string()
|
|
741
|
+
.nullable()
|
|
742
|
+
.describe("A drop-in's order (pending: pay it with order.checkout); null otherwise"),
|
|
743
|
+
classId: z.string().nullable(),
|
|
744
|
+
title: z.string().nullable(),
|
|
745
|
+
startsAt: z.string().nullable(),
|
|
746
|
+
endsAt: z.string().nullable(),
|
|
747
|
+
timeZone,
|
|
748
|
+
classState: z.string().nullable().describe("scheduled, cancelled or done"),
|
|
749
|
+
coach: z.string().nullable(),
|
|
750
|
+
room: z.string().nullable(),
|
|
751
|
+
})),
|
|
752
|
+
}),
|
|
753
|
+
risk: "read",
|
|
754
|
+
audiences: ["customer"],
|
|
755
|
+
async handler(input, ctx) {
|
|
756
|
+
// The seam gives a member their own bookings and their children's only; the filter picks
|
|
757
|
+
// whose of those (a Person they may not read gives nothing, as one that does not exist).
|
|
758
|
+
const whose = input.personId ?? (await familyOf(ctx)).self.personId;
|
|
759
|
+
const page = await ctx.ops.call("my.list", {
|
|
760
|
+
object: BOOKING,
|
|
761
|
+
filter: {
|
|
762
|
+
and: [
|
|
763
|
+
{ field: "person", op: "eq", value: whose },
|
|
764
|
+
...(input.state ? [{ field: "state", op: "eq", value: input.state }] : []),
|
|
765
|
+
],
|
|
766
|
+
},
|
|
767
|
+
limit: input.limit,
|
|
768
|
+
});
|
|
769
|
+
// Their bookings' classes, whatever the class's state (customerVia), and only those.
|
|
770
|
+
const classes = await byIds(ctx, "my.list", CLASS, page.items.map((b) => text(b.values.class)));
|
|
771
|
+
const coaches = await byIds(ctx, "public.list", COACH, [...classes.values()].map((c) => text(c.coach)));
|
|
772
|
+
const rooms = await byIds(ctx, "public.list", ROOM, [...classes.values()].map((c) => text(c.room)));
|
|
773
|
+
const now = Date.now();
|
|
774
|
+
const positions = new Map();
|
|
775
|
+
for (const booking of page.items) {
|
|
776
|
+
if (booking.values.state === "waiting") {
|
|
777
|
+
positions.set(booking.id, (await positionOf(ctx, booking.id)).position);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
const bookings = page.items
|
|
781
|
+
.map((booking) => {
|
|
782
|
+
const classId = text(booking.values.class);
|
|
783
|
+
const klass = (classId && classes.get(classId)) || {};
|
|
784
|
+
const coachId = text(klass.coach);
|
|
785
|
+
const roomId = text(klass.room);
|
|
786
|
+
return {
|
|
787
|
+
id: booking.id,
|
|
788
|
+
personId: text(booking.values.person),
|
|
789
|
+
state: text(booking.values.state),
|
|
790
|
+
position: positions.get(booking.id) ?? null,
|
|
791
|
+
holderId: text(booking.values.holder),
|
|
792
|
+
dropInOrderId: text(booking.values.dropInOrder),
|
|
793
|
+
classId,
|
|
794
|
+
title: text(klass.title),
|
|
795
|
+
startsAt: text(klass.startsAt),
|
|
796
|
+
endsAt: text(klass.endsAt),
|
|
797
|
+
timeZone: text(klass.timezone),
|
|
798
|
+
classState: text(klass.state),
|
|
799
|
+
coach: coachId ? text(coaches.get(coachId)?.name) : null,
|
|
800
|
+
room: roomId ? text(rooms.get(roomId)?.name) : null,
|
|
801
|
+
};
|
|
802
|
+
})
|
|
803
|
+
.filter((b) => !input.upcoming || (b.startsAt !== null && Date.parse(b.startsAt) > now))
|
|
804
|
+
.sort((a, b) => (a.startsAt ?? "").localeCompare(b.startsAt ?? ""));
|
|
805
|
+
return { bookings };
|
|
806
|
+
},
|
|
807
|
+
});
|
|
808
|
+
// --- Staff ----------------------------------------------------------------------------------------
|
|
809
|
+
export const findPeople = defineTool({
|
|
810
|
+
description: "Staff look a person up before booking them: People on file whose name or email contains " +
|
|
811
|
+
"the text, at most 10, with their email. Use it at the desk before adding a walk-in, so a " +
|
|
812
|
+
"member is booked as themselves. Read-only.",
|
|
813
|
+
input: z.object({ query: z.string().trim().min(2).max(100) }),
|
|
814
|
+
output: z.object({
|
|
815
|
+
people: z.array(z.object({ id: z.string(), name: z.string().nullable(), email: z.string().nullable() })),
|
|
816
|
+
}),
|
|
817
|
+
risk: "read",
|
|
818
|
+
async handler(input, ctx) {
|
|
819
|
+
const found = new Map();
|
|
820
|
+
for (const filter of [
|
|
821
|
+
{ field: "displayName", op: "contains", value: input.query },
|
|
822
|
+
{ field: "emails", op: "contains", value: input.query.toLowerCase() },
|
|
823
|
+
]) {
|
|
824
|
+
const page = await ctx.ops.call("person.list", { filter, limit: 10 });
|
|
825
|
+
for (const p of page.items) {
|
|
826
|
+
if (found.size >= 10)
|
|
827
|
+
break;
|
|
828
|
+
found.set(p.id, { id: p.id, name: p.displayName ?? null, email: p.primaryEmail ?? null });
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return { people: [...found.values()] };
|
|
832
|
+
},
|
|
833
|
+
});
|
|
834
|
+
export const bookFor = defineTool({
|
|
835
|
+
description: "Staff book a person into a class: someone on file (`personId`; look them up with " +
|
|
836
|
+
"findPeople first), or a walk-in not on file yet (`newPerson`). A walk-in and their booking " +
|
|
837
|
+
"are made in one batch, so a refused booking leaves nobody behind; the platform's duplicate " +
|
|
838
|
+
"check runs first, and a match is answered (person_exists or possible_duplicates, with who) " +
|
|
839
|
+
"rather than made twice: book them, or pass confirmNew when you checked it is someone else. " +
|
|
840
|
+
"Staff are not bound by the booking windows or by 'booked by staff only'; a class that was " +
|
|
841
|
+
"cancelled or is over, the places, one booking per person per class and the use it spends " +
|
|
842
|
+
"still hold. With `paidAtDesk` it spends no use (they paid at the desk). With `waitlist`, " +
|
|
843
|
+
"a person on file is put on a full class's waitlist instead of being refused (it spends " +
|
|
844
|
+
"nothing until the host moves them in). Audited.",
|
|
845
|
+
input: z.object({
|
|
846
|
+
classId: z.string().min(1).max(64),
|
|
847
|
+
personId: z.string().min(1).max(64).optional(),
|
|
848
|
+
newPerson: z
|
|
849
|
+
.object({
|
|
850
|
+
givenName: z.string().trim().min(1).max(100),
|
|
851
|
+
familyName: z.string().trim().max(100).optional(),
|
|
852
|
+
email: z.string().trim().email().max(320).optional(),
|
|
853
|
+
})
|
|
854
|
+
.optional()
|
|
855
|
+
.describe("A walk-in who is not on file yet"),
|
|
856
|
+
confirmNew: z
|
|
857
|
+
.boolean()
|
|
858
|
+
.default(false)
|
|
859
|
+
.describe("The possible duplicates were checked: this is someone new"),
|
|
860
|
+
holderId: z.string().min(1).max(64).optional(),
|
|
861
|
+
paidAtDesk: z.boolean().default(false),
|
|
862
|
+
waitlist: z
|
|
863
|
+
.boolean()
|
|
864
|
+
.default(false)
|
|
865
|
+
.describe("A person on file, a full class: put them on its waitlist instead"),
|
|
866
|
+
note: z.string().max(2000).optional(),
|
|
867
|
+
}),
|
|
868
|
+
output: z.union([
|
|
869
|
+
booked.extend({ personId: z.string() }),
|
|
870
|
+
waiting.extend({ personId: z.string() }),
|
|
871
|
+
refused,
|
|
872
|
+
]),
|
|
873
|
+
risk: "write",
|
|
874
|
+
async handler(input, ctx) {
|
|
875
|
+
if (!input.personId && !input.newPerson) {
|
|
876
|
+
throw new OpsCallError("invalid_input", "Give personId, or newPerson for a walk-in");
|
|
877
|
+
}
|
|
878
|
+
// Paid at the desk is for a place they take now: nobody pays at the desk for a place they
|
|
879
|
+
// may never get, and a promotion later would then spend nothing (ADR 0520).
|
|
880
|
+
if (input.paidAtDesk && input.waitlist) {
|
|
881
|
+
throw new OpsCallError("invalid_input", "paidAtDesk is for a free place taken now; put them on the waitlist without it");
|
|
882
|
+
}
|
|
883
|
+
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
884
|
+
const values = {
|
|
885
|
+
class: input.classId,
|
|
886
|
+
...(input.holderId ? { holder: input.holderId } : {}),
|
|
887
|
+
...(input.paidAtDesk ? { paidOtherwise: true } : {}),
|
|
888
|
+
...(staff?.userId ? { bookedBy: staff.userId } : {}),
|
|
889
|
+
...(input.note ? { note: input.note } : {}),
|
|
890
|
+
};
|
|
891
|
+
try {
|
|
892
|
+
if (input.personId) {
|
|
893
|
+
const { made, waiting: queued } = await bookOrWait(ctx, "record.create", { ...values, person: input.personId }, input.waitlist);
|
|
894
|
+
if (queued) {
|
|
895
|
+
const at = await positionOf(ctx, made.id);
|
|
896
|
+
return {
|
|
897
|
+
result: "waiting",
|
|
898
|
+
bookingId: made.id,
|
|
899
|
+
classId: input.classId,
|
|
900
|
+
personId: input.personId,
|
|
901
|
+
...at,
|
|
902
|
+
message: waitingMessage(at.position),
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
return {
|
|
906
|
+
result: "booked",
|
|
907
|
+
bookingId: made.id,
|
|
908
|
+
classId: input.classId,
|
|
909
|
+
personId: input.personId,
|
|
910
|
+
holderId: text(made.values.holder),
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
const walkIn = input.newPerson;
|
|
914
|
+
// The person and the booking in one batch, after the duplicate check (ADR 0507).
|
|
915
|
+
const made = await ctx.ops.call("person.createWith", {
|
|
916
|
+
person: {
|
|
917
|
+
givenName: walkIn.givenName,
|
|
918
|
+
...(walkIn.familyName ? { familyName: walkIn.familyName } : {}),
|
|
919
|
+
...(walkIn.email ? { emails: [{ email: walkIn.email }] } : {}),
|
|
920
|
+
},
|
|
921
|
+
object: BOOKING,
|
|
922
|
+
field: "person",
|
|
923
|
+
values,
|
|
924
|
+
allowDuplicates: input.confirmNew,
|
|
925
|
+
});
|
|
926
|
+
const booking = await ctx.ops.call("record.get", {
|
|
927
|
+
object: BOOKING,
|
|
928
|
+
id: made.id,
|
|
929
|
+
});
|
|
930
|
+
return {
|
|
931
|
+
result: "booked",
|
|
932
|
+
bookingId: made.id,
|
|
933
|
+
classId: input.classId,
|
|
934
|
+
personId: made.personId,
|
|
935
|
+
holderId: text(booking.values.holder),
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
return refusalOf(error, "book");
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
});
|
|
943
|
+
const cancelled = z.object({
|
|
944
|
+
result: z.enum(["cancelled", "late_cancelled"]),
|
|
945
|
+
bookingId: z.string(),
|
|
946
|
+
late: z.boolean().describe("A late cancel keeps the use the booking spent"),
|
|
947
|
+
});
|
|
948
|
+
export const cancelFor = defineTool({
|
|
949
|
+
description: "Staff cancel a booking, decided by the host's clock as a member's own cancel is: in time " +
|
|
950
|
+
"(`cancelled`, the use given back) until the class type's late-cancel time, late " +
|
|
951
|
+
"(`late_cancelled`, the use kept) after it, not at all once the class has started. With " +
|
|
952
|
+
"`keepUse` it is cancelled late whatever the time. To give a use back after the late point, a " +
|
|
953
|
+
"person uses returnUse. The place is given back either way. Only a booked booking can be " +
|
|
954
|
+
"cancelled; one that has moved on is reported as changed.",
|
|
955
|
+
input: z.object({
|
|
956
|
+
bookingId: z.string().min(1).max(64),
|
|
957
|
+
keepUse: z.boolean().default(false),
|
|
958
|
+
note: z.string().max(2000).optional(),
|
|
959
|
+
}),
|
|
960
|
+
output: z.union([cancelled, refused]),
|
|
961
|
+
risk: "write",
|
|
962
|
+
async handler(input, ctx) {
|
|
963
|
+
try {
|
|
964
|
+
// `cancel` is resolved by the host: this tool's calls are never a person's (ADR 0507).
|
|
965
|
+
const after = await ctx.ops.call("record.update", {
|
|
966
|
+
object: BOOKING,
|
|
967
|
+
id: input.bookingId,
|
|
968
|
+
from: "booked",
|
|
969
|
+
values: {
|
|
970
|
+
state: input.keepUse ? "late_cancelled" : "cancel",
|
|
971
|
+
...(input.note ? { note: input.note } : {}),
|
|
972
|
+
},
|
|
973
|
+
});
|
|
974
|
+
const state = after.values.state === "late_cancelled" ? "late_cancelled" : "cancelled";
|
|
975
|
+
return { result: state, bookingId: input.bookingId, late: state === "late_cancelled" };
|
|
976
|
+
}
|
|
977
|
+
catch (error) {
|
|
978
|
+
return refusalOf(error, "cancel");
|
|
979
|
+
}
|
|
980
|
+
},
|
|
981
|
+
});
|
|
982
|
+
export const returnUse = defineTool({
|
|
983
|
+
description: "A person on the staff cancels a booking and gives its use back whatever the time: after " +
|
|
984
|
+
"the late-cancel point, or after the class (a member who was ill, a class the coach missed). " +
|
|
985
|
+
"A person's own act: the assistant, MCP clients, automations and other code cannot call it. " +
|
|
986
|
+
"The reason is kept on the booking and in the audit log. Only a booked booking.",
|
|
987
|
+
input: z.object({
|
|
988
|
+
bookingId: z.string().min(1).max(64),
|
|
989
|
+
reason: z.string().trim().min(3).max(2000),
|
|
990
|
+
}),
|
|
991
|
+
output: z.union([
|
|
992
|
+
z.object({ result: z.literal("excused"), bookingId: z.string(), late: z.literal(false) }),
|
|
993
|
+
refused,
|
|
994
|
+
]),
|
|
995
|
+
risk: "destructive",
|
|
996
|
+
// Only a person calls it, with the pack's permission (ADR 0513); the move it makes is open to
|
|
997
|
+
// no other staff write.
|
|
998
|
+
humanOnly: true,
|
|
999
|
+
permission: "bookings:returns",
|
|
1000
|
+
async handler(input, ctx) {
|
|
1001
|
+
try {
|
|
1002
|
+
await ctx.ops.call("record.update", {
|
|
1003
|
+
object: BOOKING,
|
|
1004
|
+
id: input.bookingId,
|
|
1005
|
+
from: "booked",
|
|
1006
|
+
values: { state: "excused", note: `Use given back: ${input.reason}` },
|
|
1007
|
+
});
|
|
1008
|
+
return { result: "excused", bookingId: input.bookingId, late: false };
|
|
1009
|
+
}
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
return refusalOf(error, "cancel");
|
|
1012
|
+
}
|
|
1013
|
+
},
|
|
1014
|
+
});
|
|
1015
|
+
/** The instant a local date's midnight is in `zone` (display only: which classes a day lists). */
|
|
1016
|
+
export function localMidnight(date, zone) {
|
|
1017
|
+
const [y, m, d] = date.split("-").map(Number);
|
|
1018
|
+
const guess = Date.UTC(y, m - 1, d);
|
|
1019
|
+
const offsetAt = (instant) => {
|
|
1020
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
1021
|
+
timeZone: zone,
|
|
1022
|
+
hourCycle: "h23",
|
|
1023
|
+
year: "numeric",
|
|
1024
|
+
month: "2-digit",
|
|
1025
|
+
day: "2-digit",
|
|
1026
|
+
hour: "2-digit",
|
|
1027
|
+
minute: "2-digit",
|
|
1028
|
+
second: "2-digit",
|
|
1029
|
+
}).formatToParts(new Date(instant));
|
|
1030
|
+
const get = (type) => Number(parts.find((p) => p.type === type)?.value);
|
|
1031
|
+
const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
|
|
1032
|
+
return asUtc - instant;
|
|
1033
|
+
};
|
|
1034
|
+
const first = guess - offsetAt(guess);
|
|
1035
|
+
return guess - offsetAt(first);
|
|
1036
|
+
}
|
|
1037
|
+
const staffClass = z.object({
|
|
1038
|
+
id: z.string(),
|
|
1039
|
+
title: z.string().nullable(),
|
|
1040
|
+
classType: named,
|
|
1041
|
+
startsAt: z.string().nullable(),
|
|
1042
|
+
endsAt: z.string().nullable(),
|
|
1043
|
+
timeZone,
|
|
1044
|
+
coach: z.string().nullable(),
|
|
1045
|
+
room: z.string().nullable(),
|
|
1046
|
+
places: z.number().nullable(),
|
|
1047
|
+
booked: z.number().describe("Places taken"),
|
|
1048
|
+
held: z.number(),
|
|
1049
|
+
available: z.number().nullable(),
|
|
1050
|
+
state: z.string().nullable(),
|
|
1051
|
+
staffOnly: z.boolean().describe("Its class type is booked by staff only"),
|
|
1052
|
+
});
|
|
1053
|
+
async function staffClasses(ctx, classes) {
|
|
1054
|
+
const types = new Map();
|
|
1055
|
+
const typeIds = [...new Set(classes.map((c) => text(c.values.classType)).filter(Boolean))];
|
|
1056
|
+
if (typeIds.length) {
|
|
1057
|
+
const found = await ctx.ops.call("record.list", {
|
|
1058
|
+
object: CLASS_TYPE,
|
|
1059
|
+
filter: { field: "id", op: "in", value: typeIds },
|
|
1060
|
+
limit: typeIds.length,
|
|
1061
|
+
});
|
|
1062
|
+
for (const item of found.items)
|
|
1063
|
+
types.set(item.id, item.values);
|
|
1064
|
+
}
|
|
1065
|
+
const names = async (object, field) => {
|
|
1066
|
+
const ids = [...new Set(classes.map((c) => text(c.values[field])).filter(Boolean))];
|
|
1067
|
+
if (!ids.length)
|
|
1068
|
+
return new Map();
|
|
1069
|
+
const found = await ctx.ops.call("record.list", {
|
|
1070
|
+
object,
|
|
1071
|
+
filter: { field: "id", op: "in", value: ids },
|
|
1072
|
+
limit: ids.length,
|
|
1073
|
+
});
|
|
1074
|
+
return new Map(found.items.map((item) => [item.id, text(item.values.name)]));
|
|
1075
|
+
};
|
|
1076
|
+
const coaches = await names(COACH, "coach");
|
|
1077
|
+
const rooms = await names(ROOM, "room");
|
|
1078
|
+
return classes.map((klass) => {
|
|
1079
|
+
const v = klass.values;
|
|
1080
|
+
const typeId = text(v.classType);
|
|
1081
|
+
const type = typeId ? types.get(typeId) : undefined;
|
|
1082
|
+
return {
|
|
1083
|
+
id: klass.id,
|
|
1084
|
+
title: text(v.title) ?? text(klass.title),
|
|
1085
|
+
classType: typeId ? { id: typeId, name: text(type?.name) } : null,
|
|
1086
|
+
startsAt: text(v.startsAt),
|
|
1087
|
+
endsAt: text(v.endsAt),
|
|
1088
|
+
timeZone: text(v.timezone),
|
|
1089
|
+
coach: coaches.get(text(v.coach) ?? "") ?? null,
|
|
1090
|
+
room: rooms.get(text(v.room) ?? "") ?? null,
|
|
1091
|
+
places: num(v.places),
|
|
1092
|
+
booked: num(v.taken) ?? 0,
|
|
1093
|
+
held: num(v.held) ?? 0,
|
|
1094
|
+
available: num(v.available),
|
|
1095
|
+
state: text(v.state),
|
|
1096
|
+
// Bookings' own field on Programs' class type (registry name `bookings.staffOnly`).
|
|
1097
|
+
staffOnly: flag(type?.["bookings.staffOnly"] ?? type?.staffOnly),
|
|
1098
|
+
};
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
export const day = defineTool({
|
|
1102
|
+
description: "Staff's day view: every class on one local date (scheduled, cancelled or done), in start " +
|
|
1103
|
+
"order, with its class type, coach, room, places, how many are booked and held, and whether " +
|
|
1104
|
+
"its class type is booked by staff only. For the front desk and coaches. Read-only.",
|
|
1105
|
+
input: z.object({
|
|
1106
|
+
date: z
|
|
1107
|
+
.string()
|
|
1108
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
1109
|
+
.describe("The local date, YYYY-MM-DD"),
|
|
1110
|
+
timeZone: z
|
|
1111
|
+
.string()
|
|
1112
|
+
.min(1)
|
|
1113
|
+
.max(64)
|
|
1114
|
+
.default("UTC")
|
|
1115
|
+
.describe("The zone the date is in (the gym's, e.g. Australia/Sydney)"),
|
|
1116
|
+
}),
|
|
1117
|
+
output: z.object({ date: z.string(), classes: z.array(staffClass) }),
|
|
1118
|
+
risk: "read",
|
|
1119
|
+
// The coach role holds it (ADR 0436); staff hold it as any read tool.
|
|
1120
|
+
permission: "bookings:coach",
|
|
1121
|
+
async handler(input, ctx) {
|
|
1122
|
+
const from = localMidnight(input.date, input.timeZone);
|
|
1123
|
+
const next = new Date(Date.parse(`${input.date}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
|
|
1124
|
+
const to = localMidnight(next, input.timeZone);
|
|
1125
|
+
const page = await ctx.ops.call("record.list", {
|
|
1126
|
+
object: CLASS,
|
|
1127
|
+
filter: {
|
|
1128
|
+
and: [
|
|
1129
|
+
{ field: "startsAt", op: "gte", value: new Date(from).toISOString() },
|
|
1130
|
+
{ field: "startsAt", op: "lt", value: new Date(to).toISOString() },
|
|
1131
|
+
],
|
|
1132
|
+
},
|
|
1133
|
+
sort: { field: "startsAt", direction: "asc" },
|
|
1134
|
+
limit: 200,
|
|
1135
|
+
});
|
|
1136
|
+
return { date: input.date, classes: await staffClasses(ctx, page.items) };
|
|
1137
|
+
},
|
|
1138
|
+
});
|
|
1139
|
+
export const classList = defineTool({
|
|
1140
|
+
description: "A class's list for staff and coaches: the class (as on the day view) and every booking of " +
|
|
1141
|
+
"it with the person's name, its state (booked, waiting, cancelled, cancelled late…), " +
|
|
1142
|
+
"whether they paid at the desk, the membership or pass it spent from, who booked it, and " +
|
|
1143
|
+
"for the waitlist when they were moved in or why they were passed over. Waiters are in " +
|
|
1144
|
+
"the order they joined. Read-only.",
|
|
1145
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
1146
|
+
output: z.object({
|
|
1147
|
+
class: staffClass,
|
|
1148
|
+
bookings: z.array(z.object({
|
|
1149
|
+
id: z.string(),
|
|
1150
|
+
person: named,
|
|
1151
|
+
state: z.string().nullable(),
|
|
1152
|
+
paidAtDesk: z.boolean(),
|
|
1153
|
+
holderId: z.string().nullable(),
|
|
1154
|
+
bookedBy: z.string().nullable(),
|
|
1155
|
+
promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
|
|
1156
|
+
passedOver: z
|
|
1157
|
+
.string()
|
|
1158
|
+
.nullable()
|
|
1159
|
+
.describe("While waiting: why a free place could not be theirs (what they hold)"),
|
|
1160
|
+
})),
|
|
1161
|
+
}),
|
|
1162
|
+
risk: "read",
|
|
1163
|
+
async handler(input, ctx) {
|
|
1164
|
+
const { klass, bookings, names } = await listOf(ctx, input.classId);
|
|
1165
|
+
return {
|
|
1166
|
+
class: klass,
|
|
1167
|
+
bookings: bookings.map((booking) => {
|
|
1168
|
+
const personId = text(booking.values.person);
|
|
1169
|
+
return {
|
|
1170
|
+
id: booking.id,
|
|
1171
|
+
person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
|
|
1172
|
+
state: text(booking.values.state),
|
|
1173
|
+
paidAtDesk: flag(booking.values.paidOtherwise),
|
|
1174
|
+
holderId: text(booking.values.holder),
|
|
1175
|
+
bookedBy: text(booking.values.bookedBy),
|
|
1176
|
+
promotedAt: text(booking.values.promotedAt),
|
|
1177
|
+
passedOver: text(booking.values.passedOverReason),
|
|
1178
|
+
};
|
|
1179
|
+
}),
|
|
1180
|
+
};
|
|
1181
|
+
},
|
|
1182
|
+
});
|
|
1183
|
+
// --- Attendance, the coach's list (step 7) --------------------------------------------------------
|
|
1184
|
+
/** Who is marking a list: the staff member who called the tool (never from the input). */
|
|
1185
|
+
function marker(ctx) {
|
|
1186
|
+
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
1187
|
+
return { markedBy: staff?.userId ?? null, markedByName: staff?.name || null };
|
|
1188
|
+
}
|
|
1189
|
+
const marked = z.object({
|
|
1190
|
+
result: z.enum(["attended", "no_show", "booked"]),
|
|
1191
|
+
bookingId: z.string(),
|
|
1192
|
+
message: z.string(),
|
|
1193
|
+
});
|
|
1194
|
+
const alreadyMarked = z.object({
|
|
1195
|
+
result: z.literal("already"),
|
|
1196
|
+
bookingId: z.string(),
|
|
1197
|
+
state: z.string().nullable().describe("What the booking is now"),
|
|
1198
|
+
markedAt: z.string().nullable(),
|
|
1199
|
+
markedBy: z.string().nullable().describe("The name of who marked it first"),
|
|
1200
|
+
message: z.string(),
|
|
1201
|
+
});
|
|
1202
|
+
const listRefused = z.object({
|
|
1203
|
+
result: z.literal("refused"),
|
|
1204
|
+
reason: z
|
|
1205
|
+
.enum(["not_found", "not_started", "not_booked", "changed"])
|
|
1206
|
+
.describe("not_started: the list opens an hour before the class (see opensAt). not_booked: the " +
|
|
1207
|
+
"booking is not one that can be marked (cancelled, waiting, moved…; see state). changed: " +
|
|
1208
|
+
"it changed meanwhile; look again."),
|
|
1209
|
+
state: z.string().nullable(),
|
|
1210
|
+
opensAt: z.string().nullable(),
|
|
1211
|
+
message: z.string(),
|
|
1212
|
+
});
|
|
1213
|
+
const STATE_WORDS = {
|
|
1214
|
+
booked: "booked",
|
|
1215
|
+
attended: "ticked as come",
|
|
1216
|
+
no_show: "marked as not come",
|
|
1217
|
+
waiting: "on the waitlist",
|
|
1218
|
+
cancelled: "cancelled",
|
|
1219
|
+
late_cancelled: "cancelled late",
|
|
1220
|
+
excused: "cancelled with the class given back",
|
|
1221
|
+
cancelled_by_us: "cancelled with the class",
|
|
1222
|
+
moved: "moved to another class",
|
|
1223
|
+
left: "off the waitlist",
|
|
1224
|
+
pending: "held while paying",
|
|
1225
|
+
expired: "expired",
|
|
1226
|
+
};
|
|
1227
|
+
const words = (state) => STATE_WORDS[state ?? ""] ?? state ?? "unknown";
|
|
1228
|
+
/**
|
|
1229
|
+
* Marks one booking as `to` from where it is (one of `from`), from that position or not at all
|
|
1230
|
+
* (ADR 0437): of two coaches marking one name at once, one is made and the other is told who was
|
|
1231
|
+
* first. The host holds when a list may be marked (from an hour before the class) and which moves
|
|
1232
|
+
* a booking may make.
|
|
1233
|
+
*/
|
|
1234
|
+
async function markBooking(ctx, bookingId, to, from) {
|
|
1235
|
+
const no = (reason, message, state = null, opensAt = null) => ({ result: "refused", reason, state, opensAt, message });
|
|
1236
|
+
let record;
|
|
1237
|
+
try {
|
|
1238
|
+
record = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
|
|
1239
|
+
}
|
|
1240
|
+
catch (error) {
|
|
1241
|
+
if (error instanceof OpsCallError && error.code === "not_found") {
|
|
1242
|
+
return no("not_found", "No such booking.");
|
|
1243
|
+
}
|
|
1244
|
+
throw error;
|
|
1245
|
+
}
|
|
1246
|
+
const already = (now) => {
|
|
1247
|
+
const state = text(now.values.state);
|
|
1248
|
+
const by = text(now.values.markedByName);
|
|
1249
|
+
return {
|
|
1250
|
+
result: "already",
|
|
1251
|
+
bookingId,
|
|
1252
|
+
state,
|
|
1253
|
+
markedAt: text(now.values.markedAt),
|
|
1254
|
+
markedBy: by,
|
|
1255
|
+
message: `Already ${words(state)}${by ? ` by ${by}` : ""}.`,
|
|
1256
|
+
};
|
|
1257
|
+
};
|
|
1258
|
+
const state = text(record.values.state) ?? "";
|
|
1259
|
+
if (state === to)
|
|
1260
|
+
return already(record);
|
|
1261
|
+
if (!from.includes(state)) {
|
|
1262
|
+
return no("not_booked", `This booking is ${words(state)}: it cannot be marked.`, state);
|
|
1263
|
+
}
|
|
1264
|
+
const values = to === "booked"
|
|
1265
|
+
? { state: to, markedAt: null, markedBy: null, markedByName: null }
|
|
1266
|
+
: { state: to, markedAt: new Date().toISOString(), ...marker(ctx) };
|
|
1267
|
+
try {
|
|
1268
|
+
await ctx.ops.call("record.update", { object: BOOKING, id: bookingId, from: state, values });
|
|
1269
|
+
}
|
|
1270
|
+
catch (error) {
|
|
1271
|
+
if (!(error instanceof OpsCallError))
|
|
1272
|
+
throw error;
|
|
1273
|
+
const details = (error.details ?? {});
|
|
1274
|
+
if (details.rule === "state_window_not_open") {
|
|
1275
|
+
return no("not_started", to === "no_show"
|
|
1276
|
+
? "A no-show is marked once the class has started."
|
|
1277
|
+
: "The class's list opens an hour before it starts.", state, text(details.opensAt));
|
|
1278
|
+
}
|
|
1279
|
+
if (error.code === "conflict") {
|
|
1280
|
+
// Someone marked it first (or it moved): say who, from what it is now.
|
|
1281
|
+
const now = await ctx.ops.call("record.get", { object: BOOKING, id: bookingId });
|
|
1282
|
+
if (text(now.values.state) === to)
|
|
1283
|
+
return already(now);
|
|
1284
|
+
const is = text(now.values.state);
|
|
1285
|
+
return no("changed", `It changed meanwhile: it is now ${words(is)}.`, is);
|
|
1286
|
+
}
|
|
1287
|
+
if (details.rule === "state_move_not_declared" || details.rule === "state_final") {
|
|
1288
|
+
return no("not_booked", "This booking cannot be marked.", state);
|
|
1289
|
+
}
|
|
1290
|
+
throw error;
|
|
1291
|
+
}
|
|
1292
|
+
return {
|
|
1293
|
+
result: to,
|
|
1294
|
+
bookingId,
|
|
1295
|
+
message: to === "attended"
|
|
1296
|
+
? "Ticked: they came."
|
|
1297
|
+
: to === "no_show"
|
|
1298
|
+
? "Marked: they did not come. The class stays used."
|
|
1299
|
+
: "Unticked: booked again.",
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
const markOutput = z.union([marked, alreadyMarked, listRefused]);
|
|
1303
|
+
export const markAttended = defineTool({
|
|
1304
|
+
description: "Tick a booking on a class's list: they came. From an hour before the class, and any time " +
|
|
1305
|
+
"after it (a late correction: a no-show ticked becomes attended). Of two coaches ticking one " +
|
|
1306
|
+
"name at once, one tick is made and the other is told who was first. A booking that is " +
|
|
1307
|
+
"cancelled, waiting or moved cannot be ticked. The use it spent stays spent.",
|
|
1308
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1309
|
+
output: markOutput,
|
|
1310
|
+
risk: "write",
|
|
1311
|
+
permission: "bookings:coach",
|
|
1312
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "attended", ["booked", "no_show"]),
|
|
1313
|
+
});
|
|
1314
|
+
export const undoAttended = defineTool({
|
|
1315
|
+
description: "Untick a booking ticked by mistake: it is booked again (and, once the class is 30 minutes " +
|
|
1316
|
+
"over with others ticked, the host makes it a no-show). Who ticked it and when are cleared.",
|
|
1317
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1318
|
+
output: markOutput,
|
|
1319
|
+
risk: "write",
|
|
1320
|
+
permission: "bookings:coach",
|
|
1321
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "booked", ["attended"]),
|
|
1322
|
+
});
|
|
1323
|
+
export const markNoShow = defineTool({
|
|
1324
|
+
description: "Mark a booked booking as not come (a no-show), once the class has started. The class stays " +
|
|
1325
|
+
"used (no money, nothing else follows). The host does this itself for everyone still booked " +
|
|
1326
|
+
"30 minutes after the class ends, if anyone on the list was marked.",
|
|
1327
|
+
input: z.object({ bookingId: z.string().min(1).max(64) }),
|
|
1328
|
+
output: markOutput,
|
|
1329
|
+
risk: "write",
|
|
1330
|
+
permission: "bookings:coach",
|
|
1331
|
+
handler: (input, ctx) => markBooking(ctx, input.bookingId, "no_show", ["booked"]),
|
|
1332
|
+
});
|
|
1333
|
+
export const markAll = defineTool({
|
|
1334
|
+
description: "Tick everyone still booked on a class's list at once (from an hour before the class). Each " +
|
|
1335
|
+
"name is ticked from where it is or not at all, so a name another coach ticked meanwhile is " +
|
|
1336
|
+
"counted as already ticked, not twice.",
|
|
1337
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
1338
|
+
output: z.union([
|
|
1339
|
+
z.object({
|
|
1340
|
+
result: z.literal("marked"),
|
|
1341
|
+
classId: z.string(),
|
|
1342
|
+
ticked: z.number().describe("Names ticked now"),
|
|
1343
|
+
already: z.number().describe("Names someone else ticked meanwhile"),
|
|
1344
|
+
skipped: z.number().describe("Names that changed meanwhile (cancelled, moved…)"),
|
|
1345
|
+
}),
|
|
1346
|
+
listRefused,
|
|
1347
|
+
]),
|
|
1348
|
+
risk: "write",
|
|
1349
|
+
permission: "bookings:coach",
|
|
1350
|
+
async handler(input, ctx) {
|
|
1351
|
+
const page = await ctx.ops.call("record.list", {
|
|
1352
|
+
object: BOOKING,
|
|
1353
|
+
filter: {
|
|
1354
|
+
and: [
|
|
1355
|
+
{ field: "class", op: "eq", value: input.classId },
|
|
1356
|
+
{ field: "state", op: "eq", value: "booked" },
|
|
1357
|
+
],
|
|
1358
|
+
},
|
|
1359
|
+
sort: { field: "createdAt", direction: "asc" },
|
|
1360
|
+
limit: 200,
|
|
1361
|
+
});
|
|
1362
|
+
let ticked = 0;
|
|
1363
|
+
let already = 0;
|
|
1364
|
+
let skipped = 0;
|
|
1365
|
+
for (const booking of page.items) {
|
|
1366
|
+
const out = await markBooking(ctx, booking.id, "attended", ["booked"]);
|
|
1367
|
+
if (out.result === "attended")
|
|
1368
|
+
ticked += 1;
|
|
1369
|
+
else if (out.result === "already")
|
|
1370
|
+
already += 1;
|
|
1371
|
+
else if (out.result === "refused" && out.reason === "not_started")
|
|
1372
|
+
return out;
|
|
1373
|
+
else
|
|
1374
|
+
skipped += 1;
|
|
1375
|
+
}
|
|
1376
|
+
return { result: "marked", classId: input.classId, ticked, already, skipped };
|
|
1377
|
+
},
|
|
1378
|
+
});
|
|
1379
|
+
/** A class as staff see it, its bookings in the order they were made, and their people's names. */
|
|
1380
|
+
async function listOf(ctx, classId) {
|
|
1381
|
+
const record = await ctx.ops.call("record.get", { object: CLASS, id: classId });
|
|
1382
|
+
const [klass] = await staffClasses(ctx, [record]);
|
|
1383
|
+
const page = await ctx.ops.call("record.list", {
|
|
1384
|
+
object: BOOKING,
|
|
1385
|
+
filter: { field: "class", op: "eq", value: record.id },
|
|
1386
|
+
sort: { field: "createdAt", direction: "asc" },
|
|
1387
|
+
limit: 200,
|
|
1388
|
+
});
|
|
1389
|
+
const names = new Map();
|
|
1390
|
+
for (const id of new Set(page.items.map((b) => text(b.values.person)).filter(Boolean))) {
|
|
1391
|
+
try {
|
|
1392
|
+
const person = await ctx.ops.call("person.get", {
|
|
1393
|
+
id,
|
|
1394
|
+
});
|
|
1395
|
+
names.set(id, person?.displayName ?? null);
|
|
1396
|
+
}
|
|
1397
|
+
catch (error) {
|
|
1398
|
+
if (!(error instanceof OpsCallError) || error.code !== "not_found")
|
|
1399
|
+
throw error;
|
|
1400
|
+
names.set(id, null);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
return { klass: klass, bookings: page.items, names };
|
|
1404
|
+
}
|
|
1405
|
+
export const roster = defineTool({
|
|
1406
|
+
description: "A class's list for its coach: the class (as on the day view) and every booking of it with " +
|
|
1407
|
+
"the person's name and its state (booked, ticked, not come, waiting in the order they " +
|
|
1408
|
+
"joined, cancelled…), who marked it and when. Nothing about what anyone paid with. Read-only.",
|
|
1409
|
+
input: z.object({ classId: z.string().min(1).max(64) }),
|
|
1410
|
+
output: z.object({
|
|
1411
|
+
class: staffClass,
|
|
1412
|
+
bookings: z.array(z.object({
|
|
1413
|
+
id: z.string(),
|
|
1414
|
+
person: named,
|
|
1415
|
+
state: z.string().nullable(),
|
|
1416
|
+
markedAt: z.string().nullable(),
|
|
1417
|
+
markedBy: z.string().nullable().describe("The name of who marked it"),
|
|
1418
|
+
promotedAt: z.string().nullable().describe("When they were moved in from the waitlist"),
|
|
1419
|
+
})),
|
|
1420
|
+
}),
|
|
1421
|
+
risk: "read",
|
|
1422
|
+
permission: "bookings:coach",
|
|
1423
|
+
async handler(input, ctx) {
|
|
1424
|
+
const { klass, bookings, names } = await listOf(ctx, input.classId);
|
|
1425
|
+
return {
|
|
1426
|
+
class: klass,
|
|
1427
|
+
bookings: bookings.map((booking) => {
|
|
1428
|
+
const personId = text(booking.values.person);
|
|
1429
|
+
return {
|
|
1430
|
+
id: booking.id,
|
|
1431
|
+
person: personId ? { id: personId, name: names.get(personId) ?? null } : null,
|
|
1432
|
+
state: text(booking.values.state),
|
|
1433
|
+
markedAt: text(booking.values.markedAt),
|
|
1434
|
+
markedBy: text(booking.values.markedByName),
|
|
1435
|
+
promotedAt: text(booking.values.promotedAt),
|
|
1436
|
+
};
|
|
1437
|
+
}),
|
|
1438
|
+
};
|
|
1439
|
+
},
|
|
1440
|
+
});
|
|
1441
|
+
// --- Moving people and cancelling a class (step 7) ------------------------------------------------
|
|
1442
|
+
const moveRefusal = z
|
|
1443
|
+
.enum(["not_booked", "same_class", "started"])
|
|
1444
|
+
.describe("not_booked: only a booked booking moves. same_class: it is already on that class. started: " +
|
|
1445
|
+
"its class has started; giving its use back is returnUse's.");
|
|
1446
|
+
export const move = defineTool({
|
|
1447
|
+
description: "Staff move a member's booking to another class, with the use it spent, in one batch: the " +
|
|
1448
|
+
"old booking is moved (its place given back, to the waitlist first before its cut-off), a " +
|
|
1449
|
+
"new booking is made on the other class, and the use is spent again on it from the same " +
|
|
1450
|
+
"membership or pass. Refused whole, with nothing changed, when the other class is full " +
|
|
1451
|
+
"(places held for its waitlist included: raise its places first), was cancelled or is over, " +
|
|
1452
|
+
"they are already booked on it, or the use cannot be spent in that class's week or period. " +
|
|
1453
|
+
"Only a booked booking, before its class starts. A booking paid at the desk moves paid at " +
|
|
1454
|
+
"the desk. Audited.",
|
|
1455
|
+
input: z.object({
|
|
1456
|
+
bookingId: z.string().min(1).max(64),
|
|
1457
|
+
toClassId: z.string().min(1).max(64),
|
|
1458
|
+
note: z.string().max(2000).optional(),
|
|
1459
|
+
}),
|
|
1460
|
+
output: z.union([
|
|
1461
|
+
z.object({
|
|
1462
|
+
result: z.literal("moved"),
|
|
1463
|
+
fromBookingId: z.string(),
|
|
1464
|
+
bookingId: z.string().describe("The new booking"),
|
|
1465
|
+
classId: z.string(),
|
|
1466
|
+
holderId: z.string().nullable().describe("The membership or pass the use is spent from"),
|
|
1467
|
+
}),
|
|
1468
|
+
refused,
|
|
1469
|
+
refused.extend({ reason: moveRefusal }),
|
|
1470
|
+
]),
|
|
1471
|
+
risk: "write",
|
|
1472
|
+
async handler(input, ctx) {
|
|
1473
|
+
const no = (reason, message) => ({
|
|
1474
|
+
result: "refused",
|
|
1475
|
+
reason,
|
|
1476
|
+
message,
|
|
1477
|
+
detail: null,
|
|
1478
|
+
opensAt: null,
|
|
1479
|
+
closesAt: null,
|
|
1480
|
+
});
|
|
1481
|
+
let old;
|
|
1482
|
+
try {
|
|
1483
|
+
old = await ctx.ops.call("record.get", { object: BOOKING, id: input.bookingId });
|
|
1484
|
+
}
|
|
1485
|
+
catch (error) {
|
|
1486
|
+
if (error instanceof OpsCallError && error.code === "not_found") {
|
|
1487
|
+
return refusalOf(error, "cancel");
|
|
1488
|
+
}
|
|
1489
|
+
throw error;
|
|
1490
|
+
}
|
|
1491
|
+
const state = text(old.values.state);
|
|
1492
|
+
if (state !== "booked") {
|
|
1493
|
+
return no("not_booked", `This booking is ${words(state)}: only a booked one moves.`);
|
|
1494
|
+
}
|
|
1495
|
+
if (text(old.values.class) === input.toClassId) {
|
|
1496
|
+
return no("same_class", "It is already booked on that class.");
|
|
1497
|
+
}
|
|
1498
|
+
const staff = ctx.caller?.kind === "staff" ? ctx.caller : null;
|
|
1499
|
+
try {
|
|
1500
|
+
// The host moves the old booking in this create's batch (the allowance's `movedFrom`): its
|
|
1501
|
+
// place given back, the use spent again here from the same holder; or nothing at all.
|
|
1502
|
+
const made = await ctx.ops.call("record.create", {
|
|
1503
|
+
object: BOOKING,
|
|
1504
|
+
values: {
|
|
1505
|
+
class: input.toClassId,
|
|
1506
|
+
person: text(old.values.person),
|
|
1507
|
+
movedFrom: old.id,
|
|
1508
|
+
...(staff?.userId ? { bookedBy: staff.userId } : {}),
|
|
1509
|
+
...(input.note ? { note: input.note } : {}),
|
|
1510
|
+
},
|
|
1511
|
+
});
|
|
1512
|
+
return {
|
|
1513
|
+
result: "moved",
|
|
1514
|
+
fromBookingId: old.id,
|
|
1515
|
+
bookingId: made.id,
|
|
1516
|
+
classId: input.toClassId,
|
|
1517
|
+
holderId: text(made.values.holder),
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
catch (error) {
|
|
1521
|
+
const rule = error instanceof OpsCallError
|
|
1522
|
+
? error.details?.rule
|
|
1523
|
+
: undefined;
|
|
1524
|
+
// The old booking moved to a final state meanwhile (the member cancelled it): a race.
|
|
1525
|
+
if (rule === "state_final") {
|
|
1526
|
+
return {
|
|
1527
|
+
result: "refused",
|
|
1528
|
+
reason: "changed",
|
|
1529
|
+
message: "It changed meanwhile: it is no longer booked. Look again.",
|
|
1530
|
+
detail: null,
|
|
1531
|
+
opensAt: null,
|
|
1532
|
+
closesAt: null,
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
// The old booking's own move has a window: until its class starts.
|
|
1536
|
+
if (rule === "state_window_closed") {
|
|
1537
|
+
return no("started", "Its class has started: it can no longer be moved. A person can give its use back (returnUse).");
|
|
1538
|
+
}
|
|
1539
|
+
return refusalOf(error, "book");
|
|
1540
|
+
}
|
|
1541
|
+
},
|
|
1542
|
+
});
|
|
1543
|
+
export const cancelClass = defineTool({
|
|
1544
|
+
description: "Cancel a scheduled class that has not ended, with a reason: in the same batch every booking " +
|
|
1545
|
+
"of it holding a place or a use (booked, waiting, held while paying, ticked as come, marked " +
|
|
1546
|
+
"not come, cancelled late) is cancelled by the gym, each place given back and each use " +
|
|
1547
|
+
"returned once. A person's act: the assistant, MCP clients and automations may ask, and it " +
|
|
1548
|
+
"waits for a person to approve it. When it cannot be done (no such class, not scheduled, " +
|
|
1549
|
+
"already ended, or it changed twice while being done) it fails with the reason, so an " +
|
|
1550
|
+
"approved request shows it did not apply. (Emails to the members, and refunds of paid " +
|
|
1551
|
+
"drop-ins, come in a later release.)",
|
|
1552
|
+
input: z.object({
|
|
1553
|
+
classId: z.string().min(1).max(64),
|
|
1554
|
+
reason: z.string().trim().min(3).max(2000),
|
|
1555
|
+
}),
|
|
1556
|
+
output: z.object({
|
|
1557
|
+
result: z.literal("cancelled"),
|
|
1558
|
+
classId: z.string(),
|
|
1559
|
+
bookingsCancelled: z.number().describe("Bookings cancelled with the class"),
|
|
1560
|
+
}),
|
|
1561
|
+
risk: "destructive",
|
|
1562
|
+
// Anyone but a person waits for a person's approval (ADR 0552); the class's move into
|
|
1563
|
+
// cancelled is made by this tool and the host only.
|
|
1564
|
+
personApproves: true,
|
|
1565
|
+
permission: "bookings:cancelClasses",
|
|
1566
|
+
async handler(input, ctx) {
|
|
1567
|
+
// A refusal is an error, never an answer: an approved request that cannot apply must show
|
|
1568
|
+
// that it did not (ADR 0553).
|
|
1569
|
+
const fail = (code, reason, message) => {
|
|
1570
|
+
throw new OpsCallError(code, message, { reason });
|
|
1571
|
+
};
|
|
1572
|
+
// A race (a booking landing under the cancel, another write moving the class) is tried once
|
|
1573
|
+
// more from a fresh read; anything else is the answer.
|
|
1574
|
+
for (let attempt = 0;; attempt++) {
|
|
1575
|
+
try {
|
|
1576
|
+
await ctx.ops.call("record.update", {
|
|
1577
|
+
object: CLASS,
|
|
1578
|
+
id: input.classId,
|
|
1579
|
+
from: "scheduled",
|
|
1580
|
+
values: { state: "cancelled", cancelledReason: input.reason },
|
|
1581
|
+
});
|
|
1582
|
+
break;
|
|
1583
|
+
}
|
|
1584
|
+
catch (error) {
|
|
1585
|
+
if (!(error instanceof OpsCallError))
|
|
1586
|
+
throw error;
|
|
1587
|
+
if (error.code === "not_found")
|
|
1588
|
+
fail("not_found", "not_found", "No such class.");
|
|
1589
|
+
const details = (error.details ?? {});
|
|
1590
|
+
if (details.reason === "not_in_position") {
|
|
1591
|
+
fail("conflict", "not_scheduled", "This class is not scheduled (it was cancelled or is over).");
|
|
1592
|
+
}
|
|
1593
|
+
if (details.rule === "state_window_closed") {
|
|
1594
|
+
fail("invalid_input", "ended", "This class has ended: a class that happened is not cancelled. A person can give a booking's use back (returnUse).");
|
|
1595
|
+
}
|
|
1596
|
+
if (details.rule === "state_window_unknown") {
|
|
1597
|
+
fail("invalid_input", "no_end", "This class has no end time, so whether it has ended cannot be told: give it one first.");
|
|
1598
|
+
}
|
|
1599
|
+
if (error.code === "conflict" && attempt === 0)
|
|
1600
|
+
continue;
|
|
1601
|
+
if (error.code === "conflict") {
|
|
1602
|
+
fail("conflict", "changed", "The class or its bookings changed while it was being cancelled. Look again.");
|
|
1603
|
+
}
|
|
1604
|
+
throw error;
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
const page = await ctx.ops.call("record.list", {
|
|
1608
|
+
object: BOOKING,
|
|
1609
|
+
filter: {
|
|
1610
|
+
and: [
|
|
1611
|
+
{ field: "class", op: "eq", value: input.classId },
|
|
1612
|
+
{ field: "state", op: "eq", value: "cancelled_by_us" },
|
|
1613
|
+
],
|
|
1614
|
+
},
|
|
1615
|
+
limit: 200,
|
|
1616
|
+
});
|
|
1617
|
+
return {
|
|
1618
|
+
result: "cancelled",
|
|
1619
|
+
classId: input.classId,
|
|
1620
|
+
bookingsCancelled: page.items.length,
|
|
1621
|
+
};
|
|
1622
|
+
},
|
|
1623
|
+
});
|