@tansy/lms 0.0.0-stage → 0.1.1

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/schema.js ADDED
@@ -0,0 +1,240 @@
1
+ /** The collections the LMS creates on first install. Owners can change all of it afterwards. */
2
+ export const COLLECTIONS = ["lms-courses", "lms-sections", "lms-lessons", "lms-quizzes", "lms-enrollments", "lms-progress", "lms-attempts", "lms-certificates", "lms-my-courses", "lms-certificate", "lms-outline"];
3
+ /** Blocks a course description allows when it's created. */
4
+ export const DESCRIPTION_BLOCKS = ["lms_text", "lms_video", "lms_download"];
5
+ /** Blocks a lesson allows when it's created. Owners can add their own. */
6
+ export const LESSON_BLOCKS = [...DESCRIPTION_BLOCKS, "lms_quiz"];
7
+ /** Where a course's own content lives. An instructor writes these for their own courses only. */
8
+ export const AUTHORED = ["lms-courses", "lms-sections", "lms-lessons", "lms-quizzes"];
9
+ /** Who teaches and who runs the school. Created once, then owners change them under Roles like any other. */
10
+ export function lmsRoles() {
11
+ const dashboard = ["dashboard:access", "collection:read", "file:list", "file:read", "file:create"];
12
+ return [
13
+ {
14
+ name: "lms-instructor",
15
+ label: "Instructor",
16
+ description: "Builds courses, and edits and deletes only their own, with their sections, lessons and quizzes. Their courses carry their name.",
17
+ permissions: dashboard,
18
+ records: Object.fromEntries(AUTHORED.map((slug) => [slug, ["create", "list:own", "read:own", "update:own", "delete:own"]])),
19
+ },
20
+ {
21
+ name: "lms-manager",
22
+ label: "LMS manager",
23
+ description: "Edits every course, enrolls and revokes learners, sees progress, and changes the LMS settings.",
24
+ permissions: [...dashboard, "file:delete", "ext.lms:manage", "ext.lms:enroll"],
25
+ records: Object.fromEntries(COLLECTIONS.filter((slug) => slug !== "lms-outline").map((slug) => [slug, ["list", "read", "create", "update", "delete"]])),
26
+ },
27
+ ];
28
+ }
29
+ /** The name shown on a course. Filled from the instructor's account, and only managers can change it. */
30
+ /** Sold through the Payments plugin. Added after the first release, so migration 003 adds it to existing sites. */
31
+ export const PAID_ACCESS = { label: "Paid: learners buy it (needs the Payments plugin and a price)", value: "paid" };
32
+ /** Enrolled through a plan from the Payments plugin, and lapsed when the plan no longer covers the course. Added by migration 006. */
33
+ export const PLAN_SOURCE = { label: "Plan", value: "plan" };
34
+ export const LAPSED_STATE = { label: "Lapsed: their plan no longer covers it", value: "lapsed" };
35
+ export const BYLINE_FIELD = { name: "byline", type: "text", config: { maxLength: 200, label: "Taught by" } };
36
+ /** Filled from the title or name when left empty, so it isn't required. */
37
+ const SLUG_FIELD = {
38
+ name: "slug",
39
+ type: "text",
40
+ config: { unique: true, maxLength: 80, pattern: "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$", patternError: "Use lowercase letters, numbers and hyphens, starting and ending with a letter or number." },
41
+ };
42
+ /** A user's id. Rules compare it with @request.auth.id, and only the plugin's routes and staff write it. */
43
+ const STUDENT_FIELD = { name: "student", type: "text", config: { required: true, maxLength: 64, label: "Student (user id)" } };
44
+ const LOCKED = { createRule: null, updateRule: null, deleteRule: null };
45
+ const PUBLIC = { listRule: "", viewRule: "", ...LOCKED };
46
+ /** Records about one learner: only they may read them, and nobody but staff and the plugin writes them. */
47
+ const OWN = 'student = @request.auth.id && @request.auth.id != ""';
48
+ const LEARNER = { listRule: OWN, viewRule: OWN, ...LOCKED };
49
+ /**
50
+ * The gate. A course id in the hidden lms_courses user field means an active enrollment,
51
+ * and only the plugin writes that field. Rules read user values on every request, so
52
+ * revoking an enrollment ends access on the next one, through every way of reading records.
53
+ */
54
+ export const ENROLLED = "@request.auth.lms_courses ?= course";
55
+ const GATED = `status = "published" && (preview = true || ${ENROLLED})`;
56
+ /** The user field the gate reads. */
57
+ export const COURSES_FIELD = "lms_courses";
58
+ /**
59
+ * Only what a course page may show anyone about its lessons. Drafts stay out, and the
60
+ * lessons themselves stay gated. Quoted names, so it runs the same on SQLite and Postgres.
61
+ */
62
+ export const OUTLINE_QUERY = `SELECT "id", "title", "course", "section", "position", "preview", "durationMinutes" FROM "rec_lms_lessons" WHERE "status" = 'published'`;
63
+ /** A field the plugin's code reads or writes, by collection: the contract Extensions checks. */
64
+ export const CONTRACT = {
65
+ "lms-courses": { slug: "text", title: "text", summary: "text", byline: "text", access: "radio" },
66
+ "lms-sections": { course: "reference", title: "text", position: "number" },
67
+ "lms-lessons": { slug: "text", title: "text", course: "reference", section: "reference", position: "number", preview: "boolean", content: "stream" },
68
+ "lms-quizzes": { lesson: "reference", course: "reference", title: "text", questions: "stream", passingScore: "number", maxAttempts: "number" },
69
+ "lms-enrollments": { course: "reference", student: "text", state: "radio", source: "radio", enrolledAt: "datetime", completedAt: "datetime" },
70
+ "lms-progress": { key: "text", student: "text", course: "reference", lesson: "reference", completedAt: "datetime" },
71
+ "lms-attempts": { quiz: "reference", student: "text", answers: "json", score: "number", passed: "boolean", submittedAt: "datetime" },
72
+ "lms-certificates": { code: "text", student: "text", course: "reference", studentName: "text", issuedAt: "datetime" },
73
+ };
74
+ const position = { name: "position", type: "number", config: { format: "integer", min: 0, description: "Lower comes first." } };
75
+ export function lmsSchema(basePath) {
76
+ return {
77
+ version: 1,
78
+ collections: [
79
+ {
80
+ slug: "lms-courses",
81
+ name: "Courses",
82
+ description: "Courses, made of sections and lessons. Free courses take anyone who signs in. Others need staff to enroll each learner.",
83
+ urlPattern: `${basePath}/:slug`,
84
+ rules: { listRule: 'status = "published"', viewRule: 'status = "published"', ...LOCKED },
85
+ fields: [
86
+ { name: "title", type: "text", config: { required: true, maxLength: 200, searchable: true } },
87
+ SLUG_FIELD,
88
+ { name: "summary", type: "text", config: { multiline: true, maxLength: 500, searchable: true } },
89
+ { name: "cover", type: "image", config: {} },
90
+ { name: "description", type: "stream", config: { allowedBlocks: DESCRIPTION_BLOCKS } },
91
+ BYLINE_FIELD,
92
+ { name: "level", type: "radio", config: { options: [{ label: "Beginner", value: "beginner" }, { label: "Intermediate", value: "intermediate" }, { label: "Advanced", value: "advanced" }] } },
93
+ { name: "access", type: "radio", config: { options: [{ label: "Free: anyone signed in can enroll", value: "free" }, { label: "By enrollment: staff enroll learners", value: "enrollment" }, PAID_ACCESS], defaultValue: "free" } },
94
+ { name: "estimatedMinutes", type: "number", config: { format: "integer", min: 0 } },
95
+ ],
96
+ },
97
+ {
98
+ slug: "lms-sections",
99
+ name: "Course sections",
100
+ description: "Chapters that group a course's lessons.",
101
+ urlPattern: null,
102
+ rules: PUBLIC,
103
+ fields: [
104
+ { name: "title", type: "text", config: { required: true, maxLength: 200 } },
105
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", required: true } },
106
+ position,
107
+ ],
108
+ },
109
+ {
110
+ slug: "lms-lessons",
111
+ name: "Lessons",
112
+ description: "Open to enrolled learners. A preview lesson is open to everyone.",
113
+ urlPattern: "/learn/:slug",
114
+ rules: { listRule: GATED, viewRule: GATED, ...LOCKED },
115
+ fields: [
116
+ { name: "title", type: "text", config: { required: true, maxLength: 200 } },
117
+ SLUG_FIELD,
118
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", required: true } },
119
+ { name: "section", type: "reference", config: { collection: "lms-sections", displayField: "title" } },
120
+ position,
121
+ { name: "preview", type: "boolean", config: { description: "Open to everyone, enrolled or not." } },
122
+ { name: "content", type: "stream", config: { allowedBlocks: LESSON_BLOCKS } },
123
+ { name: "durationMinutes", type: "number", config: { format: "integer", min: 0 } },
124
+ ],
125
+ },
126
+ {
127
+ slug: "lms-quizzes",
128
+ name: "Quizzes",
129
+ description: "Graded on the server. Questions and answers are hidden: learners get the questions without answers through the plugin's route.",
130
+ urlPattern: null,
131
+ // Only enrolled learners. A quiz has no preview.
132
+ rules: { listRule: ENROLLED, viewRule: ENROLLED, ...LOCKED },
133
+ fields: [
134
+ { name: "title", type: "text", config: { required: true, maxLength: 200 } },
135
+ { name: "lesson", type: "reference", config: { collection: "lms-lessons", displayField: "title", required: true } },
136
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", description: "Set from the lesson when saved." } },
137
+ { name: "questions", type: "stream", config: { allowedBlocks: ["lms_question"], hidden: true } },
138
+ { name: "passingScore", type: "number", config: { format: "integer", min: 0, max: 100, description: "Percent needed to pass. Empty uses the site's default." } },
139
+ { name: "maxAttempts", type: "number", config: { format: "integer", min: 1, description: "Empty for no limit." } },
140
+ ],
141
+ },
142
+ {
143
+ slug: "lms-enrollments",
144
+ name: "Enrollments",
145
+ description: "Who may open which course. Revoking one ends access on the learner's next request.",
146
+ urlPattern: null,
147
+ rules: LEARNER,
148
+ fields: [
149
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", required: true } },
150
+ STUDENT_FIELD,
151
+ { name: "state", type: "radio", config: { options: [{ label: "Active", value: "active" }, { label: "Completed", value: "completed" }, { label: "Revoked", value: "revoked" }], defaultValue: "active" } },
152
+ { name: "source", type: "radio", config: { options: [{ label: "Free enrollment", value: "free" }, { label: "Staff", value: "staff" }, { label: "Purchase", value: "purchase" }], defaultValue: "staff" } },
153
+ { name: "enrolledAt", type: "datetime", config: {} },
154
+ { name: "completedAt", type: "datetime", config: {} },
155
+ ],
156
+ },
157
+ {
158
+ slug: "lms-progress",
159
+ name: "Lesson progress",
160
+ description: "Each lesson a learner has completed.",
161
+ urlPattern: null,
162
+ rules: LEARNER,
163
+ fields: [
164
+ // <student>:<lesson>, so the database itself keeps a lesson from completing twice.
165
+ { name: "key", type: "text", config: { required: true, unique: true, maxLength: 100 } },
166
+ STUDENT_FIELD,
167
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", required: true } },
168
+ { name: "lesson", type: "reference", config: { collection: "lms-lessons", displayField: "title", required: true } },
169
+ { name: "completedAt", type: "datetime", config: {} },
170
+ ],
171
+ },
172
+ {
173
+ slug: "lms-attempts",
174
+ name: "Quiz attempts",
175
+ description: "Each submitted quiz, graded on the server.",
176
+ urlPattern: null,
177
+ rules: LEARNER,
178
+ fields: [
179
+ { name: "quiz", type: "reference", config: { collection: "lms-quizzes", displayField: "title", required: true } },
180
+ STUDENT_FIELD,
181
+ { name: "answers", type: "json", config: {} },
182
+ { name: "score", type: "number", config: { min: 0, max: 100 } },
183
+ { name: "passed", type: "boolean", config: {} },
184
+ { name: "submittedAt", type: "datetime", config: {} },
185
+ ],
186
+ },
187
+ {
188
+ slug: "lms-certificates",
189
+ name: "Certificates",
190
+ description: "Issued when a learner completes a course. Anyone with the code can check one is genuine.",
191
+ urlPattern: null,
192
+ rules: LEARNER,
193
+ fields: [
194
+ { name: "code", type: "text", config: { required: true, unique: true, maxLength: 32 } },
195
+ STUDENT_FIELD,
196
+ { name: "course", type: "reference", config: { collection: "lms-courses", displayField: "title", required: true } },
197
+ { name: "studentName", type: "text", config: { maxLength: 200 } },
198
+ { name: "issuedAt", type: "datetime", config: {} },
199
+ ],
200
+ },
201
+ {
202
+ slug: "lms-my-courses",
203
+ name: "My courses page",
204
+ description: "The page where signed-in learners see their courses and progress.",
205
+ type: "singleton",
206
+ urlPattern: "/my-courses",
207
+ rules: PUBLIC,
208
+ fields: [
209
+ { name: "title", type: "text", config: { required: true, maxLength: 120 } },
210
+ { name: "intro", type: "rich_text", config: {} },
211
+ ],
212
+ },
213
+ {
214
+ slug: "lms-certificate",
215
+ name: "Certificate check page",
216
+ description: "The page where anyone can check a certificate by its code.",
217
+ type: "singleton",
218
+ urlPattern: "/certificates",
219
+ rules: PUBLIC,
220
+ fields: [
221
+ { name: "title", type: "text", config: { required: true, maxLength: 120 } },
222
+ { name: "intro", type: "rich_text", config: {} },
223
+ ],
224
+ },
225
+ {
226
+ slug: "lms-outline",
227
+ name: "Course outlines",
228
+ description: "Every published lesson's title and place, for course pages. The lessons stay gated.",
229
+ type: "view",
230
+ viewQuery: OUTLINE_QUERY,
231
+ urlPattern: null,
232
+ rules: PUBLIC,
233
+ fields: [],
234
+ },
235
+ ],
236
+ // Here rather than in the plugin's blocks, because it links to a collection this document creates.
237
+ blocks: [{ name: "lms_quiz", label: "Quiz", labels: { ar: "اختبار" }, icon: null, fields: [{ name: "quiz", type: "reference", config: { collection: "lms-quizzes", displayField: "title", required: true } }] }],
238
+ userFields: [{ name: COURSES_FIELD, type: "json", config: { hidden: true, label: "Enrolled courses", description: "Set by the LMS from active enrollments. Lesson rules read it." }, selfEditable: false }],
239
+ };
240
+ }
package/service.d.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { type ExtensionContext, type Formatters, type RecordValues, type RecordsApi } from "tansy/plugin";
2
+ export interface LmsSettings {
3
+ certificates: boolean;
4
+ requireQuizzes: boolean;
5
+ passingScore: number;
6
+ }
7
+ export declare const isUserId: (value: unknown) => value is string;
8
+ export declare const idOf: (value: unknown) => number | null;
9
+ /** A filter value for a user id. Throws on anything else, so no caller can write past the quotes. */
10
+ export declare function userFilter(field: string, userId: string): string;
11
+ export declare function exclusive<T>(key: string, work: () => Promise<T>): Promise<T>;
12
+ /** Every matching record, up to `limit`. Lists are paged at 200. */
13
+ export declare function listAll(records: RecordsApi, slug: string, query: Record<string, unknown>, limit?: number): Promise<RecordValues[]>;
14
+ /**
15
+ * Enrollments that open a course: active or completed. A revoked one is history, and a lapsed one
16
+ * came from a plan that no longer covers the course, and opens again if it does.
17
+ */
18
+ export declare const CURRENT = "state != \"revoked\" && state != \"lapsed\"";
19
+ /** A learner's enrollment in a course that still counts: active or completed. */
20
+ export declare function currentEnrollment(context: ExtensionContext, student: string, course: number): Promise<RecordValues>;
21
+ /**
22
+ * Writes the student's lms_courses from their enrollments, rather than adding or removing one id,
23
+ * so it repairs itself whatever happened before. A user who no longer exists is skipped.
24
+ */
25
+ export declare function rebuildCourses(context: ExtensionContext, student: unknown): Promise<void>;
26
+ /** The course's published lessons in reading order, with only their place. */
27
+ export declare function courseLessons(records: RecordsApi, course: number): Promise<(RecordValues & {
28
+ id: number;
29
+ })[]>;
30
+ /** Which lessons of a course the student finished, by lesson id. */
31
+ export declare function finishedLessons(context: ExtensionContext, student: string, course: number): Promise<Set<number>>;
32
+ /**
33
+ * Completes the enrollment once every published lesson is done, and every quiz passed when
34
+ * that's required. Then issues one certificate and emails it. Safe to call any number of times.
35
+ */
36
+ export declare function checkCompletion(context: ExtensionContext, settings: LmsSettings, student: unknown, course: unknown): Promise<void>;
37
+ /**
38
+ * The language to write to a learner in, with the plugin's words in it and how to read records
39
+ * in it: their chosen language when the site is published in it, otherwise the site's default.
40
+ */
41
+ export declare function learnerWords(context: Pick<ExtensionContext, "schema">, locale: string): Promise<Formatters & {
42
+ locale: string;
43
+ read: {
44
+ locale?: string;
45
+ };
46
+ }>;
47
+ /** A language for the records API from `?locale=`, on a site with more than one. Anything else reads the default. */
48
+ export declare function askedLanguage(context: Pick<ExtensionContext, "schema">, request: Request): Promise<{
49
+ locale?: undefined;
50
+ } | {
51
+ locale: string;
52
+ }>;
53
+ /** Percent done and the next lesson, for each of a learner's courses. `records` reads as the learner, so only what they may open gets a link. */
54
+ export declare function learnerCourses(context: ExtensionContext, records: RecordsApi, student: string, read?: {
55
+ locale?: string;
56
+ }): Promise<{
57
+ enrollment: {
58
+ id: unknown;
59
+ state: unknown;
60
+ enrolledAt: {} | null;
61
+ completedAt: {} | null;
62
+ };
63
+ course: {
64
+ id: unknown;
65
+ title: string;
66
+ summary: string;
67
+ cover: string | null;
68
+ recordPath: string | null;
69
+ };
70
+ lessons: number;
71
+ completed: number;
72
+ percent: number;
73
+ next: {
74
+ id: unknown;
75
+ title: string;
76
+ recordPath: string | null;
77
+ } | null;
78
+ }[]>;
79
+ export type EnrollmentSource = "free" | "staff" | "purchase" | "plan";
80
+ /**
81
+ * Enrolls the student unless they already are. A revoked enrollment stays as history, and a new
82
+ * one is made. A lapsed one opens again, so it keeps its place. Returns the enrollment and whether
83
+ * it is new.
84
+ *
85
+ * Someone in a course through their plan who then buys it or is enrolled by staff keeps it when
86
+ * the plan ends, so the enrollment takes the new source.
87
+ */
88
+ export declare function enroll(context: ExtensionContext, student: string, course: number, source: EnrollmentSource): Promise<{
89
+ enrollment: RecordValues;
90
+ created: boolean;
91
+ }>;
92
+ /**
93
+ * Plans, from the Payments plugin, read as data: LMS imports nothing from it. A person's
94
+ * `payments-entitlements` record lists the access their active plans include, by id, and the
95
+ * collections those open whole, by slug. A course is covered by a plan when that list has
96
+ * `lms-courses`, or one of the access the course is "Included in".
97
+ */
98
+ export declare const ACCESS = "payments-access";
99
+ /** The field the LMS adds to courses when Payments is installed. Any other Reference to Access on courses counts too. */
100
+ export declare const INCLUDED = "included";
101
+ export declare const INCLUDED_FIELD: {
102
+ name: string;
103
+ type: string;
104
+ config: {
105
+ collection: string;
106
+ displayField: string;
107
+ allowMultiple: boolean;
108
+ label: string;
109
+ description: string;
110
+ };
111
+ };
112
+ /** What the person's plans open, from the record Payments keeps. Without Payments, nothing. */
113
+ export declare function entitlementsOf(context: ExtensionContext, student: string): Promise<Array<number | string>>;
114
+ /** The access a course is "Included in", read from what's stored, never from a request. */
115
+ export declare function courseAccess(context: ExtensionContext, course: number): Promise<number[]>;
116
+ /** Whether these entitlements open the course: every course, or one of the access it is in. */
117
+ export declare function covers(context: ExtensionContext, access: Array<number | string>, course: number): Promise<boolean>;
118
+ /**
119
+ * Brings a learner's plan enrollments in line with what their plans cover now: a course no longer
120
+ * covered lapses, and one covered again opens where they left it. Progress, quiz attempts and
121
+ * certificates are kept either way. Reads everything as it is now, so running it again, or after a
122
+ * newer change, always leaves the right state. `course` limits it to one course.
123
+ */
124
+ export declare function reconcilePlanEnrollments(context: ExtensionContext, settings: LmsSettings, student: unknown, course?: number): Promise<void>;
package/service.js ADDED
@@ -0,0 +1,282 @@
1
+ /** The LMS's server logic, shared by its hooks and routes. Every write goes through `system.records`, so hooks and the audit log see it. */
2
+ import { randomBytes } from "node:crypto";
3
+ import { wordsIn } from "tansy/plugin";
4
+ import { siteMessages } from "./site-messages";
5
+ import { certificateCode, orderLessons, percentDone } from "./logic";
6
+ import { COURSES_FIELD } from "./schema";
7
+ /** better-auth ids are letters, digits, hyphens and underscores. Anything else never reaches a filter. */
8
+ const USER_ID = /^[A-Za-z0-9_-]{1,64}$/;
9
+ export const isUserId = (value) => typeof value === "string" && USER_ID.test(value);
10
+ export const idOf = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null);
11
+ const str = (value) => (typeof value === "string" ? value : "");
12
+ /** A filter value for a user id. Throws on anything else, so no caller can write past the quotes. */
13
+ export function userFilter(field, userId) {
14
+ if (!isUserId(userId))
15
+ throw new Error("Not a user id.");
16
+ return `${field} = "${userId}"`;
17
+ }
18
+ const queues = (globalThis.lmsQueues ??= new Map());
19
+ export function exclusive(key, work) {
20
+ const previous = queues.get(key) ?? Promise.resolve();
21
+ const run = previous.catch(() => { }).then(work);
22
+ const settled = run.catch(() => { });
23
+ queues.set(key, settled);
24
+ void settled.then(() => { if (queues.get(key) === settled)
25
+ queues.delete(key); });
26
+ return run;
27
+ }
28
+ /** Every matching record, up to `limit`. Lists are paged at 200. */
29
+ export async function listAll(records, slug, query, limit = 2000) {
30
+ const items = [];
31
+ for (let page = 1; items.length < limit; page++) {
32
+ const result = await records.list(slug, { ...query, page, perPage: 200 });
33
+ items.push(...result.items);
34
+ if (page >= result.totalPages)
35
+ break;
36
+ }
37
+ return items.slice(0, limit);
38
+ }
39
+ /**
40
+ * Enrollments that open a course: active or completed. A revoked one is history, and a lapsed one
41
+ * came from a plan that no longer covers the course, and opens again if it does.
42
+ */
43
+ export const CURRENT = 'state != "revoked" && state != "lapsed"';
44
+ /** A learner's enrollment in a course that still counts: active or completed. */
45
+ export async function currentEnrollment(context, student, course) {
46
+ const { items } = await context.system.records.list("lms-enrollments", { filter: `${userFilter("student", student)} && course = ${course} && ${CURRENT}`, sort: "createdAt", perPage: 1 });
47
+ return items[0] ?? null;
48
+ }
49
+ /**
50
+ * Writes the student's lms_courses from their enrollments, rather than adding or removing one id,
51
+ * so it repairs itself whatever happened before. A user who no longer exists is skipped.
52
+ */
53
+ export async function rebuildCourses(context, student) {
54
+ if (!isUserId(student))
55
+ return;
56
+ await exclusive(`courses:${student}`, async () => {
57
+ const enrollments = await listAll(context.system.records, "lms-enrollments", { filter: `${userFilter("student", student)} && ${CURRENT}`, fields: "course" });
58
+ const courses = [...new Set(enrollments.map((enrollment) => idOf(enrollment.course)).filter((id) => id !== null))].sort((a, b) => a - b);
59
+ const stored = await context.system.users.getValues(student);
60
+ if (!stored)
61
+ return;
62
+ // Usually already right, as the route and the hook both rebuild. Unchanged, nothing is written.
63
+ const current = Array.isArray(stored[COURSES_FIELD]) ? stored[COURSES_FIELD] : [];
64
+ if (current.length === courses.length && current.every((id, i) => id === courses[i]))
65
+ return;
66
+ await context.system.users.setValues(student, { [COURSES_FIELD]: courses });
67
+ });
68
+ }
69
+ /** The course's published lessons in reading order, with only their place. */
70
+ export async function courseLessons(records, course) {
71
+ const [lessons, sections] = await Promise.all([
72
+ listAll(records, "lms-lessons", { filter: `course = ${course} && status = "published"`, fields: "id,title,section,position" }),
73
+ listAll(records, "lms-sections", { filter: `course = ${course}`, fields: "id,position" }),
74
+ ]);
75
+ return orderLessons(lessons, sections);
76
+ }
77
+ /** Which lessons of a course the student finished, by lesson id. */
78
+ export async function finishedLessons(context, student, course) {
79
+ const progress = await listAll(context.system.records, "lms-progress", { filter: `${userFilter("student", student)} && course = ${course}`, fields: "lesson" });
80
+ return new Set(progress.map((row) => idOf(row.lesson)).filter((id) => id !== null));
81
+ }
82
+ /** Quizzes of the course's published lessons, and which of them the student has passed. */
83
+ async function quizzesLeft(context, student, course, lessonIds) {
84
+ const quizzes = (await listAll(context.system.records, "lms-quizzes", { filter: `course = ${course}`, fields: "id,lesson" })).filter((quiz) => lessonIds.has(idOf(quiz.lesson) ?? 0));
85
+ if (!quizzes.length)
86
+ return 0;
87
+ const passed = await listAll(context.system.records, "lms-attempts", { filter: `${userFilter("student", student)} && passed = true`, fields: "quiz" });
88
+ const passedIds = new Set(passed.map((attempt) => idOf(attempt.quiz)));
89
+ return quizzes.filter((quiz) => !passedIds.has(quiz.id)).length;
90
+ }
91
+ /**
92
+ * Completes the enrollment once every published lesson is done, and every quiz passed when
93
+ * that's required. Then issues one certificate and emails it. Safe to call any number of times.
94
+ */
95
+ export async function checkCompletion(context, settings, student, course) {
96
+ const courseId = idOf(course);
97
+ if (!isUserId(student) || courseId === null)
98
+ return;
99
+ await exclusive(`complete:${student}:${courseId}`, async () => {
100
+ const enrollment = await currentEnrollment(context, student, courseId);
101
+ if (!enrollment)
102
+ return;
103
+ const lessons = await courseLessons(context.system.records, courseId);
104
+ if (!lessons.length)
105
+ return;
106
+ const done = await finishedLessons(context, student, courseId);
107
+ if (!lessons.every((lesson) => done.has(lesson.id)))
108
+ return;
109
+ if (settings.requireQuizzes && (await quizzesLeft(context, student, courseId, new Set(lessons.map((lesson) => lesson.id)))) > 0)
110
+ return;
111
+ if (enrollment.state !== "completed") {
112
+ await context.system.records.update("lms-enrollments", enrollment.id, { state: "completed", completedAt: new Date().toISOString() });
113
+ }
114
+ if (settings.certificates)
115
+ await issueCertificate(context, student, courseId);
116
+ });
117
+ }
118
+ /**
119
+ * The language to write to a learner in, with the plugin's words in it and how to read records
120
+ * in it: their chosen language when the site is published in it, otherwise the site's default.
121
+ */
122
+ export async function learnerWords(context, locale) {
123
+ const languages = await context.schema.languages();
124
+ const known = languages.items.some((item) => item.code === locale) ? locale : null;
125
+ return { locale, ...wordsIn(siteMessages, locale), read: known && languages.items.length > 1 ? { locale: known } : {} };
126
+ }
127
+ /** A language for the records API from `?locale=`, on a site with more than one. Anything else reads the default. */
128
+ export async function askedLanguage(context, request) {
129
+ const asked = new URL(request.url).searchParams.get("locale");
130
+ if (!asked)
131
+ return {};
132
+ const languages = await context.schema.languages();
133
+ return languages.items.length > 1 && languages.items.some((item) => item.code === asked) ? { locale: asked } : {};
134
+ }
135
+ async function issueCertificate(context, student, course) {
136
+ const { items } = await context.system.records.list("lms-certificates", { filter: `${userFilter("student", student)} && course = ${course}`, perPage: 1, fields: "id" });
137
+ if (items.length)
138
+ return;
139
+ const user = await context.system.users.get(student);
140
+ if (!user)
141
+ return;
142
+ const { t, locale, read } = await learnerWords(context, user.locale);
143
+ const title = str((await context.system.records.get("lms-courses", course, { fields: "title", ...read }).catch(() => null))?.title) || t("lms.mail.yourCourse");
144
+ const code = certificateCode((size) => randomBytes(size));
145
+ await context.system.records.create("lms-certificates", { status: "published", code, student, course, studentName: user.name, issuedAt: new Date().toISOString() });
146
+ await context.mail.send({
147
+ to: user.email,
148
+ locale,
149
+ subject: t("lms.mail.completedSubject", { title: title.slice(0, 150) }),
150
+ body: t("lms.mail.completedBody", { name: user.name || t("lms.mail.learner"), title, code }),
151
+ }).catch((error) => console.error("[lms] certificate email", error));
152
+ }
153
+ /** Percent done and the next lesson, for each of a learner's courses. `records` reads as the learner, so only what they may open gets a link. */
154
+ export async function learnerCourses(context, records, student, read = {}) {
155
+ const enrollments = await listAll(records, "lms-enrollments", { filter: `${userFilter("student", student)} && ${CURRENT}`, sort: "-enrolledAt", fields: "id,course,state,enrolledAt,completedAt" }, 200);
156
+ return Promise.all(enrollments.map(async (enrollment) => {
157
+ const courseId = idOf(enrollment.course);
158
+ const course = await records.get("lms-courses", courseId, { fields: "id,title,slug,summary,cover", urls: "1", ...read }).catch(() => null);
159
+ const lessons = await courseLessons(records, courseId);
160
+ const done = await finishedLessons(context, student, courseId);
161
+ const next = lessons.find((lesson) => !done.has(lesson.id));
162
+ const nextLesson = next ? await records.get("lms-lessons", next.id, { fields: "id,title", urls: "1", ...read }).catch(() => null) : null;
163
+ return {
164
+ enrollment: { id: enrollment.id, state: enrollment.state, enrolledAt: enrollment.enrolledAt ?? null, completedAt: enrollment.completedAt ?? null },
165
+ course: course ? { id: course.id, title: str(course.title), summary: str(course.summary), cover: str(course.cover) || null, recordPath: str(course.recordPath) || null } : { id: courseId, title: "", summary: "", cover: null, recordPath: null },
166
+ lessons: lessons.length,
167
+ completed: lessons.filter((lesson) => done.has(lesson.id)).length,
168
+ percent: percentDone(lessons.filter((lesson) => done.has(lesson.id)).length, lessons.length),
169
+ next: nextLesson ? { id: nextLesson.id, title: str(nextLesson.title), recordPath: str(nextLesson.recordPath) || null } : null,
170
+ };
171
+ }));
172
+ }
173
+ /**
174
+ * Enrolls the student unless they already are. A revoked enrollment stays as history, and a new
175
+ * one is made. A lapsed one opens again, so it keeps its place. Returns the enrollment and whether
176
+ * it is new.
177
+ *
178
+ * Someone in a course through their plan who then buys it or is enrolled by staff keeps it when
179
+ * the plan ends, so the enrollment takes the new source.
180
+ */
181
+ export async function enroll(context, student, course, source) {
182
+ const result = await exclusive(`enroll:${student}:${course}`, async () => {
183
+ const existing = await currentEnrollment(context, student, course);
184
+ if (existing) {
185
+ if (existing.source === "plan" && source !== "plan")
186
+ return { enrollment: await context.system.records.update("lms-enrollments", existing.id, { source }), created: false };
187
+ return { enrollment: existing, created: false };
188
+ }
189
+ const { items: [lapsed] } = await context.system.records.list("lms-enrollments", { filter: `${userFilter("student", student)} && course = ${course} && state = "lapsed"`, sort: "-createdAt", perPage: 1, fields: "id" });
190
+ if (lapsed)
191
+ return { enrollment: await context.system.records.update("lms-enrollments", lapsed.id, { state: "active", source }), created: false };
192
+ const enrollment = await context.system.records.create("lms-enrollments", { status: "published", course, student, source, state: "active", enrolledAt: new Date().toISOString() });
193
+ return { enrollment, created: true };
194
+ });
195
+ // Straight away, rather than only from the hook after commit, so the learner's next request can open the course.
196
+ await rebuildCourses(context, student);
197
+ return result;
198
+ }
199
+ /**
200
+ * Plans, from the Payments plugin, read as data: LMS imports nothing from it. A person's
201
+ * `payments-entitlements` record lists the access their active plans include, by id, and the
202
+ * collections those open whole, by slug. A course is covered by a plan when that list has
203
+ * `lms-courses`, or one of the access the course is "Included in".
204
+ */
205
+ export const ACCESS = "payments-access";
206
+ const ENTITLEMENTS = "payments-entitlements";
207
+ /** The field the LMS adds to courses when Payments is installed. Any other Reference to Access on courses counts too. */
208
+ export const INCLUDED = "included";
209
+ export const INCLUDED_FIELD = {
210
+ name: INCLUDED,
211
+ type: "reference",
212
+ config: { collection: ACCESS, displayField: "name", allowMultiple: true, label: "Included in", description: "Subscribers to a plan that includes one of these may take the course without buying it." },
213
+ };
214
+ const accessIds = (value) => (Array.isArray(value) ? value : [value]).filter((id) => typeof id === "number" && Number.isSafeInteger(id) && id > 0);
215
+ /** What the person's plans open, from the record Payments keeps. Without Payments, nothing. */
216
+ export async function entitlementsOf(context, student) {
217
+ if (!isUserId(student))
218
+ return [];
219
+ const { items } = await context.system.records.list(ENTITLEMENTS, { filter: userFilter("user", student), perPage: 1, fields: "access" }).catch(() => ({ items: [] }));
220
+ const access = items[0]?.access;
221
+ return Array.isArray(access) ? access.filter((item) => typeof item === "number" || typeof item === "string") : [];
222
+ }
223
+ /** Reference fields on courses that point at Payments' access, whatever the owner named them. */
224
+ async function accessFields(context) {
225
+ const shape = await context.schema.describe("lms-courses");
226
+ return (shape?.fields ?? []).filter((field) => field.type === "reference" && field.config?.collection === ACCESS).map((field) => field.name);
227
+ }
228
+ /** The access a course is "Included in", read from what's stored, never from a request. */
229
+ export async function courseAccess(context, course) {
230
+ const fields = await accessFields(context);
231
+ if (!fields.length)
232
+ return [];
233
+ const record = await context.system.records.get("lms-courses", course, { fields: fields.join(",") }).catch(() => null);
234
+ return [...new Set(fields.flatMap((field) => accessIds(record?.[field])))];
235
+ }
236
+ /** Whether these entitlements open the course: every course, or one of the access it is in. */
237
+ export async function covers(context, access, course) {
238
+ if (!access.length)
239
+ return false;
240
+ if (access.includes("lms-courses"))
241
+ return true;
242
+ return (await courseAccess(context, course)).some((id) => access.includes(id));
243
+ }
244
+ /**
245
+ * Brings a learner's plan enrollments in line with what their plans cover now: a course no longer
246
+ * covered lapses, and one covered again opens where they left it. Progress, quiz attempts and
247
+ * certificates are kept either way. Reads everything as it is now, so running it again, or after a
248
+ * newer change, always leaves the right state. `course` limits it to one course.
249
+ */
250
+ export async function reconcilePlanEnrollments(context, settings, student, course) {
251
+ if (!isUserId(student))
252
+ return;
253
+ const restored = await exclusive(`plan:${student}`, async () => {
254
+ const enrollments = await listAll(context.system.records, "lms-enrollments", { filter: `${userFilter("student", student)} && source = "plan" && state != "revoked"${course ? ` && course = ${course}` : ""}`, fields: "id,course,state" });
255
+ if (!enrollments.length)
256
+ return [];
257
+ const access = await entitlementsOf(context, student);
258
+ const opened = [];
259
+ let changed = false;
260
+ for (const enrollment of enrollments) {
261
+ const courseId = idOf(enrollment.course);
262
+ if (courseId === null)
263
+ continue;
264
+ const covered = await covers(context, access, courseId);
265
+ if (enrollment.state === "lapsed" && covered) {
266
+ await context.system.records.update("lms-enrollments", enrollment.id, { state: "active" });
267
+ opened.push(courseId);
268
+ changed = true;
269
+ }
270
+ else if (enrollment.state !== "lapsed" && !covered) {
271
+ await context.system.records.update("lms-enrollments", enrollment.id, { state: "lapsed" });
272
+ changed = true;
273
+ }
274
+ }
275
+ if (changed)
276
+ await rebuildCourses(context, student);
277
+ return opened;
278
+ });
279
+ // A course they had finished counts as finished again.
280
+ for (const courseId of restored)
281
+ await checkCompletion(context, settings, student, courseId);
282
+ }
@@ -0,0 +1,3 @@
1
+ import type { Messages } from "tansy/plugin";
2
+ /** What learners read: course and lesson pages, quizzes, certificates and emails, as `t("lms.<key>")`. Themes and owners can word any of it differently. */
3
+ export declare const siteMessages: Record<string, Messages>;