@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/index.js ADDED
@@ -0,0 +1,576 @@
1
+ import { z } from "zod";
2
+ import { defineBlock, definePlugin, defineRoute } from "tansy/plugin";
3
+ import { CERTIFICATE_CODE, grade, normalizeCode, publicQuestion, questionsOf, slugify } from "./logic";
4
+ import { BYLINE_FIELD, COLLECTIONS, CONTRACT, LAPSED_STATE, lmsRoles, lmsSchema, PAID_ACCESS, PLAN_SOURCE } from "./schema";
5
+ import { ACCESS, askedLanguage, checkCompletion, covers, currentEnrollment, enroll, entitlementsOf, exclusive, idOf, INCLUDED_FIELD, isUserId, learnerCourses, learnerWords, listAll, rebuildCourses, reconcilePlanEnrollments, userFilter, } from "./service";
6
+ import { BLOCK_FIELD_LABELS, COLLECTION_LABELS, FIELD_LABELS, messages } from "./messages";
7
+ import { lmsTools } from "./tools";
8
+ const optionsSchema = z.strictObject({
9
+ basePath: z.string().regex(/^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/, 'Use a path such as "/courses".'),
10
+ passingScore: z.number().int().min(0).max(100),
11
+ certificates: z.boolean(),
12
+ requireQuizzes: z.boolean(),
13
+ });
14
+ /** The field a missing slug is made from, and what to call a record with an empty one. */
15
+ const SLUG_SOURCE = { "lms-courses": ["title", "course"], "lms-lessons": ["title", "lesson"] };
16
+ /** Running the school: every course, enrollments and settings. Instructors don't hold it. */
17
+ const MANAGE = "ext.lms:manage";
18
+ const settingsOf = async (context) => (await context.settings.get());
19
+ const str = (value) => (typeof value === "string" ? value : "");
20
+ /** Fields the owner may have removed are left alone, or the save would fail on a field that isn't there. */
21
+ async function fieldsOf(context, slug) {
22
+ return new Set((await context.schema.describe(slug))?.fields.map((field) => field.name) ?? []);
23
+ }
24
+ async function uniqueSlug(records, slug, base, ownId) {
25
+ for (let attempt = 1; attempt <= 50; attempt++) {
26
+ const candidate = attempt === 1 ? base : `${base.slice(0, 75)}-${attempt}`;
27
+ // slugify only produces letters, digits and hyphens, so the filter can't be broken out of.
28
+ const { items } = await records.list(slug, { filter: `slug = "${candidate}"`, perPage: 2, fields: "id" });
29
+ if (!items.some((item) => item.id !== ownId))
30
+ return candidate;
31
+ }
32
+ return `${base.slice(0, 60)}-${Date.now().toString(36)}`;
33
+ }
34
+ /** On an update, `values` holds only what changed, so the stored value fills the rest. */
35
+ const currentOf = ({ values, record }) => (name) => (Object.hasOwn(values, name) ? values[name] : record?.[name]);
36
+ async function fillSlug(context) {
37
+ const [source, fallback] = SLUG_SOURCE[context.collection.slug];
38
+ const current = currentOf(context);
39
+ if (!(await fieldsOf(context, context.collection.slug)).has("slug") || str(current("slug")))
40
+ return;
41
+ context.values.slug = await uniqueSlug(context.system.records, context.collection.slug, slugify(str(current(source)), fallback), context.record?.id);
42
+ }
43
+ /** A lesson's section has to be one of its own course's. */
44
+ async function checkSection(context) {
45
+ const current = currentOf(context);
46
+ const sectionId = idOf(current("section"));
47
+ if (sectionId === null || !(Object.hasOwn(context.values, "section") || Object.hasOwn(context.values, "course")))
48
+ return;
49
+ const section = await context.system.records.get("lms-sections", sectionId, { fields: "course" }).catch(() => null);
50
+ if (!section || section.course !== idOf(current("course")))
51
+ context.reject("Choose a section of this lesson's course.", "section");
52
+ }
53
+ const changes = (context, name) => Object.hasOwn(context.values, name) && (context.values[name] ?? null) !== (context.record?.[name] ?? null);
54
+ /**
55
+ * Someone who doesn't run the school, such as an instructor, adds sections, lessons and
56
+ * quizzes only to courses they created. Their own-record grants already keep them out of
57
+ * anyone else's records. This keeps them from attaching their own records to another's course.
58
+ */
59
+ async function checkOwnCourse(context, course, field) {
60
+ if (context.can(MANAGE) || context.can("record:update"))
61
+ return;
62
+ const courseId = idOf(course);
63
+ if (courseId === null)
64
+ return;
65
+ const { userId } = context;
66
+ const { items } = isUserId(userId) ? await context.system.records.list("lms-courses", { filter: `id = ${courseId} && ${userFilter("createdById", userId)}`, perPage: 1, fields: "id" }) : { items: [] };
67
+ if (!items.length)
68
+ context.reject("Choose one of your own courses.", field);
69
+ }
70
+ /**
71
+ * A course carries its instructor's name, taken from their account when it's created.
72
+ * Managers can write any name, such as a guest teacher's. Anyone else always gets their
73
+ * own, and can't change it.
74
+ */
75
+ async function credit(context) {
76
+ const { values, userId, event } = context;
77
+ if (!(await fieldsOf(context, "lms-courses")).has("byline"))
78
+ return;
79
+ const manages = context.can(MANAGE);
80
+ if (event === "record.beforeUpdate") {
81
+ if (!manages && changes(context, "byline"))
82
+ context.reject("Only an LMS manager can change who a course is taught by.", "byline");
83
+ return;
84
+ }
85
+ if (manages && str(values.byline).trim())
86
+ return;
87
+ const name = userId ? (await context.system.users.get(userId))?.name.trim().slice(0, 200) : "";
88
+ values.byline = name || null;
89
+ }
90
+ /** A quiz's course always follows its lesson, because the quiz's rule reads it. */
91
+ async function followLesson(context) {
92
+ const current = currentOf(context);
93
+ if (context.record && !Object.hasOwn(context.values, "lesson") && !Object.hasOwn(context.values, "course"))
94
+ return;
95
+ const lessonId = idOf(current("lesson"));
96
+ const lesson = lessonId === null ? null : await context.system.records.get("lms-lessons", lessonId, { fields: "course" }).catch(() => null);
97
+ if (!lesson)
98
+ context.reject("Choose the lesson this quiz belongs to.", "lesson");
99
+ context.values.course = lesson.course;
100
+ }
101
+ async function prepareEnrollment(context) {
102
+ const { values, reject } = context;
103
+ if (!isUserId(values.student) || !(await context.system.users.get(values.student)))
104
+ reject("There is no user with this id.", "student");
105
+ const course = idOf(values.course);
106
+ if (course === null)
107
+ reject("Choose a course.", "course");
108
+ values.state = str(values.state) || "active";
109
+ if (values.state !== "revoked" && (await currentEnrollment(context, values.student, course)))
110
+ reject("This learner is already enrolled in this course.", "student");
111
+ if (!values.enrolledAt)
112
+ values.enrolledAt = new Date().toISOString();
113
+ }
114
+ function keepEnrollmentPlace(context) {
115
+ const { values, record, reject } = context;
116
+ for (const name of ["student", "course"]) {
117
+ if (Object.hasOwn(values, name) && values[name] !== record?.[name])
118
+ reject("An enrollment can't move to another learner or course. Revoke it and enroll again.", name);
119
+ }
120
+ if (values.state === "completed" && record?.state !== "completed" && !values.completedAt)
121
+ values.completedAt = new Date().toISOString();
122
+ }
123
+ /** Payments' price field type and purchases collection. LMS reads them as data and never imports Payments. */
124
+ const PRICE_TYPE = "payments_price";
125
+ const PURCHASES = "payments-purchases";
126
+ /** One record per person, kept by Payments from their subscriptions: what their plans open. */
127
+ const ENTITLEMENTS = "payments-entitlements";
128
+ /** A person's plans changed, so their plan enrollments follow: lapsed where no longer covered, open again where they are. */
129
+ async function followEntitlements(context) {
130
+ await reconcilePlanEnrollments(context, await settingsOf(context), context.record.user);
131
+ }
132
+ /**
133
+ * A course was put in or taken out of an access, so the plan enrollments in it follow, person by
134
+ * person. Courses opened whole by an access don't change here: that's a change to the access,
135
+ * which Payments follows by updating everyone's entitlements.
136
+ */
137
+ async function followCourseAccess(context) {
138
+ const shape = await context.schema.describe("lms-courses");
139
+ const fields = (shape?.fields ?? []).filter((field) => field.type === "reference" && field.config?.collection === ACCESS).map((field) => field.name);
140
+ if (!fields.some((name) => JSON.stringify(context.record[name] ?? null) !== JSON.stringify(context.previous?.[name] ?? null)))
141
+ return;
142
+ const course = idOf(context.record.id);
143
+ if (course === null)
144
+ return;
145
+ const enrollments = await listAll(context.system.records, "lms-enrollments", { filter: `course = ${course} && source = "plan" && state != "revoked"`, fields: "student" }, 10_000);
146
+ const settings = await settingsOf(context);
147
+ for (const student of new Set(enrollments.map((enrollment) => enrollment.student)))
148
+ await reconcilePlanEnrollments(context, settings, student, course);
149
+ }
150
+ /**
151
+ * Paid courses are sold through the Payments plugin, which sells any record with its price
152
+ * field. A paid course needs a price, and only a paid course keeps one, so a free or
153
+ * staff-only course can't be bought around its access.
154
+ */
155
+ async function checkPrice(context) {
156
+ const price = (await context.schema.describe("lms-courses"))?.fields.find((field) => field.type === PRICE_TYPE);
157
+ // An edit that touches neither leaves the course as it was sold.
158
+ if (context.record && !changes(context, "access") && !(price && changes(context, price.name)))
159
+ return;
160
+ const current = currentOf(context);
161
+ if (current("access") !== "paid") {
162
+ if (!price || current(price.name) === null || current(price.name) === undefined)
163
+ return;
164
+ // Switched away from paid, the price goes with it. A price sent with it is a mistake.
165
+ if (Object.hasOwn(context.values, price.name))
166
+ context.reject("Only a paid course has a price. Choose Paid, or clear the price.", price.name);
167
+ context.values[price.name] = null;
168
+ return;
169
+ }
170
+ if (!price)
171
+ context.reject("To sell courses, install the Payments plugin and add a Price field to Courses.", "access");
172
+ const amount = current(price.name);
173
+ if (typeof amount !== "number" || amount <= 0)
174
+ context.reject("Set a price to sell this course.", price.name);
175
+ }
176
+ /** A purchase of a course from Payments is only data to LMS: `buyer`, `collection`, `recordId` and `state`. */
177
+ function purchasedCourse(record) {
178
+ const course = idOf(record.recordId);
179
+ return record.collection === "lms-courses" && isUserId(record.buyer) && course !== null ? { student: record.buyer, course } : null;
180
+ }
181
+ /**
182
+ * Enrolls the buyer of a course. A durable hook may run more than once, and enroll()
183
+ * leaves a current enrollment alone, so a repeat changes nothing.
184
+ */
185
+ async function enrollBuyer(context) {
186
+ const bought = purchasedCourse(context.record);
187
+ if (!bought || context.record.state !== "paid")
188
+ return;
189
+ // A course deleted since it was bought can't be enrolled in, and retrying wouldn't change that.
190
+ if (!(await context.system.records.get("lms-courses", bought.course, { fields: "id" }).catch(() => null)))
191
+ return;
192
+ await enroll(context, bought.student, bought.course, "purchase");
193
+ }
194
+ /** A refunded course is taken back: enrollments that came from buying it are revoked. Staff and free enrollments stay. */
195
+ async function revokeRefunded(context) {
196
+ const bought = purchasedCourse(context.record);
197
+ if (!bought || context.record.state !== "refunded" || context.previous?.state === "refunded")
198
+ return;
199
+ const enrollments = await listAll(context.system.records, "lms-enrollments", { filter: `${userFilter("student", bought.student)} && course = ${bought.course} && source = "purchase" && state != "revoked"`, fields: "id" });
200
+ for (const enrollment of enrollments)
201
+ await context.system.records.update("lms-enrollments", enrollment.id, { state: "revoked" });
202
+ if (enrollments.length)
203
+ await rebuildCourses(context, bought.student);
204
+ }
205
+ async function welcome(context) {
206
+ const { record, system, mail } = context;
207
+ if (record.state !== "active" || !isUserId(record.student))
208
+ return;
209
+ const user = await system.users.get(record.student);
210
+ if (!user)
211
+ return;
212
+ // In the learner's language, and the course's title in it when the course has one.
213
+ const { t, locale, read } = await learnerWords(context, user.locale);
214
+ const course = await system.records.get("lms-courses", record.course, { fields: "title", ...read }).catch(() => null);
215
+ const title = str(course?.title) || t("lms.mail.aCourse");
216
+ await mail.send({ to: user.email, locale, subject: t("lms.mail.enrolledSubject", { title: title.slice(0, 150) }), body: t("lms.mail.enrolledBody", { name: user.name || t("lms.mail.someone"), title }) });
217
+ }
218
+ /** Turns the CMS into a learning platform: courses, lessons, enrollments, progress, quizzes and certificates. See docs/plugins/lms.md. */
219
+ export function lms(options = {}) {
220
+ // An option left undefined, as a config reading an unset variable passes, keeps its default.
221
+ const given = Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined));
222
+ const value = { basePath: "/courses", passingScore: 70, certificates: true, requireQuizzes: true, ...given };
223
+ const beforeWrite = async (context) => {
224
+ const slug = context.collection.slug;
225
+ if (SLUG_SOURCE[slug])
226
+ await fillSlug(context);
227
+ if (slug === "lms-courses") {
228
+ await credit(context);
229
+ await checkPrice(context);
230
+ }
231
+ if ((slug === "lms-sections" || slug === "lms-lessons") && (!context.record || changes(context, "course")))
232
+ await checkOwnCourse(context, context.values.course, "course");
233
+ if (slug === "lms-lessons")
234
+ await checkSection(context);
235
+ if (slug === "lms-quizzes") {
236
+ await followLesson(context);
237
+ if (!context.record || changes(context, "lesson"))
238
+ await checkOwnCourse(context, context.values.course, "lesson");
239
+ }
240
+ };
241
+ /** Completion may follow from a lesson finished or a quiz passed, including ones staff record by hand. */
242
+ const afterProgress = async (context) => {
243
+ const { collection, record } = context;
244
+ if (collection.slug === "lms-progress")
245
+ await checkCompletion(context, await settingsOf(context), record.student, record.course);
246
+ if (collection.slug === "lms-attempts" && record.passed === true) {
247
+ const quiz = await context.system.records.get("lms-quizzes", record.quiz, { fields: "course" }).catch(() => null);
248
+ if (quiz)
249
+ await checkCompletion(context, await settingsOf(context), record.student, quiz.course);
250
+ }
251
+ };
252
+ return definePlugin({
253
+ name: "lms",
254
+ messages,
255
+ version: "0.1.1",
256
+ apiVersion: 1,
257
+ requires: { cms: "^0.1.1" },
258
+ admin: { server: "@tansy/lms/admin", client: "@tansy/lms/client", render: "@tansy/lms/render" },
259
+ csp: { frame: ["https://www.youtube-nocookie.com", "https://player.vimeo.com"] },
260
+ options: { schema: optionsSchema, value },
261
+ settings: {
262
+ permission: MANAGE,
263
+ fields: [
264
+ { name: "passingScore", type: "number", integer: true, min: 0, max: 100, default: value.passingScore, label: "Passing score (%)", description: "Needed to pass a quiz that doesn't set its own." },
265
+ { name: "requireQuizzes", type: "boolean", default: value.requireQuizzes, label: "Require quizzes", description: "A course counts as completed only once its quizzes are passed." },
266
+ { name: "certificates", type: "boolean", default: value.certificates, label: "Issue certificates", description: "Give each learner a certificate, with a code anyone can check, when they complete a course." },
267
+ ],
268
+ },
269
+ permissions: { "ext.lms": ["manage", "enroll"] },
270
+ contract: CONTRACT,
271
+ tools: lmsTools,
272
+ blocks: [
273
+ defineBlock({ name: "lms_text", label: "Text", labels: { ar: "نص" }, category: "Lesson", fields: [{ name: "body", type: "rich_text", config: { labels: { ar: "النص" } } }] }),
274
+ defineBlock({
275
+ name: "lms_video",
276
+ label: "Video",
277
+ labels: { ar: "فيديو" },
278
+ category: "Lesson",
279
+ fields: [
280
+ { name: "file", type: "file", config: { allowedTypes: ["video/mp4", "video/webm", "video/ogg"], labels: { ar: "الملف" } } },
281
+ { name: "url", type: "url", config: { allowedProtocols: ["https"], allowedDomains: ["youtube.com", "youtu.be", "vimeo.com"], description: "YouTube or Vimeo, when there's no uploaded file.", labels: { ar: "الرابط" }, descriptions: { ar: "YouTube أو Vimeo، حين لا يوجد ملف مرفوع." } } },
282
+ { name: "title", type: "text", config: { maxLength: 200, labels: { ar: "العنوان" } } },
283
+ { name: "transcript", type: "rich_text", config: { labels: { ar: "النص المكتوب" } } },
284
+ ],
285
+ }),
286
+ defineBlock({
287
+ name: "lms_download",
288
+ label: "Download",
289
+ labels: { ar: "تنزيل" },
290
+ category: "Lesson",
291
+ fields: [
292
+ { name: "file", type: "file", config: { required: true, labels: { ar: "الملف" } } },
293
+ { name: "label", type: "text", config: { maxLength: 200, labels: { ar: "النص الظاهر" } } },
294
+ ],
295
+ }),
296
+ defineBlock({
297
+ name: "lms_question",
298
+ label: "Question",
299
+ labels: { ar: "سؤال" },
300
+ category: "Quiz",
301
+ defaults: { kind: "single", choices: [] },
302
+ fields: [
303
+ { name: "prompt", type: "text", config: { required: true, multiline: true, maxLength: 2000, labels: { ar: "السؤال" } } },
304
+ { name: "kind", type: "radio", config: { labels: { ar: "النوع" }, options: [{ label: "One answer", labels: { ar: "إجابة واحدة" }, value: "single" }, { label: "Several answers", labels: { ar: "عدة إجابات" }, value: "multiple" }, { label: "Typed answer", labels: { ar: "إجابة مكتوبة" }, value: "short" }] } },
305
+ { name: "choices", type: "json", config: { description: 'For choice questions, a list such as ["Paris", "Rome"].', labels: { ar: "الخيارات" }, descriptions: { ar: 'لأسئلة الاختيار، قائمة مثل ["Paris", "Rome"].' } } },
306
+ { name: "correct", type: "json", config: { description: "The answer's position from 0, such as 1. Several: [0, 2]. Typed: the accepted answers, such as [\"Paris\"].", labels: { ar: "الإجابة الصحيحة" }, descriptions: { ar: "موضع الإجابة بدءًا من 0، مثل 1. لعدة إجابات: [0, 2]. للمكتوبة: الإجابات المقبولة، مثل [\"Paris\"]." } } },
307
+ { name: "explanation", type: "rich_text", config: { labels: { ar: "الشرح" } } },
308
+ ],
309
+ }),
310
+ ],
311
+ hooks: {
312
+ "record.beforeCreate": async (context) => {
313
+ if (context.collection.slug === "lms-enrollments")
314
+ await prepareEnrollment(context);
315
+ else
316
+ await beforeWrite(context);
317
+ },
318
+ "record.beforeUpdate": async (context) => {
319
+ if (context.collection.slug === "lms-enrollments")
320
+ keepEnrollmentPlace(context);
321
+ else
322
+ await beforeWrite(context);
323
+ },
324
+ "record.afterCreate": async (context) => {
325
+ if (context.collection.slug === "lms-enrollments") {
326
+ await rebuildCourses(context, context.record.student);
327
+ await welcome(context);
328
+ }
329
+ else if (context.collection.slug === PURCHASES)
330
+ await enrollBuyer(context);
331
+ else if (context.collection.slug === ENTITLEMENTS)
332
+ await followEntitlements(context);
333
+ else
334
+ await afterProgress(context);
335
+ },
336
+ "record.afterUpdate": async (context) => {
337
+ if (context.collection.slug === "lms-enrollments")
338
+ await rebuildCourses(context, context.record.student);
339
+ else if (context.collection.slug === PURCHASES)
340
+ await revokeRefunded(context);
341
+ else if (context.collection.slug === ENTITLEMENTS)
342
+ await followEntitlements(context);
343
+ else if (context.collection.slug === "lms-courses")
344
+ await followCourseAccess(context);
345
+ },
346
+ "record.afterDelete": async (context) => {
347
+ if (context.collection.slug === "lms-enrollments")
348
+ await rebuildCourses(context, context.record.student);
349
+ },
350
+ },
351
+ routes: [
352
+ defineRoute({
353
+ method: "POST",
354
+ path: "/courses/:id/enroll",
355
+ access: "authenticated",
356
+ audit: "lms.enroll",
357
+ handler: async (context) => {
358
+ const id = Number(context.params.id);
359
+ // As the caller, so a draft or unknown course reads as missing.
360
+ const course = await context.records.get("lms-courses", id, { fields: "id,access" });
361
+ const student = context.principal.kind === "anonymous" ? "" : context.principal.user.id;
362
+ // A free course is free for everyone. Otherwise the person's plans may cover it, read from what Payments stored.
363
+ // Under the lock the plan hook takes, so a plan ending meanwhile can't miss the enrollment made here.
364
+ const result = course.access === "free"
365
+ ? { source: "free", ...(await enroll(context, student, id, "free")) }
366
+ : await exclusive(`plan:${student}`, async () => ((await covers(context, await entitlementsOf(context, student), id)) ? { source: "plan", ...(await enroll(context, student, id, "plan")) } : null));
367
+ if (!result && course.access === "paid")
368
+ return Response.json({ error: { code: "PURCHASE_REQUIRED", message: "Buy this course, or subscribe to a plan that includes it, to enroll." } }, { status: 403 });
369
+ if (!result)
370
+ return Response.json({ error: { code: "ENROLLMENT_REQUIRED", message: "Staff enroll learners in this course." } }, { status: 403 });
371
+ const { enrollment, created, source } = result;
372
+ context.auditTarget("course", String(id), { created, source });
373
+ return { enrollment: { id: enrollment.id, state: enrollment.state }, created, source };
374
+ },
375
+ }),
376
+ defineRoute({
377
+ method: "POST",
378
+ path: "/enrollments",
379
+ access: "permission",
380
+ permission: "ext.lms:enroll",
381
+ audit: "lms.enroll_staff",
382
+ body: z.strictObject({ course: z.number().int().positive(), emails: z.array(z.email().max(320)).min(1).max(200) }),
383
+ handler: async (context) => {
384
+ const { course, emails } = context.body;
385
+ await context.system.records.get("lms-courses", course, { fields: "id" });
386
+ let enrolled = 0, already = 0, unknown = 0;
387
+ for (const email of new Set(emails.map((address) => address.toLowerCase()))) {
388
+ const user = await context.system.users.findByEmail(email);
389
+ if (!user) {
390
+ unknown++;
391
+ continue;
392
+ }
393
+ const { created } = await enroll(context, user.id, course, "staff");
394
+ if (created)
395
+ enrolled++;
396
+ else
397
+ already++;
398
+ }
399
+ // Counts only: whether an address has an account isn't this permission's business.
400
+ context.auditTarget("course", String(course), { enrolled, already, unknown });
401
+ return { enrolled, already, unknown };
402
+ },
403
+ }),
404
+ defineRoute({
405
+ method: "POST",
406
+ path: "/lessons/:id/complete",
407
+ access: "authenticated",
408
+ audit: "lms.lesson_complete",
409
+ handler: async (context) => {
410
+ const id = Number(context.params.id);
411
+ const student = context.principal.kind === "anonymous" ? "" : context.principal.user.id;
412
+ // The gate: the caller must be able to open the lesson.
413
+ const lesson = await context.records.get("lms-lessons", id, { fields: "id,course" });
414
+ const course = idOf(lesson.course);
415
+ // A preview lesson opens for anyone, but only enrolled learners make progress.
416
+ if (!(await currentEnrollment(context, student, course)))
417
+ return Response.json({ error: { code: "NOT_ENROLLED", message: "Enroll in this course to track your progress." } }, { status: 403 });
418
+ const key = `${student}:${id}`;
419
+ const done = await exclusive(`progress:${key}`, async () => {
420
+ const { items } = await context.system.records.list("lms-progress", { filter: `key = "${key}"`, perPage: 1, fields: "id" });
421
+ if (items.length)
422
+ return false;
423
+ await context.system.records.create("lms-progress", { status: "published", key, student, course, lesson: id, completedAt: new Date().toISOString() });
424
+ return true;
425
+ });
426
+ await checkCompletion(context, await settingsOf(context), student, course);
427
+ context.auditTarget("lesson", String(id), { first: done });
428
+ const enrollment = await currentEnrollment(context, student, course);
429
+ return { completed: true, first: done, courseCompleted: enrollment?.state === "completed" };
430
+ },
431
+ }),
432
+ defineRoute({
433
+ method: "GET",
434
+ path: "/me/courses",
435
+ access: "authenticated",
436
+ handler: async (context) => ({ items: await learnerCourses(context, context.records, context.principal.kind === "anonymous" ? "" : context.principal.user.id, await askedLanguage(context, context.request)) }),
437
+ }),
438
+ defineRoute({
439
+ method: "GET",
440
+ path: "/quizzes/:id",
441
+ access: "authenticated",
442
+ handler: async (context) => {
443
+ const id = Number(context.params.id);
444
+ const student = context.principal.kind === "anonymous" ? "" : context.principal.user.id;
445
+ // The rule decides who may take it. Only then are the hidden questions read, and their answers left out.
446
+ // In the learner's language, when the site has more than one.
447
+ const read = await askedLanguage(context, context.request);
448
+ const quiz = await context.records.get("lms-quizzes", id, { fields: "id,title,passingScore,maxAttempts", ...read });
449
+ const stored = await context.system.records.get("lms-quizzes", id, { fields: "questions", ...read });
450
+ const attempts = await listAll(context.system.records, "lms-attempts", { filter: `${userFilter("student", student)} && quiz = ${id}`, sort: "-submittedAt", fields: "score,passed,submittedAt" }, 200);
451
+ const maxAttempts = typeof quiz.maxAttempts === "number" ? quiz.maxAttempts : null;
452
+ return {
453
+ id,
454
+ title: str(quiz.title),
455
+ passingScore: typeof quiz.passingScore === "number" ? quiz.passingScore : (await settingsOf(context)).passingScore,
456
+ maxAttempts,
457
+ attemptsLeft: maxAttempts === null ? null : Math.max(0, maxAttempts - attempts.length),
458
+ passed: attempts.some((attempt) => attempt.passed === true),
459
+ best: attempts.reduce((best, attempt) => (typeof attempt.score === "number" && (best === null || attempt.score > best) ? attempt.score : best), null),
460
+ questions: questionsOf(stored.questions).map(publicQuestion),
461
+ };
462
+ },
463
+ }),
464
+ defineRoute({
465
+ method: "POST",
466
+ path: "/quizzes/:id/attempts",
467
+ access: "authenticated",
468
+ audit: "lms.quiz_attempt",
469
+ rateLimit: { window: 60, max: 10 },
470
+ body: z.strictObject({ answers: z.record(z.string().max(64), z.union([z.number().int().min(0).max(1000), z.array(z.number().int().min(0).max(1000)).max(50), z.string().max(500)])) }),
471
+ handler: async (context) => {
472
+ const id = Number(context.params.id);
473
+ const student = context.principal.kind === "anonymous" ? "" : context.principal.user.id;
474
+ const quiz = await context.records.get("lms-quizzes", id, { fields: "id,passingScore,maxAttempts" });
475
+ const result = await exclusive(`attempt:${student}:${id}`, async () => {
476
+ const { totalItems } = await context.system.records.list("lms-attempts", { filter: `${userFilter("student", student)} && quiz = ${id}`, perPage: 1, fields: "id" });
477
+ const maxAttempts = typeof quiz.maxAttempts === "number" ? quiz.maxAttempts : null;
478
+ if (maxAttempts !== null && totalItems >= maxAttempts)
479
+ return null;
480
+ // Graded against the questions as the learner read them, in case a translation words or orders them differently.
481
+ const stored = await context.system.records.get("lms-quizzes", id, { fields: "questions", ...(await askedLanguage(context, context.request)) });
482
+ const questions = questionsOf(stored.questions);
483
+ const { score, correct, total } = grade(questions, context.body.answers);
484
+ const passed = total > 0 && score >= (typeof quiz.passingScore === "number" ? quiz.passingScore : (await settingsOf(context)).passingScore);
485
+ const answers = Object.fromEntries(questions.filter((question) => Object.hasOwn(context.body.answers, question.id)).map((question) => [question.id, context.body.answers[question.id]]));
486
+ await context.system.records.create("lms-attempts", { status: "published", quiz: id, student, answers, score, passed, submittedAt: new Date().toISOString() });
487
+ return { score, correct, total, passed, attemptsLeft: maxAttempts === null ? null : maxAttempts - totalItems - 1 };
488
+ });
489
+ if (!result)
490
+ return Response.json({ error: { code: "NO_ATTEMPTS_LEFT", message: "You have used every attempt at this quiz." } }, { status: 409 });
491
+ context.auditTarget("quiz", String(id), { score: result.score, passed: result.passed });
492
+ if (result.passed) {
493
+ const stored = await context.system.records.get("lms-quizzes", id, { fields: "course" });
494
+ await checkCompletion(context, await settingsOf(context), student, stored.course);
495
+ }
496
+ // The score only. Which answers were right would hand the key to the next attempt.
497
+ return result;
498
+ },
499
+ }),
500
+ defineRoute({
501
+ method: "GET",
502
+ path: "/certificates/:code",
503
+ access: "public",
504
+ reason: "Anyone with a certificate's code may check it is genuine. It reveals only the name, course and date. Codes are 80 random bits, and reads are rate limited.",
505
+ handler: async (context) => {
506
+ const code = normalizeCode(String(context.params.code ?? ""));
507
+ if (!CERTIFICATE_CODE.test(code))
508
+ return Response.json({ error: { code: "NOT_FOUND", message: "No certificate has this code." } }, { status: 404 });
509
+ const { items } = await context.system.records.list("lms-certificates", { filter: `code = "${code}"`, perPage: 1, fields: "code,course,studentName,issuedAt" });
510
+ const certificate = items[0];
511
+ if (!certificate)
512
+ return Response.json({ error: { code: "NOT_FOUND", message: "No certificate has this code." } }, { status: 404 });
513
+ const course = await context.system.records.get("lms-courses", certificate.course, { fields: "title", ...(await askedLanguage(context, context.request)) }).catch(() => null);
514
+ return { code, studentName: str(certificate.studentName), course: str(course?.title), issuedAt: certificate.issuedAt ?? null };
515
+ },
516
+ }),
517
+ ],
518
+ migrations: [{
519
+ id: "001-collections",
520
+ up: async ({ schema, system }) => {
521
+ for (const slug of COLLECTIONS) {
522
+ if (await schema.describe(slug))
523
+ throw new Error(`A collection called "${slug}" already exists, and the LMS plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
524
+ }
525
+ await schema.apply(lmsSchema(value.basePath));
526
+ await system.records.create("lms-my-courses", { status: "published", title: "My courses" });
527
+ await system.records.create("lms-certificate", { status: "published", title: "Check a certificate" });
528
+ },
529
+ }, {
530
+ // Instructors are people with a role, so a course names who teaches it instead of linking a profile.
531
+ id: "002-instructors-are-people",
532
+ up: async ({ schema, roles }) => {
533
+ if (await schema.describe("lms-courses"))
534
+ await schema.addFields("lms-courses", [BYLINE_FIELD]);
535
+ for (const role of lmsRoles())
536
+ await roles.ensure(role);
537
+ },
538
+ }, {
539
+ // A third way in: learners buy the course through the Payments plugin.
540
+ id: "003-paid-courses",
541
+ up: async ({ schema }) => {
542
+ if (await schema.describe("lms-courses"))
543
+ await schema.addOptions("lms-courses", "access", [PAID_ACCESS]);
544
+ },
545
+ }, {
546
+ id: "004-names-in-languages",
547
+ up: async ({ schema }) => {
548
+ for (const [slug, labels] of Object.entries(COLLECTION_LABELS))
549
+ await schema.addLabels(slug, labels);
550
+ },
551
+ }, {
552
+ id: "005-field-names-in-languages",
553
+ up: async ({ schema }) => {
554
+ for (const [slug, fields] of Object.entries(FIELD_LABELS))
555
+ await schema.addFieldLabels(slug, fields);
556
+ for (const [block, fields] of Object.entries(BLOCK_FIELD_LABELS))
557
+ await schema.addBlockFieldLabels(block, fields);
558
+ },
559
+ }, {
560
+ // Courses included in plans, when the Payments plugin is installed (§8.3).
561
+ id: "006-plans",
562
+ up: async ({ schema }) => {
563
+ if (!(await schema.describe("lms-enrollments")))
564
+ return;
565
+ await schema.addOptions("lms-enrollments", "source", [PLAN_SOURCE]);
566
+ await schema.addOptions("lms-enrollments", "state", [LAPSED_STATE]);
567
+ // Again, now that the new choices exist: words for a choice that isn't there yet are skipped.
568
+ await schema.addFieldLabels("lms-enrollments", FIELD_LABELS["lms-enrollments"]);
569
+ if ((await schema.describe(ACCESS)) && (await schema.describe("lms-courses"))) {
570
+ await schema.addFields("lms-courses", [INCLUDED_FIELD]);
571
+ await schema.addFieldLabels("lms-courses", { included: { labels: { ar: "مشمولة في" }, descriptions: { ar: "يمكن لمشتركي خطة تشمل أحدها أخذ الدورة دون شرائها." } } });
572
+ }
573
+ },
574
+ }],
575
+ });
576
+ }