@composable-os/pack-courses 0.0.0-stage → 0.1.0-beta.8

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.
Files changed (33) hide show
  1. package/LICENSE +109 -0
  2. package/dist/automations.d.ts +12 -0
  3. package/dist/automations.js +84 -0
  4. package/dist/blocks/courses-builder/course-builder.d.ts +5 -0
  5. package/dist/blocks/courses-builder/course-builder.js +69 -0
  6. package/dist/blocks/courses-catalogue/catalogue.d.ts +6 -0
  7. package/dist/blocks/courses-catalogue/catalogue.js +21 -0
  8. package/dist/blocks/courses-course/course-page.d.ts +10 -0
  9. package/dist/blocks/courses-course/course-page.js +51 -0
  10. package/dist/blocks/courses-my-courses/my-courses.d.ts +5 -0
  11. package/dist/blocks/courses-my-courses/my-courses.js +19 -0
  12. package/dist/blocks/courses-native-catalogue/catalogue-screen.d.ts +6 -0
  13. package/dist/blocks/courses-native-catalogue/catalogue-screen.js +15 -0
  14. package/dist/blocks/courses-native-course/course-screen.d.ts +7 -0
  15. package/dist/blocks/courses-native-course/course-screen.js +18 -0
  16. package/dist/blocks/courses-native-my-courses/my-courses-screen.d.ts +5 -0
  17. package/dist/blocks/courses-native-my-courses/my-courses-screen.js +9 -0
  18. package/dist/blocks/courses-native-player/lesson-screen.d.ts +19 -0
  19. package/dist/blocks/courses-native-player/lesson-screen.js +11 -0
  20. package/dist/blocks/courses-player/player.d.ts +12 -0
  21. package/dist/blocks/courses-player/player.js +51 -0
  22. package/dist/client/index.d.ts +933 -0
  23. package/dist/client/index.js +277 -0
  24. package/dist/dashboards.d.ts +5 -0
  25. package/dist/dashboards.js +119 -0
  26. package/dist/index.d.ts +746 -0
  27. package/dist/index.js +394 -0
  28. package/dist/outline.d.ts +85 -0
  29. package/dist/outline.js +188 -0
  30. package/dist/tools.d.ts +243 -0
  31. package/dist/tools.js +778 -0
  32. package/package.json +36 -4
  33. package/README.md +0 -3
@@ -0,0 +1,277 @@
1
+ // The Courses pack's headless entry (stage 42, step 7; ADRs 0418 and 0453): functions and hooks
2
+ // over the typed client, no markup. A client app imports it as `@composable-os/pack-courses/client`
3
+ // and hands it its generated client; the courses blocks render what it returns.
4
+ //
5
+ // Nothing here decides who may watch, what is for sale or what a course costs. A lesson's material
6
+ // arrives only for a holder (the host removes it for everyone else), and a video plays only with a
7
+ // token the host signs in `media.play`, which `usePlayback` asks for again before it expires.
8
+ import { packHooks } from "@composable-os/client";
9
+ import { LESSON_KINDS, } from "../outline.js";
10
+ export { completion, findLesson, lessonsOf, nextLesson, watchedToEnd } from "../outline.js";
11
+ export const COURSE = "courses.course";
12
+ // --- Plain functions ------------------------------------------------------------------------------
13
+ /** A token is asked for again this long before it expires. */
14
+ export const PLAYBACK_REFRESH_BEFORE_MS = 5 * 60_000;
15
+ /**
16
+ * How long to wait before asking for a new token: until `PLAYBACK_REFRESH_BEFORE_MS` before it
17
+ * expires, never less than 10 seconds (a token about to expire is asked for again at once after).
18
+ */
19
+ export function refreshInMs(expiresAt, now = Date.now()) {
20
+ const at = Date.parse(expiresAt);
21
+ if (Number.isNaN(at))
22
+ return 10_000;
23
+ return Math.max(10_000, at - PLAYBACK_REFRESH_BEFORE_MS - now);
24
+ }
25
+ /** A price as the host gave it, in its currency (`99.00 AUD`). Display only: never worked out. */
26
+ export function formatPrice(price, currency) {
27
+ if (price === null || price === undefined)
28
+ return "";
29
+ try {
30
+ return currency
31
+ ? new Intl.NumberFormat(undefined, { style: "currency", currency }).format(price)
32
+ : String(price);
33
+ }
34
+ catch {
35
+ return `${price}${currency ? ` ${currency}` : ""}`;
36
+ }
37
+ }
38
+ /** A lesson's length as a reader sees it: `12 min`. Display only. */
39
+ export function minutes(duration) {
40
+ return typeof duration === "number" && duration > 0 ? `${duration} min` : "";
41
+ }
42
+ /** Where a phone asks the host for a picture (the course cover): as the Content pack's. */
43
+ export function hostMediaUrl(hostUrl) {
44
+ const host = hostUrl.replace(/\/+$/, "");
45
+ return (id, width) => `${host}/api/v1/media/${encodeURIComponent(id)}${width ? `?w=${Math.round(width)}` : ""}`;
46
+ }
47
+ /** A picture on the site's own media route (`/api/media/<id>?w=`), for the web blocks. */
48
+ export function mediaPath(id, width, base = "") {
49
+ return `${base.replace(/\/+$/, "")}/api/media/${encodeURIComponent(id)}${width ? `?w=${Math.round(width)}` : ""}`;
50
+ }
51
+ // --- The course builder's pure outline edits (as Programs' layoutEdits) -------------------------
52
+ /** A key from a title, unused in `taken`: `wrist-prep`, `wrist-prep-2`. */
53
+ export function newKey(title, taken) {
54
+ const base = title
55
+ .toLowerCase()
56
+ .replace(/[^a-z0-9]+/g, "-")
57
+ .replace(/^-+|-+$/g, "")
58
+ .slice(0, 32) || "lesson";
59
+ let key = base;
60
+ for (let n = 2; taken.has(key); n += 1)
61
+ key = `${base}-${n}`;
62
+ return key;
63
+ }
64
+ const keysOf = (outline) => new Set(outline.sections.flatMap((s) => [s.key, ...(s.lessons ?? []).map((l) => l.key)]));
65
+ /**
66
+ * Pure edits of an outline: each returns a new outline and never changes a lesson's key once it
67
+ * has one (progress is kept by it). The builder block saves the result with `record.update`.
68
+ */
69
+ export const outlineEdits = {
70
+ addSection(outline, title) {
71
+ return {
72
+ sections: [...outline.sections, { key: newKey(title, keysOf(outline)), title, lessons: [] }],
73
+ };
74
+ },
75
+ renameSection(outline, key, title) {
76
+ return {
77
+ sections: outline.sections.map((s) => (s.key === key ? { ...s, title } : s)),
78
+ };
79
+ },
80
+ removeSection(outline, key) {
81
+ return { sections: outline.sections.filter((s) => s.key !== key) };
82
+ },
83
+ addLesson(outline, section, kind, title) {
84
+ if (!LESSON_KINDS.includes(kind))
85
+ return outline;
86
+ const key = newKey(title, keysOf(outline));
87
+ const lesson = { kind, key, title };
88
+ return {
89
+ sections: outline.sections.map((s) => s.key === section ? { ...s, lessons: [...(s.lessons ?? []), lesson] } : s),
90
+ };
91
+ },
92
+ /** Changes a lesson's fields; its key and kind stay. */
93
+ updateLesson(outline, key, patch) {
94
+ const { key: _key, kind: _kind, ...rest } = patch;
95
+ return {
96
+ sections: outline.sections.map((s) => ({
97
+ ...s,
98
+ lessons: (s.lessons ?? []).map((l) => (l.key === key ? { ...l, ...rest } : l)),
99
+ })),
100
+ };
101
+ },
102
+ removeLesson(outline, key) {
103
+ return {
104
+ sections: outline.sections.map((s) => ({
105
+ ...s,
106
+ lessons: (s.lessons ?? []).filter((l) => l.key !== key),
107
+ })),
108
+ };
109
+ },
110
+ /** Moves a lesson to `index` of `section` (by drag or by keyboard). */
111
+ moveLesson(outline, key, section, index) {
112
+ const moving = outline.sections.flatMap((s) => s.lessons ?? []).find((l) => l.key === key);
113
+ if (!moving || !outline.sections.some((s) => s.key === section))
114
+ return outline;
115
+ const without = outlineEdits.removeLesson(outline, key);
116
+ return {
117
+ sections: without.sections.map((s) => {
118
+ if (s.key !== section)
119
+ return s;
120
+ const lessons = [...(s.lessons ?? [])];
121
+ lessons.splice(Math.max(0, Math.min(index, lessons.length)), 0, moving);
122
+ return { ...s, lessons };
123
+ }),
124
+ };
125
+ },
126
+ };
127
+ /**
128
+ * The operations each hook calls (ADR 0453). The public's client gets the catalogue, the course
129
+ * page and buying; a customer's client also their lessons, playback, progress and courses; the
130
+ * staff client the course builder's and the enrolment hooks too.
131
+ */
132
+ export const COURSES_HOOKS_CALL = {
133
+ useCatalogue: ["x.courses.catalogue"],
134
+ useCourse: ["x.courses.course"],
135
+ useBuy: ["x.courses.buy", "order.checkout"],
136
+ useLesson: ["x.courses.lesson"],
137
+ usePlayback: ["media.play"],
138
+ useProgress: ["x.courses.progress"],
139
+ useMyCourses: ["x.courses.myCourses"],
140
+ useStartSession: ["x.courses.startSession"],
141
+ useEnrol: ["x.courses.enrol"],
142
+ useEndEnrolment: ["x.courses.endEnrolment"],
143
+ useStats: ["x.courses.stats"],
144
+ useWorkingCopy: ["record.get"],
145
+ useSaveOutline: ["record.update"],
146
+ usePublishCourse: ["record.publish"],
147
+ useLibraryVideos: ["media.list"],
148
+ usePublishedPrograms: ["record.list"],
149
+ };
150
+ /**
151
+ * Hooks for a React or React Native app:
152
+ * `const courses = createCoursesHooks({ useQuery, useMutation }, api)`. The hooks a client cannot
153
+ * back are not there, and calling one does not compile.
154
+ */
155
+ export function createCoursesHooks(react, client) {
156
+ return packHooks(client, COURSES_HOOKS_CALL, (api) => allCoursesHooks(react, api));
157
+ }
158
+ const none = (name) => ({
159
+ queryKey: [name, "none"],
160
+ queryFn: async () => undefined,
161
+ });
162
+ function allCoursesHooks(react, api) {
163
+ const { useQuery, useMutation } = react;
164
+ return {
165
+ /** The catalogue: published courses, bundles and themes, with the host's prices. */
166
+ useCatalogue(input = {}) {
167
+ return useQuery(api.query("x.courses.catalogue", input));
168
+ },
169
+ /** One published course by its address, with whether the caller holds it. */
170
+ useCourse(slug) {
171
+ const options = slug
172
+ ? api.query("x.courses.course", { slug })
173
+ : none("course");
174
+ return useQuery({ ...options, enabled: slug !== null });
175
+ },
176
+ /** Start an order for a course or a bundle; then `checkout` it (web only). */
177
+ useBuy() {
178
+ return {
179
+ start: useMutation(api.mutation("x.courses.buy")),
180
+ checkout: useMutation(api.mutation("order.checkout")),
181
+ };
182
+ },
183
+ /** One lesson for a holder (or a free preview). */
184
+ useLesson(courseId, lessonKey) {
185
+ const options = courseId && lessonKey
186
+ ? api.query("x.courses.lesson", { courseId, lessonKey })
187
+ : none("lesson");
188
+ return useQuery({ ...options, enabled: Boolean(courseId && lessonKey) });
189
+ },
190
+ /**
191
+ * A token to play a lesson's video (or a trailer), from the host's `media.play`; asked for
192
+ * again `PLAYBACK_REFRESH_BEFORE_MS` before it expires, so a long video keeps playing.
193
+ */
194
+ usePlayback(video) {
195
+ const input = video
196
+ ? {
197
+ id: video.media,
198
+ ...(video.record ? { record: video.record } : {}),
199
+ ...(video.field ? { field: video.field } : {}),
200
+ }
201
+ : null;
202
+ const options = input ? api.query("media.play", input) : none("playback");
203
+ return useQuery({
204
+ ...options,
205
+ enabled: input !== null,
206
+ refetchInterval: (query) => {
207
+ const data = query.state.data;
208
+ return data ? refreshInMs(data.expiresAt) : false;
209
+ },
210
+ });
211
+ },
212
+ /** Mark a lesson started or done, and keep where its video was left. */
213
+ useProgress() {
214
+ return useMutation(api.mutation("x.courses.progress"));
215
+ },
216
+ /** What the caller holds, with progress. */
217
+ useMyCourses() {
218
+ return useQuery(api.query("x.courses.myCourses", {}));
219
+ },
220
+ /** A session lesson's own Programs session, once it is assigned. */
221
+ useStartSession(courseId, lessonKey) {
222
+ const options = courseId && lessonKey
223
+ ? api.query("x.courses.startSession", { courseId, lessonKey })
224
+ : none("session");
225
+ return useQuery({
226
+ ...options,
227
+ enabled: Boolean(courseId && lessonKey),
228
+ // "Preparing your sessions": ask again in a few seconds until it is there.
229
+ refetchInterval: (query) => (query.state.data?.preparing ? 3000 : false),
230
+ });
231
+ },
232
+ /** Staff: give a person access, with a reason. */
233
+ useEnrol() {
234
+ return useMutation(api.mutation("x.courses.enrol"));
235
+ },
236
+ /** Staff: end an enrolment staff gave or one imported. */
237
+ useEndEnrolment() {
238
+ return useMutation(api.mutation("x.courses.endEnrolment"));
239
+ },
240
+ /** Staff: enrolments and lessons done. */
241
+ useStats(courseId) {
242
+ return useQuery(api.query("x.courses.stats", courseId ? { courseId } : {}));
243
+ },
244
+ /** Staff: a course's working copy, as the builder edits it. */
245
+ useWorkingCopy(courseId) {
246
+ return useQuery(api.query("record.get", { object: COURSE, id: courseId }));
247
+ },
248
+ /** Staff: save the course's working copy (its outline). */
249
+ useSaveOutline() {
250
+ return useMutation(api.mutation("record.update"));
251
+ },
252
+ /** Staff: publish the course (a person; an assistant's request waits for one). */
253
+ usePublishCourse() {
254
+ return useMutation(api.mutation("record.publish"));
255
+ },
256
+ /** Staff: the library's ready videos, to pick a lesson's video. */
257
+ useLibraryVideos() {
258
+ return useQuery(api.query("media.list", {
259
+ filter: {
260
+ and: [
261
+ { field: "kind", op: "eq", value: "video" },
262
+ { field: "state", op: "eq", value: "ready" },
263
+ ],
264
+ },
265
+ limit: 100,
266
+ }));
267
+ },
268
+ /** Staff: the published Programs programs, to pick a session lesson's program. */
269
+ usePublishedPrograms() {
270
+ return useQuery(api.query("record.list", {
271
+ object: "programs.program",
272
+ filter: { field: "publishState", op: "eq", value: "published" },
273
+ limit: 100,
274
+ }));
275
+ },
276
+ };
277
+ }
@@ -0,0 +1,5 @@
1
+ import type { DashboardDeclaration } from "@composable-os/sdk";
2
+ export declare const courses: DashboardDeclaration;
3
+ export declare const coursesDashboards: {
4
+ courses: DashboardDeclaration;
5
+ };
@@ -0,0 +1,119 @@
1
+ const PAID_IN = "o.paid_at >= :paid_from AND o.paid_at < :paid_to";
2
+ const IN = (column) => `${column} >= :paid_from AND ${column} < :paid_to`;
3
+ const WEEK = (column) => `date(${column}, '-' || ((strftime('%w', ${column}) + 6) % 7) || ' days')`;
4
+ /** A course's or a bundle's paid lines in the period, with what they sold. */
5
+ const LINES = `FROM rec_order_line l JOIN rec_order o ON o.id = l.order_id
6
+ WHERE l.object_type IN ('courses.course', 'courses.bundle') AND o.state IN ('paid', 'part_paid')
7
+ AND ${PAID_IN}`;
8
+ export const courses = {
9
+ title: "Courses",
10
+ description: "Revenue by month by course and bundle, enrolments by course, completions, lessons done by " +
11
+ "week, and students with nothing done in two weeks.",
12
+ filters: [{ type: "dateRange", id: "paid", label: "Dates", default: "this_quarter" }],
13
+ widgets: [
14
+ {
15
+ id: "revenue",
16
+ type: "kpi",
17
+ title: "Revenue",
18
+ description: "Line totals of course and bundle orders paid in the period (not refunded).",
19
+ sql: `SELECT coalesce(sum(l.line_total), 0) / 100.0 AS value ${LINES}`,
20
+ mapping: { value: "value" },
21
+ options: { compare: true, format: "currency" },
22
+ layout: { w: 3, h: 1 },
23
+ },
24
+ {
25
+ id: "enrolments",
26
+ type: "kpi",
27
+ title: "New enrolments",
28
+ description: "Enrolments made in the period, bought, given or imported.",
29
+ sql: `SELECT count(*) AS value FROM rec_x_courses_enrolment e WHERE ${IN("e.created_at")}`,
30
+ mapping: { value: "value" },
31
+ options: { compare: true },
32
+ clickThrough: {
33
+ object: "courses.enrolment",
34
+ filter: {
35
+ and: [
36
+ { field: "createdAt", op: "gte", value: { $param: "paid_from" } },
37
+ { field: "createdAt", op: "lt", value: { $param: "paid_to" } },
38
+ ],
39
+ },
40
+ },
41
+ layout: { w: 3, h: 1 },
42
+ },
43
+ {
44
+ id: "lessons-done",
45
+ type: "kpi",
46
+ title: "Lessons done",
47
+ description: "Lessons students marked done in the period.",
48
+ sql: `SELECT count(*) AS value FROM rec_x_courses_progress p
49
+ WHERE p.state = 'done' AND ${IN("p.done_at")}`,
50
+ mapping: { value: "value" },
51
+ options: { compare: true },
52
+ layout: { w: 3, h: 1 },
53
+ },
54
+ {
55
+ id: "completed",
56
+ type: "kpi",
57
+ title: "Completed (imported)",
58
+ description: "Enrolments brought from the old platform marked completed.",
59
+ sql: "SELECT count(*) AS value FROM rec_x_courses_enrolment e WHERE e.completed = 1",
60
+ mapping: { value: "value" },
61
+ options: { compare: false },
62
+ layout: { w: 3, h: 1 },
63
+ },
64
+ {
65
+ id: "revenue-by-month",
66
+ type: "bar",
67
+ title: "Revenue by month",
68
+ description: "Paid line totals per month, by course or bundle.",
69
+ sql: `SELECT substr(o.paid_at, 1, 7) AS month, l.title AS item,
70
+ sum(l.line_total) / 100.0 AS revenue ${LINES}
71
+ GROUP BY month, l.title ORDER BY month, item`,
72
+ mapping: { x: "month", y: ["revenue"], series: "item" },
73
+ layout: { w: 6, h: 2 },
74
+ },
75
+ {
76
+ id: "enrolments-by-course",
77
+ type: "leaderboard",
78
+ title: "Enrolments by course",
79
+ description: "Active enrolments per course (a bundle's are counted on the bundle).",
80
+ sql: `SELECT c.id AS course_id, c.title AS label, count(e.id) AS value
81
+ FROM rec_x_courses_course c JOIN rec_x_courses_enrolment e ON e.course = c.id
82
+ WHERE e.status = 'active' GROUP BY c.id, c.title ORDER BY value DESC, label LIMIT 10`,
83
+ mapping: { label: "label", value: "value" },
84
+ clickThrough: {
85
+ object: "courses.enrolment",
86
+ filter: { field: "course", op: "eq", value: { $row: "course_id" } },
87
+ },
88
+ layout: { w: 6, h: 2 },
89
+ },
90
+ {
91
+ id: "done-by-week",
92
+ type: "line",
93
+ title: "Lessons done by week",
94
+ description: "Lessons marked done per week of the period.",
95
+ sql: `SELECT ${WEEK("p.done_at")} AS week, count(*) AS done
96
+ FROM rec_x_courses_progress p WHERE p.state = 'done' AND ${IN("p.done_at")}
97
+ GROUP BY week ORDER BY week`,
98
+ mapping: { x: "week", y: ["done"] },
99
+ layout: { w: 6, h: 2 },
100
+ },
101
+ {
102
+ id: "quiet",
103
+ type: "table",
104
+ title: "Nothing done in two weeks",
105
+ description: "Students with an active enrolment and no lesson started or done in the last 14 days.",
106
+ sql: `SELECT p.id AS id, p.display_name AS student,
107
+ (SELECT max(g.updated_at) FROM rec_x_courses_progress g WHERE g.holder = e.holder) AS last_seen
108
+ FROM rec_x_courses_enrolment e JOIN rec_person p ON p.id = e.holder
109
+ WHERE e.status = 'active' AND NOT EXISTS (
110
+ SELECT 1 FROM rec_x_courses_progress g WHERE g.holder = e.holder
111
+ AND g.updated_at >= date(:today, '-14 days'))
112
+ GROUP BY p.id ORDER BY last_seen, student LIMIT 50`,
113
+ mapping: { columns: ["student", "last_seen"] },
114
+ clickThrough: { object: "person", filter: { field: "id", op: "eq", value: { $row: "id" } } },
115
+ layout: { w: 6, h: 2 },
116
+ },
117
+ ],
118
+ };
119
+ export const coursesDashboards = { courses };