recess-cli 3.8.0 → 3.10.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.
package/dist/api.js CHANGED
@@ -7,6 +7,10 @@ const idempotencyContext = new AsyncLocalStorage();
7
7
  export function withIdempotencyContext(context, execute) {
8
8
  return idempotencyContext.run(context, execute);
9
9
  }
10
+ /** The approved operation key while a confirmed write executes. */
11
+ export function currentOperationKey() {
12
+ return idempotencyContext.getStore()?.operationKey;
13
+ }
10
14
  function applyIdempotencyHeaders(headers) {
11
15
  const context = idempotencyContext.getStore();
12
16
  if (!context)
package/dist/args.js CHANGED
@@ -4,7 +4,12 @@ import { CliError } from "./errors.js";
4
4
  * `flagString` still yields the LAST value, which is why every consumer of a
5
5
  * repeatable flag must use `flagList` instead.
6
6
  */
7
- export const REPEATABLE_FLAGS = new Set(["kid", "unassign"]);
7
+ export const REPEATABLE_FLAGS = new Set([
8
+ "bill-date",
9
+ "kid",
10
+ "note",
11
+ "unassign",
12
+ ]);
8
13
  const BOOLEAN_FLAGS = new Set([
9
14
  "clear",
10
15
  "zero-balance",
package/dist/auth.js CHANGED
@@ -12,7 +12,7 @@ function publicSession(session) {
12
12
  user: session.user,
13
13
  };
14
14
  }
15
- function openBrowser(url) {
15
+ export function openBrowser(url) {
16
16
  // Windows goes through rundll32, not `cmd /c start`: cmd treats `&` (and the
17
17
  // `%`-encoded redirect_uri) as metacharacters and chops the URL at the first
18
18
  // `&`, so the browser only ever received `?client_id=…` and the OAuth page
package/dist/cli.js CHANGED
@@ -14,8 +14,10 @@ import { runChannelsCommand } from "./commands/channels.js";
14
14
  import { runChatLogsCommand } from "./commands/chat-logs.js";
15
15
  import { runDbCommand } from "./commands/db.js";
16
16
  import { runRoomsCommand } from "./commands/rooms.js";
17
+ import { runFeedCommand } from "./commands/feed.js";
17
18
  import { runFamiliesCommand } from "./commands/families.js";
18
19
  import { runStudentsTextsCommand, runUsersPhoneCommand, } from "./commands/phone-and-texts.js";
20
+ import { runTuitionPlansCommand } from "./commands/tuition-plans.js";
19
21
  import { runMasteryCommand } from "./commands/mastery.js";
20
22
  import { runOnboardingCommand } from "./commands/onboarding.js";
21
23
  import { runScheduleCommand, runMemoryFilesCommand, } from "./commands/safe-staff-operations.js";
@@ -1456,13 +1458,13 @@ function parseGoalTemplateDocument(doc) {
1456
1458
  * author types and what the skill's prose uses; the routes take a UUID only.
1457
1459
  */
1458
1460
  /**
1459
- * `/challenges-v2/{id}/preview` on the web app: the template as the card a
1460
- * kid would see, with no chat around it. Returned by `goal-templates get`
1461
+ * `/challenges-v2/{id}` on the web app: the challenge page, where the
1462
+ * template shows as the card a kid would see. Returned by `goal-templates get`
1461
1463
  * and `create` so an agent can open it, or hand it to the human, right after
1462
1464
  * authoring.
1463
1465
  */
1464
1466
  function goalTemplatePreviewUrl(webOrigin, templateId) {
1465
- return new URL(`/challenges-v2/${encodeURIComponent(templateId)}/preview`, webOrigin).toString();
1467
+ return new URL(`/challenges-v2/${encodeURIComponent(templateId)}`, webOrigin).toString();
1466
1468
  }
1467
1469
  /** Runs the template with Rocky as a kid would (staff only; ephemeral, never touches real todos). */
1468
1470
  function goalTemplatePlayTestUrl(webOrigin, templateId) {
@@ -3545,6 +3547,23 @@ export async function executeRecessCommand(argv, options = {}) {
3545
3547
  params: { path: { eventId } },
3546
3548
  }));
3547
3549
  }
3550
+ if (noun === "events" && verb === "list") {
3551
+ const date = flagString(parsed, "date");
3552
+ if (!date) {
3553
+ throw new CliError("invalid_arguments", "events list requires --date YYYY-MM-DD.");
3554
+ }
3555
+ const timezone = flagString(parsed, "timezone");
3556
+ const search = flagString(parsed, "search");
3557
+ return unwrap(await api.client.GET("/admin/events/by-date", {
3558
+ params: {
3559
+ query: {
3560
+ date,
3561
+ ...(timezone && { timezone }),
3562
+ ...(search && { search }),
3563
+ },
3564
+ },
3565
+ }));
3566
+ }
3548
3567
  if (noun === "events" && verb === "take-attendance") {
3549
3568
  const eventId = positional(parsed, 2, "event ID");
3550
3569
  const attended = flagIdList(parsed, "attended");
@@ -4014,6 +4033,7 @@ export async function executeRecessCommand(argv, options = {}) {
4014
4033
  tags: document.tags,
4015
4034
  isStarter: document.isStarter ?? false,
4016
4035
  coinAmount: document.coinAmount ?? null,
4036
+ visibility: "PRIVATE",
4017
4037
  },
4018
4038
  details: {
4019
4039
  resolvedSetupHandler: validation.setupHandler,
@@ -4025,7 +4045,9 @@ export async function executeRecessCommand(argv, options = {}) {
4025
4045
  },
4026
4046
  }, async () => {
4027
4047
  const created = unwrap(await api.client.POST("/ai/goal-templates/", {
4028
- body: document,
4048
+ // Agent-authored templates start private; the author publishes
4049
+ // from the challenge page once it plays right.
4050
+ body: { ...document, visibility: "PRIVATE" },
4029
4051
  }));
4030
4052
  return {
4031
4053
  ...created,
@@ -4291,6 +4313,7 @@ export async function executeRecessCommand(argv, options = {}) {
4291
4313
  throw new CliError("invalid_arguments", "--coin-amount must be a positive integer.");
4292
4314
  }
4293
4315
  const visibility = flagString(parsed, "visibility");
4316
+ const targetPlatform = flagString(parsed, "target-platform");
4294
4317
  const isStarterRaw = flagString(parsed, "is-starter");
4295
4318
  const setupAudienceRaw = flagString(parsed, "setup-audience");
4296
4319
  const isStarter = isStarterRaw === undefined
@@ -4337,6 +4360,11 @@ export async function executeRecessCommand(argv, options = {}) {
4337
4360
  visibility: assertChoice(visibility, ["PUBLIC", "PRIVATE", "STAFF_ONLY"], "--visibility"),
4338
4361
  }
4339
4362
  : {}),
4363
+ ...(targetPlatform
4364
+ ? {
4365
+ targetPlatform: assertChoice(targetPlatform.toUpperCase(), ["ANY", "MOBILE", "DESKTOP"], "--target-platform"),
4366
+ }
4367
+ : {}),
4340
4368
  ...(agentInstructionsFile
4341
4369
  ? {
4342
4370
  agentInstructions: await fs.readFile(path.resolve(agentInstructionsFile), "utf8"),
@@ -4353,7 +4381,7 @@ export async function executeRecessCommand(argv, options = {}) {
4353
4381
  // shape that caused the template incident; editing an existing spec goes
4354
4382
  // through the guarded /ai patch path with its destructive-change token.
4355
4383
  if (Object.keys(body).length === 1) {
4356
- throw new CliError("invalid_arguments", "Pass at least one field to change (--title, --description, --emoji, --image-url, --coin-amount, --category, --tags, --sort-order, --is-starter, --setup-audience, --kind, --visibility, --agent-instructions-file, --output-template-file).");
4384
+ throw new CliError("invalid_arguments", "Pass at least one field to change (--title, --description, --emoji, --image-url, --coin-amount, --category, --tags, --sort-order, --is-starter, --setup-audience, --kind, --visibility, --target-platform, --agent-instructions-file, --output-template-file).");
4357
4385
  }
4358
4386
  return writeCommand(parsed, {
4359
4387
  action: "update goal template metadata (never its setupWorkflowSpec)",
@@ -5125,9 +5153,15 @@ export async function executeRecessCommand(argv, options = {}) {
5125
5153
  if (noun === "rooms") {
5126
5154
  return runRoomsCommand({ parsed, api, writeCommand });
5127
5155
  }
5156
+ if (noun === "feed") {
5157
+ return runFeedCommand({ parsed, api, writeCommand });
5158
+ }
5128
5159
  if (noun === "students" && verb === "texts") {
5129
5160
  return runStudentsTextsCommand({ parsed, api, writeCommand });
5130
5161
  }
5162
+ if (noun === "tuition-plans") {
5163
+ return runTuitionPlansCommand({ parsed, api, writeCommand });
5164
+ }
5131
5165
  if (noun === "students") {
5132
5166
  if (verb === "list") {
5133
5167
  const requestedScope = flagString(parsed, "scope");
@@ -5256,7 +5290,7 @@ export async function executeRecessCommand(argv, options = {}) {
5256
5290
  if (verb === "create") {
5257
5291
  const studentId = flagString(parsed, "student", { required: true });
5258
5292
  const title = flagString(parsed, "title", { required: true });
5259
- const estimatedTimeInMins = flagNumber(parsed, "estimated-minutes");
5293
+ const targetDurationInMins = flagNumber(parsed, "target-minutes");
5260
5294
  const body = {
5261
5295
  userId: studentId,
5262
5296
  title,
@@ -5266,7 +5300,7 @@ export async function executeRecessCommand(argv, options = {}) {
5266
5300
  ...(flagString(parsed, "url")
5267
5301
  ? { url: flagString(parsed, "url") }
5268
5302
  : {}),
5269
- ...(estimatedTimeInMins !== undefined ? { estimatedTimeInMins } : {}),
5303
+ ...(targetDurationInMins !== undefined ? { targetDurationInMins } : {}),
5270
5304
  };
5271
5305
  return writeCommand(parsed, {
5272
5306
  action: "create a todo for a managed student",
@@ -5594,8 +5628,8 @@ export async function executeRecessCommand(argv, options = {}) {
5594
5628
  title: template.title,
5595
5629
  cadence: template.cadence,
5596
5630
  consequence: verb === "assign"
5597
- ? "Appends `### <title> — <cadence>` to rocky-v3/plan.md, rebuilds Today, and writes an ACTIVE assignment row."
5598
- : "Deletes that subject block from rocky-v3/plan.md and marks the assignment REMOVED.",
5631
+ ? "Appends `### <title> — <cadence>` to the kid's memory/subjects.md (Rocky live reads it) and writes an ACTIVE assignment row."
5632
+ : "Deletes that subject block from memory/subjects.md and marks the assignment REMOVED.",
5599
5633
  },
5600
5634
  }, async () => verb === "assign"
5601
5635
  ? unwrap(await api.client.POST("/tutor-templates/{slug}/assign", {
@@ -5663,7 +5697,7 @@ export async function executeRecessCommand(argv, options = {}) {
5663
5697
  },
5664
5698
  details: {
5665
5699
  lessonNames: Object.keys(shared.lessons ?? {}),
5666
- renamingNote: "`title` is the `### <heading>` join key in every kid's plan.md — renaming later orphans existing plans.",
5700
+ renamingNote: "`title` is the `### <heading>` join key in every kid's memory/subjects.md — renaming later orphans existing blocks.",
5667
5701
  },
5668
5702
  }, async () => unwrap(await api.client.POST("/tutor-templates/", { body })));
5669
5703
  }
@@ -5682,7 +5716,7 @@ export async function executeRecessCommand(argv, options = {}) {
5682
5716
  },
5683
5717
  details: {
5684
5718
  fields: Object.keys(body),
5685
- renamingNote: "Changing `title` orphans the `### <heading>` in every plan.md already carrying this template.",
5719
+ renamingNote: "Changing `title` orphans the `### <heading>` in every memory/subjects.md already carrying this template.",
5686
5720
  },
5687
5721
  }, async () => unwrap(await api.client.PATCH("/tutor-templates/{slug}", {
5688
5722
  params: { path: { slug } },
@@ -5700,7 +5734,7 @@ export async function executeRecessCommand(argv, options = {}) {
5700
5734
  request: {},
5701
5735
  details: {
5702
5736
  title: template.title,
5703
- consequence: "The row is soft-deleted; subject blocks already written into kids' plan.md stay where they are.",
5737
+ consequence: "The row is soft-deleted; subject blocks already written into kids' memory/subjects.md stay where they are.",
5704
5738
  },
5705
5739
  }, async () => unwrap(await api.client.DELETE("/tutor-templates/{slug}", {
5706
5740
  params: { path: { slug } },
@@ -43,13 +43,15 @@ const BOOLEAN_FLAGS = new Set([
43
43
  "skill-only",
44
44
  "spec-only",
45
45
  "starter-only",
46
+ "state-funding",
47
+ "even-installments",
46
48
  "supersede",
47
49
  "unlink",
48
50
  "visual-only",
49
51
  "whole-family",
50
52
  "wait",
51
53
  ]);
52
- const REPEATABLE_FLAGS = new Set(["kid", "unassign"]);
54
+ const REPEATABLE_FLAGS = new Set(["bill-date", "kid", "note", "unassign"]);
53
55
  const GLOBAL_FLAGS = new Set([
54
56
  "deliver",
55
57
  "help",
@@ -232,6 +234,7 @@ const STAFF_COMMANDS = new Set([
232
234
  "events add",
233
235
  "events cancel",
234
236
  "events get",
237
+ "events list",
235
238
  "events reschedule",
236
239
  "events set-status",
237
240
  "events take-attendance",
@@ -0,0 +1,82 @@
1
+ import { currentOperationKey, unwrap } from "../api.js";
2
+ import { flagString, hasFlag } from "../args.js";
3
+ import { CliError } from "../errors.js";
4
+ import { flagIdList } from "./shared.js";
5
+ /**
6
+ * The post id is derived from the approved operation key: the server's replay
7
+ * fence keys on the request body, so a fresh random id on a retried
8
+ * confirmation would slip past it and publish the post twice.
9
+ */
10
+ function activityIdForOperation() {
11
+ const hex = /^op_([a-f0-9]{32})_/.exec(currentOperationKey() ?? "")?.[1];
12
+ if (!hex) {
13
+ throw new CliError("confirmation_required", "A feed post can only be published through a confirmed operation.");
14
+ }
15
+ return [
16
+ hex.slice(0, 8),
17
+ hex.slice(8, 12),
18
+ hex.slice(12, 16),
19
+ hex.slice(16, 20),
20
+ hex.slice(20),
21
+ ].join("-");
22
+ }
23
+ const describe = (person) => ({
24
+ id: person.id,
25
+ name: [person.firstName, person.lastName].filter(Boolean).join(" "),
26
+ role: person.role,
27
+ });
28
+ /**
29
+ * Read-only preflight so the approval names every recipient and the family
30
+ * adults the server adds to a private post. Sorted so a confirm-time rerun
31
+ * reproduces the approved preview byte for byte.
32
+ */
33
+ async function resolveAudience(api, userIds) {
34
+ const profiles = await Promise.all(userIds.map(async (userId) => unwrap(await api.client.GET("/admin/users/{userId}", {
35
+ params: { path: { userId } },
36
+ }))));
37
+ const disabled = profiles.filter(({ user }) => user.role === "DISABLED");
38
+ if (disabled.length) {
39
+ throw new CliError("invalid_arguments", `Disabled accounts cannot receive posts: ${disabled
40
+ .map(({ user }) => user.id)
41
+ .join(", ")}.`);
42
+ }
43
+ const adults = new Map();
44
+ for (const { user } of profiles)
45
+ for (const member of user.family?.users ?? [])
46
+ if (member.role !== "KID" && !userIds.includes(member.id))
47
+ adults.set(member.id, member);
48
+ const byId = (a, b) => a.id.localeCompare(b.id);
49
+ return {
50
+ recipients: profiles.map(({ user }) => describe(user)).sort(byId),
51
+ familyAdultsAlsoReceiving: [...adults.values()].map(describe).sort(byId),
52
+ };
53
+ }
54
+ export async function runFeedCommand({ parsed, api, writeCommand, }) {
55
+ if (parsed.positionals[1] !== "post") {
56
+ throw new CliError("invalid_arguments", "Use `feed post`.");
57
+ }
58
+ const userIds = Array.from(new Set(flagIdList(parsed, "users")));
59
+ if (userIds.length === 0) {
60
+ throw new CliError("invalid_arguments", "--users is required.");
61
+ }
62
+ const text = flagString(parsed, "text", { required: true }).trim();
63
+ if (!text) {
64
+ throw new CliError("invalid_arguments", "--text must not be empty.");
65
+ }
66
+ const sendEmailBlast = hasFlag(parsed, "send-email");
67
+ return writeCommand(parsed, {
68
+ action: `publish a private feed post to ${userIds.length} user(s) and their guardians${sendEmailBlast ? ", AND EMAIL it to all of them" : ""}`,
69
+ target: { userIds },
70
+ request: { type: "PRIVATE_UPDATE", text, sendEmailBlast },
71
+ details: await resolveAudience(api, userIds),
72
+ }, async () => unwrap(await api.client.POST("/activity/", {
73
+ body: {
74
+ id: activityIdForOperation(),
75
+ type: "PRIVATE_UPDATE",
76
+ text,
77
+ targetUserIds: userIds,
78
+ sendEmailBlast,
79
+ },
80
+ })));
81
+ }
82
+ //# sourceMappingURL=feed.js.map
@@ -97,4 +97,14 @@ export async function readJsonFile(filePath, label) {
97
97
  }
98
98
  return parsed;
99
99
  }
100
+ /** Left-aligned text columns (two-space gutter) for human-mode tables. */
101
+ export function renderColumns(rows) {
102
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
103
+ return rows
104
+ .map((row) => row
105
+ .map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column]))
106
+ .join(" ")
107
+ .trimEnd())
108
+ .join("\n");
109
+ }
100
110
  //# sourceMappingURL=shared.js.map
@@ -0,0 +1,221 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { unwrap } from "../api.js";
4
+ import { flagList, flagString, hasFlag } from "../args.js";
5
+ import { openBrowser } from "../auth.js";
6
+ import { CliError } from "../errors.js";
7
+ import { assertChoice, renderColumns } from "./shared.js";
8
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
9
+ function requiredFlag(parsed, name, pattern) {
10
+ const value = flagString(parsed, name)?.trim();
11
+ if (!value) {
12
+ throw new CliError("invalid_arguments", `Missing required --${name}.`);
13
+ }
14
+ if (pattern && !pattern.test(value)) {
15
+ throw new CliError("invalid_arguments", `--${name} must look like ${name === "state" ? "a two-letter state code" : "YYYY-MM-DD"}.`);
16
+ }
17
+ return value;
18
+ }
19
+ /** A comma-separated subset of friendly names, mapped to the server's values. */
20
+ function csvFlag(parsed, name, values) {
21
+ const raw = flagString(parsed, name)?.trim();
22
+ if (raw === undefined)
23
+ return undefined;
24
+ const picked = raw.split(",").map((v) => v.trim().toLowerCase());
25
+ const bad = picked.filter((v) => !(v in values));
26
+ if (!picked.length || bad.length) {
27
+ throw new CliError("invalid_arguments", `--${name} takes a comma-separated subset of: ${Object.keys(values).join(", ")}.`);
28
+ }
29
+ return [...new Set(picked.map((v) => values[v]))];
30
+ }
31
+ const TERM_FLAGS = {
32
+ "full-year": "INSTRUCTIONAL_180",
33
+ "school-year": "STATE_YEAR_END",
34
+ custom: "CUSTOM",
35
+ };
36
+ const PAYMENT_FLAGS = {
37
+ upfront: "PAY_IN_FULL",
38
+ installments: "INSTALLMENTS",
39
+ };
40
+ /** Dollars, with cents only when there are any (matches the PDF). */
41
+ const dollars = (cents) => `$${(cents / 100).toLocaleString("en-US", {
42
+ minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
43
+ maximumFractionDigits: 2,
44
+ })}`;
45
+ /** The tuition plan as terminal text, in the PDF's order: one block per term. */
46
+ function renderPlan(plan, webUrl, pdfPath) {
47
+ const out = [
48
+ `RECESS ACADEMY ${plan.enrollment.indicative ? "ESTIMATED " : ""}TUITION PLAN (${plan.calendarLabel})`,
49
+ ];
50
+ if (plan.enrollment.disclaimer)
51
+ out.push(`!! ${plan.enrollment.disclaimer}`);
52
+ out.push("", `Tuition options for ${plan.studentName}`, `Prepared for ${plan.parentName} · ${plan.state.name} · ${plan.enrollment.partnerSchool
53
+ ? `Through ${plan.enrollment.partnerSchool.name}`
54
+ : "Direct enrollment"}`, "", plan.introduction);
55
+ for (const o of plan.options) {
56
+ out.push("", `${o.label.toUpperCase()} (${o.startDate} → ${o.endDate}, ${o.instructionalDays} school days)`, ` ${o.description}`, renderColumns(o.paymentPlans.map((p) => [
57
+ ` ${p.label}`,
58
+ dollars(p.totalCents),
59
+ p.summary,
60
+ p.scheduleLine,
61
+ ])));
62
+ }
63
+ if (plan.staffNotes.length) {
64
+ out.push("", "Notes:", ...plan.staffNotes.map((n) => ` ${n}`));
65
+ }
66
+ out.push("", `Optional add-ons: ${plan.addOns
67
+ .map((a) => `${a.label} ${dollars(a.priceCents)} ${a.unit}`)
68
+ .join(" · ")}`, "", ...plan.footnotes.map((n) => ` · ${n}`), ...(plan.agreement
69
+ ? [
70
+ "",
71
+ "ENROLLMENT AGREEMENT (page 2 of the PDF; parent checks one and signs)",
72
+ ...plan.agreement.choices.map((c) => ` [ ] ${c.label}`),
73
+ ...plan.agreement.clauses.map((c, i) => ` ${i + 1}. ${c}`),
74
+ ]
75
+ : []), "", `Web: ${webUrl}`);
76
+ if (pdfPath)
77
+ out.push(`PDF: ${pdfPath}`);
78
+ return out.join("\n");
79
+ }
80
+ export async function runTuitionPlansCommand({ parsed, api, }) {
81
+ const verb = parsed.positionals[1];
82
+ if (verb === "states") {
83
+ return unwrap(await api.client.GET("/admin/tuition-plans/states/"));
84
+ }
85
+ if (verb !== "generate") {
86
+ throw new CliError("invalid_arguments", "Usage: recess tuition-plans generate|states. See `recess help`.");
87
+ }
88
+ const annual = Number(requiredFlag(parsed, "annual").replace(/[$,]/g, ""));
89
+ if (!Number.isFinite(annual) || annual <= 0) {
90
+ throw new CliError("invalid_arguments", "--annual must be a positive dollar amount (net of Recess financial aid).");
91
+ }
92
+ // The server owns the supported-state list; resolve against it so a bad
93
+ // code fails with the valid choices.
94
+ const { states } = unwrap(await api.client.GET("/admin/tuition-plans/states/"));
95
+ const state = assertChoice(requiredFlag(parsed, "state", /^[A-Za-z]{2}$/).toUpperCase(), states.map((s) => s.code), "--state");
96
+ const enrollment = assertChoice(requiredFlag(parsed, "enrollment"), ["direct", "partner-school"], "--enrollment") === "partner-school"
97
+ ? "PARTNER_SCHOOL"
98
+ : "DIRECT";
99
+ const partnerSchool = flagString(parsed, "partner-school")?.trim();
100
+ if (enrollment === "PARTNER_SCHOOL" && !partnerSchool) {
101
+ throw new CliError("invalid_arguments", "--enrollment partner-school needs --partner-school <slug|id> (see `recess users enrollment list-partner-schools`).");
102
+ }
103
+ if (enrollment === "DIRECT" && partnerSchool) {
104
+ throw new CliError("invalid_arguments", "--partner-school applies only with --enrollment partner-school.");
105
+ }
106
+ // Add-on overrides; omitted = the server's school-pricing defaults.
107
+ const addOnFlag = (name, integer) => {
108
+ const raw = flagString(parsed, name)?.trim().replace(/[$,]/g, "");
109
+ if (raw === undefined)
110
+ return undefined;
111
+ const value = Number(raw);
112
+ if (!Number.isFinite(value) ||
113
+ value <= 0 ||
114
+ (integer && !Number.isInteger(value))) {
115
+ throw new CliError("invalid_arguments", `--${name} must be a positive ${integer ? "whole number" : "dollar amount"}.`);
116
+ }
117
+ return value;
118
+ };
119
+ const electivePrice = addOnFlag("elective-price", false);
120
+ const oneOnOnePrice = addOnFlag("one-on-one-price", false);
121
+ const oneOnOneSessions = addOnFlag("one-on-one-sessions", true);
122
+ const addOnQuery = {
123
+ ...(electivePrice !== undefined ? { electivePrice } : {}),
124
+ ...(oneOnOnePrice !== undefined ? { oneOnOnePrice } : {}),
125
+ ...(oneOnOneSessions !== undefined ? { oneOnOneSessions } : {}),
126
+ };
127
+ // Optional: without it the sheet leaves out the student's age.
128
+ const dob = flagString(parsed, "dob")?.trim();
129
+ if (dob && !ISO_DATE.test(dob)) {
130
+ throw new CliError("invalid_arguments", "--dob must look like YYYY-MM-DD.");
131
+ }
132
+ // Omitted = the full matrix (full year + school year [+ custom with --end]) ×
133
+ // (upfront + installments). A full year past July 1 drops out of the
134
+ // default; asking for it explicitly is refused by the server.
135
+ const endDate = flagString(parsed, "end")?.trim();
136
+ if (endDate && !ISO_DATE.test(endDate)) {
137
+ throw new CliError("invalid_arguments", "--end must look like YYYY-MM-DD.");
138
+ }
139
+ const terms = csvFlag(parsed, "terms", TERM_FLAGS);
140
+ if (terms?.includes("CUSTOM") && !endDate) {
141
+ throw new CliError("invalid_arguments", "--terms custom needs --end YYYY-MM-DD.");
142
+ }
143
+ if (endDate && terms && !terms.includes("CUSTOM")) {
144
+ throw new CliError("invalid_arguments", "--end adds the custom term; include custom in --terms.");
145
+ }
146
+ const payments = csvFlag(parsed, "payments", PAYMENT_FLAGS);
147
+ // Staff overrides: notes printed on the sheet, and moved invoice dates.
148
+ const notes = flagList(parsed, "note")
149
+ .map((n) => n.trim())
150
+ .filter(Boolean);
151
+ const billDates = flagList(parsed, "bill-date").map((raw) => {
152
+ const [key, date] = raw.split("=").map((v) => v.trim().toLowerCase());
153
+ if (!key ||
154
+ !date ||
155
+ !/^(upfront|[1-9]\d*)$/.test(key) ||
156
+ !ISO_DATE.test(date)) {
157
+ throw new CliError("invalid_arguments", `--bill-date takes upfront=YYYY-MM-DD or N=YYYY-MM-DD (installment N), got "${raw}".`);
158
+ }
159
+ return `${key}=${date}`;
160
+ });
161
+ const even = hasFlag(parsed, "even-installments");
162
+ const subsetQuery = {
163
+ ...(even ? { evenInstallments: "true" } : {}),
164
+ ...(billDates.length ? { billDates: billDates.join(",") } : {}),
165
+ ...(endDate ? { endDate } : {}),
166
+ ...(terms ? { terms: terms.join(",") } : {}),
167
+ ...(payments ? { payments: payments.join(",") } : {}),
168
+ };
169
+ const query = {
170
+ parentName: requiredFlag(parsed, "parent"),
171
+ studentName: requiredFlag(parsed, "student"),
172
+ ...(dob ? { studentDob: dob } : {}),
173
+ state,
174
+ startDate: requiredFlag(parsed, "start", ISO_DATE),
175
+ annualTuition: annual,
176
+ stateFunding: hasFlag(parsed, "state-funding") ? "true" : "false",
177
+ enrollment,
178
+ ...(partnerSchool ? { partnerSchool } : {}),
179
+ ...addOnQuery,
180
+ ...subsetQuery,
181
+ ...(notes.length ? { notes } : {}),
182
+ };
183
+ const plan = unwrap(await api.client.GET("/admin/tuition-plans/", { params: { query } }));
184
+ const search = new URLSearchParams({
185
+ parentName: query.parentName,
186
+ studentName: query.studentName,
187
+ ...(dob ? { studentDob: dob } : {}),
188
+ state: query.state,
189
+ startDate: query.startDate,
190
+ annualTuition: String(annual),
191
+ ...(query.stateFunding === "true" ? { stateFunding: "true" } : {}),
192
+ enrollment,
193
+ ...(partnerSchool ? { partnerSchool } : {}),
194
+ ...Object.fromEntries(Object.entries(addOnQuery).map(([k, v]) => [k, String(v)])),
195
+ ...subsetQuery,
196
+ });
197
+ for (const note of notes)
198
+ search.append("notes", note);
199
+ const webUrl = new URL(`/admin/tuition-plans?${search}`, api.config.webOrigin).toString();
200
+ let pdfPath;
201
+ const pdfFlag = flagString(parsed, "pdf");
202
+ if (pdfFlag) {
203
+ const pdf = await api.client.GET("/admin/tuition-plans/pdf/", {
204
+ params: { query },
205
+ parseAs: "arrayBuffer",
206
+ });
207
+ const bytes = unwrap(pdf);
208
+ pdfPath = path.resolve(pdfFlag);
209
+ await fs.writeFile(pdfPath, new Uint8Array(bytes));
210
+ }
211
+ if (hasFlag(parsed, "open"))
212
+ openBrowser(webUrl);
213
+ if (!hasFlag(parsed, "json"))
214
+ return { help: renderPlan(plan, webUrl, pdfPath) };
215
+ return {
216
+ webUrl,
217
+ ...(pdfPath ? { pdfPath } : {}),
218
+ plan,
219
+ };
220
+ }
221
+ //# sourceMappingURL=tuition-plans.js.map
@@ -1,6 +1,7 @@
1
1
  import { unwrap } from "../api.js";
2
2
  import { flagString, hasFlag } from "../args.js";
3
3
  import { apiError, CliError } from "../errors.js";
4
+ import { renderColumns } from "./shared.js";
4
5
  const NONE = "—";
5
6
  const WEEKDAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
6
7
  async function fetchTemplatesAndRooms(ctx) {
@@ -29,15 +30,6 @@ function templateDays(template) {
29
30
  .filter((day) => WEEKDAYS.includes(day));
30
31
  return days.length > 0 ? days : null;
31
32
  }
32
- function renderColumns(rows) {
33
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
34
- return rows
35
- .map((row) => row
36
- .map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column]))
37
- .join(" ")
38
- .trimEnd())
39
- .join("\n");
40
- }
41
33
  /** `village events` — every editable Recess Hour template and its Town Center zone. */
42
34
  async function listEvents(ctx) {
43
35
  const { templates, rooms } = await fetchTemplatesAndRooms(ctx);
package/dist/help.js CHANGED
@@ -184,6 +184,14 @@ Usage:
184
184
  recess [--json] channels members add <channel-id> <user-id...> [--role MEMBER|MODERATOR|ADMIN] [--confirm]
185
185
  recess [--json] channels members set-role <channel-id> <user-id...> --role MEMBER|MODERATOR|ADMIN [--confirm]
186
186
  recess [--json] channels members remove <channel-id> <user-id...> [--confirm]
187
+ recess [--json] tuition-plans generate --parent TEXT --student TEXT [--dob YYYY-MM-DD]
188
+ --state XX --start YYYY-MM-DD --annual DOLLARS --enrollment direct|partner-school
189
+ [--partner-school <slug|id>] [--state-funding] [--elective-price DOLLARS]
190
+ [--one-on-one-price DOLLARS] [--one-on-one-sessions N] [--end YYYY-MM-DD]
191
+ [--terms full-year,school-year,custom] [--payments upfront,installments]
192
+ [--note TEXT]... [--bill-date upfront|N=YYYY-MM-DD]... [--even-installments]
193
+ [--pdf <path>] [--open]
194
+ recess [--json] tuition-plans states
187
195
  recess [--json] cohorts get <cohort-id> [--events-tab ACTIVE|ENDED|CANCELED|ARCHIVED]
188
196
  recess [--json] cohorts schedule get <cohort-id>
189
197
  recess [--json] cohorts schedule set <cohort-id> --days <MO,WE> --time <09:30> [--timezone <zone>] --effective-date <YYYY-MM-DD> --notify none|parents [--confirm] [--approval-token <token>]
@@ -195,7 +203,9 @@ Usage:
195
203
  recess [--json] cohorts resume-billing <cohort-id> [--confirm]
196
204
  recess [--json] cohorts email <cohort-id> --target ALL_PARENTS|ALL_PARENTS_GUIDES
197
205
  --content TEXT [--confirm]
206
+ recess [--json] feed post --users <id,id,...> --text TEXT [--send-email] [--confirm]
198
207
  recess [--json] events get <event-id>
208
+ recess [--json] events list --date YYYY-MM-DD [--timezone <iana>] [--search TEXT]
199
209
  recess [--json] events take-attendance <event-id> --attended <id,id,...>
200
210
  [--absent <id,id,...>] [--excused <id,id,...>] [--confirm]
201
211
  recess [--json] events cancel <event-id> --reason TEXT [--confirm]
@@ -419,8 +429,8 @@ Usage:
419
429
  [--title TEXT] [--description TEXT] [--emoji X] [--category TEXT] [--tags A,B]
420
430
  [--image-url URL] [--coin-amount N] [--sort-order N] [--is-starter true|false]
421
431
  [--setup-audience KID_FRIENDLY|PARENT_SETUP] [--kind SIMPLE|BLUEPRINT]
422
- [--visibility PUBLIC|PRIVATE|STAFF_ONLY] [--agent-instructions-file <path>]
423
- [--output-template-file <path>] [--confirm]
432
+ [--visibility PUBLIC|PRIVATE|STAFF_ONLY] [--target-platform ANY|MOBILE|DESKTOP]
433
+ [--agent-instructions-file <path>] [--output-template-file <path>] [--confirm]
424
434
  recess [--json] goal-templates delete <template-id> --expected-version N [--confirm]
425
435
  recess [--json] goal-templates generate-image <template-id|slug>
426
436
  [--prompt TEXT] [--confirm]
@@ -458,7 +468,7 @@ Usage:
458
468
  --entries-file <path.json> --delta TEXT [--replace-description-pointer]
459
469
  [--confirm --approval-token TOKEN]
460
470
  recess [--json] todos create --student <kid-id> --title TEXT
461
- [--due-date YYYY-MM-DD] [--estimated-minutes N] [--url URL] [--confirm]
471
+ [--due-date YYYY-MM-DD] [--target-minutes N] [--url URL] [--confirm]
462
472
  recess [--json] todos edit <todo-id> --patch-file <path/patch.json>
463
473
  [--confirm --approval-token TOKEN]
464
474
  recess [--json] todos complete <todo-id> --xp N
@@ -649,6 +659,29 @@ omitted for US; US ZIPs must be 12345 or 12345-6789. Each entry replaces the
649
659
  family's whole address. The preview is the server's dry run: before and after
650
660
  for every family that changes.
651
661
 
662
+ Tuition-plan notes: "generate" computes a Recess Academy tuition plan (nothing is
663
+ stored): a 180-instructional-day term at --annual (tuition net of Recess aid) and
664
+ a term through the state's typical school-year end. Each is paid in full upfront
665
+ (5% off, per /school/tuition) or quarterly; Florida is instead cash upfront or
666
+ monthly in arrears (Step Up pays only in arrears). --state-funding (family pays
667
+ with ESA funds) makes quarters follow the state's ESA funding dates where Recess
668
+ has them (AZ). It returns the /admin/tuition-plans web URL (--open opens it)
669
+ and, with --pdf, writes the letterhead PDF to that path. "states" lists the
670
+ supported states and their year-end dates. --enrollment partner-school
671
+ (with --partner-school, e.g. wonder-ed) marks the plan an estimate: the partner
672
+ school of record makes the final determination. Add-on prices default to
673
+ $160/month per extra elective and $400 per 4 tutoring sessions; --elective-price,
674
+ --one-on-one-price, and --one-on-one-sessions override them on this sheet.
675
+ --end YYYY-MM-DD adds a custom term through that date (priced by school days).
676
+ --terms and --payments pick a subset of the matrix (default: every term ×
677
+ upfront + installments). Full-year and custom terms may not end after July 1:
678
+ a full year that would is left out of the default and refused if asked for.
679
+ --note TEXT (repeatable) prints a note on the sheet. --bill-date (repeatable)
680
+ moves an invoice date: upfront=YYYY-MM-DD for pay in full, N=YYYY-MM-DD for
681
+ installment N in every term; due dates follow and dates must stay in order.
682
+ --even-installments splits each installment plan evenly in whole dollars (any
683
+ remainder on the first payment) instead of pricing each by its school days.
684
+
652
685
  Payout notes: amounts are integer cents. "payout items add" without --date
653
686
  defaults the item date to the penultimate day of the invoice's cycle (its
654
687
  endDate minus one day) and shows the computed date in the preview.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recess-cli",
3
- "version": "3.8.0",
3
+ "version": "3.10.0",
4
4
  "description": "Safe Recess administration and family AI tools from the command line.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {