recess-cli 3.10.0 → 3.12.0

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.
@@ -0,0 +1,357 @@
1
+ import { unwrap } from "../api.js";
2
+ import { flagList, flagString, hasFlag } from "../args.js";
3
+ import { CliError } from "../errors.js";
4
+ import { assertChoice, positional, renderColumns, } from "./shared.js";
5
+ import { parseTuitionPlanSpecFlags } from "./tuition-plans.js";
6
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
7
+ const dollars = (cents) => `$${(cents / 100).toLocaleString("en-US", {
8
+ minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
9
+ maximumFractionDigits: 2,
10
+ })}`;
11
+ const STEP_LABELS = {
12
+ ACCOUNT: "waiting for the parent to create the account",
13
+ SIGN: "waiting for the tuition plan signature",
14
+ CONSENT: "waiting for parental consent",
15
+ QUESTIONS: "waiting for the enrollment questions",
16
+ PAYMENT: "waiting for payment",
17
+ DONE: "done",
18
+ };
19
+ /** One packet as terminal text: who, where they are, and each kid's answers. */
20
+ function renderPacket(packet, admissionUrl) {
21
+ const when = (iso) => (iso ? iso.slice(0, 10) : "–");
22
+ const out = [
23
+ `ADMISSION PACKET ${packet.id}`,
24
+ `${packet.parentFirstName} ${packet.parentLastName} <${packet.parentEmail}>${packet.parentPhone ? ` · ${packet.parentPhone}` : ""} · ${packet.stateCode}`,
25
+ `${packet.enrollmentType === "PARTNER_SCHOOL" ? `Through ${packet.partnerSchool?.name ?? "partner school"}` : packet.enrollmentType === "PROGRAM" ? "Online learning program" : "Direct enrollment"} · ${packet.institution.name} · tier ${packet.tierId}${packet.paywallCents ? ` · paywall ${dollars(packet.paywallCents)}` : " · no paywall"}`,
26
+ `Status: ${packet.status} (${STEP_LABELS[packet.step]})`,
27
+ packet.financialAidApplication
28
+ ? `Financial aid answers in the envelope: application ${packet.financialAidApplication.id} (${packet.financialAidApplication.createdAt.slice(0, 10)})`
29
+ : "No financial aid application attached (nothing to initial).",
30
+ "",
31
+ renderColumns([
32
+ [" Sent", when(packet.sentAt), `emails: ${packet.emailSendCount}`],
33
+ [
34
+ " Account",
35
+ when(packet.accountCreatedAt),
36
+ packet.familyId ? `family ${packet.familyId}` : "",
37
+ ],
38
+ [
39
+ " Signed",
40
+ when(packet.signedAt),
41
+ packet.chosenOptionId
42
+ ? `option ${packet.chosenOptionId}${packet.documensoEnvelopeId ? ` · documenso ${packet.documensoEnvelopeId}` : ""}`
43
+ : "",
44
+ ],
45
+ [" Consent", when(packet.consentedAt), ""],
46
+ [" Questions", when(packet.questionsCompletedAt), ""],
47
+ ...(packet.paywallCents ? [[" Paid", when(packet.paidAt), ""]] : []),
48
+ [" Complete", when(packet.completedAt), ""],
49
+ ]),
50
+ ];
51
+ if (packet.status === "VOIDED") {
52
+ out.push(`Voided ${when(packet.voidedAt)}: ${packet.voidReason ?? ""}`);
53
+ }
54
+ if (packet.agreedPlan?.length) {
55
+ out.push("", "Agreed plan (as signed):");
56
+ for (const kid of packet.agreedPlan) {
57
+ out.push(` ${kid.studentName}: ${kid.term.label}, ${kid.payment.label.toLowerCase()} · ${kid.term.startDate} to ${kid.term.endDate} (${kid.term.instructionalDays} days) · total ${dollars(kid.payment.totalCents)}${kid.payment.discountCents ? ` (saves ${dollars(kid.payment.discountCents)})` : ""}`);
58
+ for (const inst of kid.installments) {
59
+ out.push(` ${inst.label}: ${dollars(inst.amountCents)}${inst.award === "PENDING" ? " at most, set once the award is confirmed" : ""} · invoiced ${inst.invoiceDate} · due ${inst.dueDate}`);
60
+ }
61
+ }
62
+ }
63
+ if (packet.signedAt) {
64
+ out.push(packet.signedAgreementKey
65
+ ? `Signed agreement archived ${when(packet.signedAgreementAt)}: ${packet.signedAgreementKey}`
66
+ : packet.documensoEnvelopeId
67
+ ? "Signed agreement not archived yet (run `recess admissions archive-agreement <packet-id>`)."
68
+ : "Signed outside Documenso: no agreement file on record.");
69
+ }
70
+ out.push("", "Kids:");
71
+ for (const kid of packet.kids) {
72
+ out.push(` ${kid.firstName}${kid.lastName ? ` ${kid.lastName}` : ""}${kid.birthdate ? ` · born ${kid.birthdate}` : ""}${kid.grade ? ` · grade ${kid.grade}` : ""}${kid.gender ? ` · gender ${kid.gender}` : ""}${kid.ethnicity ? ` · ethnicity ${kid.ethnicity}` : ""}${kid.hispanicLatino ? ` · Hispanic/Latino ${kid.hispanicLatino}` : ""}${kid.kidUserId ? ` · user ${kid.kidUserId}` : ""}`);
73
+ if (kid.responses) {
74
+ for (const [key, value] of Object.entries(kid.responses)) {
75
+ const shown = Array.isArray(value)
76
+ ? value
77
+ .map((v) => typeof v === "object" && v && "fileName" in v
78
+ ? String(v.fileName)
79
+ : String(v))
80
+ .join("; ")
81
+ : String(value);
82
+ if (shown)
83
+ out.push(` ${key}: ${shown}`);
84
+ }
85
+ }
86
+ }
87
+ out.push("", `Plan spec: ${Object.entries(packet.planSpec)
88
+ .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join("|") : String(v)}`)
89
+ .join(" ")}`);
90
+ if (packet.staffNotes)
91
+ out.push(`Staff notes: ${packet.staffNotes}`);
92
+ if (admissionUrl)
93
+ out.push("", `Link: ${admissionUrl}`);
94
+ return out.join("\n");
95
+ }
96
+ const STATUSES = [
97
+ "SENT",
98
+ "ACCOUNT_CREATED",
99
+ "SIGNED",
100
+ "CONSENTED",
101
+ "QUESTIONS_DONE",
102
+ "COMPLETE",
103
+ "VOIDED",
104
+ ];
105
+ export async function runAdmissionsCommand({ parsed, api, writeCommand, }) {
106
+ const verb = parsed.positionals[1];
107
+ const json = hasFlag(parsed, "json");
108
+ if (verb === "list") {
109
+ const status = flagString(parsed, "status");
110
+ const { packets } = unwrap(await api.client.GET("/admin/admissions/", {
111
+ params: {
112
+ query: {
113
+ ...(status
114
+ ? {
115
+ status: assertChoice(status.toUpperCase(), STATUSES, "--status"),
116
+ }
117
+ : {}),
118
+ ...(flagString(parsed, "email")
119
+ ? { email: flagString(parsed, "email") }
120
+ : {}),
121
+ limit: Number(flagString(parsed, "limit") ?? 50),
122
+ },
123
+ },
124
+ }));
125
+ if (json)
126
+ return { packets };
127
+ return {
128
+ help: packets.length
129
+ ? renderColumns([
130
+ ["ID", "Parent", "Kids", "State", "Status", "Step"],
131
+ ...packets.map((p) => [
132
+ p.id,
133
+ `${p.parentFirstName} ${p.parentLastName} <${p.parentEmail}>`,
134
+ p.kids.map((k) => k.firstName).join(", "),
135
+ p.stateCode,
136
+ p.status,
137
+ STEP_LABELS[p.step],
138
+ ]),
139
+ ])
140
+ : "No admission packets.",
141
+ };
142
+ }
143
+ if (verb === "get") {
144
+ const packetId = positional(parsed, 2, "packet ID");
145
+ const { packet } = unwrap(await api.client.GET("/admin/admissions/{packetId}", {
146
+ params: { path: { packetId } },
147
+ }));
148
+ return json ? { packet } : { help: renderPacket(packet) };
149
+ }
150
+ if (verb === "create") {
151
+ const parentName = flagString(parsed, "parent", { required: true })
152
+ .trim()
153
+ .split(/\s+/);
154
+ if (parentName.length < 2) {
155
+ throw new CliError("invalid_arguments", '--parent needs a first and last name, e.g. --parent "Jordan Rivera".');
156
+ }
157
+ const kids = flagList(parsed, "kid").map((raw) => {
158
+ // "First Last:YYYY-MM-DD[:grade]"; the last name is optional.
159
+ const [who, birthdate, grade] = raw.split(":").map((v) => v.trim());
160
+ const names = (who ?? "").split(/\s+/).filter(Boolean);
161
+ if (!names.length || (birthdate && !ISO_DATE.test(birthdate))) {
162
+ throw new CliError("invalid_arguments", `--kid takes "First Last:YYYY-MM-DD[:grade]", got "${raw}".`);
163
+ }
164
+ return {
165
+ firstName: names[0],
166
+ ...(names.length > 1 ? { lastName: names.slice(1).join(" ") } : {}),
167
+ ...(birthdate ? { birthdate } : {}),
168
+ ...(grade ? { grade } : {}),
169
+ };
170
+ });
171
+ if (!kids.length) {
172
+ throw new CliError("invalid_arguments", 'At least one --kid "First Last:YYYY-MM-DD[:grade]" is required.');
173
+ }
174
+ const enrollmentChoice = assertChoice(flagString(parsed, "enrollment", { required: true }), ["direct", "partner-school", "program"], "--enrollment");
175
+ const enrollment = enrollmentChoice === "partner-school"
176
+ ? "PARTNER_SCHOOL"
177
+ : enrollmentChoice === "program"
178
+ ? "PROGRAM"
179
+ : "DIRECT";
180
+ const partnerSchool = flagString(parsed, "partner-school")?.trim();
181
+ if (enrollment === "PARTNER_SCHOOL" && !partnerSchool) {
182
+ throw new CliError("invalid_arguments", "--enrollment partner-school needs --partner-school <slug|id>.");
183
+ }
184
+ const paywallRaw = flagString(parsed, "paywall")?.replace(/[$,]/g, "");
185
+ const paywall = paywallRaw === undefined ? undefined : Number(paywallRaw);
186
+ if (paywall !== undefined && (!Number.isFinite(paywall) || paywall <= 0)) {
187
+ throw new CliError("invalid_arguments", "--paywall must be a positive dollar amount (the family share to collect in the dashboard).");
188
+ }
189
+ const plan = parseTuitionPlanSpecFlags(parsed);
190
+ const warnings = [];
191
+ if (paywall !== undefined && enrollment === "PARTNER_SCHOOL") {
192
+ warnings.push("A paywall on a partner-school enrollment is unusual: the partner usually invoices.");
193
+ }
194
+ if (paywall !== undefined && plan.stateFunding === "true") {
195
+ warnings.push("A paywall on an ESA-funded plan is unusual: those invoices are paid later from the award.");
196
+ }
197
+ const staffNotes = flagList(parsed, "staff-note")
198
+ .map((n) => n.trim())
199
+ .filter(Boolean)
200
+ .join("\n");
201
+ const body = {
202
+ ...(flagString(parsed, "application")
203
+ ? { applicationId: flagString(parsed, "application") }
204
+ : {}),
205
+ ...(flagString(parsed, "financial-aid")
206
+ ? { financialAidApplicationId: flagString(parsed, "financial-aid") }
207
+ : {}),
208
+ institutionSlug: flagString(parsed, "school", { required: true }),
209
+ enrollment,
210
+ ...(partnerSchool ? { partnerSchool } : {}),
211
+ parentFirstName: parentName[0],
212
+ parentLastName: parentName.slice(1).join(" "),
213
+ parentEmail: flagString(parsed, "email", { required: true }),
214
+ ...(flagString(parsed, "phone")
215
+ ? { parentPhone: flagString(parsed, "phone") }
216
+ : {}),
217
+ state: flagString(parsed, "state", { required: true }).toUpperCase(),
218
+ ...(flagString(parsed, "tier")
219
+ ? { tierId: flagString(parsed, "tier") }
220
+ : {}),
221
+ kids,
222
+ plan: plan,
223
+ ...(paywall !== undefined
224
+ ? { paywallCents: Math.round(paywall * 100) }
225
+ : {}),
226
+ ...(staffNotes ? { staffNotes } : {}),
227
+ sendEmail: !hasFlag(parsed, "no-email"),
228
+ };
229
+ return writeCommand(parsed, {
230
+ action: `create an admission packet for ${body.parentEmail} (${kids.map((k) => k.firstName).join(", ")}) and ${body.sendEmail ? "email them the link" : "return the link without emailing"}`,
231
+ target: { parentEmail: body.parentEmail, school: body.institutionSlug },
232
+ request: body,
233
+ ...(warnings.length ? { details: { warnings } } : {}),
234
+ }, async () => {
235
+ const result = unwrap(await api.client.POST("/admin/admissions/", { body }));
236
+ if (json)
237
+ return result;
238
+ return {
239
+ help: [
240
+ renderPacket(result.packet, result.admissionUrl),
241
+ "",
242
+ `Tuition plan: ${result.plan.introduction}`,
243
+ ...result.plan.options.map((o) => ` ${o.id}: ${o.label} ${dollars(o.totalCents)}`),
244
+ "",
245
+ result.emailed
246
+ ? `Emailed ${result.packet.parentEmail}.`
247
+ : "Not emailed (--no-email); send the link yourself.",
248
+ ...warnings.map((w) => `Warning: ${w}`),
249
+ ].join("\n"),
250
+ };
251
+ });
252
+ }
253
+ if (verb === "resend") {
254
+ const packetId = positional(parsed, 2, "packet ID");
255
+ const sendEmail = !hasFlag(parsed, "no-email");
256
+ return writeCommand(parsed, {
257
+ action: `mint a new link for admission packet ${packetId} (the old link stops working)${sendEmail ? " and email it" : ""}`,
258
+ target: { packetId },
259
+ request: { sendEmail },
260
+ }, async () => {
261
+ const result = unwrap(await api.client.POST("/admin/admissions/{packetId}/resend", {
262
+ params: { path: { packetId } },
263
+ body: { sendEmail },
264
+ }));
265
+ return json
266
+ ? result
267
+ : { help: renderPacket(result.packet, result.admissionUrl) };
268
+ });
269
+ }
270
+ if (verb === "void") {
271
+ const packetId = positional(parsed, 2, "packet ID");
272
+ const reason = flagString(parsed, "reason", { required: true });
273
+ return writeCommand(parsed, {
274
+ action: `void admission packet ${packetId}`,
275
+ target: { packetId },
276
+ request: { reason },
277
+ }, async () => {
278
+ const result = unwrap(await api.client.POST("/admin/admissions/{packetId}/void", {
279
+ params: { path: { packetId } },
280
+ body: { reason },
281
+ }));
282
+ return json ? result : { help: renderPacket(result.packet) };
283
+ });
284
+ }
285
+ if (verb === "mark-signed") {
286
+ const packetId = positional(parsed, 2, "packet ID");
287
+ const optionId = flagString(parsed, "option", { required: true });
288
+ const note = flagString(parsed, "note");
289
+ return writeCommand(parsed, {
290
+ action: `mark admission packet ${packetId} as signed outside the dashboard (option ${optionId})`,
291
+ target: { packetId },
292
+ request: { optionId, ...(note ? { note } : {}) },
293
+ }, async () => {
294
+ const result = unwrap(await api.client.POST("/admin/admissions/{packetId}/mark-signed", {
295
+ params: { path: { packetId } },
296
+ body: { optionId, ...(note ? { note } : {}) },
297
+ }));
298
+ return json ? result : { help: renderPacket(result.packet) };
299
+ });
300
+ }
301
+ if (verb === "requote") {
302
+ const packetId = positional(parsed, 2, "packet ID");
303
+ // --keep-plan reopens the choice on the stored plan (e.g. the family
304
+ // wants monthly after signing pay in full); otherwise the plan flags
305
+ // replace it.
306
+ const keepPlan = hasFlag(parsed, "keep-plan");
307
+ const plan = keepPlan ? null : parseTuitionPlanSpecFlags(parsed);
308
+ const paywallRaw = flagString(parsed, "paywall")?.replace(/[$,]/g, "");
309
+ const paywall = paywallRaw === undefined ? undefined : Number(paywallRaw);
310
+ if (paywall !== undefined && (!Number.isFinite(paywall) || paywall <= 0)) {
311
+ throw new CliError("invalid_arguments", "--paywall must be a positive dollar amount; --no-paywall removes it.");
312
+ }
313
+ if (paywall !== undefined && hasFlag(parsed, "no-paywall")) {
314
+ throw new CliError("invalid_arguments", "Use --paywall DOLLARS or --no-paywall, not both.");
315
+ }
316
+ const note = flagString(parsed, "note")?.trim();
317
+ // Undefined keeps the packet's paywall; null removes it.
318
+ const paywallCents = paywall !== undefined
319
+ ? Math.round(paywall * 100)
320
+ : hasFlag(parsed, "no-paywall")
321
+ ? null
322
+ : undefined;
323
+ const body = {
324
+ ...(plan ? { plan: plan } : {}),
325
+ ...(paywallCents !== undefined ? { paywallCents } : {}),
326
+ ...(note ? { note } : {}),
327
+ };
328
+ return writeCommand(parsed, {
329
+ action: `requote admission packet ${packetId}: ${keepPlan ? "reopen the payment choice on the same plan" : "replace its tuition plan"}${paywallCents === null ? " and remove the paywall" : paywallCents ? ` and set the paywall to ${dollars(paywallCents)}` : ""}; the family signs again from the same link`,
330
+ target: { packetId },
331
+ request: body,
332
+ }, async () => {
333
+ const result = unwrap(await api.client.POST("/admin/admissions/{packetId}/requote", {
334
+ params: { path: { packetId } },
335
+ body,
336
+ }));
337
+ return json ? result : { help: renderPacket(result.packet) };
338
+ });
339
+ }
340
+ if (verb === "archive-agreement") {
341
+ const packetId = positional(parsed, 2, "packet ID");
342
+ return writeCommand(parsed, {
343
+ action: `copy admission packet ${packetId}'s signed agreement from Documenso into our storage`,
344
+ target: { packetId },
345
+ request: {},
346
+ }, async () => {
347
+ const result = unwrap(await api.client.POST("/admin/admissions/{packetId}/archive-agreement", { params: { path: { packetId } } }));
348
+ return json
349
+ ? result
350
+ : {
351
+ help: `${result.archived ? "Archived." : "Nothing to archive yet: the envelope is not complete, or the packet was signed outside Documenso."}\n\n${renderPacket(result.packet)}`,
352
+ };
353
+ });
354
+ }
355
+ throw new CliError("invalid_arguments", "Usage: recess admissions create|get|list|resend|void|mark-signed|requote|archive-agreement. See `recess help`.");
356
+ }
357
+ //# sourceMappingURL=admissions.js.map
@@ -125,9 +125,12 @@ export async function runApplicationsCommand({ parsed, api, writeCommand, }) {
125
125
  if (noun === "applications" && verb === "qualify") {
126
126
  const applicationId = positional(parsed, 2, "application ID");
127
127
  const qualityOverride = assertChoice(flagString(parsed, "quality", { required: true }), APPLICATION_QUALITIES, "--quality");
128
- const reason = flagString(parsed, "reason", { required: true }).trim();
128
+ // --override-reason is stored on the application; --reason (audit) is the
129
+ // fallback only for older invocations.
130
+ const reason = (flagString(parsed, "override-reason") ??
131
+ flagString(parsed, "reason", { required: true })).trim();
129
132
  if (!reason) {
130
- throw new CliError("invalid_arguments", "--reason must not be empty.");
133
+ throw new CliError("invalid_arguments", "--override-reason must not be empty.");
131
134
  }
132
135
  const body = { qualityOverride, reason };
133
136
  return writeCommand(parsed, {
@@ -190,9 +193,12 @@ export async function runApplicationsCommand({ parsed, api, writeCommand, }) {
190
193
  }
191
194
  if (noun === "applications" && verb === "close") {
192
195
  const applicationId = positional(parsed, 2, "application ID");
193
- const reason = flagString(parsed, "reason", { required: true }).trim();
196
+ // --close-reason is stored on the application; --reason (audit) is the
197
+ // fallback only for older invocations.
198
+ const reason = (flagString(parsed, "close-reason") ??
199
+ flagString(parsed, "reason", { required: true })).trim();
194
200
  if (!reason) {
195
- throw new CliError("invalid_arguments", "--reason must not be empty.");
201
+ throw new CliError("invalid_arguments", "--close-reason must not be empty.");
196
202
  }
197
203
  const body = { reason };
198
204
  return writeCommand(parsed, {
@@ -112,12 +112,14 @@ export async function runChannelsCommand({ parsed, api, writeCommand, }) {
112
112
  : assertChoice(audienceFlag, AUDIENCES, "--audience");
113
113
  const description = flagString(parsed, "description");
114
114
  const joinAsAdmin = !hasFlag(parsed, "no-join");
115
+ const staffOnlyPosting = hasFlag(parsed, "staff-only");
115
116
  const imagePath = flagString(parsed, "image");
116
117
  const image = imagePath ? await readChannelImage(imagePath) : undefined;
117
118
  const body = {
118
119
  name,
119
120
  type,
120
121
  joinAsAdmin,
122
+ staffOnlyPosting,
121
123
  ...(audience !== undefined ? { audience } : {}),
122
124
  ...(description !== undefined ? { description } : {}),
123
125
  };
@@ -187,6 +189,24 @@ export async function runChannelsCommand({ parsed, api, writeCommand, }) {
187
189
  },
188
190
  }, async () => api.uploadChannelImage(channelId, image.bytes, image.fileName, image.mimeType));
189
191
  }
192
+ if (verb === "staff-only") {
193
+ const channelId = positional(parsed, 2, "channel ID");
194
+ const setting = parsed.positionals[3];
195
+ if (setting !== "on" && setting !== "off") {
196
+ throw new CliError("invalid_arguments", "Usage: channels staff-only <channel-id> on|off");
197
+ }
198
+ const staffOnlyPosting = setting === "on";
199
+ return writeCommand(parsed, {
200
+ action: staffOnlyPosting
201
+ ? "make the channel staff-only: kids and guardians can read but not send messages"
202
+ : "let every member send messages in the channel again",
203
+ target: { channelId },
204
+ request: { staffOnlyPosting },
205
+ }, async () => unwrap(await api.client.PATCH("/admin/channels/{channelId}/staff-only", {
206
+ params: { path: { channelId } },
207
+ body: { staffOnlyPosting },
208
+ })));
209
+ }
190
210
  if (verb === "join") {
191
211
  const channelId = positional(parsed, 2, "channel ID");
192
212
  const body = { channelId };
@@ -266,6 +286,6 @@ export async function runChannelsCommand({ parsed, api, writeCommand, }) {
266
286
  }
267
287
  throw new CliError("invalid_arguments", "Use channels members list|add|set-role|remove <channel-id> ...");
268
288
  }
269
- throw new CliError("invalid_arguments", "Use channels list|create|set-image|join or channels members list|add|set-role|remove.");
289
+ throw new CliError("invalid_arguments", "Use channels list|create|set-image|staff-only|join or channels members list|add|set-role|remove.");
270
290
  }
271
291
  //# sourceMappingURL=channels.js.map
@@ -757,11 +757,13 @@ export async function runOnboardingCommand({ parsed, api, writeCommand, }) {
757
757
  }
758
758
  if (verb === "meeting-cancel") {
759
759
  const meetingId = positional(parsed, 2, "meeting ID");
760
- const reason = flagString(parsed, "reason", { required: true }).trim();
761
- if (!reason) {
762
- throw new CliError("invalid_arguments", "--reason must not be empty.");
760
+ // Family-facing: the server emails this text to the family. --reason
761
+ // stays the audit-log note only.
762
+ const message = flagString(parsed, "message")?.trim();
763
+ if (!message) {
764
+ throw new CliError("invalid_arguments", 'onboarding meeting-cancel requires --message TEXT: it is emailed to the family verbatim. --reason is only the audit-log note. Example: recess onboarding meeting-cancel <meeting-id> --message "We need to move our call; we will send a new time shortly." --reason "Guide unavailable"');
763
765
  }
764
- const body = { reason };
766
+ const body = { reason: message };
765
767
  return writeCommand(parsed, {
766
768
  action: "cancel the Cal.com booking and email the family the supplied reason (provisional until its webhook settles)",
767
769
  target: { meetingId },
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { unwrap } from "../api.js";
4
+ import { flagString, hasFlag } from "../args.js";
5
+ import { CliError } from "../errors.js";
6
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
7
+ /**
8
+ * `recess reports activity` — the weekly student activity report, generated on
9
+ * the server (GET /admin/activity-reports/) and written to a local folder: the
10
+ * summary PDF, the CSV bundle, and the per-student summaries JSON.
11
+ */
12
+ export async function runReportsCommand({ parsed, api, }) {
13
+ const verb = parsed.positionals[1];
14
+ if (verb !== "activity") {
15
+ throw new CliError("invalid_arguments", "Usage: recess reports activity --partner-school <slug|id> | --guide <name|email|id> | --cohort <cohort-id>. See `recess help`.");
16
+ }
17
+ const partnerSchool = flagString(parsed, "partner-school")?.trim();
18
+ const guide = flagString(parsed, "guide")?.trim();
19
+ const cohortId = flagString(parsed, "cohort")?.trim();
20
+ if ([partnerSchool, guide, cohortId].filter(Boolean).length !== 1) {
21
+ throw new CliError("invalid_arguments", "Pass exactly one of --partner-school, --guide, or --cohort.");
22
+ }
23
+ const weekStart = flagString(parsed, "week")?.trim();
24
+ if (weekStart && !ISO_DATE.test(weekStart)) {
25
+ throw new CliError("invalid_arguments", "--week must be the Monday of the week, as YYYY-MM-DD.");
26
+ }
27
+ const query = {
28
+ ...(partnerSchool ? { partnerSchool } : {}),
29
+ ...(guide ? { guide } : {}),
30
+ ...(cohortId ? { cohortId } : {}),
31
+ ...(weekStart ? { weekStart } : {}),
32
+ ai: hasFlag(parsed, "no-ai") ? "false" : "true",
33
+ };
34
+ const report = unwrap(await api.client.GET("/admin/activity-reports/", { params: { query } }));
35
+ const stem = `${report.slug}_${report.weekStart}`;
36
+ const dir = path.resolve(flagString(parsed, "out") ?? stem);
37
+ await fs.mkdir(dir, { recursive: true });
38
+ const files = [];
39
+ // Student data: write each file to a fresh 0600 temp file, then rename it
40
+ // over the destination. A plain writeFile keeps an existing file's looser
41
+ // mode and would follow a symlink planted at the destination.
42
+ const write = async (name, data) => {
43
+ const file = path.join(dir, name);
44
+ const tmp = path.join(dir, `.${name}.${process.pid}.${Date.now()}.tmp`);
45
+ try {
46
+ await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
47
+ await fs.rename(tmp, file);
48
+ }
49
+ catch (error) {
50
+ // Remove our (possibly partial) temp file; EEXIST means it isn't ours.
51
+ if (error.code !== "EEXIST") {
52
+ await fs.rm(tmp, { force: true });
53
+ }
54
+ throw error;
55
+ }
56
+ files.push(file);
57
+ };
58
+ await write(`${stem}_summary.pdf`, Buffer.from(report.pdfBase64, "base64"));
59
+ for (const [name, text] of Object.entries(report.csv))
60
+ await write(name, text);
61
+ if (report.summaries) {
62
+ await write(`${stem}_summaries.json`, `${JSON.stringify(report.summaries, null, 2)}\n`);
63
+ }
64
+ const result = {
65
+ title: report.title,
66
+ weekStart: report.weekStart,
67
+ weekEnd: report.weekEnd,
68
+ studentCount: report.studentCount,
69
+ groups: report.groups,
70
+ dir,
71
+ files,
72
+ };
73
+ if (hasFlag(parsed, "json"))
74
+ return result;
75
+ return {
76
+ help: [
77
+ `${report.title}: ${report.weekStart} to ${report.weekEnd}`,
78
+ `${report.studentCount} students${report.groups.length ? ` in ${report.groups.length} groups` : ""}${report.summaries ? "" : " (no AI summaries)"}`,
79
+ `Wrote ${files.length} files to ${dir}`,
80
+ ...files.map((f) => ` ${path.basename(f)}`),
81
+ ].join("\n"),
82
+ };
83
+ }
84
+ //# sourceMappingURL=reports.js.map
@@ -5,13 +5,14 @@ import { unwrap } from "../api.js";
5
5
  import { flagString, hasFlag } from "../args.js";
6
6
  import { CliError } from "../errors.js";
7
7
  import { appendJobEvent } from "../jobs.js";
8
+ import { resolveApprovalToken } from "../safety.js";
8
9
  import { assertChoice, positional } from "./shared.js";
9
10
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
10
11
  function recoveryKey(ctx) {
11
12
  if (!hasFlag(ctx.parsed, "confirm"))
12
13
  return undefined;
13
14
  const key = flagString(ctx.parsed, "operation-key");
14
- const token = flagString(ctx.parsed, "approval-token");
15
+ const token = resolveApprovalToken(ctx.parsed);
15
16
  if (key && (!token || !key.endsWith(`_${token}`)))
16
17
  throw new CliError("approval_mismatch", "Recovery requires the original operation key and approval token.");
17
18
  return key;
@@ -24,7 +25,7 @@ async function recovered(ctx, row, expectedInputHash) {
24
25
  status: row.outcome === "outcome_unknown" ? "unknown" : "completed",
25
26
  timestamp: new Date().toISOString(),
26
27
  action: "recover staff operation",
27
- fingerprint: flagString(ctx.parsed, "approval-token"),
28
+ fingerprint: resolveApprovalToken(ctx.parsed),
28
29
  target: { apiOrigin: ctx.api.config.apiOrigin },
29
30
  result: row,
30
31
  });