forge
Explore
Log in

Don't you dare go Hollow

🏦 stable choice ids, real bank paging, private-by-default templates

Browse files at this commit

88492c2f932a51db5da342c1e22f91a1b6d10037Ahmet Kaan GümüşParent: 0f9e79a
  • fix
    • 🏦 stable choice ids, real bank paging, private-by-default templates
Show full message
fix: 🏦 stable choice ids, real bank paging, private-by-default templates

- choices become {id, text} with server-minted stable ids; correct and
  the student's selected answer name an id, never a position, and
  option images key off the id
- fix: blanking a choice above the marked one silently moved the answer
  key on graded exams — the form sent a pre-compaction index
- fix: removeChoice left correct pointing at the row that slid into the
  deleted slot
- delete the download-then-reupload image restore in both panels and
  drop src/lib/choice-compaction.ts: a PATCH now preserves images for
  every choice whose id is unchanged, so the compensating transaction
  has nothing to compensate for
- extract the choice-edit reducer to src/lib/choice-set.ts and property
  test it with fast-check (devDependency, out of the bundle): text,
  picture and correct-flag stay attached to a choice identity across
  arbitrary edit sequences
- bank list is server-paged, newest first, with server-side text search
  — it silently hid every template past the first 100 while still
  reporting saves as successful
- search folds Turkish casing: q=istanbul now finds İSTANBUL, and one
  shared table folds the needle and the column so they cannot drift
- templates are private by default with an explicit share step; the
  confirm names the consequence, since publishing hands the answer key
  to every teacher in the school and copies cannot be recalled
- source_bank splits into from_bank and banked_as, so a question added
  from the bank no longer claims it was already saved to it
- bank page shows how many exam copies a template has, and a question
  added from the bank can be refreshed from its template until the
  first attempt starts
- no more silent first-item defaults: subject and target subject must
  be picked, and an unavailable stored subject is shown, not swapped
- live contract suite (bun run test:contract) against a real backend,
  skipped without CONTRACT_BASE_URL

42 changed files +1461 -468

bun.lockmodified+5 -0
@@ -18,6 +18,7 @@
18 "@tailwindcss/postcss": "^4.3.3",18 "@tailwindcss/postcss": "^4.3.3",
19 "@tanstack/solid-router-devtools": "^1.167.0",19 "@tanstack/solid-router-devtools": "^1.167.0",
20 "@types/node": "^26.1.1",20 "@types/node": "^26.1.1",
21+ "fast-check": "^4.9.0",
21 "postcss": "^8.5.22",22 "postcss": "^8.5.22",
22 "tailwindcss": "^4.3.3",23 "tailwindcss": "^4.3.3",
23 "tailwindcss-animate": "^1.0.7",24 "tailwindcss-animate": "^1.0.7",
@@ -447,6 +448,8 @@
447 448
448 "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="],449 "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="],
449 450
451+ "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="],
452+
450 "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],453 "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
451 454
452 "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],455 "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@@ -521,6 +524,8 @@
521 524
522 "postcss": ["postcss@8.5.22", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ=="],525 "postcss": ["postcss@8.5.22", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ=="],
523 526
527+ "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="],
528+
524 "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="],529 "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="],
525 530
526 "rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="],531 "rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="],
history.txtadded+5 -0
@@ -0,0 +1,5 @@
1+#V2
2+DELETE subject:`01KYB0E968ZHJ7CRP1TXXZDHT1`; DELETE user:`01KYB0E963KQ4NRX8AHVQ7795J`;
3+SELECT VALUE [path, sha256] FROM meta;
4+REMOVE TABLE IF EXISTS doc;
5+REMOVE TABLE IF EXISTS meta;
package.jsonmodified+3 -1
@@ -9,7 +9,8 @@
9 "preview": "vite preview",9 "preview": "vite preview",
10 "check": "tsc --noEmit",10 "check": "tsc --noEmit",
11 "test": "vitest run",11 "test": "vitest run",
12- "test:watch": "vitest"12+ "test:watch": "vitest",
13+ "test:contract": "vitest run --config vitest.contract.config.ts"
13 },14 },
14 "dependencies": {15 "dependencies": {
15 "@kobalte/core": "^0.13.12",16 "@kobalte/core": "^0.13.12",
@@ -25,6 +26,7 @@
25 "@tailwindcss/postcss": "^4.3.3",26 "@tailwindcss/postcss": "^4.3.3",
26 "@tanstack/solid-router-devtools": "^1.167.0",27 "@tanstack/solid-router-devtools": "^1.167.0",
27 "@types/node": "^26.1.1",28 "@types/node": "^26.1.1",
29+ "fast-check": "^4.9.0",
28 "postcss": "^8.5.22",30 "postcss": "^8.5.22",
29 "tailwindcss": "^4.3.3",31 "tailwindcss": "^4.3.3",
30 "tailwindcss-animate": "^1.0.7",32 "tailwindcss-animate": "^1.0.7",
src/api/__tests__/bank-questions/bank-questions.test.tsmodified+51 -12
@@ -45,13 +45,40 @@ describe("bank-questions API", () => {
45 expect(init?.method).toBe("GET");45 expect(init?.method).toBe("GET");
46 });46 });
47 47
48- it("getBankQuestions passes subject, owner and page params", async () => {48+ it("getBankQuestions carries used_count, the list-only copy tally", async () => {
49+ // How many exam questions were copied out of each template — joined for the
50+ // whole page by the backend. An untouched template is 0, and the UI stays
51+ // quiet on 0 rather than printing it.
52+ const mockPage = {
53+ items: [
54+ { id: "b1", text: "reused", used_count: 3 },
55+ { id: "b2", text: "never used", used_count: 0 },
56+ ],
57+ total: 2,
58+ };
59+ mockFetchSuccess(mockPage);
60+
61+ const result = await getBankQuestions();
62+ expect(result.items[0].used_count).toBe(3);
63+ expect(result.items[1].used_count).toBe(0);
64+ });
65+
66+ it("getBankQuestions passes subject, owner, q and page params", async () => {
67+ mockFetchSuccess({ items: [], total: 0 });
68+
69+ await getBankQuestions({ subject: "sub1", owner: "me", q: "newton", limit: 20, offset: 40 });
70+
71+ const [url] = lastFetchCall();
72+ expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&q=newton&limit=20&offset=40");
73+ });
74+
75+ it("getBankQuestions sends the visibility filter server-side, with paging", async () => {
49 mockFetchSuccess({ items: [], total: 0 });76 mockFetchSuccess({ items: [], total: 0 });
50 77
51- await getBankQuestions({ subject: "sub1", owner: "me", limit: 20, offset: 40 });78+ await getBankQuestions({ visibility: "private", limit: 12, offset: 12 });
52 79
53 const [url] = lastFetchCall();80 const [url] = lastFetchCall();
54- expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&limit=20&offset=40");81+ expect(url).toBe("/api/bank-questions?visibility=private&limit=12&offset=12");
55 });82 });
56 83
57 it("getBankQuestionById calls /bank-questions/:bid", async () => {84 it("getBankQuestionById calls /bank-questions/:bid", async () => {
@@ -90,6 +117,18 @@ describe("bank-questions API", () => {
90 expect(init?.method).toBe("DELETE");117 expect(init?.method).toBe("DELETE");
91 });118 });
92 119
120+ it("patchBankQuestionById serializes a visibility change", async () => {
121+ mockFetchSuccess({ id: "b1", visibility: "school" });
122+
123+ const result = await patchBankQuestionById("b1", { visibility: "school" });
124+ expect(result.visibility).toBe("school");
125+
126+ const [url, init] = lastFetchCall();
127+ expect(url).toBe("/api/bank-questions/b1");
128+ expect(init?.method).toBe("PATCH");
129+ expect(init?.body).toBe(JSON.stringify({ visibility: "school" }));
130+ });
131+
93 it("postBankQuestionImage calls /bank-questions/:bid/image with FormData", async () => {132 it("postBankQuestionImage calls /bank-questions/:bid/image with FormData", async () => {
94 const mockMeta = { content_type: "image/png", size: 100 };133 const mockMeta = { content_type: "image/png", size: 100 };
95 mockFetchSuccess(mockMeta, 201);134 mockFetchSuccess(mockMeta, 201);
@@ -125,37 +164,37 @@ describe("bank-questions API", () => {
125 expect(init?.method).toBe("DELETE");164 expect(init?.method).toBe("DELETE");
126 });165 });
127 166
128- it("postBankChoiceImage calls /bank-questions/:bid/choices/:index/image with FormData", async () => {167+ it("postBankChoiceImage calls /bank-questions/:bid/choices/:choiceId/image with FormData", async () => {
129 const mockMeta = { content_type: "image/png", size: 100 };168 const mockMeta = { content_type: "image/png", size: 100 };
130 mockFetchSuccess(mockMeta, 201);169 mockFetchSuccess(mockMeta, 201);
131 170
132 const file = new File(["test"], "test.png", { type: "image/png" });171 const file = new File(["test"], "test.png", { type: "image/png" });
133- const result = await postBankChoiceImage("b1", 2, file);172+ const result = await postBankChoiceImage("b1", "c2", file);
134 expect(result).toEqual(mockMeta);173 expect(result).toEqual(mockMeta);
135 174
136 const [url, init] = lastFetchCall();175 const [url, init] = lastFetchCall();
137- expect(url).toBe("/api/bank-questions/b1/choices/2/image");176+ expect(url).toBe("/api/bank-questions/b1/choices/c2/image");
138 expect(init?.method).toBe("POST");177 expect(init?.method).toBe("POST");
139 expect(init?.body).toBeInstanceOf(FormData);178 expect(init?.body).toBeInstanceOf(FormData);
140 });179 });
141 180
142- it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:index/image", async () => {181+ it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:choiceId/image", async () => {
143 mockFetchBlob(new Blob(["img"], { type: "image/png" }));182 mockFetchBlob(new Blob(["img"], { type: "image/png" }));
144 183
145- const result = await getBankChoiceImageBlob("b1", 2);184+ const result = await getBankChoiceImageBlob("b1", "c2");
146 expect(result).toBeInstanceOf(Blob);185 expect(result).toBeInstanceOf(Blob);
147 186
148 const [url] = lastFetchCall();187 const [url] = lastFetchCall();
149- expect(url).toBe("/api/bank-questions/b1/choices/2/image");188+ expect(url).toBe("/api/bank-questions/b1/choices/c2/image");
150 });189 });
151 190
152- it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:index/image", async () => {191+ it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:choiceId/image", async () => {
153 mockFetch204();192 mockFetch204();
154 193
155- await deleteBankChoiceImage("b1", 2);194+ await deleteBankChoiceImage("b1", "c2");
156 195
157 const [url, init] = lastFetchCall();196 const [url, init] = lastFetchCall();
158- expect(url).toBe("/api/bank-questions/b1/choices/2/image");197+ expect(url).toBe("/api/bank-questions/b1/choices/c2/image");
159 expect(init?.method).toBe("DELETE");198 expect(init?.method).toBe("DELETE");
160 });199 });
161 });200 });
src/api/__tests__/contract/bank-questions.contract.test.tsadded+276 -0
@@ -0,0 +1,276 @@
1+import { api, contractBaseUrl, isLive, json, loginAdmin, pngFile, SKIP_MESSAGE } from "./helpers/live-client";
2+import type { BankQuestion, Course, ExamQuestion, Subject } from "@/api/client";
3+
4+if (!isLive) console.warn(SKIP_MESSAGE);
5+
6+describe.skipIf(!isLive)(`bank-questions contract @ ${contractBaseUrl}`, () => {
7+ let courseId = "";
8+ let subjectId = "";
9+ let questionId = "";
10+
11+ beforeAll(async () => {
12+ await loginAdmin();
13+ const course = await json<Course>("/courses", {
14+ method: "POST",
15+ body: { title: `contract-${Date.now()}` },
16+ });
17+ courseId = course.id;
18+ const subject = await json<Subject>(`/courses/${courseId}/subjects`, {
19+ method: "POST",
20+ body: { name: "contract subject" },
21+ });
22+ subjectId = subject.id;
23+ });
24+
25+ /** Templates created by the paging/search tests, torn down with the course. */
26+ const scratchIds: string[] = [];
27+
28+ afterAll(async () => {
29+ for (const id of scratchIds) await api(`/bank-questions/${id}`, { method: "DELETE" });
30+ if (questionId) await api(`/bank-questions/${questionId}`, { method: "DELETE" });
31+ if (courseId) await api(`/courses/${courseId}`, { method: "DELETE" });
32+ });
33+
34+ const createTemplate = async (text: string) => {
35+ const created = await json<BankQuestion>("/bank-questions", {
36+ method: "POST",
37+ body: { subject_id: subjectId, text, kind: "text", points: 1 },
38+ });
39+ scratchIds.push(created.id);
40+ return created;
41+ };
42+
43+ it("GET /bank-questions answers the {items,total,limit,offset} envelope", async () => {
44+ const page = await json<Record<string, unknown>>("/bank-questions?limit=5");
45+ expect(Array.isArray(page.items)).toBe(true);
46+ expect(typeof page.total).toBe("number");
47+ expect(typeof page.limit).toBe("number");
48+ expect(typeof page.offset).toBe("number");
49+ });
50+
51+ it("a trailing slash on the nest-root route 404s", async () => {
52+ const res = await api("/bank-questions/");
53+ expect(res.status).toBe(404);
54+ });
55+
56+ it("creates a choice template, minting an id per choice and resolving correct by key", async () => {
57+ const created = await json<BankQuestion>("/bank-questions", {
58+ method: "POST",
59+ body: {
60+ subject_id: subjectId,
61+ text: "contract: which one?",
62+ kind: "choice",
63+ points: 1,
64+ // Client-local keys: the server replaces them, but `correct` may name one.
65+ choices: [{ id: "new:1", text: "A" }, { id: "new:2", text: "B" }],
66+ correct: "new:2",
67+ },
68+ });
69+ questionId = created.id;
70+ expect(created).toMatchObject({ subject: subjectId, kind: "choice", points: 1 });
71+ expect(created.choices?.map((choice) => choice.text)).toEqual(["A", "B"]);
72+ for (const choice of created.choices ?? []) expect(typeof choice.id).toBe("string");
73+ // Server-minted, so not the key we sent — and it still names the row we marked.
74+ expect(created.correct).toBe(created.choices?.[1].id);
75+ expect(created.correct).not.toBe("new:2");
76+ expect(typeof created.owner).toBe("string");
77+ expect(typeof created.created_at).toBe("number");
78+ });
79+
80+ it("rejects a duplicate choice key and a correct that names nothing submitted", async () => {
81+ const dupe = await api("/bank-questions", {
82+ method: "POST",
83+ body: {
84+ subject_id: subjectId,
85+ text: "contract: dupe",
86+ kind: "choice",
87+ points: 1,
88+ choices: [{ id: "k", text: "A" }, { id: "k", text: "B" }],
89+ correct: "k",
90+ },
91+ });
92+ expect(dupe.status).toBe(400);
93+
94+ const stray = await api("/bank-questions", {
95+ method: "POST",
96+ body: {
97+ subject_id: subjectId,
98+ text: "contract: stray correct",
99+ kind: "choice",
100+ points: 1,
101+ choices: [{ id: "a", text: "A" }, { id: "b", text: "B" }],
102+ correct: "zzz",
103+ },
104+ });
105+ expect(stray.status).toBe(400);
106+ });
107+
108+ it("stores per-option images keyed by choice id and reports them in choice_images", async () => {
109+ const question = await json<BankQuestion>(`/bank-questions/${questionId}`);
110+ for (const choice of question.choices ?? []) {
111+ const body = new FormData();
112+ body.append("file", pngFile(`choice-${choice.id}.png`));
113+ const res = await api(`/bank-questions/${questionId}/choices/${choice.id}/image`, {
114+ method: "POST",
115+ body,
116+ });
117+ expect(res.status).toBe(201);
118+ }
119+ const fetched = await json<BankQuestion>(`/bank-questions/${questionId}`);
120+ expect(fetched.choice_images?.[0]).toBeTruthy();
121+ expect(fetched.choice_images?.[1]).toBeTruthy();
122+ });
123+
124+ it("PATCH without a choices key keeps the per-option images", async () => {
125+ const patched = await json<BankQuestion>(`/bank-questions/${questionId}`, {
126+ method: "PATCH",
127+ body: { text: "contract: still which one?" },
128+ });
129+ expect(patched.choice_images?.[0]).toBeTruthy();
130+ expect(patched.choice_images?.[1]).toBeTruthy();
131+ });
132+
133+ // The whole point of the remodel: resubmitting the choices WITH their ids is no
134+ // longer a wipe, so the client needs no download-then-reupload compensation.
135+ it("PATCH resubmitting the stored ids keeps every image and the answer key", async () => {
136+ const before = await json<BankQuestion>(`/bank-questions/${questionId}`);
137+ const ids = (before.choices ?? []).map((choice) => choice.id);
138+ const patched = await json<BankQuestion>(`/bank-questions/${questionId}`, {
139+ method: "PATCH",
140+ body: {
141+ choices: [{ id: ids[0], text: "A" }, { id: ids[1], text: "B renamed" }],
142+ correct: ids[1],
143+ },
144+ });
145+ expect(patched.choices?.map((choice) => choice.id)).toEqual(ids);
146+ expect(patched.correct).toBe(ids[1]);
147+ expect(patched.choice_images?.[0]).toBeTruthy();
148+ expect(patched.choice_images?.[1]).toBeTruthy();
149+ const blob = await api(`/bank-questions/${questionId}/choices/${ids[0]}/image`);
150+ expect(blob.status).toBe(200);
151+ });
152+
153+ // Dropping option A: only A's picture goes, B keeps its own and stays markable.
154+ it("PATCH replacing one option drops that option's image only", async () => {
155+ const before = await json<BankQuestion>(`/bank-questions/${questionId}`);
156+ const kept = before.choices![1];
157+ const patched = await json<BankQuestion>(`/bank-questions/${questionId}`, {
158+ method: "PATCH",
159+ body: {
160+ choices: [{ id: "new:9", text: "A replaced" }, { id: kept.id, text: kept.text }],
161+ correct: kept.id,
162+ },
163+ });
164+ expect(patched.choices?.[1].id).toBe(kept.id);
165+ expect(patched.choices?.[0].id).not.toBe(before.choices![0].id);
166+ expect(patched.choice_images?.[0]).toBeNull();
167+ expect(patched.choice_images?.[1]).toBeTruthy();
168+ expect(patched.correct).toBe(kept.id);
169+
170+ // 400, not 404: the id no longer names a choice of this question, so the
171+ // route rejects it before it ever looks for a blob.
172+ const gone = await api(`/bank-questions/${questionId}/choices/${before.choices![0].id}/image`);
173+ expect(gone.ok).toBe(false);
174+ expect(gone.status).toBe(400);
175+ });
176+
177+ // The app is EN/TR: `İ` lowercases to `i` + U+0307 in both Rust and
178+ // SurrealQL, so an unfolded server search made `istanbul` and `İSTANBUL` two
179+ // disjoint queries and a Turkish teacher typing lowercase got an empty bank.
180+ it("?q= folds Turkish casing and diacritics in both directions", async () => {
181+ const tag = `tr${Date.now()}`;
182+ await createTemplate(`${tag} İSTANBUL kaç ilçedir?`);
183+ await createTemplate(`${tag} istanbul boğazı nerededir?`);
184+
185+ for (const needle of ["istanbul", "İSTANBUL", "ıstanbul", "ISTANBUL"]) {
186+ const page = await json<{ total: number; items: BankQuestion[] }>(
187+ `/bank-questions?q=${encodeURIComponent(`${tag} ${needle}`)}`,
188+ );
189+ expect(page.total, `needle ${needle}`).toBe(2);
190+ expect(page.items).toHaveLength(2);
191+ }
192+ for (const needle of ["ilce", "ilçe", "bogaz", "boğaz"]) {
193+ const page = await json<{ total: number }>(
194+ `/bank-questions?q=${encodeURIComponent(needle)}&subject=${subjectId}`,
195+ );
196+ expect(page.total, `needle ${needle}`).toBe(1);
197+ }
198+ const miss = await json<{ total: number }>(`/bank-questions?q=${tag}-ankara`);
199+ expect(miss.total).toBe(0);
200+ });
201+
202+ // Regression for the whole-table-then-slice list: template #101 onward was
203+ // unreachable, and `total` counted the page instead of the matches.
204+ it("pages past 100 with an honest total and joined-on names", async () => {
205+ const tag = `pg${Date.now()}`;
206+ for (let i = 0; i < 105; i++) await createTemplate(`${tag} ${String(i).padStart(3, "0")}`);
207+
208+ type Page = { total: number; items: BankQuestion[]; limit: number; offset: number };
209+ const first = await json<Page>(`/bank-questions?subject=${subjectId}&q=${tag}&limit=100`);
210+ expect(first.total).toBe(105);
211+ expect(first.items).toHaveLength(100);
212+ // Newest first, and the names are joined on server-side.
213+ expect(first.items[0].text).toBe(`${tag} 104`);
214+ expect(first.items[0].subject_name).toBe("contract subject");
215+ expect(typeof first.items[0].owner_name).toBe("string");
216+
217+ const second = await json<Page>(
218+ `/bank-questions?subject=${subjectId}&q=${tag}&limit=100&offset=100`,
219+ );
220+ expect(second.total).toBe(105);
221+ expect(second.items).toHaveLength(5);
222+ expect(second.items[4].text).toBe(`${tag} 000`);
223+ });
224+ // Provenance made useful: the list says how many exam questions were copied
225+ // out of a template, and a copy that drifted can be pulled back in line.
226+ it("reports used_count on the list and refreshes a copy from its template", async () => {
227+ const tag = `use${Date.now()}`;
228+ const template = await createTemplate(`${tag} original text`);
229+ const exam = await json<{ id: string }>(`/courses/${courseId}/exams`, {
230+ method: "POST",
231+ body: { title: tag, kind: "final" },
232+ });
233+
234+ const copy = await json<ExamQuestion>(
235+ `/exams/${exam.id}/questions/from-bank/${template.id}`,
236+ { method: "POST", body: { subject_id: subjectId } },
237+ );
238+ expect(copy.from_bank).toBe(template.id);
239+
240+ // One grouped join on the list; the single-template GET stays at 0.
241+ const page = await json<{ items: BankQuestion[] }>(`/bank-questions?q=${tag}`);
242+ expect(page.items.find((item) => item.id === template.id)?.used_count).toBe(1);
243+ const single = await json<BankQuestion>(`/bank-questions/${template.id}`);
244+ expect(single.used_count).toBe(0);
245+
246+ // The copy drifts locally, the template is fixed, and the refresh wins.
247+ await json<ExamQuestion>(`/exams/${exam.id}/questions/${copy.id}`, {
248+ method: "PATCH",
249+ body: { text: `${tag} local drift`, points: 9 },
250+ });
251+ await json<BankQuestion>(`/bank-questions/${template.id}`, {
252+ method: "PATCH",
253+ body: { text: `${tag} corrected text`, points: 3 },
254+ });
255+ const refreshed = await json<ExamQuestion>(
256+ `/exams/${exam.id}/questions/${copy.id}/refresh-from-bank`,
257+ { method: "POST" },
258+ );
259+ expect(refreshed.id).toBe(copy.id);
260+ expect(refreshed.text).toBe(`${tag} corrected text`);
261+ expect(refreshed.points).toBe(3);
262+ expect(refreshed.from_bank).toBe(template.id);
263+
264+ // A hand-authored question has no template to refresh from: 400, not 404.
265+ const plain = await json<ExamQuestion>(`/exams/${exam.id}/questions`, {
266+ method: "POST",
267+ body: { subject_id: subjectId, text: `${tag} mine`, kind: "text", points: 1 },
268+ });
269+ const refused = await api(`/exams/${exam.id}/questions/${plain.id}/refresh-from-bank`, {
270+ method: "POST",
271+ });
272+ expect(refused.status).toBe(400);
273+
274+ await api(`/exams/${exam.id}`, { method: "DELETE" });
275+ });
276+});
src/api/__tests__/contract/helpers/live-client.tsadded+82 -0
@@ -0,0 +1,82 @@
1+/**
2+ * Minimal live-backend client for the contract suite: a cookie jar (fetch keeps
3+ * none of its own in bun/node) plus a hard timeout so a dead port fails fast
4+ * instead of hanging the run. Boot recipe: see vitest.contract.config.ts.
5+ */
6+// The app's tsconfig has no node types (browser build), so reach env this way.
7+const env: Record<string, string | undefined> =
8+ (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {};
9+
10+export const contractBaseUrl = (env.CONTRACT_BASE_URL ?? "").replace(/\/+$/, "");
11+export const isLive = contractBaseUrl !== "";
12+
13+export const SKIP_MESSAGE =
14+ "[contract] CONTRACT_BASE_URL unset — skipping live contract tests. " +
15+ "Boot a scratch backend (see vitest.contract.config.ts) and re-run with " +
16+ "CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract";
17+
18+const TIMEOUT_MS = 10_000;
19+let cookie = "";
20+
21+type Init = { method?: string; body?: unknown; headers?: Record<string, string> };
22+
23+/** Raw request — returns the Response so tests can assert on status codes. */
24+export async function api(path: string, init: Init = {}): Promise<Response> {
25+ const headers: Record<string, string> = { ...init.headers };
26+ if (cookie) headers.Cookie = cookie;
27+
28+ let body: BodyInit | undefined;
29+ if (init.body instanceof FormData) {
30+ body = init.body;
31+ } else if (init.body !== undefined) {
32+ headers["Content-Type"] = "application/json";
33+ body = JSON.stringify(init.body);
34+ }
35+
36+ const res = await fetch(`${contractBaseUrl}${path}`, {
37+ method: init.method ?? "GET",
38+ headers,
39+ body,
40+ redirect: "manual",
41+ signal: AbortSignal.timeout(TIMEOUT_MS),
42+ });
43+
44+ const setCookies = res.headers.getSetCookie?.() ?? [];
45+ for (const raw of setCookies) {
46+ const pair = raw.split(";")[0];
47+ if (pair.startsWith("session=")) cookie = pair;
48+ }
49+ return res;
50+}
51+
52+/** Request + JSON body, throwing on a non-2xx so setup failures are loud. */
53+export async function json<T>(path: string, init: Init = {}): Promise<T> {
54+ const res = await api(path, init);
55+ const text = await res.text();
56+ if (!res.ok) {
57+ throw new Error(`${init.method ?? "GET"} ${path} → ${res.status} ${text}`);
58+ }
59+ return (text ? JSON.parse(text) : null) as T;
60+}
61+
62+/** Log in as the seeded admin; the session cookie lands in the jar. */
63+export async function loginAdmin(): Promise<void> {
64+ await json("/auth/login", {
65+ method: "POST",
66+ body: {
67+ username: env.ADMIN_USERNAME ?? "admin",
68+ password: env.ADMIN_PASSWORD ?? "admin123",
69+ },
70+ });
71+}
72+
73+/** Smallest valid 1x1 PNG, for the image-upload steps. */
74+export function pngFile(name: string): File {
75+ const bytes = Uint8Array.from(
76+ atob(
77+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
78+ ),
79+ (c) => c.charCodeAt(0),
80+ );
81+ return new File([bytes], name, { type: "image/png" });
82+}
src/api/__tests__/exams/exam-attempts.test.tsmodified+2 -2
@@ -60,10 +60,10 @@ describe("exams API - attempts", () => {
60 });60 });
61 61
62 it("postExamAttemptAnswer calls /exams/:id/attempt/answers with data", async () => {62 it("postExamAttemptAnswer calls /exams/:id/attempt/answers with data", async () => {
63- const mockAnswer = { selected: 1 };63+ const mockAnswer = { selected: "c1" };
64 mockFetchSuccess(mockAnswer);64 mockFetchSuccess(mockAnswer);
65 65
66- const data = { question_id: "q1", selected: 1 };66+ const data = { question_id: "q1", selected: "c1" };
67 const result = await postExamAttemptAnswer("ex1", data);67 const result = await postExamAttemptAnswer("ex1", data);
68 expect(result).toEqual(mockAnswer);68 expect(result).toEqual(mockAnswer);
69 69
src/api/__tests__/exams/exam-questions.test.tsmodified+33 -8
@@ -8,6 +8,7 @@ import { deleteExamQuestionImage } from "../../exams";
8 import { postExamChoiceImage } from "../../exams";8 import { postExamChoiceImage } from "../../exams";
9 import { deleteExamChoiceImage } from "../../exams";9 import { deleteExamChoiceImage } from "../../exams";
10 import { postExamQuestionFromBank } from "../../exams";10 import { postExamQuestionFromBank } from "../../exams";
11+import { postExamQuestionRefreshFromBank } from "../../exams";
11 import { postExamQuestionToBank } from "../../exams";12 import { postExamQuestionToBank } from "../../exams";
12 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";13 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
13 14
@@ -17,11 +18,15 @@ describe("exams API - questions", () => {
17 });18 });
18 19
19 it("getExamQuestions calls /exams/:id/questions", async () => {20 it("getExamQuestions calls /exams/:id/questions", async () => {
20- const mockPage = { items: [{ id: "q1" }], total: 1 };21+ // Both provenance links ride the list untouched: `from_bank` (added out of
22+ // the bank) and `banked_as` (a template minted by saving this question).
23+ const mockPage = { items: [{ id: "q1", from_bank: "b1", banked_as: "b2" }], total: 1 };
21 mockFetchSuccess(mockPage);24 mockFetchSuccess(mockPage);
22 25
23 const result = await getExamQuestions("ex1");26 const result = await getExamQuestions("ex1");
24 expect(result).toEqual({ ...mockPage, limit: null, offset: 0 });27 expect(result).toEqual({ ...mockPage, limit: null, offset: 0 });
28+ expect(result.items[0].from_bank).toBe("b1");
29+ expect(result.items[0].banked_as).toBe("b2");
25 30
26 const [url, init] = lastFetchCall();31 const [url, init] = lastFetchCall();
27 expect(url).toBe("/api/exams/ex1/questions");32 expect(url).toBe("/api/exams/ex1/questions");
@@ -90,36 +95,40 @@ describe("exams API - questions", () => {
90 expect(init?.method).toBe("DELETE");95 expect(init?.method).toBe("DELETE");
91 });96 });
92 97
93- it("postExamChoiceImage calls /exams/:id/questions/:qid/choices/:index/image with FormData", async () => {98+ it("postExamChoiceImage calls /exams/:id/questions/:qid/choices/:choiceId/image with FormData", async () => {
94 const mockMeta = { content_type: "image/png", size: 100 };99 const mockMeta = { content_type: "image/png", size: 100 };
95 mockFetchSuccess(mockMeta);100 mockFetchSuccess(mockMeta);
96 101
97 const file = new File(["test"], "test.png", { type: "image/png" });102 const file = new File(["test"], "test.png", { type: "image/png" });
98- const result = await postExamChoiceImage("ex1", "q1", 2, file);103+ const result = await postExamChoiceImage("ex1", "q1", "c2", file);
99 expect(result).toEqual(mockMeta);104 expect(result).toEqual(mockMeta);
100 105
101 const [url, init] = lastFetchCall();106 const [url, init] = lastFetchCall();
102- expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image");107+ expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image");
103 expect(init?.method).toBe("POST");108 expect(init?.method).toBe("POST");
104 expect(init?.body).toBeInstanceOf(FormData);109 expect(init?.body).toBeInstanceOf(FormData);
105 });110 });
106 111
107- it("deleteExamChoiceImage calls /exams/:id/questions/:qid/choices/:index/image", async () => {112+ it("deleteExamChoiceImage calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => {
108 mockFetch204();113 mockFetch204();
109 114
110- await deleteExamChoiceImage("ex1", "q1", 2);115+ await deleteExamChoiceImage("ex1", "q1", "c2");
111 116
112 const [url, init] = lastFetchCall();117 const [url, init] = lastFetchCall();
113- expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image");118+ expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image");
114 expect(init?.method).toBe("DELETE");119 expect(init?.method).toBe("DELETE");
115 });120 });
116 121
117 it("postExamQuestionFromBank calls /exams/:id/questions/from-bank/:bid with subject_id", async () => {122 it("postExamQuestionFromBank calls /exams/:id/questions/from-bank/:bid with subject_id", async () => {
118- const mockQuestion = { id: "q9", source_bank: "b1" };123+ // Provenance is two separate fields: coming *from* the bank leaves
124+ // `banked_as` null, so the UI can't claim the question was saved to it.
125+ const mockQuestion = { id: "q9", from_bank: "b1", banked_as: null };
119 mockFetchSuccess(mockQuestion, 201);126 mockFetchSuccess(mockQuestion, 201);
120 127
121 const result = await postExamQuestionFromBank("ex1", "b1", "sub1");128 const result = await postExamQuestionFromBank("ex1", "b1", "sub1");
122 expect(result).toEqual(mockQuestion);129 expect(result).toEqual(mockQuestion);
130+ expect(result.from_bank).toBe("b1");
131+ expect(result.banked_as).toBeNull();
123 132
124 const [url, init] = lastFetchCall();133 const [url, init] = lastFetchCall();
125 expect(url).toBe("/api/exams/ex1/questions/from-bank/b1");134 expect(url).toBe("/api/exams/ex1/questions/from-bank/b1");
@@ -139,4 +148,20 @@ describe("exams API - questions", () => {
139 expect(init?.method).toBe("POST");148 expect(init?.method).toBe("POST");
140 expect(init?.body).toBeUndefined();149 expect(init?.body).toBeUndefined();
141 });150 });
151+
152+ it("postExamQuestionRefreshFromBank calls /exams/:id/questions/:qid/refresh-from-bank with no body", async () => {
153+ // The question keeps its id and its `from_bank` link; only the content is
154+ // re-copied from the template.
155+ const mockQuestion = { id: "q1", text: "fixed in the template", from_bank: "b1" };
156+ mockFetchSuccess(mockQuestion);
157+
158+ const result = await postExamQuestionRefreshFromBank("ex1", "q1");
159+ expect(result).toEqual(mockQuestion);
160+ expect(result.from_bank).toBe("b1");
161+
162+ const [url, init] = lastFetchCall();
163+ expect(url).toBe("/api/exams/ex1/questions/q1/refresh-from-bank");
164+ expect(init?.method).toBe("POST");
165+ expect(init?.body).toBeUndefined();
166+ });
142 });167 });
src/api/__tests__/exams/exams.test.tsmodified+3 -3
@@ -27,14 +27,14 @@ describe("exams API - core", () => {
27 expect(init?.method).toBe("GET");27 expect(init?.method).toBe("GET");
28 });28 });
29 29
30- it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:index/image", async () => {30+ it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => {
31 mockFetchBlob(new Blob(["img"], { type: "image/png" }));31 mockFetchBlob(new Blob(["img"], { type: "image/png" }));
32 32
33- const result = await getExamChoiceImageBlob("ex1", "q1", 2);33+ const result = await getExamChoiceImageBlob("ex1", "q1", "c2");
34 expect(result).toBeInstanceOf(Blob);34 expect(result).toBeInstanceOf(Blob);
35 35
36 const [url, init] = lastFetchCall();36 const [url, init] = lastFetchCall();
37- expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image");37+ expect(url).toBe("/api/exams/ex1/questions/q1/choices/c2/image");
38 expect(init?.method).toBeUndefined();38 expect(init?.method).toBeUndefined();
39 });39 });
40 40
src/api/bank-questions/deleteBankChoiceImage.tsmodified+2 -2
@@ -1,5 +1,5 @@
1 import { client } from "../client";1 import { client } from "../client";
2 2
3-export function deleteBankChoiceImage(bankQuestionId: string, index: number): Promise<void> {3+export function deleteBankChoiceImage(bankQuestionId: string, choiceId: string): Promise<void> {
4- return client<void>(`/bank-questions/${bankQuestionId}/choices/${index}/image`, { method: "DELETE" });4+ return client<void>(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, { method: "DELETE" });
5 }5 }
src/api/bank-questions/getBankChoiceImageBlob.tsmodified+2 -2
@@ -1,5 +1,5 @@
1 import { blobClient } from "../client";1 import { blobClient } from "../client";
2 2
3-export function getBankChoiceImageBlob(bankQuestionId: string, index: number, signal?: AbortSignal): Promise<Blob> {3+export function getBankChoiceImageBlob(bankQuestionId: string, choiceId: string, signal?: AbortSignal): Promise<Blob> {
4- return blobClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, signal);4+ return blobClient(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, signal);
5 }5 }
src/api/bank-questions/getBankQuestions.tsmodified+13 -3
@@ -1,9 +1,17 @@
1 import { client } from "../client";1 import { client } from "../client";
2 import { appendPageParams, normalizePage, type Page, type PageParams } from "../client";2 import { appendPageParams, normalizePage, type Page, type PageParams } from "../client";
3-import type { BankQuestion } from "../client";3+import type { BankQuestion, BankVisibility } from "../client";
4 4
5-/** `owner` takes a user id or the literal "me". */5+/**
6-export type BankQuestionFilters = PageParams & { subject?: string; owner?: string };6+ * `owner` takes a user id or the literal "me". `visibility` only narrows what the
7+ * caller may already see — "private" is effectively their own drafts.
8+ */
9+export type BankQuestionFilters = PageParams & {
10+ subject?: string;
11+ owner?: string;
12+ q?: string;
13+ visibility?: BankVisibility;
14+};
7 15
8 export async function getBankQuestions(16 export async function getBankQuestions(
9 params?: BankQuestionFilters,17 params?: BankQuestionFilters,
@@ -12,6 +20,8 @@ export async function getBankQuestions(
12 const query = new URLSearchParams();20 const query = new URLSearchParams();
13 if (params?.subject) query.set("subject", params.subject);21 if (params?.subject) query.set("subject", params.subject);
14 if (params?.owner) query.set("owner", params.owner);22 if (params?.owner) query.set("owner", params.owner);
23+ if (params?.q) query.set("q", params.q);
24+ if (params?.visibility) query.set("visibility", params.visibility);
15 appendPageParams(query, params);25 appendPageParams(query, params);
16 const value = query.toString();26 const value = query.toString();
17 const data = await client<unknown>(`/bank-questions${value ? `?${value}` : ""}`, { signal });27 const data = await client<unknown>(`/bank-questions${value ? `?${value}` : ""}`, { signal });
src/api/bank-questions/patchBankQuestionById.tsmodified+7 -3
@@ -1,13 +1,17 @@
1 import { client } from "../client";1 import { client } from "../client";
2-import type { BankQuestion, QuestionKind } from "../client";2+import type { BankQuestion, BankVisibility, QuestionKind } from "../client";
3 3
4 export type PatchBankQuestionBody = {4 export type PatchBankQuestionBody = {
5 subject_id?: string;5 subject_id?: string;
6 text?: string;6 text?: string;
7 kind?: QuestionKind;7 kind?: QuestionKind;
8 points?: number;8 points?: number;
9- choices?: string[] | null;9+ /** Each option carries its key: a known key keeps that option (and its image), any other is new. */
10- correct?: number | null;10+ choices?: { id?: string | null; text: string }[] | null;
11+ /** Choice id — must name one of the submitted choices. */
12+ correct?: string | null;
13+ /** Publishing (`school`) hands the answer key to every teacher — send it only on an explicit choice. */
14+ visibility?: BankVisibility;
11 };15 };
12 16
13 export function patchBankQuestionById(17 export function patchBankQuestionById(
src/api/bank-questions/postBankChoiceImage.tsmodified+2 -2
@@ -1,8 +1,8 @@
1 import { formClient } from "../client";1 import { formClient } from "../client";
2 import type { ImageMeta } from "../client";2 import type { ImageMeta } from "../client";
3 3
4-export function postBankChoiceImage(bankQuestionId: string, index: number, file: File, signal?: AbortSignal): Promise<ImageMeta> {4+export function postBankChoiceImage(bankQuestionId: string, choiceId: string, file: File, signal?: AbortSignal): Promise<ImageMeta> {
5 const body = new FormData();5 const body = new FormData();
6 body.append("file", file);6 body.append("file", file);
7- return formClient<ImageMeta>(`/bank-questions/${bankQuestionId}/choices/${index}/image`, body, signal);7+ return formClient<ImageMeta>(`/bank-questions/${bankQuestionId}/choices/${choiceId}/image`, body, signal);
8 }8 }
src/api/bank-questions/postBankQuestion.tsmodified+4 -2
@@ -6,8 +6,10 @@ export type BankQuestionBody = {
6 text: string;6 text: string;
7 kind: QuestionKind;7 kind: QuestionKind;
8 points: number;8 points: number;
9- choices?: string[] | null;9+ /** Each option carries its key: a known key keeps that option (and its image), any other is new. */
10- correct?: number | null;10+ choices?: { id?: string | null; text: string }[] | null;
11+ /** Choice id — must name one of the submitted choices. */
12+ correct?: string | null;
11 };13 };
12 14
13 export function postBankQuestion(body: BankQuestionBody): Promise<BankQuestion> {15 export function postBankQuestion(body: BankQuestionBody): Promise<BankQuestion> {
src/api/client/types.tsmodified+26 -9
@@ -207,6 +207,9 @@ export type ExamResult = {
207 graded_by: PersonRef;207 graded_by: PersonRef;
208 };208 };
209 209
210+/** One option of a choice question. `id` is stable across edits, so its image survives. */
211+export type Choice = { id: string; text: string };
212+
210 export type ExamQuestion = {213 export type ExamQuestion = {
211 id: string;214 id: string;
212 exam: string;215 exam: string;
@@ -214,27 +217,41 @@ export type ExamQuestion = {
214 text: string;217 text: string;
215 kind: QuestionKind;218 kind: QuestionKind;
216 points: number;219 points: number;
217- choices: string[] | null;220+ choices: Choice[] | null;
218- correct: number | null;221+ correct: string | null;
219 image?: ImageMeta | null;222 image?: ImageMeta | null;
220 choice_images?: (ImageMeta | null)[] | null;223 choice_images?: (ImageMeta | null)[] | null;
221- source_bank?: string | null; // bank question this was copied from, if any224+ from_bank?: string | null; // bank template this question was added from, if any
225+ banked_as?: string | null; // bank template last created by saving this question, if any
222 };226 };
223 227
228+/** `private`: owner + admins only. `school`: every teacher can see it and its answer key. */
229+export type BankVisibility = "private" | "school";
230+
224 /** Reusable question stored in the school-wide question bank, outside any exam. */231 /** Reusable question stored in the school-wide question bank, outside any exam. */
225 export type BankQuestion = {232 export type BankQuestion = {
226 id: string;233 id: string;
227 owner: string; // user id234 owner: string; // user id
228- subject: string; // subject id (origin metadata)235+ owner_name: string;
236+ subject: string | null; // subject id (origin metadata); null once that subject is deleted
237+ subject_name: string;
229 text: string;238 text: string;
230 kind: QuestionKind;239 kind: QuestionKind;
231 points: number;240 points: number;
232- choices: string[] | null;241+ choices: Choice[] | null;
233- correct: number | null;242+ correct: string | null;
234 image?: ImageMeta | null;243 image?: ImageMeta | null;
235 choice_images?: (ImageMeta | null)[] | null;244 choice_images?: (ImageMeta | null)[] | null;
236 source_exam?: string | null;245 source_exam?: string | null;
246+ visibility: BankVisibility; // new templates start "private"
237 created_at: number; // UTC unix ms247 created_at: number; // UTC unix ms
248+ /**
249+ * How many exam questions were copied out of this template. Each copy is
250+ * detached, so editing the template never reaches them — this is the
251+ * divergence surface. List-only, exactly like `subject_name`/`owner_name`:
252+ * the single-template endpoints return 0.
253+ */
254+ used_count: number;
238 };255 };
239 256
240 export type ExamAttempt = {257 export type ExamAttempt = {
@@ -257,7 +274,7 @@ export type ExamAttempt = {
257 };274 };
258 275
259 export type AttemptAnswer = {276 export type AttemptAnswer = {
260- selected?: number | null;277+ selected?: string | null;
261 text?: string | null;278 text?: string | null;
262 updated_at?: number;279 updated_at?: number;
263 answer_image?: ImageMeta | null;280 answer_image?: ImageMeta | null;
@@ -269,7 +286,7 @@ export type AttemptQuestionResponse = {
269 text: string;286 text: string;
270 kind: QuestionKind;287 kind: QuestionKind;
271 points: number;288 points: number;
272- choices: string[] | null;289+ choices: Choice[] | null;
273 image?: ImageMeta | null;290 image?: ImageMeta | null;
274 choice_images?: (ImageMeta | null)[] | null;291 choice_images?: (ImageMeta | null)[] | null;
275 answer: AttemptAnswer | null;292 answer: AttemptAnswer | null;
@@ -364,7 +381,7 @@ export type ExamStatistics = {
364 381
365 export type StudentAnswer = {382 export type StudentAnswer = {
366 question: string;383 question: string;
367- selected: number | null;384+ selected: string | null;
368 text: string | null;385 text: string | null;
369 updated_at: number;386 updated_at: number;
370 is_correct: boolean | null;387 is_correct: boolean | null;
src/api/exams/deleteExamChoiceImage.tsmodified+2 -2
@@ -1,5 +1,5 @@
1 import { client } from "../client";1 import { client } from "../client";
2 2
3-export function deleteExamChoiceImage(examId: string, questionId: string, index: number): Promise<void> {3+export function deleteExamChoiceImage(examId: string, questionId: string, choiceId: string): Promise<void> {
4- return client<void>(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, { method: "DELETE" });4+ return client<void>(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, { method: "DELETE" });
5 }5 }
src/api/exams/getExamChoiceImageBlob.tsmodified+2 -2
@@ -1,5 +1,5 @@
1 import { blobClient } from "../client";1 import { blobClient } from "../client";
2 2
3-export function getExamChoiceImageBlob(examId: string, questionId: string, index: number, signal?: AbortSignal): Promise<Blob> {3+export function getExamChoiceImageBlob(examId: string, questionId: string, choiceId: string, signal?: AbortSignal): Promise<Blob> {
4- return blobClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, signal);4+ return blobClient(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, signal);
5 }5 }
src/api/exams/index.tsmodified+1 -0
@@ -37,4 +37,5 @@ export * from "./getExamReviewAttemptAnswers";
37 export * from "./getExamReviewAttemptAnswerImage";37 export * from "./getExamReviewAttemptAnswerImage";
38 export * from "./getStudentMarksHistory";38 export * from "./getStudentMarksHistory";
39 export * from "./postExamQuestionFromBank";39 export * from "./postExamQuestionFromBank";
40+export * from "./postExamQuestionRefreshFromBank";
40 export * from "./postExamQuestionToBank";41 export * from "./postExamQuestionToBank";
src/api/exams/patchExamQuestionById.tsmodified+4 -2
@@ -6,8 +6,10 @@ export type PatchExamQuestionBody = {
6 text?: string | null;6 text?: string | null;
7 kind?: QuestionKind | null;7 kind?: QuestionKind | null;
8 points?: number | null;8 points?: number | null;
9- choices?: string[] | null;9+ /** Each option carries its key: a known key keeps that option (and its image), any other is new. */
10- correct?: number | null;10+ choices?: { id?: string | null; text: string }[] | null;
11+ /** Choice id — must name one of the submitted choices. */
12+ correct?: string | null;
11 };13 };
12 14
13 export function patchExamQuestionById(15 export function patchExamQuestionById(
src/api/exams/postExamAttemptAnswer.tsmodified+1 -1
@@ -3,7 +3,7 @@ import type { AttemptAnswer } from "../client";
3 3
4 export type PostExamAttemptAnswerBody = {4 export type PostExamAttemptAnswerBody = {
5 question_id: string;5 question_id: string;
6- selected?: number | null;6+ selected?: string | null; // choice id
7 text?: string | null;7 text?: string | null;
8 };8 };
9 9
src/api/exams/postExamChoiceImage.tsmodified+2 -2
@@ -1,8 +1,8 @@
1 import { formClient } from "../client";1 import { formClient } from "../client";
2 import type { ImageMeta } from "../client";2 import type { ImageMeta } from "../client";
3 3
4-export function postExamChoiceImage(examId: string, questionId: string, index: number, file: File, signal?: AbortSignal): Promise<ImageMeta> {4+export function postExamChoiceImage(examId: string, questionId: string, choiceId: string, file: File, signal?: AbortSignal): Promise<ImageMeta> {
5 const body = new FormData();5 const body = new FormData();
6 body.append("file", file);6 body.append("file", file);
7- return formClient<ImageMeta>(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, body, signal);7+ return formClient<ImageMeta>(`/exams/${examId}/questions/${questionId}/choices/${choiceId}/image`, body, signal);
8 }8 }
src/api/exams/postExamQuestion.tsmodified+4 -2
@@ -6,8 +6,10 @@ export type ExamQuestionBody = {
6 text: string;6 text: string;
7 kind: QuestionKind;7 kind: QuestionKind;
8 points: number;8 points: number;
9- choices?: string[] | null;9+ /** Each option carries its key: a known key keeps that option (and its image), any other is new. */
10- correct?: number | null;10+ choices?: { id?: string | null; text: string }[] | null;
11+ /** Choice id — must name one of the submitted choices. */
12+ correct?: string | null;
11 };13 };
12 14
13 export function postExamQuestion(examId: string, body: ExamQuestionBody): Promise<ExamQuestion> {15 export function postExamQuestion(examId: string, body: ExamQuestionBody): Promise<ExamQuestion> {
src/api/exams/postExamQuestionRefreshFromBank.tsadded+17 -0
@@ -0,0 +1,17 @@
1+import { client } from "../client";
2+import type { ExamQuestion } from "../client";
3+
4+/**
5+ * Re-copy the question's bank template over it — the escape hatch for a copy that
6+ * drifted from its template (a bank↔exam copy is deep, never a live link). Only
7+ * for a question that still has `from_bank`; the backend refuses with 409 once
8+ * any attempt exists, and 400 when there is no template to refresh from.
9+ */
10+export function postExamQuestionRefreshFromBank(
11+ examId: string,
12+ questionId: string,
13+): Promise<ExamQuestion> {
14+ return client<ExamQuestion>(`/exams/${examId}/questions/${questionId}/refresh-from-bank`, {
15+ method: "POST",
16+ });
17+}
src/components/exams/answer-sheet-view.tsxmodified+6 -6
@@ -234,11 +234,11 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
234 {(choice, ci) => (234 {(choice, ci) => (
235 <div235 <div
236 class={`flex items-center gap-2 rounded-sm border px-3 py-2 text-sm ${236 class={`flex items-center gap-2 rounded-sm border px-3 py-2 text-sm ${
237- ci() === row.question.correct && ci() === row.answer?.selected237+ choice.id === row.question.correct && choice.id === row.answer?.selected
238 ? "border-success bg-success/10"238 ? "border-success bg-success/10"
239- : ci() === row.question.correct239+ : choice.id === row.question.correct
240 ? "border-success/50 bg-success/5"240 ? "border-success/50 bg-success/5"
241- : ci() === row.answer?.selected241+ : choice.id === row.answer?.selected
242 ? "border-destructive bg-destructive/10"242 ? "border-destructive bg-destructive/10"
243 : "border-border"243 : "border-border"
244 }`}244 }`}
@@ -246,11 +246,11 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
246 <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md border bg-background text-[11px] font-semibold text-foreground">246 <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md border bg-background text-[11px] font-semibold text-foreground">
247 {String.fromCharCode(65 + ci())}247 {String.fromCharCode(65 + ci())}
248 </span>248 </span>
249- <span>{choice}</span>249+ <span>{choice.text}</span>
250- <Show when={ci() === row.answer?.selected && ci() !== row.question.correct}>250+ <Show when={choice.id === row.answer?.selected && choice.id !== row.question.correct}>
251 <Badge variant="destructive" class="ml-auto text-[10px]">✗</Badge>251 <Badge variant="destructive" class="ml-auto text-[10px]">✗</Badge>
252 </Show>252 </Show>
253- {ci() === row.question.correct && (253+ {choice.id === row.question.correct && (
254 <Badge variant="outline" class="ml-auto border-success/50 bg-success/10 text-success text-[10px]">254 <Badge variant="outline" class="ml-auto border-success/50 bg-success/10 text-success text-[10px]">
255 <IconCheck class="h-3 w-3" />255 <IconCheck class="h-3 w-3" />
256 </Badge>256 </Badge>
src/components/exams/bank-question-form.tsxmodified+70 -46
@@ -1,7 +1,6 @@
1-import { For, Show, createResource, createSignal } from "solid-js";1+import { For, Show, createEffect, createResource, createSignal } from "solid-js";
2-import type { BankQuestion, Course } from "@/api/client";2+import type { BankQuestion, BankVisibility, Course } from "@/api/client";
3 import {3 import {
4- getBankChoiceImageBlob,
5 patchBankQuestionById,4 patchBankQuestionById,
6 postBankChoiceImage,5 postBankChoiceImage,
7 postBankQuestion,6 postBankQuestion,
@@ -11,7 +10,8 @@ import { getBankQuestionImageBlob } from "@/api/bank-questions";
11 import { getCourseSubjects } from "@/api/courses";10 import { getCourseSubjects } from "@/api/courses";
12 import { getSubjectById } from "@/api/subjects";11 import { getSubjectById } from "@/api/subjects";
13 import { QuestionForm, type QuestionValues } from "@/components/exams/question-form";12 import { QuestionForm, type QuestionValues } from "@/components/exams/question-form";
14-import { planChoiceImageRestore } from "@/lib/choice-compaction";13+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
14+import { IconUsers } from "@/components/ui/icons";
15 import { Label } from "@/components/ui/label";15 import { Label } from "@/components/ui/label";
16 import { Select } from "@/components/ui/select";16 import { Select } from "@/components/ui/select";
17 import { useT } from "@/stores/preferences-context";17 import { useT } from "@/stores/preferences-context";
@@ -24,8 +24,7 @@ import { useT } from "@/stores/preferences-context";
24 export function BankQuestionForm(props: {24 export function BankQuestionForm(props: {
25 initial?: BankQuestion;25 initial?: BankQuestion;
26 courses: Course[];26 courses: Course[];
27- /** `imagesLost` is set when an option image could not be carried over the edit. */27+ onSaved: (question: BankQuestion) => void;
28- onSaved: (question: BankQuestion, imagesLost?: string) => void;
29 onCancel: () => void;28 onCancel: () => void;
30 }) {29 }) {
31 const t = useT();30 const t = useT();
@@ -35,57 +34,54 @@ export function BankQuestionForm(props: {
35 async (subjectId) => (await getSubjectById(subjectId).catch(() => null))?.course ?? "",34 async (subjectId) => (await getSubjectById(subjectId).catch(() => null))?.course ?? "",
36 );35 );
37 const [courseId, setCourseId] = createSignal("");36 const [courseId, setCourseId] = createSignal("");
38- const selectedCourse = () => courseId() || initialCourse() || props.courses[0]?.id || "";37+ // Editing keeps the template's own course even when it is not one of ours (it is
38+ // shown as a disabled option); only a new template falls back to the first course.
39+ const selectedCourse = () =>
40+ courseId() || initialCourse() || (props.initial ? "" : props.courses[0]?.id) || "";
41+ const originUnknown = () =>
42+ !!initialCourse() && !props.courses.some((course) => course.id === initialCourse());
39 const [subjects] = createResource(43 const [subjects] = createResource(
40 () => selectedCourse() || null,44 () => selectedCourse() || null,
41 async (id) => (await getCourseSubjects(id)).items,45 async (id) => (await getCourseSubjects(id)).items,
42 );46 );
43 47
48+ // A template is private until its owner deliberately shares it; switching to
49+ // "school" waits on a confirmation dialog that spells out what that hands over.
50+ const [visibility, setVisibility] = createSignal<BankVisibility>("private");
51+ const [confirmShare, setConfirmShare] = createSignal<((shared: boolean) => void) | null>(null);
52+ createEffect(() => setVisibility(props.initial?.visibility ?? "private"));
53+
44 const imageBase = () => `/api/bank-questions/${props.initial?.id}`;54 const imageBase = () => `/api/bank-questions/${props.initial?.id}`;
45 55
46 const submit = async (values: QuestionValues) => {56 const submit = async (values: QuestionValues) => {
47- const { image, choice_images, choice_sources, ...body } = values;57+ const { image, choice_images, ...body } = values;
48 const existing = props.initial;58 const existing = props.initial;
49 59
50- // PATCH with a `choices` key wipes every stored option image server-side, so60+ // Sharing is the only irreversible half of this form — ask before anything is sent.
51- // fetch the ones the user is keeping first and put them back afterwards.61+ const sharing = visibility() === "school" && existing?.visibility !== "school";
52- // `choice_sources` maps each surviving choice to the option it came from,62+ if (sharing) {
53- // because blank choices are dropped and would otherwise shift the indices.63+ const confirmed = await new Promise<boolean>((resolve) => setConfirmShare(() => resolve));
54- const lost: number[] = [];64+ setConfirmShare(null);
55- const keep: { index: number; file: File }[] = [];65+ if (!confirmed) return;
56- if (existing && body.kind === "choice") {
57- const plan = planChoiceImageRestore(choice_sources ?? [], existing.choice_images ?? [], choice_images);
58- for (const slot of plan) {
59- try {
60- const blob = await getBankChoiceImageBlob(existing.id, slot.source);
61- keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) });
62- } catch {
63- lost.push(slot.index); // the PATCH below deletes it regardless — say so
64- }
65- }
66 }66 }
67 67
68- const saved = existing68+ // POST has no visibility field — a new template is always born private, so
69- ? await patchBankQuestionById(existing.id, body)69+ // sharing one is a follow-up PATCH.
70+ let saved = existing
71+ ? await patchBankQuestionById(existing.id, {
72+ ...body,
73+ ...(visibility() !== existing.visibility ? { visibility: visibility() } : {}),
74+ })
70 : await postBankQuestion(body);75 : await postBankQuestion(body);
76+ if (sharing && !existing) saved = await patchBankQuestionById(saved.id, { visibility: "school" });
71 if (image) await postBankQuestionImage(saved.id, image);77 if (image) await postBankQuestionImage(saved.id, image);
78+ // The saved choices come back in the submitted order, so the freshly picked
79+ // files line up with them — and every untouched option kept its own picture.
72 for (const [index, file] of (choice_images ?? []).entries()) {80 for (const [index, file] of (choice_images ?? []).entries()) {
73- if (file) await postBankChoiceImage(saved.id, index, file);81+ const choiceId = saved.choices?.[index]?.id;
74- }82+ if (file && choiceId) await postBankChoiceImage(saved.id, choiceId, file);
75- // One failed restore must not abandon the rest: upload each independently.
76- for (const slot of keep) {
77- try {
78- await postBankChoiceImage(saved.id, slot.index, slot.file);
79- } catch {
80- lost.push(slot.index);
81- }
82 }83 }
83- props.onSaved(84+ props.onSaved(saved);
84- saved,
85- lost.length > 0
86- ? t("questions.imagesLost", { options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", ") })
87- : undefined,
88- );
89 };85 };
90 86
91 return (87 return (
@@ -102,26 +98,54 @@ export function BankQuestionForm(props: {
102 value={selectedCourse()}98 value={selectedCourse()}
103 onChange={(event) => setCourseId(event.currentTarget.value)}99 onChange={(event) => setCourseId(event.currentTarget.value)}
104 >100 >
101+ <option value="">{t("bank.courseSelect")}</option>
102+ <Show when={originUnknown()}>
103+ <option value={initialCourse()} disabled>{t("bank.courseUnavailable")}</option>
104+ </Show>
105 <For each={props.courses}>{(course) => <option value={course.id}>{course.title}</option>}</For>105 <For each={props.courses}>{(course) => <option value={course.id}>{course.title}</option>}</For>
106 </Select>106 </Select>
107 <p class="text-[11px] text-muted-foreground">{t("bank.courseHint")}</p>107 <p class="text-[11px] text-muted-foreground">{t("bank.courseHint")}</p>
108 </div>108 </div>
109 109
110- <Show when={props.initial?.choice_images?.some(Boolean)}>110+ <div class="space-y-1.5 rounded-lg border bg-card p-3.5 shadow-xs">
111- <p class="rounded-lg border border-destructive/20 bg-destructive/8 px-3 py-2 text-xs text-destructive">111+ <Label for="bank-visibility" class="text-xs font-semibold text-muted-foreground">{t("bank.whoCanSee")}</Label>
112- {t("bank.choiceImagesWarning")}112+ <Select
113+ id="bank-visibility"
114+ class="h-9 py-1.5 text-sm"
115+ value={visibility()}
116+ onChange={(event) => setVisibility(event.currentTarget.value as BankVisibility)}
117+ >
118+ <option value="private">{t("bank.onlyMe")}</option>
119+ <option value="school">{t("bank.sharedWithSchool")}</option>
120+ </Select>
121+ <p class="text-[11px] text-muted-foreground">
122+ {visibility() === "school" ? t("bank.sharedWithSchoolHint") : t("bank.onlyMeHint")}
113 </p>123 </p>
114- </Show>124+ </div>
115 125
116 <QuestionForm126 <QuestionForm
117 initial={props.initial}127 initial={props.initial}
118 subjects={subjects() ?? []}128 subjects={subjects() ?? []}
129+ subjectsPending={initialCourse.loading || subjects.loading}
119 imageSrc={props.initial?.image ? `${imageBase()}/image` : undefined}130 imageSrc={props.initial?.image ? `${imageBase()}/image` : undefined}
120- choiceImageSrc={(index) => `${imageBase()}/choices/${index}/image`}131+ choiceImageSrc={(choiceId) => `${imageBase()}/choices/${choiceId}/image`}
121 loadImageBlob={props.initial ? () => getBankQuestionImageBlob(props.initial!.id) : undefined}132 loadImageBlob={props.initial ? () => getBankQuestionImageBlob(props.initial!.id) : undefined}
122 onSubmit={submit}133 onSubmit={submit}
123 onCancel={props.onCancel}134 onCancel={props.onCancel}
124 />135 />
136+
137+ <ConfirmDialog
138+ open={confirmShare() != null}
139+ onOpenChange={(open) => {
140+ if (!open) confirmShare()?.(false);
141+ }}
142+ title={t("bank.shareTitle")}
143+ description={t("bank.shareBody")}
144+ confirmLabel={t("bank.shareConfirm")}
145+ icon={<IconUsers class="h-4 w-4" />}
146+ summary={props.initial?.text || t("bank.sharedWithSchoolHint")}
147+ onConfirm={() => confirmShare()?.(true)}
148+ />
125 </div>149 </div>
126 );150 );
127 }151 }
src/components/exams/bank-question-picker.tsxmodified+43 -18
@@ -1,4 +1,4 @@
1-import { For, Show, createMemo, createResource, createSignal } from "solid-js";1+import { For, Show, createResource, createSignal } from "solid-js";
2 import type { BankQuestion, Subject } from "@/api/client";2 import type { BankQuestion, Subject } from "@/api/client";
3 import { formatApiError } from "@/api/client";3 import { formatApiError } from "@/api/client";
4 import { getBankQuestions } from "@/api/bank-questions";4 import { getBankQuestions } from "@/api/bank-questions";
@@ -6,11 +6,14 @@ import { Badge } from "@/components/ui/badge";
6 import { Button } from "@/components/ui/button";6 import { Button } from "@/components/ui/button";
7 import { Input } from "@/components/ui/input";7 import { Input } from "@/components/ui/input";
8 import { Label } from "@/components/ui/label";8 import { Label } from "@/components/ui/label";
9+import { PaginationControls } from "@/components/ui/pagination-controls";
9 import { Select } from "@/components/ui/select";10 import { Select } from "@/components/ui/select";
10 import { cn } from "@/lib/cn";11 import { cn } from "@/lib/cn";
11-import { usePreferences, useT } from "@/stores/preferences-context";12+import { createDebouncedSignal } from "@/lib/create-debounced-signal";
13+import { totalPages as pagesOf } from "@/lib/list-page";
14+import { useT } from "@/stores/preferences-context";
12 15
13-const BANK_LIMIT = 100;16+const PICKER_PAGE_SIZE = 20;
14 17
15 /** Pick a bank template and copy it into an exam under one of that exam's subjects. */18 /** Pick a bank template and copy it into an exam under one of that exam's subjects. */
16 export function BankQuestionPicker(props: {19 export function BankQuestionPicker(props: {
@@ -19,22 +22,27 @@ export function BankQuestionPicker(props: {
19 onCancel: () => void;22 onCancel: () => void;
20 }) {23 }) {
21 const t = useT();24 const t = useT();
22- const { locale } = usePreferences();25+ const [query, setQuery, debouncedQuery] = createDebouncedSignal();
23- const [query, setQuery] = createSignal("");26+ const [page, setPage] = createSignal(0);
24 const [selected, setSelected] = createSignal<BankQuestion | null>(null);27 const [selected, setSelected] = createSignal<BankQuestion | null>(null);
25 const [subjectId, setSubjectId] = createSignal("");28 const [subjectId, setSubjectId] = createSignal("");
26 const [error, setError] = createSignal("");29 const [error, setError] = createSignal("");
27 const [pending, setPending] = createSignal(false);30 const [pending, setPending] = createSignal(false);
28- // ponytail: first 100 templates, narrowed client-side — the bank has no text31+ const [templates] = createResource(
29- // search endpoint. Swap for a server query when the bank outgrows one page.32+ () => ({ page: page(), q: debouncedQuery().trim() }),
30- const [templates] = createResource(async () => (await getBankQuestions({ limit: BANK_LIMIT })).items);33+ (params) =>
34+ getBankQuestions({
35+ limit: PICKER_PAGE_SIZE,
36+ offset: params.page * PICKER_PAGE_SIZE,
37+ ...(params.q ? { q: params.q } : {}),
38+ }),
39+ );
31 40
32- const targetSubject = () => subjectId() || props.subjects[0]?.id || "";41+ // No default: the teacher files the copy under a subject deliberately, or not at all.
33- const visible = createMemo(() => {42+ const targetSubject = () => subjectId();
34- const q = query().trim().toLocaleLowerCase(locale());43+ // .latest: the list lives in a dialog with no <Suspense>, so paging must not blank it.
35- const items = templates() ?? [];44+ const visible = () => templates.latest?.items ?? [];
36- return q ? items.filter((item) => item.text.toLocaleLowerCase(locale()).includes(q)) : items;45+ const total = () => templates.latest?.total ?? 0;
37- });
38 46
39 const insert = async () => {47 const insert = async () => {
40 const template = selected();48 const template = selected();
@@ -61,7 +69,10 @@ export function BankQuestionPicker(props: {
61 class="h-9 rounded-lg text-sm"69 class="h-9 rounded-lg text-sm"
62 value={query()}70 value={query()}
63 placeholder={t("bank.search")}71 placeholder={t("bank.search")}
64- onInput={(event) => setQuery(event.currentTarget.value)}72+ onInput={(event) => {
73+ setQuery(event.currentTarget.value);
74+ setPage(0);
75+ }}
65 />76 />
66 77
67 <div class="max-h-72 space-y-1.5 overflow-y-auto rounded-lg border bg-muted/20 p-1.5">78 <div class="max-h-72 space-y-1.5 overflow-y-auto rounded-lg border bg-muted/20 p-1.5">
@@ -96,6 +107,15 @@ export function BankQuestionPicker(props: {
96 </Show>107 </Show>
97 </div>108 </div>
98 109
110+ <Show when={total() > 0}>
111+ <p class="text-xs tabular-nums text-muted-foreground">
112+ {t("bank.countShown", { shown: visible().length, total: total() })}
113+ </p>
114+ </Show>
115+ <Show when={pagesOf(total(), PICKER_PAGE_SIZE) > 1}>
116+ <PaginationControls page={page()} totalPages={pagesOf(total(), PICKER_PAGE_SIZE)} onPageChange={setPage} />
117+ </Show>
118+
99 <Show when={selected()}>119 <Show when={selected()}>
100 {(template) => (120 {(template) => (
101 <div class="space-y-2 rounded-lg border bg-card p-3 shadow-xs">121 <div class="space-y-2 rounded-lg border bg-card p-3 shadow-xs">
@@ -114,11 +134,11 @@ export function BankQuestionPicker(props: {
114 <li134 <li
115 class={cn(135 class={cn(
116 "flex items-start gap-2 rounded-md px-2 py-1",136 "flex items-start gap-2 rounded-md px-2 py-1",
117- index() === template().correct ? "bg-primary/10 font-medium" : "text-muted-foreground",137+ choice.id === template().correct ? "bg-primary/10 font-medium" : "text-muted-foreground",
118 )}138 )}
119 >139 >
120 <span class="font-mono text-[11px] font-bold">{String.fromCharCode(65 + index())}</span>140 <span class="font-mono text-[11px] font-bold">{String.fromCharCode(65 + index())}</span>
121- <span class="min-w-0 flex-1 whitespace-pre-wrap">{choice}</span>141+ <span class="min-w-0 flex-1 whitespace-pre-wrap">{choice.text}</span>
122 </li>142 </li>
123 )}143 )}
124 </For>144 </For>
@@ -130,7 +150,7 @@ export function BankQuestionPicker(props: {
130 150
131 <div class="space-y-1.5">151 <div class="space-y-1.5">
132 <Label for="bank-target-subject" class="text-xs font-semibold text-muted-foreground">152 <Label for="bank-target-subject" class="text-xs font-semibold text-muted-foreground">
133- {t("bank.targetSubject")}153+ {t("bank.targetSubject")} <span class="text-destructive">*</span>
134 </Label>154 </Label>
135 <Show155 <Show
136 when={props.subjects.length > 0}156 when={props.subjects.length > 0}
@@ -140,10 +160,15 @@ export function BankQuestionPicker(props: {
140 id="bank-target-subject"160 id="bank-target-subject"
141 class="h-9 py-1.5 text-sm"161 class="h-9 py-1.5 text-sm"
142 value={targetSubject()}162 value={targetSubject()}
163+ required
143 onChange={(event) => setSubjectId(event.currentTarget.value)}164 onChange={(event) => setSubjectId(event.currentTarget.value)}
144 >165 >
166+ <option value="">{t("subjects.select")}</option>
145 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>167 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>
146 </Select>168 </Select>
169+ <Show when={!targetSubject()}>
170+ <p class="text-[11px] text-muted-foreground">{t("bank.targetSubjectHint")}</p>
171+ </Show>
147 </Show>172 </Show>
148 </div>173 </div>
149 174
src/components/exams/exam-questions-panel.tsxmodified+91 -52
@@ -3,10 +3,10 @@ import { deleteExamChoiceImage } from "@/api/exams";
3 import { deleteExamQuestionImage } from "@/api/exams";3 import { deleteExamQuestionImage } from "@/api/exams";
4 import { deleteExamQuestionById } from "@/api/exams";4 import { deleteExamQuestionById } from "@/api/exams";
5 import { getCourseSubjects } from "@/api/courses";5 import { getCourseSubjects } from "@/api/courses";
6-import { getExamChoiceImageBlob } from "@/api/exams";
7 import { getExamQuestionImageBlob } from "@/api/exams";6 import { getExamQuestionImageBlob } from "@/api/exams";
8 import { getExamQuestions } from "@/api/exams";7 import { getExamQuestions } from "@/api/exams";
9 import { postExamQuestionFromBank } from "@/api/exams";8 import { postExamQuestionFromBank } from "@/api/exams";
9+import { postExamQuestionRefreshFromBank } from "@/api/exams";
10 import { postExamQuestionToBank } from "@/api/exams";10 import { postExamQuestionToBank } from "@/api/exams";
11 import { patchExamQuestionById } from "@/api/exams";11 import { patchExamQuestionById } from "@/api/exams";
12 import { postExamChoiceImage } from "@/api/exams";12 import { postExamChoiceImage } from "@/api/exams";
@@ -21,9 +21,8 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
21 import { FormDialog } from "@/components/ui/form-dialog";21 import { FormDialog } from "@/components/ui/form-dialog";
22 import { BankQuestionPicker } from "@/components/exams/bank-question-picker";22 import { BankQuestionPicker } from "@/components/exams/bank-question-picker";
23 import { QuestionForm, type QuestionValues } from "@/components/exams/question-form";23 import { QuestionForm, type QuestionValues } from "@/components/exams/question-form";
24-import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons";24+import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconRefresh, IconTrash } from "@/components/ui/icons";
25 import { PageSpinner } from "@/components/ui/page-spinner";25 import { PageSpinner } from "@/components/ui/page-spinner";
26-import { planChoiceImageRestore } from "@/lib/choice-compaction";
27 import { createFlash } from "@/lib/flash";26 import { createFlash } from "@/lib/flash";
28 import { hasMinRole } from "@/lib/roles";27 import { hasMinRole } from "@/lib/roles";
29 import { useAuth } from "@/stores/auth-context";28 import { useAuth } from "@/stores/auth-context";
@@ -57,8 +56,10 @@ export function ExamQuestionsPanel(props: {
57 const [editing, setEditing] = createSignal<ExamQuestion | null>(null);56 const [editing, setEditing] = createSignal<ExamQuestion | null>(null);
58 const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null);57 const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null);
59 const [confirmBank, setConfirmBank] = createSignal<ExamQuestion | null>(null);58 const [confirmBank, setConfirmBank] = createSignal<ExamQuestion | null>(null);
60- // Older backends never write `source_bank` back onto the exam question after a59+ const [confirmRefresh, setConfirmRefresh] = createSignal<ExamQuestion | null>(null);
61- // to-bank save, so remember what this session banked and treat both as "banked".60+ // The `banked_as` back-link only shows up after the refetch (and older backends
61+ // never write it at all), so remember what this session banked and treat both
62+ // as saved.
62 const [bankedIds, setBankedIds] = createSignal<string[]>([]);63 const [bankedIds, setBankedIds] = createSignal<string[]>([]);
63 const [error, setError] = createSignal("");64 const [error, setError] = createSignal("");
64 const [imagePending, setImagePending] = createSignal("");65 const [imagePending, setImagePending] = createSignal("");
@@ -77,7 +78,11 @@ export function ExamQuestionsPanel(props: {
77 // `.latest` — a bare read there re-suspends on every refetch (insert-from-bank,78 // `.latest` — a bare read there re-suspends on every refetch (insert-from-bank,
78 // save, delete) and blanks the surrounding page for the whole fetch.79 // save, delete) and blanks the surrounding page for the whole fetch.
79 const questionCount = () => questions.latest?.length ?? 0;80 const questionCount = () => questions.latest?.length ?? 0;
80- const isBanked = (question: ExamQuestion) => Boolean(question.source_bank) || bankedIds().includes(question.id);81+ // Two separate links, never conflated: `banked_as` is set only by a save to the
82+ // bank, `from_bank` only by an insert out of it. A question added from the bank
83+ // has not been saved to it, so it must not offer "save another copy".
84+ const isSavedToBank = (question: ExamQuestion) => Boolean(question.banked_as) || bankedIds().includes(question.id);
85+ const isFromBank = (question: ExamQuestion) => Boolean(question.from_bank);
81 const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId;86 const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId;
82 const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE)));87 const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE)));
83 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));88 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
@@ -103,43 +108,17 @@ export function ExamQuestionsPanel(props: {
103 try {108 try {
104 const q = editing();109 const q = editing();
105 const isNewQuestion = !q;110 const isNewQuestion = !q;
106- // choice_sources is form-only bookkeeping — never send it to the backend.111+ const { image, choice_images, ...body } = values;
107- const { image, choice_images, choice_sources, ...body } = values;
108-
109- // A PATCH carrying `choices` wipes every stored option image, so pull the
110- // ones the user kept first and put them back under their new indices.
111- const lost: number[] = [];
112- const keep: { index: number; file: File }[] = [];
113- if (q && body.kind === "choice") {
114- for (const slot of planChoiceImageRestore(choice_sources ?? [], q.choice_images ?? [], choice_images)) {
115- try {
116- const blob = await getExamChoiceImageBlob(props.examId, q.id, slot.source);
117- keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) });
118- } catch {
119- lost.push(slot.index); // the write below drops it either way — report it
120- }
121- }
122- }
123 112
124 const saved = q113 const saved = q
125 ? await patchExamQuestionById(props.examId, q.id, body)114 ? await patchExamQuestionById(props.examId, q.id, body)
126 : await postExamQuestion(props.examId, body);115 : await postExamQuestion(props.examId, body);
127 if (image) await postExamQuestionImage(props.examId, saved.id, image);116 if (image) await postExamQuestionImage(props.examId, saved.id, image);
117+ // The saved choices come back in the submitted order, so the freshly picked
118+ // files line up with them — and every untouched option kept its own picture.
128 for (const [index, file] of (choice_images ?? []).entries()) {119 for (const [index, file] of (choice_images ?? []).entries()) {
129- if (file) await postExamChoiceImage(props.examId, saved.id, index, file);120+ const choiceId = saved.choices?.[index]?.id;
130- }121+ if (file && choiceId) await postExamChoiceImage(props.examId, saved.id, choiceId, file);
131- // Independent uploads: one failure must not strand the remaining images.
132- for (const slot of keep) {
133- try {
134- await postExamChoiceImage(props.examId, saved.id, slot.index, slot.file);
135- } catch {
136- lost.push(slot.index);
137- }
138- }
139- if (lost.length > 0) {
140- setError(t("questions.imagesLost", {
141- options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", "),
142- }));
143 }122 }
144 if (q) {123 if (q) {
145 setFlash(t("common.saved"));124 setFlash(t("common.saved"));
@@ -178,6 +157,24 @@ export function ExamQuestionsPanel(props: {
178 }157 }
179 };158 };
180 159
160+ // Re-copy the template over this question. Offered only while `from_bank` is
161+ // set: the bank delete cascade clears it, so a template that is gone takes the
162+ // action with it rather than leaving a button that can only fail.
163+ const refreshFromBank = async (question: ExamQuestion) => {
164+ if (banking()) return;
165+ setError("");
166+ setBanking(question.id);
167+ try {
168+ await postExamQuestionRefreshFromBank(props.examId, question.id);
169+ setFlash(t("bank.refreshed"));
170+ await refetch();
171+ } catch (err) {
172+ setError(formatApiError(err));
173+ } finally {
174+ setBanking("");
175+ }
176+ };
177+
181 const removeQuestionImage = async (question: ExamQuestion) => {178 const removeQuestionImage = async (question: ExamQuestion) => {
182 if (props.readOnly) return;179 if (props.readOnly) return;
183 setError("");180 setError("");
@@ -193,12 +190,12 @@ export function ExamQuestionsPanel(props: {
193 }190 }
194 };191 };
195 192
196- const removeChoiceImage = async (question: ExamQuestion, index: number) => {193+ const removeChoiceImage = async (question: ExamQuestion, choiceId: string) => {
197 if (props.readOnly) return;194 if (props.readOnly) return;
198 setError("");195 setError("");
199- setImagePending(`${question.id}:choice:${index}`);196+ setImagePending(`${question.id}:choice:${choiceId}`);
200 try {197 try {
201- await deleteExamChoiceImage(props.examId, question.id, index);198+ await deleteExamChoiceImage(props.examId, question.id, choiceId);
202 await refetch();199 await refetch();
203 setFlash(t("common.deleted"));200 setFlash(t("common.deleted"));
204 } catch (err) {201 } catch (err) {
@@ -279,8 +276,9 @@ export function ExamQuestionsPanel(props: {
279 <QuestionForm276 <QuestionForm
280 initial={formInitial()}277 initial={formInitial()}
281 subjects={subjects() ?? []}278 subjects={subjects() ?? []}
279+ subjectsPending={subjects.loading}
282 imageSrc={editing() ? `/api/exams/${props.examId}/questions/${editing()!.id}/image` : undefined}280 imageSrc={editing() ? `/api/exams/${props.examId}/questions/${editing()!.id}/image` : undefined}
283- choiceImageSrc={(index) => `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${index}/image`}281+ choiceImageSrc={(choiceId) => `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${choiceId}/image`}
284 loadImageBlob={editing() ? () => getExamQuestionImageBlob(props.examId, editing()!.id) : undefined}282 loadImageBlob={editing() ? () => getExamQuestionImageBlob(props.examId, editing()!.id) : undefined}
285 onCancel={() => {283 onCancel={() => {
286 setEditing(null);284 setEditing(null);
@@ -334,12 +332,18 @@ export function ExamQuestionsPanel(props: {
334 <Badge variant="outline" class="font-mono">332 <Badge variant="outline" class="font-mono">
335 {q.points} {t("questions.points")}333 {q.points} {t("questions.points")}
336 </Badge>334 </Badge>
337- {/* `source_bank` is set in both directions (inserted from the335+ {/* One badge per direction: a question can be both (added
338- bank, or saved to it), so the badge stays origin-neutral. */}336+ from the bank, then saved back), so they stack. */}
339- <Show when={isBanked(q)}>337+ <Show when={isFromBank(q)}>
338+ <Badge variant="outline" class="gap-1 border-sky-500/40 text-sky-700 dark:text-sky-400">
339+ <IconArchive class="h-3 w-3" />
340+ {t("bank.fromBankBadge")}
341+ </Badge>
342+ </Show>
343+ <Show when={isSavedToBank(q)}>
340 <Badge variant="outline" class="gap-1 border-amber-500/40 text-amber-700 dark:text-amber-400">344 <Badge variant="outline" class="gap-1 border-amber-500/40 text-amber-700 dark:text-amber-400">
341 <IconArchive class="h-3 w-3" />345 <IconArchive class="h-3 w-3" />
342- {t("bank.inBankBadge")}346+ {t("bank.savedToBankBadge")}
343 </Badge>347 </Badge>
344 </Show>348 </Show>
345 </div>349 </div>
@@ -369,7 +373,7 @@ export function ExamQuestionsPanel(props: {
369 {(choice, choiceIndex) => (373 {(choice, choiceIndex) => (
370 <li374 <li
371 class={375 class={
372- choiceIndex() === q.correct376+ choice.id === q.correct
373 ? "flex items-start gap-3 rounded-md border border-primary/30 bg-primary/10 px-3 py-2 font-medium text-foreground"377 ? "flex items-start gap-3 rounded-md border border-primary/30 bg-primary/10 px-3 py-2 font-medium text-foreground"
374 : "flex items-start gap-3 rounded-md border border-transparent bg-muted/30 px-3 py-2 text-muted-foreground"378 : "flex items-start gap-3 rounded-md border border-transparent bg-muted/30 px-3 py-2 text-muted-foreground"
375 }379 }
@@ -378,10 +382,10 @@ export function ExamQuestionsPanel(props: {
378 {String.fromCharCode(65 + choiceIndex())}382 {String.fromCharCode(65 + choiceIndex())}
379 </span>383 </span>
380 <span class="min-w-0 flex-1 space-y-2 whitespace-pre-wrap">384 <span class="min-w-0 flex-1 space-y-2 whitespace-pre-wrap">
381- <span class="block">{choice}</span>385+ <span class="block">{choice.text}</span>
382 <Show when={q.choice_images?.[choiceIndex()]}>386 <Show when={q.choice_images?.[choiceIndex()]}>
383 <img387 <img
384- src={`/api/exams/${props.examId}/questions/${q.id}/choices/${choiceIndex()}/image`}388+ src={`/api/exams/${props.examId}/questions/${q.id}/choices/${choice.id}/image`}
385 alt={t("questions.choiceImage")}389 alt={t("questions.choiceImage")}
386 class="h-32 w-full max-w-md rounded-md border bg-background object-contain"390 class="h-32 w-full max-w-md rounded-md border bg-background object-contain"
387 />391 />
@@ -392,8 +396,8 @@ export function ExamQuestionsPanel(props: {
392 variant="ghost"396 variant="ghost"
393 size="sm"397 size="sm"
394 class="h-7 px-2 text-xs text-destructive"398 class="h-7 px-2 text-xs text-destructive"
395- disabled={imagePending() === `${q.id}:choice:${choiceIndex()}`}399+ disabled={imagePending() === `${q.id}:choice:${choice.id}`}
396- onClick={() => void removeChoiceImage(q, choiceIndex())}400+ onClick={() => void removeChoiceImage(q, choice.id)}
397 >401 >
398 {t("common.delete")}402 {t("common.delete")}
399 </Button>403 </Button>
@@ -416,10 +420,27 @@ export function ExamQuestionsPanel(props: {
416 size="sm"420 size="sm"
417 class="h-8 gap-1.5 px-2.5 text-xs"421 class="h-8 gap-1.5 px-2.5 text-xs"
418 disabled={banking() === q.id}422 disabled={banking() === q.id}
419- onClick={() => (isBanked(q) ? setConfirmBank(q) : void saveToBank(q))}423+ onClick={() => (isSavedToBank(q) ? setConfirmBank(q) : void saveToBank(q))}
420 >424 >
421 <IconArchive class="h-3.5 w-3.5" />425 <IconArchive class="h-3.5 w-3.5" />
422- {isBanked(q) ? t("bank.saveCopyToBank") : t("bank.saveToBank")}426+ {isSavedToBank(q) ? t("bank.saveCopyToBank") : t("bank.saveToBank")}
427+ </Button>
428+ </Show>
429+ {/* Only while the question still points at a live
430+ template: the bank delete cascade clears
431+ `from_bank`, and the exam-side freeze is what
432+ `readOnly` already reflects. */}
433+ <Show when={!props.readOnly && isFromBank(q)}>
434+ <Button
435+ type="button"
436+ variant="outline"
437+ size="sm"
438+ class="h-8 gap-1.5 px-2.5 text-xs"
439+ disabled={banking() === q.id}
440+ onClick={() => setConfirmRefresh(q)}
441+ >
442+ <IconRefresh class="h-3.5 w-3.5" />
443+ {t("bank.refresh")}
423 </Button>444 </Button>
424 </Show>445 </Show>
425 <Show when={!props.readOnly}>446 <Show when={!props.readOnly}>
@@ -501,6 +522,24 @@ export function ExamQuestionsPanel(props: {
501 }}522 }}
502 />523 />
503 524
525+ <ConfirmDialog
526+ open={confirmRefresh() != null}
527+ onOpenChange={(open) => {
528+ if (!open) setConfirmRefresh(null);
529+ }}
530+ title={t("bank.refreshTitle")}
531+ description={t("bank.refreshBody")}
532+ confirmLabel={t("bank.refreshConfirm")}
533+ icon={<IconRefresh class="h-4 w-4" />}
534+ summary={confirmRefresh()?.text ?? ""}
535+ onConfirm={async () => {
536+ const q = confirmRefresh();
537+ if (!q) return;
538+ setConfirmRefresh(null);
539+ await refreshFromBank(q);
540+ }}
541+ />
542+
504 <ConfirmDialog543 <ConfirmDialog
505 open={removeQuestion() != null}544 open={removeQuestion() != null}
506 onOpenChange={(open) => {545 onOpenChange={(open) => {
src/components/exams/exam-room-ws.tsxmodified+9 -13
@@ -256,19 +256,19 @@ export function ExamRoomWS(props: { exam: Exam }) {
256 if (ws && ws.readyState === WebSocket.OPEN) {256 if (ws && ws.readyState === WebSocket.OPEN) {
257 const payload: Record<string, unknown> = { type: "answer", question_id: question.id };257 const payload: Record<string, unknown> = { type: "answer", question_id: question.id };
258 if (question.kind === "choice") {258 if (question.kind === "choice") {
259- payload.selected = Number(value);259+ payload.selected = value; // choice id, not a position
260 } else {260 } else {
261 payload.text = value;261 payload.text = value;
262 }262 }
263 sendWs(payload);263 sendWs(payload);
264 setQuestions((prev) =>264 setQuestions((prev) =>
265- prev.map((q) => (q.id === question.id ? { ...q, answer: { ...q.answer, selected: question.kind === "choice" ? Number(value) : undefined, text: question.kind === "text" ? value : undefined } } : q)),265+ prev.map((q) => (q.id === question.id ? { ...q, answer: { ...q.answer, selected: question.kind === "choice" ? value : undefined, text: question.kind === "text" ? value : undefined } } : q)),
266 );266 );
267 } else {267 } else {
268 setPending(true);268 setPending(true);
269 try {269 try {
270 if (question.kind === "choice") {270 if (question.kind === "choice") {
271- await postExamAttemptAnswer(props.exam.id, { question_id: question.id, selected: Number(value) });271+ await postExamAttemptAnswer(props.exam.id, { question_id: question.id, selected: value });
272 } else {272 } else {
273 await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value });273 await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value });
274 }274 }
@@ -682,9 +682,7 @@ function QuestionAnswerCardWS(props: {
682 const { locale } = usePreferences();682 const { locale } = usePreferences();
683 const [value, setValue] = createSignal(683 const [value, setValue] = createSignal(
684 props.question.kind === "choice"684 props.question.kind === "choice"
685- ? props.question.answer?.selected != null685+ ? props.question.answer?.selected ?? ""
686- ? String(props.question.answer.selected)
687- : ""
688 : props.question.answer?.text ?? "",686 : props.question.answer?.text ?? "",
689 );687 );
690 const [saved, setSaved] = createSignal(false);688 const [saved, setSaved] = createSignal(false);
@@ -698,9 +696,7 @@ function QuestionAnswerCardWS(props: {
698 questionId = props.question.id;696 questionId = props.question.id;
699 setValue(697 setValue(
700 props.question.kind === "choice"698 props.question.kind === "choice"
701- ? props.question.answer?.selected != null699+ ? props.question.answer?.selected ?? ""
702- ? String(props.question.answer.selected)
703- : ""
704 : props.question.answer?.text ?? "",700 : props.question.answer?.text ?? "",
705 );701 );
706 setSaved(false);702 setSaved(false);
@@ -838,17 +834,17 @@ function QuestionAnswerCardWS(props: {
838 disabled={props.disabled}834 disabled={props.disabled}
839 onClick={() => {835 onClick={() => {
840 setSaved(false);836 setSaved(false);
841- setValue(String(choiceIndex()));837+ setValue(choice.id);
842 }}838 }}
843 >839 >
844- <span class={value() === String(choiceIndex()) ? "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-primary bg-primary text-xs font-semibold text-primary-foreground" : "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-input bg-background text-xs font-semibold text-foreground"}>840+ <span class={value() === choice.id ? "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-primary bg-primary text-xs font-semibold text-primary-foreground" : "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-input bg-background text-xs font-semibold text-foreground"}>
845 {String.fromCharCode(65 + choiceIndex())}841 {String.fromCharCode(65 + choiceIndex())}
846 </span>842 </span>
847 <span class="min-w-0 space-y-2">843 <span class="min-w-0 space-y-2">
848- <span class="block whitespace-pre-wrap">{choice}</span>844+ <span class="block whitespace-pre-wrap">{choice.text}</span>
849 <Show when={props.question.choice_images?.[choiceIndex()]}>845 <Show when={props.question.choice_images?.[choiceIndex()]}>
850 <img846 <img
851- src={`/api/exams/${props.question.exam}/questions/${props.question.id}/choices/${choiceIndex()}/image`}847+ src={`/api/exams/${props.question.exam}/questions/${props.question.id}/choices/${choice.id}/image`}
852 alt={t("questions.choiceImage")}848 alt={t("questions.choiceImage")}
853 class="h-36 w-full max-w-md rounded-md border bg-muted/20 object-contain"849 class="h-36 w-full max-w-md rounded-md border bg-muted/20 object-contain"
854 />850 />
src/components/exams/question-form.tsxmodified+89 -85
@@ -1,6 +1,6 @@
1 import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy, untrack } from "solid-js";1 import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy, untrack } from "solid-js";
2 import { formatApiError } from "@/api/client";2 import { formatApiError } from "@/api/client";
3-import type { ImageMeta, QuestionKind, Subject } from "@/api/client";3+import type { Choice, ImageMeta, QuestionKind, Subject } from "@/api/client";
4 import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client";4 import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client";
5 import { getSettings } from "@/api/settings";5 import { getSettings } from "@/api/settings";
6 import type { DrawScene } from "@/lib/draw-stroke";6 import type { DrawScene } from "@/lib/draw-stroke";
@@ -10,7 +10,17 @@ import { Input } from "@/components/ui/input";
10 import { Label } from "@/components/ui/label";10 import { Label } from "@/components/ui/label";
11 import { Select } from "@/components/ui/select";11 import { Select } from "@/components/ui/select";
12 import { Textarea } from "@/components/ui/textarea";12 import { Textarea } from "@/components/ui/textarea";
13-import { compactChoices } from "@/lib/choice-compaction";13+import {
14+ addChoice as addChoiceRow,
15+ blankChoiceSet,
16+ removeChoice as removeChoiceRow,
17+ setChoiceImage as setChoiceImageIn,
18+ setChoiceText,
19+ setCorrect as setCorrectIn,
20+ storedChoiceSet,
21+ submitChoices,
22+ type ChoiceSet,
23+} from "@/lib/choice-set";
14 import { cn } from "@/lib/cn";24 import { cn } from "@/lib/cn";
15 import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";25 import { formatBytes, maxUploadBytes } from "@/lib/upload-limits";
16 import { useT } from "@/stores/preferences-context";26 import { useT } from "@/stores/preferences-context";
@@ -23,26 +33,24 @@ export type QuestionValues = {
23 text: string;33 text: string;
24 kind: QuestionKind;34 kind: QuestionKind;
25 points: number;35 points: number;
26- choices: string[] | null;36+ /** Each row keeps its key: a stored id keeps that option, a `new:` id is a new one. */
27- correct: number | null;37+ choices: Choice[] | null;
38+ /** Choice id, never an index. */
39+ correct: string | null;
28 image: File | null;40 image: File | null;
41+ /** Freshly picked files, aligned to `choices`. */
29 choice_images: (File | null)[] | null;42 choice_images: (File | null)[] | null;
30- /**
31- * For each surviving choice, the index it had in `initial.choices` (or -1 when
32- * it was added in this edit). Blank choices are dropped on submit, so callers
33- * that must re-attach per-choice server state need this old→new map.
34- */
35- choice_sources: number[] | null;
36 };43 };
37 44
38 /** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */45 /** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */
39 export type QuestionFormInitial = {46 export type QuestionFormInitial = {
40- subject: string;47+ /** Null for a bank template whose origin subject has since been deleted. */
48+ subject: string | null;
41 text: string;49 text: string;
42 kind: QuestionKind;50 kind: QuestionKind;
43 points: number;51 points: number;
44- choices: string[] | null;52+ choices: Choice[] | null;
45- correct: number | null;53+ correct: string | null;
46 image?: ImageMeta | null;54 image?: ImageMeta | null;
47 choice_images?: (ImageMeta | null)[] | null;55 choice_images?: (ImageMeta | null)[] | null;
48 };56 };
@@ -50,9 +58,11 @@ export type QuestionFormInitial = {
50 export function QuestionForm(props: {58 export function QuestionForm(props: {
51 initial?: QuestionFormInitial;59 initial?: QuestionFormInitial;
52 subjects: Subject[];60 subjects: Subject[];
61+ /** True while `subjects` is still loading, so a missing subject is not misreported. */
62+ subjectsPending?: boolean;
53 /** Existing stored image, as a URL the browser can GET (exam or bank path). */63 /** Existing stored image, as a URL the browser can GET (exam or bank path). */
54 imageSrc?: string;64 imageSrc?: string;
55- choiceImageSrc?: (index: number) => string;65+ choiceImageSrc?: (choiceId: string) => string;
56 /** Reload the stored image so an existing drawing can be edited, not redrawn. */66 /** Reload the stored image so an existing drawing can be edited, not redrawn. */
57 loadImageBlob?: () => Promise<Blob>;67 loadImageBlob?: () => Promise<Blob>;
58 submitLabel?: string;68 submitLabel?: string;
@@ -62,18 +72,16 @@ export function QuestionForm(props: {
62 const t = useT();72 const t = useT();
63 let textAreaRef: HTMLTextAreaElement | undefined;73 let textAreaRef: HTMLTextAreaElement | undefined;
64 const [text, setText] = createSignal(props.initial?.text ?? "");74 const [text, setText] = createSignal(props.initial?.text ?? "");
65- const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? props.subjects[0]?.id ?? "");75+ // No first-subject default: the subject is submitted, so the user picks it.
76+ const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? "");
66 const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? "choice");77 const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? "choice");
67 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));78 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));
68- const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]);79+ const [choiceSet, setChoiceSet] = createSignal<ChoiceSet>(
69- const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0);80+ props.initial ? storedChoiceSet(props.initial.choices, props.initial.correct) : blankChoiceSet(),
81+ );
70 const [image, setImage] = createSignal<File | null>(null);82 const [image, setImage] = createSignal<File | null>(null);
71 const [drawing, setDrawing] = createSignal(false);83 const [drawing, setDrawing] = createSignal(false);
72 const [editScene, setEditScene] = createSignal<DrawScene | null>(null);84 const [editScene, setEditScene] = createSignal<DrawScene | null>(null);
73- const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null));
74- // Index each row still holds in `initial.choices` (-1 once added here), so a
75- // caller can map surviving choices back to the server-side option they came from.
76- const [choiceSources, setChoiceSources] = createSignal<number[]>(choices().map((_, index) => index));
77 const [error, setError] = createSignal("");85 const [error, setError] = createSignal("");
78 const [pending, setPending] = createSignal(false);86 const [pending, setPending] = createSignal(false);
79 const [settings] = createResource(async () => {87 const [settings] = createResource(async () => {
@@ -91,24 +99,28 @@ export function QuestionForm(props: {
91 const initial = props.initial;99 const initial = props.initial;
92 untrack(() => {100 untrack(() => {
93 setText(initial?.text ?? "");101 setText(initial?.text ?? "");
94- setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? "");102+ setSubjectId(initial?.subject ?? "");
95 setKind(initial?.kind ?? "choice");103 setKind(initial?.kind ?? "choice");
96 setPoints(String(initial?.points ?? 1));104 setPoints(String(initial?.points ?? 1));
97- setChoices(initial?.choices ?? ["", "", "", ""]);105+ setChoiceSet(initial ? storedChoiceSet(initial.choices, initial.correct) : blankChoiceSet());
98- setCorrect(initial?.correct ?? 0);
99 setImage(null);106 setImage(null);
100 setDrawing(false);107 setDrawing(false);
101 setEditScene(null);108 setEditScene(null);
102- setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null));
103- setChoiceSources((initial?.choices ?? ["", "", "", ""]).map((_, index) => (initial ? index : -1)));
104 setError("");109 setError("");
105 });110 });
106 });111 });
107 112
108- // Once subjects load, preselect the first one if nothing is chosen yet.113+ // The stored subject is not in the list this user can pick from (foreign course,
109- createEffect(() => {114+ // or they lost access to it). Never swap it silently — show it, and make them pick.
110- if (!subjectId()) setSubjectId(props.subjects[0]?.id ?? "");115+ const subjectUnavailable = () => {
111- });116+ const current = props.initial?.subject;
117+ return (
118+ !!current &&
119+ !props.subjectsPending &&
120+ subjectId() === current &&
121+ !props.subjects.some((subject) => subject.id === current)
122+ );
123+ };
112 124
113 // Blank pad for a fresh drawing; reload the stored scene to edit an existing one.125 // Blank pad for a fresh drawing; reload the stored scene to edit an existing one.
114 const startDrawing = () => {126 const startDrawing = () => {
@@ -142,8 +154,12 @@ export function QuestionForm(props: {
142 resizeTextArea();154 resizeTextArea();
143 });155 });
144 156
145- const setChoice = (index: number, value: string) => {157+ const rows = () => choiceSet().rows;
146- setChoices((current) => current.map((choice, i) => (i === index ? value : choice)));158+ // Stored option images arrive as an array aligned to `initial.choices`, so look
159+ // one up by the row's id — the row's display position may have moved.
160+ const storedImage = (id: string) => {
161+ const index = props.initial?.choices?.findIndex((choice) => choice.id === id) ?? -1;
162+ return index >= 0 ? props.initial?.choice_images?.[index] ?? null : null;
147 };163 };
148 164
149 const validImage = (file: File | null): file is File => {165 const validImage = (file: File | null): file is File => {
@@ -162,68 +178,51 @@ export function QuestionForm(props: {
162 if (validImage(file)) setImage(file);178 if (validImage(file)) setImage(file);
163 };179 };
164 180
165- const setChoiceImage = (index: number, file: File | null) => {181+ const addChoice = () => setChoiceSet((set) => addChoiceRow(set, BANK_QUESTION_LIMITS.maxChoices));
182+ const removeChoice = (id: string) => setChoiceSet((set) => removeChoiceRow(set, id));
183+ const setChoice = (id: string, value: string) => setChoiceSet((set) => setChoiceText(set, id, value));
184+ const setCorrect = (id: string) => setChoiceSet((set) => setCorrectIn(set, id));
185+
186+ const setChoiceImage = (id: string, file: File | null) => {
166 if (file) {187 if (file) {
167 setError("");188 setError("");
168 if (!validImage(file)) return;189 if (!validImage(file)) return;
169 }190 }
170- setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null)));191+ setChoiceSet((set) => setChoiceImageIn(set, id, file));
171- };
172-
173- const addChoice = () => {
174- const max = BANK_QUESTION_LIMITS.maxChoices;
175- setChoices((current) => (current.length >= max ? current : [...current, ""]));
176- setChoiceImages((current) => (current.length >= max ? current : [...current, null]));
177- setChoiceSources((current) => (current.length >= max ? current : [...current, -1]));
178- };
179-
180- const removeChoice = (index: number) => {
181- const remaining = choices().length - 1;
182- setChoices((current) => current.filter((_, i) => i !== index));
183- setChoiceImages((current) => current.filter((_, i) => i !== index));
184- setChoiceSources((current) => current.filter((_, i) => i !== index));
185- // Deleting a row above the answer shifts it down; deleting the answer row
186- // itself moves the mark to the row that took its place (visible in the UI).
187- setCorrect((current) => {
188- if (index < current) return Math.max(0, current - 1);
189- if (index > current) return current;
190- return Math.max(0, Math.min(current, remaining - 1));
191- });
192 };192 };
193 193
194 const validate = (): QuestionValues | string => {194 const validate = (): QuestionValues | string => {
195 const body = text().trim();195 const body = text().trim();
196 const subject = subjectId().trim();196 const subject = subjectId().trim();
197 if (!subject) return t("questions.subjectRequired");197 if (!subject) return t("questions.subjectRequired");
198+ if (subjectUnavailable()) return t("questions.subjectUnavailableHelp");
198 if (!body) return t("questions.textRequired");199 if (!body) return t("questions.textRequired");
199 if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax");200 if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax");
200 const p = Number(points());201 const p = Number(points());
201 if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange");202 if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange");
202 if (kind() === "text") {203 if (kind() === "text") {
203- return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null, choice_sources: null };204+ return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null };
204 }205 }
205- const compacted = compactChoices(choices(), choiceImages(), choiceSources(), correct());206+ const submitted = submitChoices(choiceSet());
206- const cleanChoices = compacted.choices;
207 if (207 if (
208- cleanChoices.length < BANK_QUESTION_LIMITS.minChoices ||208+ submitted.choices.length < BANK_QUESTION_LIMITS.minChoices ||
209- cleanChoices.length > BANK_QUESTION_LIMITS.maxChoices ||209+ submitted.choices.length > BANK_QUESTION_LIMITS.maxChoices ||
210- cleanChoices.some((choice) => choice.length > BANK_QUESTION_LIMITS.choiceTextMaxLen)210+ submitted.choices.some((choice) => choice.text.length > BANK_QUESTION_LIMITS.choiceTextMaxLen)
211 ) {211 ) {
212 return t("questions.choicesRange");212 return t("questions.choicesRange");
213 }213 }
214- // The marked row survived compaction as `compacted.correct`; -1 means the user214+ // Nothing is marked for the user: either they never picked, or they blanked
215- // blanked the very choice they had marked, so make them pick again.215+ // the row they had picked. Both end here, and both need a deliberate pick.
216- if (compacted.correct < 0) return t("questions.correctBlanked");216+ if (!submitted.correct) return t("questions.correctRequired");
217 return {217 return {
218 subject_id: subject,218 subject_id: subject,
219 text: body,219 text: body,
220 kind: "choice",220 kind: "choice",
221 points: p,221 points: p,
222- choices: cleanChoices,222+ choices: submitted.choices,
223- correct: compacted.correct,223+ correct: submitted.correct,
224 image: image(),224 image: image(),
225- choice_images: compacted.images,225+ choice_images: submitted.images,
226- choice_sources: compacted.sources,
227 };226 };
228 };227 };
229 228
@@ -332,8 +331,14 @@ export function QuestionForm(props: {
332 <Label for="question-subject" class="mb-1 block text-xs font-semibold text-muted-foreground">{t("subjects.subject")}</Label>331 <Label for="question-subject" class="mb-1 block text-xs font-semibold text-muted-foreground">{t("subjects.subject")}</Label>
333 <Select id="question-subject" class="h-9 py-1.5 text-sm" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>332 <Select id="question-subject" class="h-9 py-1.5 text-sm" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>
334 <option value="">{t("subjects.select")}</option>333 <option value="">{t("subjects.select")}</option>
334+ <Show when={subjectUnavailable()}>
335+ <option value={props.initial?.subject ?? ""} disabled>{t("questions.subjectUnavailable")}</option>
336+ </Show>
335 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>337 <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>
336 </Select>338 </Select>
339+ <Show when={subjectUnavailable()}>
340+ <p class="mt-1 text-[11px] text-destructive">{t("questions.subjectUnavailableHelp")}</p>
341+ </Show>
337 </div>342 </div>
338 <div>343 <div>
339 <Label class="mb-1 block text-xs font-semibold text-muted-foreground">{t("questions.kind")}</Label>344 <Label class="mb-1 block text-xs font-semibold text-muted-foreground">{t("questions.kind")}</Label>
@@ -375,19 +380,18 @@ export function QuestionForm(props: {
375 <div class="rounded-lg border bg-card p-3.5 shadow-xs">380 <div class="rounded-lg border bg-card p-3.5 shadow-xs">
376 <div class="mb-3 flex items-center justify-between gap-2 border-b border-border/50 pb-2">381 <div class="mb-3 flex items-center justify-between gap-2 border-b border-border/50 pb-2">
377 <Label class="text-sm font-semibold">{t("questions.choices")}</Label>382 <Label class="text-sm font-semibold">{t("questions.choices")}</Label>
378- <Button type="button" variant="outline" size="sm" class="h-7 gap-1 text-xs" disabled={choices().length >= 10} onClick={addChoice}>383+ <Button type="button" variant="outline" size="sm" class="h-7 gap-1 text-xs" disabled={rows().length >= BANK_QUESTION_LIMITS.maxChoices} onClick={addChoice}>
379 <IconPlus class="h-3.5 w-3.5" />384 <IconPlus class="h-3.5 w-3.5" />
380 {t("questions.addChoice")}385 {t("questions.addChoice")}
381 </Button>386 </Button>
382 </div>387 </div>
383 <div class="space-y-2">388 <div class="space-y-2">
384- <Index each={choices()}>389+ <Index each={rows()}>
385- {(choice, index) => {390+ {(row, index) => {
386- const isCorrect = () => correct() === index;391+ const isCorrect = () => choiceSet().correct === row().id;
387- // Stored images are keyed by the option's ORIGINAL index, which drifts392+ // Keyed by the row's own id, so a stored option keeps its picture no
388- // from the display row once a choice is removed; -1 = added just now.393+ // matter where it sits now; null = a row the server has never seen.
389- const storedIndex = () => choiceSources()[index] ?? -1;394+ const stored = () => storedImage(row().id);
390- const storedImage = () => (storedIndex() >= 0 ? props.initial?.choice_images?.[storedIndex()] : null);
391 return (395 return (
392 <div396 <div
393 class={cn(397 class={cn(
@@ -403,7 +407,7 @@ export function QuestionForm(props: {
403 ? "bg-emerald-600 text-white shadow-2xs"407 ? "bg-emerald-600 text-white shadow-2xs"
404 : "border bg-background text-muted-foreground hover:border-emerald-400 hover:text-emerald-600",408 : "border bg-background text-muted-foreground hover:border-emerald-400 hover:text-emerald-600",
405 )}409 )}
406- onClick={() => setCorrect(index)}410+ onClick={() => setCorrect(row().id)}
407 title={t("questions.correct")}411 title={t("questions.correct")}
408 >412 >
409 {isCorrect() ? <IconCheck class="h-3.5 w-3.5" /> : String.fromCharCode(65 + index)}413 {isCorrect() ? <IconCheck class="h-3.5 w-3.5" /> : String.fromCharCode(65 + index)}
@@ -411,10 +415,10 @@ export function QuestionForm(props: {
411 <div class="min-w-0 flex-1 space-y-1.5">415 <div class="min-w-0 flex-1 space-y-1.5">
412 <Input416 <Input
413 class="h-8 text-sm"417 class="h-8 text-sm"
414- value={choice()}418+ value={row().text}
415 maxlength={500}419 maxlength={500}
416 placeholder={t("questions.choicePlaceholder", { index: String.fromCharCode(65 + index) })}420 placeholder={t("questions.choicePlaceholder", { index: String.fromCharCode(65 + index) })}
417- onInput={(e) => setChoice(index, e.currentTarget.value)}421+ onInput={(e) => setChoice(row().id, e.currentTarget.value)}
418 />422 />
419 <div class="flex items-center gap-2">423 <div class="flex items-center gap-2">
420 <input424 <input
@@ -422,15 +426,15 @@ export function QuestionForm(props: {
422 type="file"426 type="file"
423 accept="image/png,image/jpeg,image/webp,image/gif"427 accept="image/png,image/jpeg,image/webp,image/gif"
424 class="sr-only"428 class="sr-only"
425- onChange={(event) => setChoiceImage(index, event.currentTarget.files?.[0] ?? null)}429+ onChange={(event) => setChoiceImage(row().id, event.currentTarget.files?.[0] ?? null)}
426 />430 />
427 <label for={`choice-image-${index}`} class="flex cursor-pointer items-center gap-1 rounded-md border border-dashed bg-muted/20 px-2 py-0.5 text-[10px] font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">431 <label for={`choice-image-${index}`} class="flex cursor-pointer items-center gap-1 rounded-md border border-dashed bg-muted/20 px-2 py-0.5 text-[10px] font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground">
428 <IconFileImage class="h-3 w-3" />432 <IconFileImage class="h-3 w-3" />
429- {choiceImages()[index]?.name ?? t("questions.choiceImage")}433+ {row().image?.name ?? t("questions.choiceImage")}
430 </label>434 </label>
431- <Show when={storedImage() && props.choiceImageSrc}>435+ <Show when={stored() && props.choiceImageSrc}>
432 <img436 <img
433- src={props.choiceImageSrc?.(storedIndex())}437+ src={props.choiceImageSrc?.(row().id)}
434 alt={t("questions.choiceImage")}438 alt={t("questions.choiceImage")}
435 class="h-8 w-12 rounded border bg-muted/20 object-contain"439 class="h-8 w-12 rounded border bg-muted/20 object-contain"
436 />440 />
@@ -441,9 +445,9 @@ export function QuestionForm(props: {
441 type="button"445 type="button"
442 variant="ghost"446 variant="ghost"
443 size="sm"447 size="sm"
444- disabled={choices().length <= 2}448+ disabled={rows().length <= BANK_QUESTION_LIMITS.minChoices}
445 class="mt-0.5 h-6 w-6 p-0 text-muted-foreground hover:text-destructive"449 class="mt-0.5 h-6 w-6 p-0 text-muted-foreground hover:text-destructive"
446- onClick={() => removeChoice(index)}450+ onClick={() => removeChoice(row().id)}
447 >451 >
448 <IconTrash class="h-3.5 w-3.5" />452 <IconTrash class="h-3.5 w-3.5" />
449 </Button>453 </Button>
src/i18n/messages.tsmodified+81 -18
@@ -428,12 +428,13 @@ export type MessageKey =
428 | "questions.editDrawing"428 | "questions.editDrawing"
429 | "questions.choiceImage"429 | "questions.choiceImage"
430 | "questions.subjectRequired"430 | "questions.subjectRequired"
431+ | "questions.subjectUnavailable"
432+ | "questions.subjectUnavailableHelp"
431 | "questions.textRequired"433 | "questions.textRequired"
432 | "questions.pointsRange"434 | "questions.pointsRange"
433 | "questions.choicesRange"435 | "questions.choicesRange"
436+ | "questions.correctRequired"
434 | "questions.correctRange"437 | "questions.correctRange"
435- | "questions.correctBlanked"
436- | "questions.imagesLost"
437 | "bank.title"438 | "bank.title"
438 | "bank.subtitle"439 | "bank.subtitle"
439 | "bank.empty"440 | "bank.empty"
@@ -444,7 +445,9 @@ export type MessageKey =
444 | "bank.created"445 | "bank.created"
445 | "bank.copyNotice"446 | "bank.copyNotice"
446 | "bank.courseHint"447 | "bank.courseHint"
447- | "bank.choiceImagesWarning"448+ | "bank.courseSelect"
449+ | "bank.courseUnavailable"
450+ | "bank.targetSubjectHint"
448 | "bank.fromBank"451 | "bank.fromBank"
449 | "bank.pickTemplate"452 | "bank.pickTemplate"
450 | "bank.targetSubject"453 | "bank.targetSubject"
@@ -456,10 +459,28 @@ export type MessageKey =
456 | "bank.saveCopyBody"459 | "bank.saveCopyBody"
457 | "bank.saveCopyConfirm"460 | "bank.saveCopyConfirm"
458 | "bank.savedToBank"461 | "bank.savedToBank"
459- | "bank.inBankBadge"462+ | "bank.fromBankBadge"
463+ | "bank.savedToBankBadge"
460 | "bank.search"464 | "bank.search"
461 | "bank.pickerEmpty"465 | "bank.pickerEmpty"
462 | "bank.noSubjects"466 | "bank.noSubjects"
467+ | "bank.countTotal"
468+ | "bank.countShown"
469+ | "bank.whoCanSee"
470+ | "bank.onlyMe"
471+ | "bank.sharedWithSchool"
472+ | "bank.onlyMeHint"
473+ | "bank.sharedWithSchoolHint"
474+ | "bank.shareTitle"
475+ | "bank.shareBody"
476+ | "bank.shareConfirm"
477+ | "bank.startsPrivate"
478+ | "bank.usedInExams"
479+ | "bank.refresh"
480+ | "bank.refreshTitle"
481+ | "bank.refreshBody"
482+ | "bank.refreshConfirm"
483+ | "bank.refreshed"
463 | "subjects.title"484 | "subjects.title"
464 | "subjects.item"485 | "subjects.item"
465 | "subjects.subject"486 | "subjects.subject"
@@ -1416,12 +1437,13 @@ const en: Dict = {
1416 "questions.editDrawing": "Edit drawing",1437 "questions.editDrawing": "Edit drawing",
1417 "questions.choiceImage": "Choice image",1438 "questions.choiceImage": "Choice image",
1418 "questions.subjectRequired": "Select a subject for this question",1439 "questions.subjectRequired": "Select a subject for this question",
1440+ "questions.subjectUnavailable": "Current subject — no longer available to you",
1441+ "questions.subjectUnavailableHelp": "The subject saved on this question is not in the list you can pick from. Choose a subject from the list to save.",
1419 "questions.textRequired": "Question text is required",1442 "questions.textRequired": "Question text is required",
1420 "questions.pointsRange": "Points must be an integer from 1 to 100",1443 "questions.pointsRange": "Points must be an integer from 1 to 100",
1421 "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters",1444 "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters",
1445+ "questions.correctRequired": "Mark one choice as the correct answer before saving.",
1422 "questions.correctRange": "Correct index must point to one of the choices",1446 "questions.correctRange": "Correct index must point to one of the choices",
1423- "questions.correctBlanked": "The choice you marked correct is now empty. Type it back in, or mark another choice correct.",
1424- "questions.imagesLost": "Saved, but the image for choice {options} could not be carried over the edit. Add it again.",
1425 "bank.title": "Question bank",1447 "bank.title": "Question bank",
1426 "bank.subtitle": "Reusable question templates every teacher can use.",1448 "bank.subtitle": "Reusable question templates every teacher can use.",
1427 "bank.empty": "No templates yet.",1449 "bank.empty": "No templates yet.",
@@ -1431,8 +1453,10 @@ const en: Dict = {
1431 "bank.mine": "Mine",1453 "bank.mine": "Mine",
1432 "bank.created": "Created",1454 "bank.created": "Created",
1433 "bank.copyNotice": "Adding a template to an exam makes a copy. Editing the template later does not change questions already added.",1455 "bank.copyNotice": "Adding a template to an exam makes a copy. Editing the template later does not change questions already added.",
1456+ "bank.courseSelect": "Select course",
1457+ "bank.courseUnavailable": "Original course — not one of your courses",
1458+ "bank.targetSubjectHint": "Pick the subject this copy belongs to in this exam.",
1434 "bank.courseHint": "Templates are tagged with a subject, so pick the course that subject belongs to. The template stays usable in every course.",1459 "bank.courseHint": "Templates are tagged with a subject, so pick the course that subject belongs to. The template stays usable in every course.",
1435- "bank.choiceImagesWarning": "Changing the choices clears the choice images stored on the server. Images for choices you keep are uploaded again, and you will be told if any could not be carried over.",
1436 "bank.fromBank": "Add from bank",1460 "bank.fromBank": "Add from bank",
1437 "bank.pickTemplate": "Pick a template",1461 "bank.pickTemplate": "Pick a template",
1438 "bank.targetSubject": "Subject in this exam",1462 "bank.targetSubject": "Subject in this exam",
@@ -1441,13 +1465,31 @@ const en: Dict = {
1441 "bank.saveToBank": "Save to bank",1465 "bank.saveToBank": "Save to bank",
1442 "bank.saveCopyToBank": "Save another copy to bank",1466 "bank.saveCopyToBank": "Save another copy to bank",
1443 "bank.saveCopyTitle": "Save a second copy?",1467 "bank.saveCopyTitle": "Save a second copy?",
1444- "bank.saveCopyBody": "This question is already linked to a bank template. Saving creates a second, separate template instead of updating the existing one. The two copies are independent: editing one never changes the other.",1468+ "bank.saveCopyBody": "This question is already linked to a bank template. Saving creates a second, separate template instead of updating the existing one. The two copies are independent: editing one never changes the other. The new template is private: only you can see it until you choose to share it.",
1445 "bank.saveCopyConfirm": "Save another copy",1469 "bank.saveCopyConfirm": "Save another copy",
1446- "bank.savedToBank": "Question copied to the bank.",1470+ "bank.savedToBank": "Question copied to the bank. Only you can see it until you share it.",
1447- "bank.inBankBadge": "In bank",1471+ "bank.fromBankBadge": "Added from bank",
1448- "bank.search": "Search templates",1472+ "bank.savedToBankBadge": "Saved to bank",
1473+ "bank.search": "Search question text",
1449 "bank.pickerEmpty": "No matching template.",1474 "bank.pickerEmpty": "No matching template.",
1450 "bank.noSubjects": "This exam's course has no subjects yet. Add a subject to the course first.",1475 "bank.noSubjects": "This exam's course has no subjects yet. Add a subject to the course first.",
1476+ "bank.countTotal": "{total} templates in total.",
1477+ "bank.countShown": "Showing {shown} of {total} — search to narrow it down.",
1478+ "bank.whoCanSee": "Who can see it",
1479+ "bank.onlyMe": "Only me",
1480+ "bank.sharedWithSchool": "Shared with the school",
1481+ "bank.onlyMeHint": "Only you can see this question and its answer. This is the safe choice.",
1482+ "bank.sharedWithSchoolHint": "Every teacher in the school can see this question and its correct answer.",
1483+ "bank.shareTitle": "Share this question with the whole school?",
1484+ "bank.shareBody": "Every teacher in the school will be able to see this question and its correct answer. If the question is on an exam that has not finished yet, they can see the answer before your students sit it. Other teachers can copy it into their own exams, and those copies stay with them even if you make the question private again or delete it. You cannot take a copy back.",
1485+ "bank.shareConfirm": "Yes, share it",
1486+ "bank.startsPrivate": "The saved template starts private: only you can see it until you choose to share it.",
1487+ "bank.usedInExams": "Copies in exams",
1488+ "bank.refresh": "Update from template",
1489+ "bank.refreshTitle": "Update this question from its template?",
1490+ "bank.refreshBody": "This question is a copy made from a bank template. Updating replaces its text, points, options, correct answer and pictures with what the template says today. Anything you changed on this copy is lost. It only works before anyone starts the exam, so no student's answers can be affected.",
1491+ "bank.refreshConfirm": "Yes, update it",
1492+ "bank.refreshed": "Question updated from its template.",
1451 "subjects.title": "Subjects",1493 "subjects.title": "Subjects",
1452 "subjects.item": "Subject",1494 "subjects.item": "Subject",
1453 "subjects.subject": "Subject",1495 "subjects.subject": "Subject",
@@ -2342,12 +2384,13 @@ const tr: Dict = {
2342 "questions.editDrawing": "Çizimi düzenle",2384 "questions.editDrawing": "Çizimi düzenle",
2343 "questions.choiceImage": "Seçenek görseli",2385 "questions.choiceImage": "Seçenek görseli",
2344 "questions.subjectRequired": "Bu soru için konu seç",2386 "questions.subjectRequired": "Bu soru için konu seç",
2387+ "questions.subjectUnavailable": "Şu anki konu — artık sana açık değil",
2388+ "questions.subjectUnavailableHelp": "Bu soruda kayıtlı konu, seçebileceğin listede yok. Kaydetmek için listeden bir konu seç.",
2345 "questions.textRequired": "Soru metni gerekli",2389 "questions.textRequired": "Soru metni gerekli",
2346 "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı",2390 "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı",
2347 "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı",2391 "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı",
2392+ "questions.correctRequired": "Kaydetmeden önce bir seçeneği doğru cevap olarak işaretle.",
2348 "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",2393 "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",
2349- "questions.correctBlanked": "Doğru olarak işaretlediğin seçenek şu an boş. Metni tekrar yaz ya da başka bir seçeneği doğru işaretle.",
2350- "questions.imagesLost": "Kaydedildi, ancak {options} seçeneğinin görseli bu düzenlemede taşınamadı. Görseli tekrar ekle.",
2351 "bank.title": "Soru bankası",2394 "bank.title": "Soru bankası",
2352 "bank.subtitle": "Bütün öğretmenlerin kullanabildiği, yeniden kullanılabilir soru şablonları.",2395 "bank.subtitle": "Bütün öğretmenlerin kullanabildiği, yeniden kullanılabilir soru şablonları.",
2353 "bank.empty": "Henüz şablon yok.",2396 "bank.empty": "Henüz şablon yok.",
@@ -2357,8 +2400,10 @@ const tr: Dict = {
2357 "bank.mine": "Benimkiler",2400 "bank.mine": "Benimkiler",
2358 "bank.created": "Eklenme",2401 "bank.created": "Eklenme",
2359 "bank.copyNotice": "Şablonu sınava eklemek bir kopya oluşturur. Şablonu sonradan düzenlemek, daha önce eklenmiş soruları değiştirmez.",2402 "bank.copyNotice": "Şablonu sınava eklemek bir kopya oluşturur. Şablonu sonradan düzenlemek, daha önce eklenmiş soruları değiştirmez.",
2403+ "bank.courseSelect": "Ders seç",
2404+ "bank.courseUnavailable": "Özgün ders — senin derslerinden değil",
2405+ "bank.targetSubjectHint": "Bu kopyanın bu sınavda hangi konuya gireceğini seç.",
2360 "bank.courseHint": "Şablonlar bir konuyla etiketlenir; o konunun bağlı olduğu dersi seç. Şablon yine de her derste kullanılabilir.",2406 "bank.courseHint": "Şablonlar bir konuyla etiketlenir; o konunun bağlı olduğu dersi seç. Şablon yine de her derste kullanılabilir.",
2361- "bank.choiceImagesWarning": "Seçenekleri değiştirmek, sunucudaki seçenek görsellerini siler. Koruduğun seçeneklerin görselleri yeniden yüklenir; taşınamayan olursa sana bildirilir.",
2362 "bank.fromBank": "Bankadan ekle",2407 "bank.fromBank": "Bankadan ekle",
2363 "bank.pickTemplate": "Şablon seç",2408 "bank.pickTemplate": "Şablon seç",
2364 "bank.targetSubject": "Bu sınavdaki konu",2409 "bank.targetSubject": "Bu sınavdaki konu",
@@ -2367,13 +2412,31 @@ const tr: Dict = {
2367 "bank.saveToBank": "Bankaya kaydet",2412 "bank.saveToBank": "Bankaya kaydet",
2368 "bank.saveCopyToBank": "Bankaya yeni bir kopya kaydet",2413 "bank.saveCopyToBank": "Bankaya yeni bir kopya kaydet",
2369 "bank.saveCopyTitle": "İkinci bir kopya kaydedilsin mi?",2414 "bank.saveCopyTitle": "İkinci bir kopya kaydedilsin mi?",
2370- "bank.saveCopyBody": "Bu soru bir banka şablonuna zaten bağlı. Kaydetmek mevcut şablonu güncellemez; bankada ikinci, ayrı bir şablon oluşturur. İki kopya birbirinden bağımsızdır: birini düzenlemek diğerini hiçbir zaman değiştirmez.",2415+ "bank.saveCopyBody": "Bu soru bir banka şablonuna zaten bağlı. Kaydetmek mevcut şablonu güncellemez; bankada ikinci, ayrı bir şablon oluşturur. İki kopya birbirinden bağımsızdır: birini düzenlemek diğerini hiçbir zaman değiştirmez. Yeni şablon gizlidir: sen paylaşmayı seçene kadar onu yalnızca sen görebilirsin.",
2371 "bank.saveCopyConfirm": "Yeni kopya kaydet",2416 "bank.saveCopyConfirm": "Yeni kopya kaydet",
2372- "bank.savedToBank": "Soru bankaya kopyalandı.",2417+ "bank.savedToBank": "Soru bankaya kopyalandı. Sen paylaşana kadar onu yalnızca sen görebilirsin.",
2373- "bank.inBankBadge": "Bankada",2418+ "bank.fromBankBadge": "Bankadan eklendi",
2374- "bank.search": "Şablonlarda ara",2419+ "bank.savedToBankBadge": "Bankaya kaydedildi",
2420+ "bank.search": "Soru metninde ara",
2375 "bank.pickerEmpty": "Eşleşen şablon yok.",2421 "bank.pickerEmpty": "Eşleşen şablon yok.",
2376 "bank.noSubjects": "Bu sınavın dersinde henüz konu yok. Önce derse bir konu ekle.",2422 "bank.noSubjects": "Bu sınavın dersinde henüz konu yok. Önce derse bir konu ekle.",
2423+ "bank.countTotal": "Toplam {total} şablon.",
2424+ "bank.countShown": "{total} şablondan {shown} tanesi gösteriliyor — daraltmak için arama yap.",
2425+ "bank.whoCanSee": "Kimler görebilir",
2426+ "bank.onlyMe": "Yalnızca ben",
2427+ "bank.sharedWithSchool": "Okulla paylaşıldı",
2428+ "bank.onlyMeHint": "Bu soruyu ve cevabını yalnızca sen görebilirsin. Güvenli seçenek budur.",
2429+ "bank.sharedWithSchoolHint": "Okuldaki bütün öğretmenler bu soruyu ve doğru cevabını görebilir.",
2430+ "bank.shareTitle": "Bu soru bütün okulla paylaşılsın mı?",
2431+ "bank.shareBody": "Okuldaki bütün öğretmenler bu soruyu ve doğru cevabını görebilecek. Soru henüz bitmemiş bir sınavdaysa, öğrencilerin sınava girmeden önce cevabı görebilirler. Diğer öğretmenler soruyu kendi sınavlarına kopyalayabilir; sen soruyu sonradan yeniden gizlesen ya da silsen bile o kopyalar onlarda kalır. Alınan kopyaları geri alamazsın.",
2432+ "bank.shareConfirm": "Evet, paylaş",
2433+ "bank.startsPrivate": "Kaydedilen şablon gizli başlar: sen paylaşmayı seçene kadar onu yalnızca sen görebilirsin.",
2434+ "bank.usedInExams": "Sınavlardaki kopyalar",
2435+ "bank.refresh": "Şablondan güncelle",
2436+ "bank.refreshTitle": "Bu soru şablonundan güncellensin mi?",
2437+ "bank.refreshBody": "Bu soru, bir soru bankası şablonundan alınmış bir kopya. Güncellersen sorunun metni, puanı, seçenekleri, doğru cevabı ve resimleri şablonun bugünkü hâliyle değiştirilir. Bu kopyada yaptığın değişiklikler kaybolur. Bu işlem yalnızca sınava kimse başlamadan önce yapılabilir, bu yüzden hiçbir öğrencinin cevabı etkilenmez.",
2438+ "bank.refreshConfirm": "Evet, güncelle",
2439+ "bank.refreshed": "Soru şablonundan güncellendi.",
2377 "subjects.title": "Konular",2440 "subjects.title": "Konular",
2378 "subjects.item": "Konu",2441 "subjects.item": "Konu",
2379 "subjects.subject": "Konu",2442 "subjects.subject": "Konu",
src/lib/answer-sheet.test.tsmodified+5 -5
@@ -10,8 +10,8 @@ function question(id: string, overrides: Partial<ExamQuestion> = {}): ExamQuesti
10 text: `Question ${id}`,10 text: `Question ${id}`,
11 kind: "choice",11 kind: "choice",
12 points: 10,12 points: 10,
13- choices: ["a", "b"],13+ choices: [{ id: "cA", text: "a" }, { id: "cB", text: "b" }],
14- correct: 0,14+ correct: "cA",
15 ...overrides,15 ...overrides,
16 };16 };
17 }17 }
@@ -19,7 +19,7 @@ function question(id: string, overrides: Partial<ExamQuestion> = {}): ExamQuesti
19 function answer(questionId: string, overrides: Partial<StudentAnswer> = {}): StudentAnswer {19 function answer(questionId: string, overrides: Partial<StudentAnswer> = {}): StudentAnswer {
20 return {20 return {
21 question: questionId,21 question: questionId,
22- selected: 0,22+ selected: "cA",
23 text: null,23 text: null,
24 updated_at: 1,24 updated_at: 1,
25 is_correct: true,25 is_correct: true,
@@ -30,11 +30,11 @@ function answer(questionId: string, overrides: Partial<StudentAnswer> = {}): Stu
30 test("pairs each question with its answer by id, keeping question order", () => {30 test("pairs each question with its answer by id, keeping question order", () => {
31 const rows = joinAnswerSheet(31 const rows = joinAnswerSheet(
32 [question("q1"), question("q2")],32 [question("q1"), question("q2")],
33- [answer("q2", { selected: 1, is_correct: false }), answer("q1")],33+ [answer("q2", { selected: "cB", is_correct: false }), answer("q1")],
34 );34 );
35 expect(rows.map((r) => r.question.id)).toEqual(["q1", "q2"]);35 expect(rows.map((r) => r.question.id)).toEqual(["q1", "q2"]);
36 expect(rows[0].answer?.is_correct).toBe(true);36 expect(rows[0].answer?.is_correct).toBe(true);
37- expect(rows[1].answer?.selected).toBe(1);37+ expect(rows[1].answer?.selected).toBe("cB");
38 });38 });
39 39
40 test("unanswered question yields a null answer", () => {40 test("unanswered question yields a null answer", () => {
src/lib/choice-compaction.test.tsdeleted+0 -57
@@ -1,57 +0,0 @@
1-import { describe, expect, it } from "vitest";
2-import { compactChoices, planChoiceImageRestore } from "./choice-compaction";
3-
4-const meta = { content_type: "image/png", size: 1 };
5-const noImages = (n: number) => Array.from({ length: n }, () => null);
6-
7-describe("compactChoices", () => {
8- it("keeps the answer on the same choice when a choice above it is blanked", () => {
9- // A B C D with D marked correct; the user blanks B.
10- const result = compactChoices(["A", "", "C", "D"], noImages(4), [0, 1, 2, 3], 3);
11- expect(result.choices).toEqual(["A", "C", "D"]);
12- expect(result.sources).toEqual([0, 2, 3]);
13- expect(result.correct).toBe(2);
14- expect(result.choices[result.correct]).toBe("D"); // same text the user picked
15- });
16-
17- it("rejects the edit when the choice marked correct is the blanked one", () => {
18- const result = compactChoices(["A", "", "C"], noImages(3), [0, 1, 2], 1);
19- expect(result.correct).toBe(-1);
20- });
21-
22- it("resolves an answer marked on a newly added row", () => {
23- // D was added in this edit (source -1) and marked correct; B was blanked.
24- const result = compactChoices(["A", "", "C", "D"], noImages(4), [0, 1, 2, -1], 3);
25- expect(result.correct).toBe(2);
26- expect(result.sources).toEqual([0, 2, -1]);
27- });
28-
29- it("carries picked files with their choice and trims text", () => {
30- const file = new File([], "c.png");
31- const result = compactChoices(["A", " ", " C "], [null, file, file], [0, 1, 2], 2);
32- expect(result.choices).toEqual(["A", "C"]);
33- expect(result.images).toEqual([null, file]);
34- expect(result.correct).toBe(1);
35- });
36-});
37-
38-describe("planChoiceImageRestore", () => {
39- it("restores to the post-compaction slot, not the original index", () => {
40- // A, B, C all had images; the user blanked B, so C survives as index 1.
41- const plan = planChoiceImageRestore([0, 2], [meta, meta, meta], null);
42- expect(plan).toEqual([
43- { index: 0, source: 0 },
44- { index: 1, source: 2 },
45- ]);
46- // never plans an index past the choices that survived
47- expect(plan.every((slot) => slot.index < 2)).toBe(true);
48- });
49-
50- it("skips new choices, imageless options, and options the user replaced", () => {
51- const replacements = [null, new File([], "b.png"), null];
52- expect(planChoiceImageRestore([0, 1, -1], [meta, meta, null], replacements)).toEqual([
53- { index: 0, source: 0 },
54- ]);
55- expect(planChoiceImageRestore([0, 1], [null, null], null)).toEqual([]);
56- });
57-});
src/lib/choice-compaction.tsdeleted+0 -54
@@ -1,54 +0,0 @@
1-export type CompactedChoices = {
2- choices: string[];
3- images: (File | null)[];
4- /** Index each surviving choice had in the stored question, -1 if added in this edit. */
5- sources: number[];
6- /** Index of the correct choice after compaction, or -1 if that row was left blank. */
7- correct: number;
8-};
9-
10-/**
11- * Editing a question drops blank choices before submit, which shifts every index
12- * after the gap. Everything keyed by position — the answer key and the per-option
13- * images — has to move with it, so do the drop once, here, and hand back the
14- * already-shifted values.
15- */
16-export function compactChoices(
17- choices: string[],
18- images: (File | null)[],
19- /** Original index per row as displayed, -1 for a row added in this edit. */
20- sources: number[],
21- /** Row the user marked correct, as an index into `choices`. */
22- correct: number,
23-): CompactedChoices {
24- const kept = choices
25- .map((choice, row) => ({ choice: choice.trim(), image: images[row] ?? null, source: sources[row] ?? -1, row }))
26- .filter((item) => item.choice);
27- return {
28- choices: kept.map((item) => item.choice),
29- images: kept.map((item) => item.image),
30- sources: kept.map((item) => item.source),
31- // Follow the row the user actually picked; -1 means they blanked it and must choose again.
32- correct: kept.findIndex((item) => item.row === correct),
33- };
34-}
35-
36-/**
37- * A PATCH carrying `choices` deletes every stored option image server-side, so a
38- * choice edit has to re-upload the images the user kept. Blank choices are dropped
39- * on submit, so the option an image came from (its `source`) and the slot it must
40- * go back to (its new index) are different numbers — uploading to the old index
41- * either lands on the wrong option or is rejected as out of range.
42- */
43-export function planChoiceImageRestore(
44- /** `QuestionValues.choice_sources`: original index per surviving choice, -1 if new. */
45- sources: number[],
46- /** `choice_images` as stored on the server today, indexed by original position. */
47- stored: (unknown | null)[],
48- /** Freshly picked files per surviving choice; a replaced option needs no restore. */
49- replacements: (File | null)[] | null,
50-): { index: number; source: number }[] {
51- return sources
52- .map((source, index) => ({ index, source }))
53- .filter((slot) => slot.source >= 0 && stored[slot.source] != null && !replacements?.[slot.index]);
54-}
src/lib/choice-set.property.test.tsadded+176 -0
@@ -0,0 +1,176 @@
1+import fc from "fast-check";
2+import { expect, test } from "vitest";
3+import {
4+ addChoice,
5+ blankChoiceSet,
6+ type ChoiceSet,
7+ moveChoice,
8+ removeChoice,
9+ setChoiceImage,
10+ setChoiceText,
11+ setCorrect,
12+ storedChoiceSet,
13+ submitChoices,
14+} from "./choice-set";
15+
16+/**
17+ * The example tests pin down seven known edits. These generate the edits
18+ * instead, because every bug this reducer exists to kill lived in a *relation*
19+ * between values — a row, its picture, the answer key, a student's answer —
20+ * and an example can only re-assert the author's own mental model of it.
21+ *
22+ * The one invariant, restated: anything attached to a row (text, picture, the
23+ * correct mark) stays attached to that row's id across any sequence of edits.
24+ */
25+
26+const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
27+const ulidArb = fc
28+ .array(fc.constantFrom(...BASE32.split("")), { minLength: 26, maxLength: 26 })
29+ .map((chars) => chars.join(""));
30+
31+/** Blank, whitespace-only, duplicated and arbitrary texts all matter here. */
32+const textArb = fc.oneof(
33+ fc.constant(""),
34+ fc.constant(" "),
35+ fc.constant("dup"),
36+ fc.string({ maxLength: 8 }),
37+);
38+
39+let stamped = 0;
40+const stampFile = () => ({ name: `f${(stamped += 1)}` }) as unknown as File;
41+
42+type Op =
43+ | { t: "add" }
44+ | { t: "remove"; p: number }
45+ | { t: "move"; p: number; q: number }
46+ | { t: "text"; p: number; text: string }
47+ | { t: "image"; p: number; keep: boolean }
48+ | { t: "correct"; p: number }
49+ | { t: "correctUnknown"; id: string };
50+
51+const pick = fc.double({ min: 0, max: 0.999, noNaN: true });
52+const opArb: fc.Arbitrary<Op> = fc.oneof(
53+ fc.constant<Op>({ t: "add" }),
54+ fc.record({ t: fc.constant<"remove">("remove"), p: pick }),
55+ fc.record({ t: fc.constant<"move">("move"), p: pick, q: pick }),
56+ fc.record({ t: fc.constant<"text">("text"), p: pick, text: textArb }),
57+ fc.record({ t: fc.constant<"image">("image"), p: pick, keep: fc.boolean() }),
58+ fc.record({ t: fc.constant<"correct">("correct"), p: pick }),
59+ fc.record({ t: fc.constant<"correctUnknown">("correctUnknown"), id: fc.oneof(ulidArb, fc.constant("new:0")) }),
60+);
61+
62+/** Starting points: fresh forms, stored questions, empty sets, sets at max. */
63+const startArb = fc.integer({ min: 2, max: 10 }).chain((max) =>
64+ fc.oneof(
65+ fc.integer({ min: 0, max }).map((n) => ({ max, set: blankChoiceSet(n) })),
66+ fc
67+ .uniqueArray(fc.record({ id: ulidArb, text: textArb }), { maxLength: max, selector: (c) => c.id })
68+ .chain((choices) =>
69+ (choices.length ? fc.option(fc.constantFrom(...choices.map((c) => c.id)), { nil: null }) : fc.constant(null))
70+ .map((correct) => ({ max, set: storedChoiceSet(choices, correct) })),
71+ ),
72+ ),
73+);
74+
75+const ids = (set: ChoiceSet) => set.rows.map((row) => row.id);
76+const at = (set: ChoiceSet, p: number) => (set.rows.length ? set.rows[Math.floor(p * set.rows.length)].id : "absent");
77+
78+/** Apply one op and return it plus the id it was allowed to touch (if any). */
79+function apply(set: ChoiceSet, op: Op, max: number): { next: ChoiceSet; touched: string | null } {
80+ switch (op.t) {
81+ case "add":
82+ return { next: addChoice(set, max), touched: null };
83+ case "remove":
84+ return { next: removeChoice(set, at(set, op.p)), touched: at(set, op.p) };
85+ case "move":
86+ return { next: moveChoice(set, at(set, op.p), Math.floor(op.q * Math.max(set.rows.length, 1))), touched: null };
87+ case "text":
88+ return { next: setChoiceText(set, at(set, op.p), op.text), touched: at(set, op.p) };
89+ case "image":
90+ return { next: setChoiceImage(set, at(set, op.p), op.keep ? stampFile() : null), touched: at(set, op.p) };
91+ case "correct":
92+ return { next: setCorrect(set, at(set, op.p)), touched: null };
93+ case "correctUnknown":
94+ return { next: setCorrect(set, op.id), touched: null };
95+ }
96+}
97+
98+test("every edit sequence keeps text, picture and answer key attached to their row id", () => {
99+ fc.assert(
100+ fc.property(startArb, fc.array(opArb, { maxLength: 25 }), ({ max, set: start }, ops) => {
101+ let set = start;
102+ for (const op of ops) {
103+ const before = set;
104+ const { next, touched } = apply(set, op, max);
105+ set = next;
106+
107+ // Ids are unique at all times, and the row count never exceeds max.
108+ expect(new Set(ids(set)).size).toBe(set.rows.length);
109+ expect(set.rows.length).toBeLessThanOrEqual(max);
110+
111+ // No op invents or duplicates an id: add appends exactly one new id,
112+ // remove drops exactly the targeted one, everything else permutes.
113+ const gained = ids(set).filter((id) => !ids(before).includes(id));
114+ const lost = ids(before).filter((id) => !ids(set).includes(id));
115+ expect(gained.length).toBe(op.t === "add" && before.rows.length < max ? 1 : 0);
116+ expect(lost).toEqual(op.t === "remove" && ids(before).includes(touched!) ? [touched] : []);
117+
118+ // The attachment invariant: a surviving row the op did not target keeps
119+ // its exact text and its exact File object, whatever moved around it.
120+ for (const row of set.rows) {
121+ const was = before.rows.find((r) => r.id === row.id);
122+ if (!was || row.id === touched) continue;
123+ expect(row.text).toBe(was.text);
124+ expect(row.image).toBe(was.image);
125+ }
126+
127+ // `correct` only ever names a live row (or nothing) — never an index,
128+ // never a removed row.
129+ if (set.correct !== null) expect(ids(set)).toContain(set.correct);
130+ }
131+
132+ const out = submitChoices(set);
133+ const outIds = out.choices.map((c) => c.id);
134+
135+ // Output is a subset of the live rows, in row order, no id invented or
136+ // duplicated, and it is exactly the non-blank rows.
137+ expect(new Set(outIds).size).toBe(outIds.length);
138+ expect(outIds).toEqual(ids(set).filter((id) => set.rows.find((r) => r.id === id)!.text.trim()));
139+ for (const [i, choice] of out.choices.entries()) {
140+ const row = set.rows.find((r) => r.id === choice.id)!;
141+ expect(choice.text).toBe(row.text.trim());
142+ // The picture rides the id, not the position, after blanks are dropped.
143+ expect(out.images[i]).toBe(row.image);
144+ }
145+
146+ // The answer key survives the drop iff its row survived it.
147+ const marked = set.rows.find((r) => r.id === set.correct);
148+ expect(out.correct).toBe(marked && marked.text.trim() ? set.correct : null);
149+ if (out.correct !== null) expect(outIds).toContain(out.correct);
150+ }),
151+ { numRuns: 500 },
152+ );
153+});
154+
155+test("reordering is invisible on the wire: same rows, same pictures, same answer key", () => {
156+ fc.assert(
157+ fc.property(startArb, fc.array(fc.record({ p: pick, q: pick }), { maxLength: 15 }), ({ set: start }, moves) => {
158+ // Give every row a distinguishable picture so a positional mix-up shows.
159+ let set = start.rows.reduce((acc, row) => setChoiceImage(acc, row.id, stampFile()), start);
160+ const before = submitChoices(set);
161+ for (const move of moves) {
162+ set = moveChoice(set, at(set, move.p), Math.floor(move.q * Math.max(set.rows.length, 1)));
163+ }
164+ const after = submitChoices(set);
165+
166+ expect(after.correct).toBe(before.correct);
167+ expect([...after.choices].sort((a, b) => a.id.localeCompare(b.id))).toEqual(
168+ [...before.choices].sort((a, b) => a.id.localeCompare(b.id)),
169+ );
170+ // Each id keeps its own File across the reordering.
171+ const pairs = (out: typeof before) => out.choices.map((c, i) => [c.id, out.images[i]] as const);
172+ expect(new Map(pairs(after))).toEqual(new Map(pairs(before)));
173+ }),
174+ { numRuns: 300 },
175+ );
176+});
src/lib/choice-set.test.tsadded+61 -0
@@ -0,0 +1,61 @@
1+import { expect, test } from "vitest";
2+import {
3+ addChoice,
4+ blankChoiceSet,
5+ moveChoice,
6+ newChoiceId,
7+ removeChoice,
8+ setChoiceText,
9+ setCorrect,
10+ storedChoiceSet,
11+ submitChoices,
12+} from "./choice-set";
13+
14+const stored = () =>
15+ storedChoiceSet([{ id: "A", text: "one" }, { id: "B", text: "two" }, { id: "C", text: "three" }], "B");
16+
17+test("a fresh set pre-marks nothing", () => {
18+ const set = blankChoiceSet();
19+ expect(set.rows).toHaveLength(4);
20+ expect(set.correct).toBeNull();
21+ expect(new Set(set.rows.map((r) => r.id)).size).toBe(4);
22+});
23+
24+test("minted ids are unique and cannot collide with a stored ULID", () => {
25+ expect(newChoiceId()).not.toBe(newChoiceId());
26+ expect(newChoiceId()).toContain(":"); // ':' is not in Crockford base32
27+});
28+
29+test("dropping a blank row leaves the marked row's id untouched", () => {
30+ const set = setChoiceText(stored(), "A", " ");
31+ expect(submitChoices(set)).toEqual({
32+ choices: [{ id: "B", text: "two" }, { id: "C", text: "three" }],
33+ images: [null, null],
34+ correct: "B",
35+ });
36+});
37+
38+test("reordering carries ids, so the answer key follows its choice", () => {
39+ const moved = moveChoice(stored(), "B", 2);
40+ expect(moved.rows.map((r) => r.id)).toEqual(["A", "C", "B"]);
41+ expect(submitChoices(moved).correct).toBe("B");
42+});
43+
44+test("removing or blanking the marked row unmarks it instead of shifting the key", () => {
45+ expect(removeChoice(stored(), "B").correct).toBeNull();
46+ expect(submitChoices(setChoiceText(stored(), "B", "")).correct).toBeNull();
47+});
48+
49+test("a new row is markable, because it carries a client-minted key", () => {
50+ const added = addChoice(stored(), 10);
51+ const fresh = added.rows[3].id;
52+ const marked = setChoiceText(setCorrect(added, fresh), fresh, "four");
53+ const out = submitChoices(marked);
54+ expect(out.correct).toBe(fresh);
55+ expect(out.choices.map((c) => c.id)).toContain(fresh);
56+});
57+
58+test("add respects the max and setCorrect ignores an unknown id", () => {
59+ expect(addChoice(blankChoiceSet(10), 10).rows).toHaveLength(10);
60+ expect(setCorrect(stored(), "nope").correct).toBe("B");
61+});
src/lib/choice-set.tsadded+86 -0
@@ -0,0 +1,86 @@
1+import type { Choice } from "@/api/client";
2+
3+/** One editable choice row: a stable key, its text, and a not-yet-uploaded image. */
4+export type ChoiceRow = Choice & { image: File | null };
5+
6+/** The whole choices region of the question form. `correct` names a row by id. */
7+export type ChoiceSet = {
8+ rows: ChoiceRow[];
9+ correct: string | null;
10+};
11+
12+let minted = 0;
13+
14+/**
15+ * Key for a row the server has never seen. The server keeps any submitted key it
16+ * already stores and treats every other key as a new option, so this only has to
17+ * be unique within one payload — and `correct` can name a brand-new row with it.
18+ * `:` is not in Crockford base32, so it can never collide with a stored ULID.
19+ */
20+export function newChoiceId(): string {
21+ minted += 1;
22+ return `new:${minted}`;
23+}
24+
25+export function blankChoiceSet(count = 4): ChoiceSet {
26+ return { rows: Array.from({ length: count }, () => ({ id: newChoiceId(), text: "", image: null })), correct: null };
27+}
28+
29+/** Edit an existing question: stored ids come along, so images stay attached. */
30+export function storedChoiceSet(choices: Choice[] | null | undefined, correct: string | null | undefined): ChoiceSet {
31+ if (!choices) return blankChoiceSet();
32+ return {
33+ rows: choices.map((choice) => ({ id: choice.id, text: choice.text, image: null })),
34+ correct: correct ?? null,
35+ };
36+}
37+
38+export function addChoice(set: ChoiceSet, max: number): ChoiceSet {
39+ if (set.rows.length >= max) return set;
40+ return { ...set, rows: [...set.rows, { id: newChoiceId(), text: "", image: null }] };
41+}
42+
43+/** Removing the marked row unmarks it — there is no neighbouring index to fall back to. */
44+export function removeChoice(set: ChoiceSet, id: string): ChoiceSet {
45+ return {
46+ rows: set.rows.filter((row) => row.id !== id),
47+ correct: set.correct === id ? null : set.correct,
48+ };
49+}
50+
51+export function setChoiceText(set: ChoiceSet, id: string, text: string): ChoiceSet {
52+ return { ...set, rows: set.rows.map((row) => (row.id === id ? { ...row, text } : row)) };
53+}
54+
55+export function setChoiceImage(set: ChoiceSet, id: string, image: File | null): ChoiceSet {
56+ return { ...set, rows: set.rows.map((row) => (row.id === id ? { ...row, image } : row)) };
57+}
58+
59+export function setCorrect(set: ChoiceSet, id: string): ChoiceSet {
60+ return set.rows.some((row) => row.id === id) ? { ...set, correct: id } : set;
61+}
62+
63+/** Move a row to another position; ids travel with their text, image and mark. */
64+export function moveChoice(set: ChoiceSet, id: string, to: number): ChoiceSet {
65+ const from = set.rows.findIndex((row) => row.id === id);
66+ if (from < 0 || to < 0 || to >= set.rows.length || to === from) return set;
67+ const rows = [...set.rows];
68+ const [row] = rows.splice(from, 1);
69+ rows.splice(to, 0, row);
70+ return { ...set, rows };
71+}
72+
73+/**
74+ * What actually goes on the wire: blank rows dropped, ids kept. Every row carries
75+ * a key, so the server re-attaches each surviving option's picture itself — no
76+ * index bookkeeping, no download-and-reupload. `correct` is null when the marked
77+ * row was left blank or never picked; the caller reports that to the user.
78+ */
79+export function submitChoices(set: ChoiceSet): { choices: Choice[]; images: (File | null)[]; correct: string | null } {
80+ const kept = set.rows.map((row) => ({ ...row, text: row.text.trim() })).filter((row) => row.text);
81+ return {
82+ choices: kept.map((row) => ({ id: row.id, text: row.text })),
83+ images: kept.map((row) => row.image),
84+ correct: kept.some((row) => row.id === set.correct) ? set.correct : null,
85+ };
86+}
src/lib/create-debounced-signal.test.tsadded+49 -0
@@ -0,0 +1,49 @@
1+import { createRoot } from "solid-js";
2+import { createDebouncedSignal } from "./create-debounced-signal";
3+
4+describe("createDebouncedSignal", () => {
5+ beforeEach(() => vi.useFakeTimers());
6+ afterEach(() => vi.useRealTimers());
7+
8+ it("updates raw at once and the debounced copy only after the delay", () => {
9+ createRoot((dispose) => {
10+ const [raw, set, debounced] = createDebouncedSignal("", 300);
11+ set("ne");
12+ expect(raw()).toBe("ne");
13+ expect(debounced()).toBe("");
14+ vi.advanceTimersByTime(299);
15+ expect(debounced()).toBe("");
16+ vi.advanceTimersByTime(1);
17+ expect(debounced()).toBe("ne");
18+ dispose();
19+ });
20+ });
21+
22+ it("keeps only the last keystroke when typing faster than the delay", () => {
23+ createRoot((dispose) => {
24+ const values: string[] = [];
25+ const [, set, debounced] = createDebouncedSignal("", 300);
26+ set("n");
27+ vi.advanceTimersByTime(100);
28+ set("ne");
29+ vi.advanceTimersByTime(100);
30+ set("newton");
31+ vi.advanceTimersByTime(300);
32+ values.push(debounced());
33+ expect(values).toEqual(["newton"]);
34+ dispose();
35+ });
36+ });
37+
38+ it("cancels a pending update when the owner disposes", () => {
39+ let read = () => "";
40+ createRoot((dispose) => {
41+ const [, set, debounced] = createDebouncedSignal("", 300);
42+ read = debounced;
43+ set("newton");
44+ dispose();
45+ });
46+ vi.advanceTimersByTime(500);
47+ expect(read()).toBe("");
48+ });
49+});
src/lib/create-debounced-signal.tsadded+18 -0
@@ -0,0 +1,18 @@
1+import { createSignal, onCleanup } from "solid-js";
2+
3+/**
4+ * Text input signal plus a copy that only catches up `delay` ms after typing
5+ * stops — bind the raw one to the input, the debounced one to the query params.
6+ */
7+export function createDebouncedSignal(initial = "", delay = 300) {
8+ const [raw, setRaw] = createSignal(initial);
9+ const [debounced, setDebounced] = createSignal(initial);
10+ let timer: ReturnType<typeof setTimeout> | undefined;
11+ const set = (value: string) => {
12+ setRaw(value);
13+ clearTimeout(timer);
14+ timer = setTimeout(() => setDebounced(value), delay);
15+ };
16+ onCleanup(() => clearTimeout(timer));
17+ return [raw, set, debounced] as const;
18+}
src/pages/question-bank-page.tsxmodified+95 -54
@@ -2,8 +2,6 @@ import { Show, Suspense, createMemo, createResource, createSignal } from "solid-
2 import type { ColumnDef } from "@tanstack/solid-table";2 import type { ColumnDef } from "@tanstack/solid-table";
3 import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions";3 import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions";
4 import { getCourses } from "@/api/courses";4 import { getCourses } from "@/api/courses";
5-import { getSubjectById } from "@/api/subjects";
6-import { getUserById } from "@/api/users";
7 import { formatApiError } from "@/api/client";5 import { formatApiError } from "@/api/client";
8 import type { BankQuestion } from "@/api/client";6 import type { BankQuestion } from "@/api/client";
9 import { BankQuestionForm } from "@/components/exams/bank-question-form";7 import { BankQuestionForm } from "@/components/exams/bank-question-form";
@@ -13,10 +11,11 @@ import { Badge } from "@/components/ui/badge";
13 import { Button } from "@/components/ui/button";11 import { Button } from "@/components/ui/button";
14 import { ConfirmDialog } from "@/components/ui/confirm-dialog";12 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
15 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";13 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
16-import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";14+import { IconEdit, IconEyeOff, IconPlus, IconTrash, IconUsers } from "@/components/ui/icons";
17 import { DropdownSelect } from "@/components/ui/select";15 import { DropdownSelect } from "@/components/ui/select";
18 import { SidePanel } from "@/components/ui/side-panel";16 import { SidePanel } from "@/components/ui/side-panel";
19 import { TableRowActions } from "@/components/ui/table-row-actions";17 import { TableRowActions } from "@/components/ui/table-row-actions";
18+import { createDebouncedSignal } from "@/lib/create-debounced-signal";
20 import { createFlash } from "@/lib/flash";19 import { createFlash } from "@/lib/flash";
21 import { formatDate } from "@/lib/format";20 import { formatDate } from "@/lib/format";
22 import { hasMinRole } from "@/lib/roles";21 import { hasMinRole } from "@/lib/roles";
@@ -39,48 +38,44 @@ function QuestionBankContent() {
39 const { locale } = usePreferences();38 const { locale } = usePreferences();
40 const [ownerFilter, setOwnerFilter] = createSignal<"all" | "me">("all");39 const [ownerFilter, setOwnerFilter] = createSignal<"all" | "me">("all");
41 const [subjectFilter, setSubjectFilter] = createSignal("all");40 const [subjectFilter, setSubjectFilter] = createSignal("all");
41+ const [visibilityFilter, setVisibilityFilter] = createSignal<"all" | "private" | "school">("all");
42+ const [page, setPage] = createSignal(0);
43+ const [query, setQuery, debouncedQuery] = createDebouncedSignal();
42 const [createOpen, setCreateOpen] = createSignal(false);44 const [createOpen, setCreateOpen] = createSignal(false);
43 const [editing, setEditing] = createSignal<BankQuestion | null>(null);45 const [editing, setEditing] = createSignal<BankQuestion | null>(null);
44 const [removing, setRemoving] = createSignal<BankQuestion | null>(null);46 const [removing, setRemoving] = createSignal<BankQuestion | null>(null);
47+ // ponytail: the subject dropdown lists the subjects seen while browsing — the
48+ // backend has no "all subjects" endpoint. Widen once one exists.
45 const [subjectNames, setSubjectNames] = createSignal<Record<string, string>>({});49 const [subjectNames, setSubjectNames] = createSignal<Record<string, string>>({});
46- const [ownerNames, setOwnerNames] = createSignal<Record<string, string>>({});
47 const [flash, setFlash] = createFlash();50 const [flash, setFlash] = createFlash();
48 const [error, setError] = createSignal("");51 const [error, setError] = createSignal("");
49 52
50- // ponytail: first 100 templates per filter — matches how the other list pages
51- // page client-side. Move to `manualPagination` once a school outgrows it.
52 const [list, { refetch }] = createResource(53 const [list, { refetch }] = createResource(
53- () => ({ owner: ownerFilter(), subject: subjectFilter() }),54+ () => ({
55+ page: page(),
56+ owner: ownerFilter(),
57+ subject: subjectFilter(),
58+ visibility: visibilityFilter(),
59+ q: debouncedQuery().trim(),
60+ }),
54 async (filters) => {61 async (filters) => {
55- const items = (62+ const result = await getBankQuestions({
56- await getBankQuestions({63+ limit: BANK_PAGE_SIZE,
57- limit: 100,64+ offset: filters.page * BANK_PAGE_SIZE,
58- ...(filters.owner === "me" ? { owner: "me" } : {}),65+ ...(filters.owner === "me" ? { owner: "me" } : {}),
59- ...(filters.subject !== "all" ? { subject: filters.subject } : {}),66+ ...(filters.subject !== "all" ? { subject: filters.subject } : {}),
60- })67+ ...(filters.visibility !== "all" ? { visibility: filters.visibility } : {}),
61- ).items;68+ ...(filters.q ? { q: filters.q } : {}),
62- const subjects = [...new Set(items.map((item) => item.subject))].filter((id) => !subjectNames()[id]);69+ });
63- const owners = [...new Set(items.map((item) => item.owner))].filter((id) => !ownerNames()[id]);70+ setSubjectNames((current) => {
64- await Promise.all([71+ const next = { ...current };
65- ...subjects.map((id) =>72+ for (const item of result.items) if (item.subject) next[item.subject] = item.subject_name;
66- getSubjectById(id)73+ return next;
67- .then((subject) => setSubjectNames((current) => ({ ...current, [id]: subject.name })))74+ });
68- .catch(() => {}),75+ return result;
69- ),
70- ...owners.map((id) =>
71- getUserById(id)
72- .then((user) =>
73- setOwnerNames((current) => ({
74- ...current,
75- [id]: [user.name, user.surname].filter(Boolean).join(" ") || user.username,
76- })),
77- )
78- .catch(() => {}),
79- ),
80- ]);
81- return items;
82 },76 },
83 );77 );
78+ const total = () => list.latest?.total ?? 0;
84 79
85 // Only courses the teacher can author in supply subjects for a new template.80 // Only courses the teacher can author in supply subjects for a new template.
86 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);81 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);
@@ -96,17 +91,9 @@ function QuestionBankContent() {
96 }),91 }),
97 );92 );
98 93
99- const subjectName = (id: string) => subjectNames()[id] ?? id;
100- const ownerName = (id: string) => ownerNames()[id] ?? id;
101 const canEdit = (question: BankQuestion) =>94 const canEdit = (question: BankQuestion) =>
102 question.owner === auth.user()?.id || hasMinRole(auth.user()?.role, "admin");95 question.owner === auth.user()?.id || hasMinRole(auth.user()?.role, "admin");
103 96
104- const searchTemplate = (question: BankQuestion, query: string) =>
105- [question.text, subjectName(question.subject), ownerName(question.owner)]
106- .join(" ")
107- .toLocaleLowerCase(locale())
108- .includes(query.toLocaleLowerCase(locale()));
109-
110 const columns = createMemo<ColumnDef<BankQuestion>[]>(() => [97 const columns = createMemo<ColumnDef<BankQuestion>[]>(() => [
111 {98 {
112 accessorKey: "text",99 accessorKey: "text",
@@ -130,16 +117,47 @@ function QuestionBankContent() {
130 },117 },
131 {118 {
132 id: "subject",119 id: "subject",
133- accessorFn: (question) => subjectName(question.subject),120+ accessorFn: (question) => question.subject_name,
134 header: t("subjects.subject"),121 header: t("subjects.subject"),
135 meta: { cellClass: "truncate text-muted-foreground" },122 meta: { cellClass: "truncate text-muted-foreground" },
136 },123 },
124+ {
125+ id: "visibility",
126+ accessorFn: (question) => question.visibility,
127+ header: t("bank.whoCanSee"),
128+ meta: { headerClass: "text-center", cellClass: "text-center" },
129+ cell: (cell) => (
130+ <Show
131+ when={cell.row.original.visibility === "school"}
132+ fallback={
133+ <Badge variant="secondary" class="gap-1 whitespace-nowrap">
134+ <IconEyeOff class="h-3 w-3" />
135+ {t("bank.onlyMe")}
136+ </Badge>
137+ }
138+ >
139+ <Badge variant="outline" class="gap-1 whitespace-nowrap border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300">
140+ <IconUsers class="h-3 w-3" />
141+ {t("bank.sharedWithSchool")}
142+ </Badge>
143+ </Show>
144+ ),
145+ },
137 {146 {
138 id: "owner",147 id: "owner",
139- accessorFn: (question) => ownerName(question.owner),148+ accessorFn: (question) => question.owner_name,
140 header: t("bank.owner"),149 header: t("bank.owner"),
141 meta: { cellClass: "truncate text-muted-foreground" },150 meta: { cellClass: "truncate text-muted-foreground" },
142 },151 },
152+ {
153+ id: "used",
154+ accessorFn: (question) => question.used_count,
155+ header: t("bank.usedInExams"),
156+ meta: { headerClass: "text-center", cellClass: "mono text-center text-muted-foreground" },
157+ // A template nobody copied stays blank: "0" is noise on a page where
158+ // most rows are fresh.
159+ cell: (cell) => <Show when={cell.row.original.used_count > 0}>{cell.row.original.used_count}</Show>,
160+ },
143 {161 {
144 accessorKey: "created_at",162 accessorKey: "created_at",
145 header: t("bank.created"),163 header: t("bank.created"),
@@ -188,13 +206,13 @@ function QuestionBankContent() {
188 </Show>206 </Show>
189 207
190 <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">208 <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">
191- <Suspense fallback={<DataTableSkeleton columns={7} rows={8} />}>209+ <Suspense fallback={<DataTableSkeleton columns={9} rows={8} />}>
192 <Show when={list.error}>210 <Show when={list.error}>
193 <Alert variant="destructive">{formatApiError(list.error)}</Alert>211 <Alert variant="destructive">{formatApiError(list.error)}</Alert>
194 </Show>212 </Show>
195 <DataTable213 <DataTable
196 title={t("bank.title")}214 title={t("bank.title")}
197- description={t("bank.subtitle")}215+ description={`${t("bank.subtitle")} ${t("bank.countTotal", { total: total() })}`}
198 actions={216 actions={
199 <Show when={manageableCourses().length > 0}>217 <Show when={manageableCourses().length > 0}>
200 <Button type="button" size="sm" class="min-w-30 rounded-lg" onClick={() => setCreateOpen(true)}>218 <Button type="button" size="sm" class="min-w-30 rounded-lg" onClick={() => setCreateOpen(true)}>
@@ -204,28 +222,51 @@ function QuestionBankContent() {
204 </Show>222 </Show>
205 }223 }
206 columns={columns()}224 columns={columns()}
207- data={list() ?? []}225+ data={list()?.items ?? []}
208- tableClass="table-fixed min-w-5xl"226+ tableClass="table-fixed min-w-6xl"
209 filterPlaceholder={t("bank.search")}227 filterPlaceholder={t("bank.search")}
210- searchPredicate={searchTemplate}228+ searchValue={query()}
229+ onSearchInput={(value) => {
230+ setQuery(value);
231+ setPage(0);
232+ }}
211 enablePagination233 enablePagination
212- pageSize={BANK_PAGE_SIZE}234+ manualPagination={{ pageIndex: page(), pageSize: BANK_PAGE_SIZE, total: total(), onPageChange: setPage }}
213 empty={t("bank.empty")}235 empty={t("bank.empty")}
214 filters={236 filters={
215 <div class="flex flex-wrap items-center gap-2.5">237 <div class="flex flex-wrap items-center gap-2.5">
216 <DropdownSelect238 <DropdownSelect
217 labelPrefix={t("bank.owner")}239 labelPrefix={t("bank.owner")}
218 value={ownerFilter()}240 value={ownerFilter()}
219- onChange={(value) => setOwnerFilter(value as "all" | "me")}241+ onChange={(value) => {
242+ setOwnerFilter(value as "all" | "me");
243+ setPage(0);
244+ }}
220 options={[245 options={[
221 { value: "all", label: t("common.all") },246 { value: "all", label: t("common.all") },
222 { value: "me", label: t("bank.mine") },247 { value: "me", label: t("bank.mine") },
223 ]}248 ]}
224 />249 />
250+ <DropdownSelect
251+ labelPrefix={t("bank.whoCanSee")}
252+ value={visibilityFilter()}
253+ onChange={(value) => {
254+ setVisibilityFilter(value as "all" | "private" | "school");
255+ setPage(0);
256+ }}
257+ options={[
258+ { value: "all", label: t("common.all") },
259+ { value: "private", label: t("bank.onlyMe") },
260+ { value: "school", label: t("bank.sharedWithSchool") },
261+ ]}
262+ />
225 <DropdownSelect263 <DropdownSelect
226 labelPrefix={t("subjects.subject")}264 labelPrefix={t("subjects.subject")}
227 value={subjectFilter()}265 value={subjectFilter()}
228- onChange={(value) => setSubjectFilter(value)}266+ onChange={(value) => {
267+ setSubjectFilter(value);
268+ setPage(0);
269+ }}
229 options={subjectOptions()}270 options={subjectOptions()}
230 />271 />
231 </div>272 </div>
@@ -249,11 +290,11 @@ function QuestionBankContent() {
249 <BankQuestionForm290 <BankQuestionForm
250 initial={editing() ?? undefined}291 initial={editing() ?? undefined}
251 courses={manageableCourses()}292 courses={manageableCourses()}
252- onSaved={async (_question, imagesLost) => {293+ onSaved={async () => {
253 const wasEdit = editing() != null;294 const wasEdit = editing() != null;
254 setCreateOpen(false);295 setCreateOpen(false);
255 setEditing(null);296 setEditing(null);
256- setError(imagesLost ?? "");297+ setError("");
257 setFlash(wasEdit ? t("common.saved") : t("common.created"));298 setFlash(wasEdit ? t("common.saved") : t("common.created"));
258 await refetch();299 await refetch();
259 }}300 }}
vitest.config.tsmodified+2 -0
@@ -11,5 +11,7 @@ export default defineConfig({
11 globals: true,11 globals: true,
12 environment: "node",12 environment: "node",
13 include: ["src/**/*.test.ts"],13 include: ["src/**/*.test.ts"],
14+ // Live-backend suite, run separately: `bun run test:contract`.
15+ exclude: ["**/node_modules/**", "**/dist/**", "src/api/__tests__/contract/**"],
14 },16 },
15 });17 });
vitest.contract.config.tsadded+31 -0
@@ -0,0 +1,31 @@
1+import path from "node:path";
2+import { defineConfig } from "vitest/config";
3+
4+/**
5+ * Contract suite — runs against a REAL backend, never mocked fetch.
6+ * Excluded from `bun run test` (see `exclude` in vitest.config.ts).
7+ *
8+ * Boot a throwaway backend (do not point this at the container on :8080):
9+ * ~/.surrealdb/surreal start --user root --pass root --bind 127.0.0.1:8100 memory
10+ * cd ../../Rust/hezarfen_backend && PORT=8081 DB_URL=ws://127.0.0.1:8100 \
11+ * DB_USER=root DB_PASS=root ADMIN_USERNAME=admin ADMIN_PASSWORD=admin123 cargo run
12+ * Then:
13+ * CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract
14+ *
15+ * Without CONTRACT_BASE_URL the whole suite skips (green, not failed).
16+ * Optional: ADMIN_USERNAME / ADMIN_PASSWORD (default admin / admin123).
17+ */
18+export default defineConfig({
19+ resolve: {
20+ alias: {
21+ "@": path.resolve(__dirname, "./src"),
22+ },
23+ },
24+ test: {
25+ globals: true,
26+ environment: "node",
27+ include: ["src/api/__tests__/contract/**/*.contract.test.ts"],
28+ testTimeout: 30_000,
29+ hookTimeout: 30_000,
30+ },
31+});