🏦 school-wide question bank with two-way exam bridges
Browse files at this commit0f9e79aaf18d95e7b5fbfbdf4aea4aa5114ff735Parent: f986b51- feat
- 🏦 school-wide question bank with two-way exam bridges
32 changed files +1481 -74
- src/api/__tests__/bank-questions/bank-questions.test.ts +161 -0
- src/api/__tests__/client/client.test.ts +16 -0
- src/api/__tests__/exams/exam-questions.test.ts +28 -0
- src/api/__tests__/exams/exams.test.ts +12 -0
- src/api/bank-questions/deleteBankChoiceImage.ts +5 -0
- src/api/bank-questions/deleteBankQuestionById.ts +5 -0
- src/api/bank-questions/deleteBankQuestionImage.ts +5 -0
- src/api/bank-questions/getBankChoiceImageBlob.ts +5 -0
- src/api/bank-questions/getBankQuestionById.ts +6 -0
- src/api/bank-questions/getBankQuestionImageBlob.ts +5 -0
- src/api/bank-questions/getBankQuestions.ts +19 -0
- src/api/bank-questions/index.ts +11 -0
- src/api/bank-questions/patchBankQuestionById.ts +18 -0
- src/api/bank-questions/postBankChoiceImage.ts +8 -0
- src/api/bank-questions/postBankQuestion.ts +15 -0
- src/api/bank-questions/postBankQuestionImage.ts +8 -0
- src/api/client/client.ts +20 -0
- src/api/client/types.ts +26 -0
- src/api/exams/getExamChoiceImageBlob.ts +5 -0
- src/api/exams/index.ts +3 -0
- src/api/exams/postExamQuestionFromBank.ts +14 -0
- src/api/exams/postExamQuestionToBank.ts +7 -0
- src/components/exams/bank-question-form.tsx +127 -0
- src/components/exams/bank-question-picker.tsx +167 -0
- src/components/exams/exam-questions-panel.tsx +182 -35
- src/components/exams/question-form.tsx +103 -39
- src/components/layout/nav-items.ts +2 -0
- src/i18n/messages.ts +87 -0
- src/lib/choice-compaction.test.ts +57 -0
- src/lib/choice-compaction.ts +54 -0
- src/pages/question-bank-page.tsx +292 -0
- src/routes/router.tsx +8 -0
src/api/__tests__/bank-questions/bank-questions.test.tsadded+161 -0
| @@ -0,0 +1,161 @@ | ||
| 1 | +import { afterEach, describe, expect, it, vi } from "vitest"; | |
| 2 | +import { | |
| 3 | + deleteBankChoiceImage, | |
| 4 | + deleteBankQuestionById, | |
| 5 | + deleteBankQuestionImage, | |
| 6 | + getBankChoiceImageBlob, | |
| 7 | + getBankQuestionById, | |
| 8 | + getBankQuestionImageBlob, | |
| 9 | + getBankQuestions, | |
| 10 | + patchBankQuestionById, | |
| 11 | + postBankChoiceImage, | |
| 12 | + postBankQuestion, | |
| 13 | + postBankQuestionImage, | |
| 14 | +} from "../../bank-questions"; | |
| 15 | +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; | |
| 16 | + | |
| 17 | +describe("bank-questions API", () => { | |
| 18 | + afterEach(() => { | |
| 19 | + vi.restoreAllMocks(); | |
| 20 | + }); | |
| 21 | + | |
| 22 | + it("postBankQuestion calls /bank-questions with data", async () => { | |
| 23 | + const mockQuestion = { id: "b1" }; | |
| 24 | + mockFetchSuccess(mockQuestion, 201); | |
| 25 | + | |
| 26 | + const data = { subject_id: "sub1", text: "Q?", kind: "choice" as const, points: 10 }; | |
| 27 | + const result = await postBankQuestion(data); | |
| 28 | + expect(result).toEqual(mockQuestion); | |
| 29 | + | |
| 30 | + const [url, init] = lastFetchCall(); | |
| 31 | + expect(url).toBe("/api/bank-questions"); | |
| 32 | + expect(init?.method).toBe("POST"); | |
| 33 | + expect(init?.body).toBe(JSON.stringify(data)); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("getBankQuestions calls /bank-questions without a query when unfiltered", async () => { | |
| 37 | + const mockPage = { items: [{ id: "b1" }], total: 1 }; | |
| 38 | + mockFetchSuccess(mockPage); | |
| 39 | + | |
| 40 | + const result = await getBankQuestions(); | |
| 41 | + expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); | |
| 42 | + | |
| 43 | + const [url, init] = lastFetchCall(); | |
| 44 | + expect(url).toBe("/api/bank-questions"); | |
| 45 | + expect(init?.method).toBe("GET"); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("getBankQuestions passes subject, owner and page params", async () => { | |
| 49 | + mockFetchSuccess({ items: [], total: 0 }); | |
| 50 | + | |
| 51 | + await getBankQuestions({ subject: "sub1", owner: "me", limit: 20, offset: 40 }); | |
| 52 | + | |
| 53 | + const [url] = lastFetchCall(); | |
| 54 | + expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&limit=20&offset=40"); | |
| 55 | + }); | |
| 56 | + | |
| 57 | + it("getBankQuestionById calls /bank-questions/:bid", async () => { | |
| 58 | + const mockQuestion = { id: "b1" }; | |
| 59 | + mockFetchSuccess(mockQuestion); | |
| 60 | + | |
| 61 | + const result = await getBankQuestionById("b1"); | |
| 62 | + expect(result).toEqual(mockQuestion); | |
| 63 | + | |
| 64 | + const [url, init] = lastFetchCall(); | |
| 65 | + expect(url).toBe("/api/bank-questions/b1"); | |
| 66 | + expect(init?.method).toBe("GET"); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("patchBankQuestionById calls /bank-questions/:bid with updates", async () => { | |
| 70 | + const mockQuestion = { id: "b1", text: "Updated" }; | |
| 71 | + mockFetchSuccess(mockQuestion); | |
| 72 | + | |
| 73 | + const updates = { text: "Updated" }; | |
| 74 | + const result = await patchBankQuestionById("b1", updates); | |
| 75 | + expect(result).toEqual(mockQuestion); | |
| 76 | + | |
| 77 | + const [url, init] = lastFetchCall(); | |
| 78 | + expect(url).toBe("/api/bank-questions/b1"); | |
| 79 | + expect(init?.method).toBe("PATCH"); | |
| 80 | + expect(init?.body).toBe(JSON.stringify(updates)); | |
| 81 | + }); | |
| 82 | + | |
| 83 | + it("deleteBankQuestionById calls /bank-questions/:bid", async () => { | |
| 84 | + mockFetch204(); | |
| 85 | + | |
| 86 | + await deleteBankQuestionById("b1"); | |
| 87 | + | |
| 88 | + const [url, init] = lastFetchCall(); | |
| 89 | + expect(url).toBe("/api/bank-questions/b1"); | |
| 90 | + expect(init?.method).toBe("DELETE"); | |
| 91 | + }); | |
| 92 | + | |
| 93 | + it("postBankQuestionImage calls /bank-questions/:bid/image with FormData", async () => { | |
| 94 | + const mockMeta = { content_type: "image/png", size: 100 }; | |
| 95 | + mockFetchSuccess(mockMeta, 201); | |
| 96 | + | |
| 97 | + const file = new File(["test"], "test.png", { type: "image/png" }); | |
| 98 | + const result = await postBankQuestionImage("b1", file); | |
| 99 | + expect(result).toEqual(mockMeta); | |
| 100 | + | |
| 101 | + const [url, init] = lastFetchCall(); | |
| 102 | + expect(url).toBe("/api/bank-questions/b1/image"); | |
| 103 | + expect(init?.method).toBe("POST"); | |
| 104 | + expect(init?.body).toBeInstanceOf(FormData); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + it("getBankQuestionImageBlob calls /bank-questions/:bid/image", async () => { | |
| 108 | + mockFetchBlob(new Blob(["img"], { type: "image/png" })); | |
| 109 | + | |
| 110 | + const result = await getBankQuestionImageBlob("b1"); | |
| 111 | + expect(result).toBeInstanceOf(Blob); | |
| 112 | + | |
| 113 | + const [url, init] = lastFetchCall(); | |
| 114 | + expect(url).toBe("/api/bank-questions/b1/image"); | |
| 115 | + expect(init?.method).toBeUndefined(); | |
| 116 | + }); | |
| 117 | + | |
| 118 | + it("deleteBankQuestionImage calls /bank-questions/:bid/image", async () => { | |
| 119 | + mockFetch204(); | |
| 120 | + | |
| 121 | + await deleteBankQuestionImage("b1"); | |
| 122 | + | |
| 123 | + const [url, init] = lastFetchCall(); | |
| 124 | + expect(url).toBe("/api/bank-questions/b1/image"); | |
| 125 | + expect(init?.method).toBe("DELETE"); | |
| 126 | + }); | |
| 127 | + | |
| 128 | + it("postBankChoiceImage calls /bank-questions/:bid/choices/:index/image with FormData", async () => { | |
| 129 | + const mockMeta = { content_type: "image/png", size: 100 }; | |
| 130 | + mockFetchSuccess(mockMeta, 201); | |
| 131 | + | |
| 132 | + const file = new File(["test"], "test.png", { type: "image/png" }); | |
| 133 | + const result = await postBankChoiceImage("b1", 2, file); | |
| 134 | + expect(result).toEqual(mockMeta); | |
| 135 | + | |
| 136 | + const [url, init] = lastFetchCall(); | |
| 137 | + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); | |
| 138 | + expect(init?.method).toBe("POST"); | |
| 139 | + expect(init?.body).toBeInstanceOf(FormData); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:index/image", async () => { | |
| 143 | + mockFetchBlob(new Blob(["img"], { type: "image/png" })); | |
| 144 | + | |
| 145 | + const result = await getBankChoiceImageBlob("b1", 2); | |
| 146 | + expect(result).toBeInstanceOf(Blob); | |
| 147 | + | |
| 148 | + const [url] = lastFetchCall(); | |
| 149 | + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:index/image", async () => { | |
| 153 | + mockFetch204(); | |
| 154 | + | |
| 155 | + await deleteBankChoiceImage("b1", 2); | |
| 156 | + | |
| 157 | + const [url, init] = lastFetchCall(); | |
| 158 | + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); | |
| 159 | + expect(init?.method).toBe("DELETE"); | |
| 160 | + }); | |
| 161 | +}); |
src/api/__tests__/client/client.test.tsmodified+16 -0
| @@ -139,6 +139,22 @@ describe("client", () => { | ||
| 139 | 139 | ); |
| 140 | 140 | }); |
| 141 | 141 | |
| 142 | + it("localizes question-bank permission and attempt conflicts", () => { | |
| 143 | + // exact backend strings from web/bank_questions.rs + web/exams.rs | |
| 144 | + expect(formatApiErrorMessage("only the template's owner or an admin can change it", "tr")).toBe( | |
| 145 | + "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", | |
| 146 | + ); | |
| 147 | + expect( | |
| 148 | + formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", "en"), | |
| 149 | + ).toBe("Only this course's teachers or a manager can save this question to the bank."); | |
| 150 | + expect(formatApiError(new ApiError(409, "cannot change questions after attempts have started"), "tr")).toBe( | |
| 151 | + "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", | |
| 152 | + ); | |
| 153 | + expect( | |
| 154 | + formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can author questions", "tr"), | |
| 155 | + ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir."); | |
| 156 | + }); | |
| 157 | + | |
| 142 | 158 | it("handles unknown messages with sentence case", () => { |
| 143 | 159 | expect(formatApiErrorMessage("custom error occurred", "en")).toBe("Custom error occurred"); |
| 144 | 160 | expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı: Custom error occurred"); |
src/api/__tests__/exams/exam-questions.test.tsmodified+28 -0
| @@ -7,6 +7,8 @@ import { postExamQuestionImage } from "../../exams"; | ||
| 7 | 7 | import { deleteExamQuestionImage } from "../../exams"; |
| 8 | 8 | import { postExamChoiceImage } from "../../exams"; |
| 9 | 9 | import { deleteExamChoiceImage } from "../../exams"; |
| 10 | +import { postExamQuestionFromBank } from "../../exams"; | |
| 11 | +import { postExamQuestionToBank } from "../../exams"; | |
| 10 | 12 | import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; |
| 11 | 13 | |
| 12 | 14 | describe("exams API - questions", () => { |
| @@ -111,4 +113,30 @@ describe("exams API - questions", () => { | ||
| 111 | 113 | expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); |
| 112 | 114 | expect(init?.method).toBe("DELETE"); |
| 113 | 115 | }); |
| 116 | + | |
| 117 | + it("postExamQuestionFromBank calls /exams/:id/questions/from-bank/:bid with subject_id", async () => { | |
| 118 | + const mockQuestion = { id: "q9", source_bank: "b1" }; | |
| 119 | + mockFetchSuccess(mockQuestion, 201); | |
| 120 | + | |
| 121 | + const result = await postExamQuestionFromBank("ex1", "b1", "sub1"); | |
| 122 | + expect(result).toEqual(mockQuestion); | |
| 123 | + | |
| 124 | + const [url, init] = lastFetchCall(); | |
| 125 | + expect(url).toBe("/api/exams/ex1/questions/from-bank/b1"); | |
| 126 | + expect(init?.method).toBe("POST"); | |
| 127 | + expect(init?.body).toBe(JSON.stringify({ subject_id: "sub1" })); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("postExamQuestionToBank calls /exams/:id/questions/:qid/to-bank with no body", async () => { | |
| 131 | + const mockBankQuestion = { id: "b1", source_exam: "ex1" }; | |
| 132 | + mockFetchSuccess(mockBankQuestion, 201); | |
| 133 | + | |
| 134 | + const result = await postExamQuestionToBank("ex1", "q1"); | |
| 135 | + expect(result).toEqual(mockBankQuestion); | |
| 136 | + | |
| 137 | + const [url, init] = lastFetchCall(); | |
| 138 | + expect(url).toBe("/api/exams/ex1/questions/q1/to-bank"); | |
| 139 | + expect(init?.method).toBe("POST"); | |
| 140 | + expect(init?.body).toBeUndefined(); | |
| 141 | + }); | |
| 114 | 142 | }); |
src/api/__tests__/exams/exams.test.tsmodified+12 -0
| @@ -4,6 +4,7 @@ import { getExamById } from "../../exams"; | ||
| 4 | 4 | import { patchExamById } from "../../exams"; |
| 5 | 5 | import { deleteExamById } from "../../exams"; |
| 6 | 6 | import { getExamQuestionImageBlob } from "../../exams"; |
| 7 | +import { getExamChoiceImageBlob } from "../../exams"; | |
| 7 | 8 | import { postExamAttemptAnswerImage } from "../../exams"; |
| 8 | 9 | import { deleteExamAttemptAnswerImage } from "../../exams"; |
| 9 | 10 | import { getExamAnswerImageBlob } from "../../exams"; |
| @@ -26,6 +27,17 @@ describe("exams API - core", () => { | ||
| 26 | 27 | expect(init?.method).toBe("GET"); |
| 27 | 28 | }); |
| 28 | 29 | |
| 30 | + it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:index/image", async () => { | |
| 31 | + mockFetchBlob(new Blob(["img"], { type: "image/png" })); | |
| 32 | + | |
| 33 | + const result = await getExamChoiceImageBlob("ex1", "q1", 2); | |
| 34 | + expect(result).toBeInstanceOf(Blob); | |
| 35 | + | |
| 36 | + const [url, init] = lastFetchCall(); | |
| 37 | + expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); | |
| 38 | + expect(init?.method).toBeUndefined(); | |
| 39 | + }); | |
| 40 | + | |
| 29 | 41 | it("getExamById calls /exams/:id", async () => { |
| 30 | 42 | const mockExam = { id: "ex1", title: "Exam" }; |
| 31 | 43 | mockFetchSuccess(mockExam); |
src/api/bank-questions/deleteBankChoiceImage.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | + | |
| 3 | +export function deleteBankChoiceImage(bankQuestionId: string, index: number): Promise<void> { | |
| 4 | + return client<void>(`/bank-questions/${bankQuestionId}/choices/${index}/image`, { method: "DELETE" }); | |
| 5 | +} |
src/api/bank-questions/deleteBankQuestionById.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | + | |
| 3 | +export function deleteBankQuestionById(bankQuestionId: string): Promise<void> { | |
| 4 | + return client<void>(`/bank-questions/${bankQuestionId}`, { method: "DELETE" }); | |
| 5 | +} |
src/api/bank-questions/deleteBankQuestionImage.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | + | |
| 3 | +export function deleteBankQuestionImage(bankQuestionId: string): Promise<void> { | |
| 4 | + return client<void>(`/bank-questions/${bankQuestionId}/image`, { method: "DELETE" }); | |
| 5 | +} |
src/api/bank-questions/getBankChoiceImageBlob.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { blobClient } from "../client"; | |
| 2 | + | |
| 3 | +export function getBankChoiceImageBlob(bankQuestionId: string, index: number, signal?: AbortSignal): Promise<Blob> { | |
| 4 | + return blobClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, signal); | |
| 5 | +} |
src/api/bank-questions/getBankQuestionById.tsadded+6 -0
| @@ -0,0 +1,6 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { BankQuestion } from "../client"; | |
| 3 | + | |
| 4 | +export function getBankQuestionById(bankQuestionId: string, signal?: AbortSignal): Promise<BankQuestion> { | |
| 5 | + return client<BankQuestion>(`/bank-questions/${bankQuestionId}`, { signal }); | |
| 6 | +} |
src/api/bank-questions/getBankQuestionImageBlob.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { blobClient } from "../client"; | |
| 2 | + | |
| 3 | +export function getBankQuestionImageBlob(bankQuestionId: string, signal?: AbortSignal): Promise<Blob> { | |
| 4 | + return blobClient(`/bank-questions/${bankQuestionId}/image`, signal); | |
| 5 | +} |
src/api/bank-questions/getBankQuestions.tsadded+19 -0
| @@ -0,0 +1,19 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; | |
| 3 | +import type { BankQuestion } from "../client"; | |
| 4 | + | |
| 5 | +/** `owner` takes a user id or the literal "me". */ | |
| 6 | +export type BankQuestionFilters = PageParams & { subject?: string; owner?: string }; | |
| 7 | + | |
| 8 | +export async function getBankQuestions( | |
| 9 | + params?: BankQuestionFilters, | |
| 10 | + signal?: AbortSignal, | |
| 11 | +): Promise<Page<BankQuestion>> { | |
| 12 | + const query = new URLSearchParams(); | |
| 13 | + if (params?.subject) query.set("subject", params.subject); | |
| 14 | + if (params?.owner) query.set("owner", params.owner); | |
| 15 | + appendPageParams(query, params); | |
| 16 | + const value = query.toString(); | |
| 17 | + const data = await client<unknown>(`/bank-questions${value ? `?${value}` : ""}`, { signal }); | |
| 18 | + return normalizePage<BankQuestion>(data); | |
| 19 | +} |
src/api/bank-questions/index.tsadded+11 -0
| @@ -0,0 +1,11 @@ | ||
| 1 | +export * from "./postBankQuestion"; | |
| 2 | +export * from "./getBankQuestions"; | |
| 3 | +export * from "./getBankQuestionById"; | |
| 4 | +export * from "./patchBankQuestionById"; | |
| 5 | +export * from "./deleteBankQuestionById"; | |
| 6 | +export * from "./postBankQuestionImage"; | |
| 7 | +export * from "./getBankQuestionImageBlob"; | |
| 8 | +export * from "./deleteBankQuestionImage"; | |
| 9 | +export * from "./postBankChoiceImage"; | |
| 10 | +export * from "./getBankChoiceImageBlob"; | |
| 11 | +export * from "./deleteBankChoiceImage"; |
src/api/bank-questions/patchBankQuestionById.tsadded+18 -0
| @@ -0,0 +1,18 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { BankQuestion, QuestionKind } from "../client"; | |
| 3 | + | |
| 4 | +export type PatchBankQuestionBody = { | |
| 5 | + subject_id?: string; | |
| 6 | + text?: string; | |
| 7 | + kind?: QuestionKind; | |
| 8 | + points?: number; | |
| 9 | + choices?: string[] | null; | |
| 10 | + correct?: number | null; | |
| 11 | +}; | |
| 12 | + | |
| 13 | +export function patchBankQuestionById( | |
| 14 | + bankQuestionId: string, | |
| 15 | + body: PatchBankQuestionBody, | |
| 16 | +): Promise<BankQuestion> { | |
| 17 | + return client<BankQuestion>(`/bank-questions/${bankQuestionId}`, { method: "PATCH", body }); | |
| 18 | +} |
src/api/bank-questions/postBankChoiceImage.tsadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { formClient } from "../client"; | |
| 2 | +import type { ImageMeta } from "../client"; | |
| 3 | + | |
| 4 | +export function postBankChoiceImage(bankQuestionId: string, index: number, file: File, signal?: AbortSignal): Promise<ImageMeta> { | |
| 5 | + const body = new FormData(); | |
| 6 | + body.append("file", file); | |
| 7 | + return formClient<ImageMeta>(`/bank-questions/${bankQuestionId}/choices/${index}/image`, body, signal); | |
| 8 | +} |
src/api/bank-questions/postBankQuestion.tsadded+15 -0
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { BankQuestion, QuestionKind } from "../client"; | |
| 3 | + | |
| 4 | +export type BankQuestionBody = { | |
| 5 | + subject_id: string; | |
| 6 | + text: string; | |
| 7 | + kind: QuestionKind; | |
| 8 | + points: number; | |
| 9 | + choices?: string[] | null; | |
| 10 | + correct?: number | null; | |
| 11 | +}; | |
| 12 | + | |
| 13 | +export function postBankQuestion(body: BankQuestionBody): Promise<BankQuestion> { | |
| 14 | + return client<BankQuestion>(`/bank-questions`, { method: "POST", body }); | |
| 15 | +} |
src/api/bank-questions/postBankQuestionImage.tsadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +import { formClient } from "../client"; | |
| 2 | +import type { ImageMeta } from "../client"; | |
| 3 | + | |
| 4 | +export function postBankQuestionImage(bankQuestionId: string, file: File, signal?: AbortSignal): Promise<ImageMeta> { | |
| 5 | + const body = new FormData(); | |
| 6 | + body.append("file", file); | |
| 7 | + return formClient<ImageMeta>(`/bank-questions/${bankQuestionId}/image`, body, signal); | |
| 8 | +} |
src/api/client/client.tsmodified+20 -0
| @@ -90,6 +90,26 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | ||
| 90 | 90 | en: "The repeated slots overlap each other.", |
| 91 | 91 | tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", |
| 92 | 92 | }, |
| 93 | + "only the template's owner or an admin can change it": { | |
| 94 | + en: "Only the teacher who created this template (or an admin) can change it.", | |
| 95 | + tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", | |
| 96 | + }, | |
| 97 | + "only the course creator, an assigned teacher, or a manager/admin can author questions": { | |
| 98 | + en: "Only this course's teachers or a manager can add questions to this exam.", | |
| 99 | + tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.", | |
| 100 | + }, | |
| 101 | + "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": { | |
| 102 | + en: "Only this course's teachers or a manager can save this question to the bank.", | |
| 103 | + tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.", | |
| 104 | + }, | |
| 105 | + "cannot change questions after attempts have started": { | |
| 106 | + en: "Students have already started this exam, so its questions can no longer change.", | |
| 107 | + tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", | |
| 108 | + }, | |
| 109 | + "bank questions still reference this subject — re-tag or delete them first": { | |
| 110 | + en: "Question bank templates still use this subject. Re-tag or delete them first.", | |
| 111 | + tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.", | |
| 112 | + }, | |
| 93 | 113 | "course not found": { |
| 94 | 114 | en: "Course not found.", |
| 95 | 115 | tr: "Ders bulunamadı.", |
src/api/client/types.tsmodified+26 -0
| @@ -125,6 +125,15 @@ export const APPOINTMENT_LIMITS = { | ||
| 125 | 125 | maxSlotOccurrences: 52, // MAX_SLOT_OCCURRENCES for repeat_weekly |
| 126 | 126 | } as const; |
| 127 | 127 | |
| 128 | +export const BANK_QUESTION_LIMITS = { | |
| 129 | + textMaxLen: 2000, // MAX_QUESTION_TEXT_LEN | |
| 130 | + choiceTextMaxLen: 500, // MAX_CHOICE_TEXT_LEN | |
| 131 | + minPoints: 1, // MIN_QUESTION_POINTS | |
| 132 | + maxPoints: 100, // MAX_QUESTION_POINTS | |
| 133 | + minChoices: 2, // MIN_QUESTION_CHOICES | |
| 134 | + maxChoices: 10, // MAX_QUESTION_CHOICES | |
| 135 | +} as const; | |
| 136 | + | |
| 128 | 137 | export type Course = { |
| 129 | 138 | id: string; |
| 130 | 139 | creator: PersonRef; |
| @@ -209,6 +218,23 @@ export type ExamQuestion = { | ||
| 209 | 218 | correct: number | null; |
| 210 | 219 | image?: ImageMeta | null; |
| 211 | 220 | choice_images?: (ImageMeta | null)[] | null; |
| 221 | + source_bank?: string | null; // bank question this was copied from, if any | |
| 222 | +}; | |
| 223 | + | |
| 224 | +/** Reusable question stored in the school-wide question bank, outside any exam. */ | |
| 225 | +export type BankQuestion = { | |
| 226 | + id: string; | |
| 227 | + owner: string; // user id | |
| 228 | + subject: string; // subject id (origin metadata) | |
| 229 | + text: string; | |
| 230 | + kind: QuestionKind; | |
| 231 | + points: number; | |
| 232 | + choices: string[] | null; | |
| 233 | + correct: number | null; | |
| 234 | + image?: ImageMeta | null; | |
| 235 | + choice_images?: (ImageMeta | null)[] | null; | |
| 236 | + source_exam?: string | null; | |
| 237 | + created_at: number; // UTC unix ms | |
| 212 | 238 | }; |
| 213 | 239 | |
| 214 | 240 | export type ExamAttempt = { |
src/api/exams/getExamChoiceImageBlob.tsadded+5 -0
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { blobClient } from "../client"; | |
| 2 | + | |
| 3 | +export function getExamChoiceImageBlob(examId: string, questionId: string, index: number, signal?: AbortSignal): Promise<Blob> { | |
| 4 | + return blobClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, signal); | |
| 5 | +} |
src/api/exams/index.tsmodified+3 -0
| @@ -8,6 +8,7 @@ export * from "./patchExamQuestionById"; | ||
| 8 | 8 | export * from "./deleteExamQuestionById"; |
| 9 | 9 | export * from "./postExamQuestionImage"; |
| 10 | 10 | export * from "./getExamQuestionImageBlob"; |
| 11 | +export * from "./getExamChoiceImageBlob"; | |
| 11 | 12 | export * from "./deleteExamQuestionImage"; |
| 12 | 13 | export * from "./postExamChoiceImage"; |
| 13 | 14 | export * from "./deleteExamChoiceImage"; |
| @@ -35,3 +36,5 @@ export * from "./getExamReviewAttempts"; | ||
| 35 | 36 | export * from "./getExamReviewAttemptAnswers"; |
| 36 | 37 | export * from "./getExamReviewAttemptAnswerImage"; |
| 37 | 38 | export * from "./getStudentMarksHistory"; |
| 39 | +export * from "./postExamQuestionFromBank"; | |
| 40 | +export * from "./postExamQuestionToBank"; |
src/api/exams/postExamQuestionFromBank.tsadded+14 -0
| @@ -0,0 +1,14 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { ExamQuestion } from "../client"; | |
| 3 | + | |
| 4 | +/** Copy a bank question into this exam; `subjectId` is the exam-side subject. */ | |
| 5 | +export function postExamQuestionFromBank( | |
| 6 | + examId: string, | |
| 7 | + bankQuestionId: string, | |
| 8 | + subjectId: string, | |
| 9 | +): Promise<ExamQuestion> { | |
| 10 | + return client<ExamQuestion>(`/exams/${examId}/questions/from-bank/${bankQuestionId}`, { | |
| 11 | + method: "POST", | |
| 12 | + body: { subject_id: subjectId }, | |
| 13 | + }); | |
| 14 | +} |
src/api/exams/postExamQuestionToBank.tsadded+7 -0
| @@ -0,0 +1,7 @@ | ||
| 1 | +import { client } from "../client"; | |
| 2 | +import type { BankQuestion } from "../client"; | |
| 3 | + | |
| 4 | +/** Copy an exam question into the caller's question bank. */ | |
| 5 | +export function postExamQuestionToBank(examId: string, questionId: string): Promise<BankQuestion> { | |
| 6 | + return client<BankQuestion>(`/exams/${examId}/questions/${questionId}/to-bank`, { method: "POST" }); | |
| 7 | +} |
src/components/exams/bank-question-form.tsxadded+127 -0
| @@ -0,0 +1,127 @@ | ||
| 1 | +import { For, Show, createResource, createSignal } from "solid-js"; | |
| 2 | +import type { BankQuestion, Course } from "@/api/client"; | |
| 3 | +import { | |
| 4 | + getBankChoiceImageBlob, | |
| 5 | + patchBankQuestionById, | |
| 6 | + postBankChoiceImage, | |
| 7 | + postBankQuestion, | |
| 8 | + postBankQuestionImage, | |
| 9 | +} from "@/api/bank-questions"; | |
| 10 | +import { getBankQuestionImageBlob } from "@/api/bank-questions"; | |
| 11 | +import { getCourseSubjects } from "@/api/courses"; | |
| 12 | +import { getSubjectById } from "@/api/subjects"; | |
| 13 | +import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; | |
| 14 | +import { planChoiceImageRestore } from "@/lib/choice-compaction"; | |
| 15 | +import { Label } from "@/components/ui/label"; | |
| 16 | +import { Select } from "@/components/ui/select"; | |
| 17 | +import { useT } from "@/stores/preferences-context"; | |
| 18 | + | |
| 19 | +/** | |
| 20 | + * Create/edit a bank template. Wraps the shared `QuestionForm` with the | |
| 21 | + * course→subject pick the bank needs (a template carries a subject id, but the | |
| 22 | + * backend has no school-wide subject list — subjects are reached through a course). | |
| 23 | + */ | |
| 24 | +export function BankQuestionForm(props: { | |
| 25 | + initial?: BankQuestion; | |
| 26 | + courses: Course[]; | |
| 27 | + /** `imagesLost` is set when an option image could not be carried over the edit. */ | |
| 28 | + onSaved: (question: BankQuestion, imagesLost?: string) => void; | |
| 29 | + onCancel: () => void; | |
| 30 | +}) { | |
| 31 | + const t = useT(); | |
| 32 | + // Editing: resolve the template's subject to learn which course to preselect. | |
| 33 | + const [initialCourse] = createResource( | |
| 34 | + () => props.initial?.subject ?? null, | |
| 35 | + async (subjectId) => (await getSubjectById(subjectId).catch(() => null))?.course ?? "", | |
| 36 | + ); | |
| 37 | + const [courseId, setCourseId] = createSignal(""); | |
| 38 | + const selectedCourse = () => courseId() || initialCourse() || props.courses[0]?.id || ""; | |
| 39 | + const [subjects] = createResource( | |
| 40 | + () => selectedCourse() || null, | |
| 41 | + async (id) => (await getCourseSubjects(id)).items, | |
| 42 | + ); | |
| 43 | + | |
| 44 | + const imageBase = () => `/api/bank-questions/${props.initial?.id}`; | |
| 45 | + | |
| 46 | + const submit = async (values: QuestionValues) => { | |
| 47 | + const { image, choice_images, choice_sources, ...body } = values; | |
| 48 | + const existing = props.initial; | |
| 49 | + | |
| 50 | + // PATCH with a `choices` key wipes every stored option image server-side, so | |
| 51 | + // fetch the ones the user is keeping first and put them back afterwards. | |
| 52 | + // `choice_sources` maps each surviving choice to the option it came from, | |
| 53 | + // because blank choices are dropped and would otherwise shift the indices. | |
| 54 | + const lost: number[] = []; | |
| 55 | + const keep: { index: number; file: File }[] = []; | |
| 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 | + } | |
| 67 | + | |
| 68 | + const saved = existing | |
| 69 | + ? await patchBankQuestionById(existing.id, body) | |
| 70 | + : await postBankQuestion(body); | |
| 71 | + if (image) await postBankQuestionImage(saved.id, image); | |
| 72 | + for (const [index, file] of (choice_images ?? []).entries()) { | |
| 73 | + if (file) await postBankChoiceImage(saved.id, index, file); | |
| 74 | + } | |
| 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 | + props.onSaved( | |
| 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 | + }; | |
| 90 | + | |
| 91 | + return ( | |
| 92 | + <div class="space-y-4"> | |
| 93 | + <p class="rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-xs text-muted-foreground"> | |
| 94 | + {t("bank.copyNotice")} | |
| 95 | + </p> | |
| 96 | + | |
| 97 | + <div class="space-y-1.5 rounded-lg border bg-card p-3.5 shadow-xs"> | |
| 98 | + <Label for="bank-course" class="text-xs font-semibold text-muted-foreground">{t("nav.courses")}</Label> | |
| 99 | + <Select | |
| 100 | + id="bank-course" | |
| 101 | + class="h-9 py-1.5 text-sm" | |
| 102 | + value={selectedCourse()} | |
| 103 | + onChange={(event) => setCourseId(event.currentTarget.value)} | |
| 104 | + > | |
| 105 | + <For each={props.courses}>{(course) => <option value={course.id}>{course.title}</option>}</For> | |
| 106 | + </Select> | |
| 107 | + <p class="text-[11px] text-muted-foreground">{t("bank.courseHint")}</p> | |
| 108 | + </div> | |
| 109 | + | |
| 110 | + <Show when={props.initial?.choice_images?.some(Boolean)}> | |
| 111 | + <p class="rounded-lg border border-destructive/20 bg-destructive/8 px-3 py-2 text-xs text-destructive"> | |
| 112 | + {t("bank.choiceImagesWarning")} | |
| 113 | + </p> | |
| 114 | + </Show> | |
| 115 | + | |
| 116 | + <QuestionForm | |
| 117 | + initial={props.initial} | |
| 118 | + subjects={subjects() ?? []} | |
| 119 | + imageSrc={props.initial?.image ? `${imageBase()}/image` : undefined} | |
| 120 | + choiceImageSrc={(index) => `${imageBase()}/choices/${index}/image`} | |
| 121 | + loadImageBlob={props.initial ? () => getBankQuestionImageBlob(props.initial!.id) : undefined} | |
| 122 | + onSubmit={submit} | |
| 123 | + onCancel={props.onCancel} | |
| 124 | + /> | |
| 125 | + </div> | |
| 126 | + ); | |
| 127 | +} |
src/components/exams/bank-question-picker.tsxadded+167 -0
| @@ -0,0 +1,167 @@ | ||
| 1 | +import { For, Show, createMemo, createResource, createSignal } from "solid-js"; | |
| 2 | +import type { BankQuestion, Subject } from "@/api/client"; | |
| 3 | +import { formatApiError } from "@/api/client"; | |
| 4 | +import { getBankQuestions } from "@/api/bank-questions"; | |
| 5 | +import { Badge } from "@/components/ui/badge"; | |
| 6 | +import { Button } from "@/components/ui/button"; | |
| 7 | +import { Input } from "@/components/ui/input"; | |
| 8 | +import { Label } from "@/components/ui/label"; | |
| 9 | +import { Select } from "@/components/ui/select"; | |
| 10 | +import { cn } from "@/lib/cn"; | |
| 11 | +import { usePreferences, useT } from "@/stores/preferences-context"; | |
| 12 | + | |
| 13 | +const BANK_LIMIT = 100; | |
| 14 | + | |
| 15 | +/** Pick a bank template and copy it into an exam under one of that exam's subjects. */ | |
| 16 | +export function BankQuestionPicker(props: { | |
| 17 | + subjects: Subject[]; | |
| 18 | + onInsert: (bankQuestionId: string, subjectId: string) => Promise<void>; | |
| 19 | + onCancel: () => void; | |
| 20 | +}) { | |
| 21 | + const t = useT(); | |
| 22 | + const { locale } = usePreferences(); | |
| 23 | + const [query, setQuery] = createSignal(""); | |
| 24 | + const [selected, setSelected] = createSignal<BankQuestion | null>(null); | |
| 25 | + const [subjectId, setSubjectId] = createSignal(""); | |
| 26 | + const [error, setError] = createSignal(""); | |
| 27 | + const [pending, setPending] = createSignal(false); | |
| 28 | + // ponytail: first 100 templates, narrowed client-side — the bank has no text | |
| 29 | + // search endpoint. Swap for a server query when the bank outgrows one page. | |
| 30 | + const [templates] = createResource(async () => (await getBankQuestions({ limit: BANK_LIMIT })).items); | |
| 31 | + | |
| 32 | + const targetSubject = () => subjectId() || props.subjects[0]?.id || ""; | |
| 33 | + const visible = createMemo(() => { | |
| 34 | + const q = query().trim().toLocaleLowerCase(locale()); | |
| 35 | + const items = templates() ?? []; | |
| 36 | + return q ? items.filter((item) => item.text.toLocaleLowerCase(locale()).includes(q)) : items; | |
| 37 | + }); | |
| 38 | + | |
| 39 | + const insert = async () => { | |
| 40 | + const template = selected(); | |
| 41 | + const subject = targetSubject(); | |
| 42 | + if (!template || !subject || pending()) return; | |
| 43 | + setError(""); | |
| 44 | + setPending(true); | |
| 45 | + try { | |
| 46 | + await props.onInsert(template.id, subject); | |
| 47 | + } catch (err) { | |
| 48 | + setError(formatApiError(err)); | |
| 49 | + } finally { | |
| 50 | + setPending(false); | |
| 51 | + } | |
| 52 | + }; | |
| 53 | + | |
| 54 | + return ( | |
| 55 | + <div class="space-y-3"> | |
| 56 | + <p class="rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-xs text-muted-foreground"> | |
| 57 | + {t("bank.copyNotice")} | |
| 58 | + </p> | |
| 59 | + | |
| 60 | + <Input | |
| 61 | + class="h-9 rounded-lg text-sm" | |
| 62 | + value={query()} | |
| 63 | + placeholder={t("bank.search")} | |
| 64 | + onInput={(event) => setQuery(event.currentTarget.value)} | |
| 65 | + /> | |
| 66 | + | |
| 67 | + <div class="max-h-72 space-y-1.5 overflow-y-auto rounded-lg border bg-muted/20 p-1.5"> | |
| 68 | + <Show | |
| 69 | + when={visible().length > 0} | |
| 70 | + fallback={<p class="p-3 text-center text-sm text-muted-foreground">{t("bank.pickerEmpty")}</p>} | |
| 71 | + > | |
| 72 | + <For each={visible()}> | |
| 73 | + {(template) => ( | |
| 74 | + <button | |
| 75 | + type="button" | |
| 76 | + class={cn( | |
| 77 | + "w-full rounded-md border px-3 py-2 text-left transition-colors", | |
| 78 | + selected()?.id === template.id | |
| 79 | + ? "border-primary/50 bg-primary/10" | |
| 80 | + : "border-transparent bg-background hover:bg-muted/60", | |
| 81 | + )} | |
| 82 | + onClick={() => setSelected(template)} | |
| 83 | + > | |
| 84 | + <p class="line-clamp-2 text-sm font-medium">{template.text}</p> | |
| 85 | + <div class="mt-1 flex flex-wrap items-center gap-1.5"> | |
| 86 | + <Badge variant="outline" class="text-[10px]"> | |
| 87 | + {template.kind === "choice" ? t("questions.kind.choice") : t("questions.kind.text")} | |
| 88 | + </Badge> | |
| 89 | + <Badge variant="secondary" class="font-mono text-[10px]"> | |
| 90 | + {template.points} {t("questions.points")} | |
| 91 | + </Badge> | |
| 92 | + </div> | |
| 93 | + </button> | |
| 94 | + )} | |
| 95 | + </For> | |
| 96 | + </Show> | |
| 97 | + </div> | |
| 98 | + | |
| 99 | + <Show when={selected()}> | |
| 100 | + {(template) => ( | |
| 101 | + <div class="space-y-2 rounded-lg border bg-card p-3 shadow-xs"> | |
| 102 | + <p class="whitespace-pre-wrap text-sm font-medium">{template().text}</p> | |
| 103 | + <Show when={template().image}> | |
| 104 | + <img | |
| 105 | + src={`/api/bank-questions/${template().id}/image`} | |
| 106 | + alt={t("questions.image")} | |
| 107 | + class="h-40 w-full max-w-md rounded-md border bg-muted/20 object-contain" | |
| 108 | + /> | |
| 109 | + </Show> | |
| 110 | + <Show when={template().kind === "choice"}> | |
| 111 | + <ol class="grid gap-1 text-sm"> | |
| 112 | + <For each={template().choices ?? []}> | |
| 113 | + {(choice, index) => ( | |
| 114 | + <li | |
| 115 | + class={cn( | |
| 116 | + "flex items-start gap-2 rounded-md px-2 py-1", | |
| 117 | + index() === template().correct ? "bg-primary/10 font-medium" : "text-muted-foreground", | |
| 118 | + )} | |
| 119 | + > | |
| 120 | + <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> | |
| 122 | + </li> | |
| 123 | + )} | |
| 124 | + </For> | |
| 125 | + </ol> | |
| 126 | + </Show> | |
| 127 | + </div> | |
| 128 | + )} | |
| 129 | + </Show> | |
| 130 | + | |
| 131 | + <div class="space-y-1.5"> | |
| 132 | + <Label for="bank-target-subject" class="text-xs font-semibold text-muted-foreground"> | |
| 133 | + {t("bank.targetSubject")} | |
| 134 | + </Label> | |
| 135 | + <Show | |
| 136 | + when={props.subjects.length > 0} | |
| 137 | + fallback={<p class="text-xs text-destructive">{t("bank.noSubjects")}</p>} | |
| 138 | + > | |
| 139 | + <Select | |
| 140 | + id="bank-target-subject" | |
| 141 | + class="h-9 py-1.5 text-sm" | |
| 142 | + value={targetSubject()} | |
| 143 | + onChange={(event) => setSubjectId(event.currentTarget.value)} | |
| 144 | + > | |
| 145 | + <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For> | |
| 146 | + </Select> | |
| 147 | + </Show> | |
| 148 | + </div> | |
| 149 | + | |
| 150 | + {error() && <p class="rounded-sm bg-destructive/10 px-3 py-1.5 text-sm text-destructive">{error()}</p>} | |
| 151 | + | |
| 152 | + <div class="flex flex-wrap items-center gap-2 pt-1"> | |
| 153 | + <Button | |
| 154 | + type="button" | |
| 155 | + class="h-8 text-xs font-semibold" | |
| 156 | + disabled={!selected() || !targetSubject() || pending()} | |
| 157 | + onClick={() => void insert()} | |
| 158 | + > | |
| 159 | + {t("bank.insert")} | |
| 160 | + </Button> | |
| 161 | + <Button type="button" variant="outline" class="h-8 text-xs font-semibold" onClick={props.onCancel}> | |
| 162 | + {t("common.cancel")} | |
| 163 | + </Button> | |
| 164 | + </div> | |
| 165 | + </div> | |
| 166 | + ); | |
| 167 | +} |
src/components/exams/exam-questions-panel.tsxmodified+182 -35
| @@ -3,7 +3,11 @@ import { deleteExamChoiceImage } from "@/api/exams"; | ||
| 3 | 3 | import { deleteExamQuestionImage } from "@/api/exams"; |
| 4 | 4 | import { deleteExamQuestionById } from "@/api/exams"; |
| 5 | 5 | import { getCourseSubjects } from "@/api/courses"; |
| 6 | +import { getExamChoiceImageBlob } from "@/api/exams"; | |
| 7 | +import { getExamQuestionImageBlob } from "@/api/exams"; | |
| 6 | 8 | import { getExamQuestions } from "@/api/exams"; |
| 9 | +import { postExamQuestionFromBank } from "@/api/exams"; | |
| 10 | +import { postExamQuestionToBank } from "@/api/exams"; | |
| 7 | 11 | import { patchExamQuestionById } from "@/api/exams"; |
| 8 | 12 | import { postExamChoiceImage } from "@/api/exams"; |
| 9 | 13 | import { postExamQuestionImage } from "@/api/exams"; |
| @@ -15,10 +19,14 @@ import { Badge } from "@/components/ui/badge"; | ||
| 15 | 19 | import { Button } from "@/components/ui/button"; |
| 16 | 20 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 17 | 21 | import { FormDialog } from "@/components/ui/form-dialog"; |
| 22 | +import { BankQuestionPicker } from "@/components/exams/bank-question-picker"; | |
| 18 | 23 | import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; |
| 19 | -import { IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; | |
| 24 | +import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; | |
| 20 | 25 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 26 | +import { planChoiceImageRestore } from "@/lib/choice-compaction"; | |
| 21 | 27 | import { createFlash } from "@/lib/flash"; |
| 28 | +import { hasMinRole } from "@/lib/roles"; | |
| 29 | +import { useAuth } from "@/stores/auth-context"; | |
| 22 | 30 | import { useT } from "@/stores/preferences-context"; |
| 23 | 31 | |
| 24 | 32 | const QUESTION_PAGE_SIZE = 1; |
| @@ -32,6 +40,10 @@ export function ExamQuestionsPanel(props: { | ||
| 32 | 40 | onCreateOpenChange?: (open: boolean) => void; |
| 33 | 41 | }) { |
| 34 | 42 | const t = useT(); |
| 43 | + const auth = useAuth(); | |
| 44 | + const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher"); | |
| 45 | + const [bankOpen, setBankOpen] = createSignal(false); | |
| 46 | + const [banking, setBanking] = createSignal(""); | |
| 35 | 47 | const [subjects] = createResource(() => props.courseId, async (courseId) => (await getCourseSubjects(courseId)).items); |
| 36 | 48 | const [questions, { refetch }] = createResource(() => props.examId, async (examId) => { |
| 37 | 49 | try { |
| @@ -44,6 +56,10 @@ export function ExamQuestionsPanel(props: { | ||
| 44 | 56 | const [showForm, setShowForm] = createSignal(false); |
| 45 | 57 | const [editing, setEditing] = createSignal<ExamQuestion | null>(null); |
| 46 | 58 | const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null); |
| 59 | + const [confirmBank, setConfirmBank] = createSignal<ExamQuestion | null>(null); | |
| 60 | + // Older backends never write `source_bank` back onto the exam question after a | |
| 61 | + // to-bank save, so remember what this session banked and treat both as "banked". | |
| 62 | + const [bankedIds, setBankedIds] = createSignal<string[]>([]); | |
| 47 | 63 | const [error, setError] = createSignal(""); |
| 48 | 64 | const [imagePending, setImagePending] = createSignal(""); |
| 49 | 65 | const [flash, setFlash] = createFlash(); |
| @@ -57,6 +73,11 @@ export function ExamQuestionsPanel(props: { | ||
| 57 | 73 | |
| 58 | 74 | const formInitial = createMemo(() => editing() ?? undefined); |
| 59 | 75 | const questionList = createMemo(() => questions() ?? []); |
| 76 | + // The header badge renders outside the <Suspense> below, so it must read | |
| 77 | + // `.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 | + const questionCount = () => questions.latest?.length ?? 0; | |
| 80 | + const isBanked = (question: ExamQuestion) => Boolean(question.source_bank) || bankedIds().includes(question.id); | |
| 60 | 81 | const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId; |
| 61 | 82 | const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE))); |
| 62 | 83 | const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); |
| @@ -82,7 +103,24 @@ export function ExamQuestionsPanel(props: { | ||
| 82 | 103 | try { |
| 83 | 104 | const q = editing(); |
| 84 | 105 | const isNewQuestion = !q; |
| 85 | - const { image, choice_images, ...body } = values; | |
| 106 | + // choice_sources is form-only bookkeeping — never send it to the backend. | |
| 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 | + | |
| 86 | 124 | const saved = q |
| 87 | 125 | ? await patchExamQuestionById(props.examId, q.id, body) |
| 88 | 126 | : await postExamQuestion(props.examId, body); |
| @@ -90,6 +128,19 @@ export function ExamQuestionsPanel(props: { | ||
| 90 | 128 | for (const [index, file] of (choice_images ?? []).entries()) { |
| 91 | 129 | if (file) await postExamChoiceImage(props.examId, saved.id, index, file); |
| 92 | 130 | } |
| 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 | + } | |
| 93 | 144 | if (q) { |
| 94 | 145 | setFlash(t("common.saved")); |
| 95 | 146 | } else { |
| @@ -104,6 +155,29 @@ export function ExamQuestionsPanel(props: { | ||
| 104 | 155 | } |
| 105 | 156 | }; |
| 106 | 157 | |
| 158 | + const insertFromBank = async (bankQuestionId: string, subjectId: string) => { | |
| 159 | + await postExamQuestionFromBank(props.examId, bankQuestionId, subjectId); | |
| 160 | + setBankOpen(false); | |
| 161 | + setFlash(t("bank.inserted")); | |
| 162 | + await refetch(); | |
| 163 | + }; | |
| 164 | + | |
| 165 | + const saveToBank = async (question: ExamQuestion) => { | |
| 166 | + if (banking()) return; | |
| 167 | + setError(""); | |
| 168 | + setBanking(question.id); | |
| 169 | + try { | |
| 170 | + await postExamQuestionToBank(props.examId, question.id); | |
| 171 | + setBankedIds((ids) => (ids.includes(question.id) ? ids : [...ids, question.id])); | |
| 172 | + setFlash(t("bank.savedToBank")); | |
| 173 | + await refetch(); | |
| 174 | + } catch (err) { | |
| 175 | + setError(formatApiError(err)); | |
| 176 | + } finally { | |
| 177 | + setBanking(""); | |
| 178 | + } | |
| 179 | + }; | |
| 180 | + | |
| 107 | 181 | const removeQuestionImage = async (question: ExamQuestion) => { |
| 108 | 182 | if (props.readOnly) return; |
| 109 | 183 | setError(""); |
| @@ -144,26 +218,53 @@ export function ExamQuestionsPanel(props: { | ||
| 144 | 218 | <div class="flex items-center gap-2"> |
| 145 | 219 | <h2 class="font-display text-base font-semibold">{t("questions.title")}</h2> |
| 146 | 220 | <Badge variant="secondary" class="rounded-full font-mono text-xs"> |
| 147 | - {questionList().length} | |
| 221 | + {questionCount()} | |
| 148 | 222 | </Badge> |
| 149 | 223 | </div> |
| 150 | 224 | <Show when={!props.readOnly}> |
| 151 | - <Button | |
| 152 | - type="button" | |
| 153 | - variant="default" | |
| 154 | - size="sm" | |
| 155 | - class="h-8 gap-1.5 rounded-md text-xs font-semibold" | |
| 156 | - onClick={() => { | |
| 157 | - setEditing(null); | |
| 158 | - setFormOpen(true); | |
| 159 | - }} | |
| 160 | - > | |
| 161 | - <IconPlus class="h-3.5 w-3.5" /> | |
| 162 | - {t("questions.add")} | |
| 163 | - </Button> | |
| 225 | + <div class="flex flex-wrap items-center gap-1.5"> | |
| 226 | + <Show when={isTeacherPlus()}> | |
| 227 | + <Button | |
| 228 | + type="button" | |
| 229 | + variant="outline" | |
| 230 | + size="sm" | |
| 231 | + class="h-8 gap-1.5 rounded-md text-xs font-semibold" | |
| 232 | + onClick={() => setBankOpen(true)} | |
| 233 | + > | |
| 234 | + <IconArchive class="h-3.5 w-3.5" /> | |
| 235 | + {t("bank.fromBank")} | |
| 236 | + </Button> | |
| 237 | + </Show> | |
| 238 | + <Button | |
| 239 | + type="button" | |
| 240 | + variant="default" | |
| 241 | + size="sm" | |
| 242 | + class="h-8 gap-1.5 rounded-md text-xs font-semibold" | |
| 243 | + onClick={() => { | |
| 244 | + setEditing(null); | |
| 245 | + setFormOpen(true); | |
| 246 | + }} | |
| 247 | + > | |
| 248 | + <IconPlus class="h-3.5 w-3.5" /> | |
| 249 | + {t("questions.add")} | |
| 250 | + </Button> | |
| 251 | + </div> | |
| 164 | 252 | </Show> |
| 165 | 253 | </div> |
| 166 | 254 | |
| 255 | + <FormDialog | |
| 256 | + open={bankOpen() && !props.readOnly} | |
| 257 | + onOpenChange={setBankOpen} | |
| 258 | + title={t("bank.pickTemplate")} | |
| 259 | + description={t("bank.title")} | |
| 260 | + > | |
| 261 | + <BankQuestionPicker | |
| 262 | + subjects={subjects() ?? []} | |
| 263 | + onInsert={insertFromBank} | |
| 264 | + onCancel={() => setBankOpen(false)} | |
| 265 | + /> | |
| 266 | + </FormDialog> | |
| 267 | + | |
| 167 | 268 | <FormDialog |
| 168 | 269 | open={formOpen() || editing() != null} |
| 169 | 270 | onOpenChange={(open) => { |
| @@ -178,6 +279,9 @@ export function ExamQuestionsPanel(props: { | ||
| 178 | 279 | <QuestionForm |
| 179 | 280 | initial={formInitial()} |
| 180 | 281 | subjects={subjects() ?? []} |
| 282 | + imageSrc={editing() ? `/api/exams/${props.examId}/questions/${editing()!.id}/image` : undefined} | |
| 283 | + choiceImageSrc={(index) => `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${index}/image`} | |
| 284 | + loadImageBlob={editing() ? () => getExamQuestionImageBlob(props.examId, editing()!.id) : undefined} | |
| 181 | 285 | onCancel={() => { |
| 182 | 286 | setEditing(null); |
| 183 | 287 | setFormOpen(false); |
| @@ -230,6 +334,14 @@ export function ExamQuestionsPanel(props: { | ||
| 230 | 334 | <Badge variant="outline" class="font-mono"> |
| 231 | 335 | {q.points} {t("questions.points")} |
| 232 | 336 | </Badge> |
| 337 | + {/* `source_bank` is set in both directions (inserted from the | |
| 338 | + bank, or saved to it), so the badge stays origin-neutral. */} | |
| 339 | + <Show when={isBanked(q)}> | |
| 340 | + <Badge variant="outline" class="gap-1 border-amber-500/40 text-amber-700 dark:text-amber-400"> | |
| 341 | + <IconArchive class="h-3 w-3" /> | |
| 342 | + {t("bank.inBankBadge")} | |
| 343 | + </Badge> | |
| 344 | + </Show> | |
| 233 | 345 | </div> |
| 234 | 346 | <Show when={q.image}> |
| 235 | 347 | <img |
| @@ -293,26 +405,43 @@ export function ExamQuestionsPanel(props: { | ||
| 293 | 405 | </ol> |
| 294 | 406 | </Show> |
| 295 | 407 | </div> |
| 296 | - <Show when={!props.readOnly}> | |
| 408 | + {/* Saving to the bank copies the question out; it never touches the | |
| 409 | + exam, so it stays available on a finished/read-only exam. */} | |
| 410 | + <Show when={isTeacherPlus() || !props.readOnly}> | |
| 297 | 411 | <div class="flex items-center gap-1.5"> |
| 298 | - <Button | |
| 299 | - type="button" | |
| 300 | - variant="outline" | |
| 301 | - size="sm" | |
| 302 | - class="h-8 px-2.5 text-xs" | |
| 303 | - onClick={() => setEditing(q)} | |
| 304 | - > | |
| 305 | - {t("common.edit")} | |
| 306 | - </Button> | |
| 307 | - <Button | |
| 308 | - type="button" | |
| 309 | - variant="ghost" | |
| 310 | - size="sm" | |
| 311 | - class="h-8 w-8 p-0 text-destructive" | |
| 312 | - onClick={() => setRemoveQuestion(q)} | |
| 313 | - > | |
| 314 | - <IconTrash class="h-4 w-4" /> | |
| 315 | - </Button> | |
| 412 | + <Show when={isTeacherPlus()}> | |
| 413 | + <Button | |
| 414 | + type="button" | |
| 415 | + variant="outline" | |
| 416 | + size="sm" | |
| 417 | + class="h-8 gap-1.5 px-2.5 text-xs" | |
| 418 | + disabled={banking() === q.id} | |
| 419 | + onClick={() => (isBanked(q) ? setConfirmBank(q) : void saveToBank(q))} | |
| 420 | + > | |
| 421 | + <IconArchive class="h-3.5 w-3.5" /> | |
| 422 | + {isBanked(q) ? t("bank.saveCopyToBank") : t("bank.saveToBank")} | |
| 423 | + </Button> | |
| 424 | + </Show> | |
| 425 | + <Show when={!props.readOnly}> | |
| 426 | + <Button | |
| 427 | + type="button" | |
| 428 | + variant="outline" | |
| 429 | + size="sm" | |
| 430 | + class="h-8 px-2.5 text-xs" | |
| 431 | + onClick={() => setEditing(q)} | |
| 432 | + > | |
| 433 | + {t("common.edit")} | |
| 434 | + </Button> | |
| 435 | + <Button | |
| 436 | + type="button" | |
| 437 | + variant="ghost" | |
| 438 | + size="sm" | |
| 439 | + class="h-8 w-8 p-0 text-destructive" | |
| 440 | + onClick={() => setRemoveQuestion(q)} | |
| 441 | + > | |
| 442 | + <IconTrash class="h-4 w-4" /> | |
| 443 | + </Button> | |
| 444 | + </Show> | |
| 316 | 445 | </div> |
| 317 | 446 | </Show> |
| 318 | 447 | </div> |
| @@ -354,6 +483,24 @@ export function ExamQuestionsPanel(props: { | ||
| 354 | 483 | </Show> |
| 355 | 484 | </Suspense> |
| 356 | 485 | |
| 486 | + <ConfirmDialog | |
| 487 | + open={confirmBank() != null} | |
| 488 | + onOpenChange={(open) => { | |
| 489 | + if (!open) setConfirmBank(null); | |
| 490 | + }} | |
| 491 | + title={t("bank.saveCopyTitle")} | |
| 492 | + description={t("bank.saveCopyBody")} | |
| 493 | + confirmLabel={t("bank.saveCopyConfirm")} | |
| 494 | + icon={<IconArchive class="h-4 w-4" />} | |
| 495 | + summary={confirmBank()?.text ?? ""} | |
| 496 | + onConfirm={async () => { | |
| 497 | + const q = confirmBank(); | |
| 498 | + if (!q) return; | |
| 499 | + setConfirmBank(null); | |
| 500 | + await saveToBank(q); | |
| 501 | + }} | |
| 502 | + /> | |
| 503 | + | |
| 357 | 504 | <ConfirmDialog |
| 358 | 505 | open={removeQuestion() != null} |
| 359 | 506 | onOpenChange={(open) => { |
src/components/exams/question-form.tsxmodified+103 -39
| @@ -1,8 +1,7 @@ | ||
| 1 | -import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy } from "solid-js"; | |
| 1 | +import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy, untrack } from "solid-js"; | |
| 2 | 2 | import { formatApiError } from "@/api/client"; |
| 3 | -import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; | |
| 4 | -import { QUESTION_KINDS } from "@/api/client"; | |
| 5 | -import { getExamQuestionImageBlob } from "@/api/exams"; | |
| 3 | +import type { ImageMeta, QuestionKind, Subject } from "@/api/client"; | |
| 4 | +import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client"; | |
| 6 | 5 | import { getSettings } from "@/api/settings"; |
| 7 | 6 | import type { DrawScene } from "@/lib/draw-stroke"; |
| 8 | 7 | import { Button } from "@/components/ui/button"; |
| @@ -11,6 +10,7 @@ import { Input } from "@/components/ui/input"; | ||
| 11 | 10 | import { Label } from "@/components/ui/label"; |
| 12 | 11 | import { Select } from "@/components/ui/select"; |
| 13 | 12 | import { Textarea } from "@/components/ui/textarea"; |
| 13 | +import { compactChoices } from "@/lib/choice-compaction"; | |
| 14 | 14 | import { cn } from "@/lib/cn"; |
| 15 | 15 | import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; |
| 16 | 16 | import { useT } from "@/stores/preferences-context"; |
| @@ -27,11 +27,35 @@ export type QuestionValues = { | ||
| 27 | 27 | correct: number | null; |
| 28 | 28 | image: File | null; |
| 29 | 29 | 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 | +}; | |
| 37 | + | |
| 38 | +/** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */ | |
| 39 | +export type QuestionFormInitial = { | |
| 40 | + subject: string; | |
| 41 | + text: string; | |
| 42 | + kind: QuestionKind; | |
| 43 | + points: number; | |
| 44 | + choices: string[] | null; | |
| 45 | + correct: number | null; | |
| 46 | + image?: ImageMeta | null; | |
| 47 | + choice_images?: (ImageMeta | null)[] | null; | |
| 30 | 48 | }; |
| 31 | 49 | |
| 32 | 50 | export function QuestionForm(props: { |
| 33 | - initial?: ExamQuestion; | |
| 51 | + initial?: QuestionFormInitial; | |
| 34 | 52 | subjects: Subject[]; |
| 53 | + /** Existing stored image, as a URL the browser can GET (exam or bank path). */ | |
| 54 | + imageSrc?: string; | |
| 55 | + choiceImageSrc?: (index: number) => string; | |
| 56 | + /** Reload the stored image so an existing drawing can be edited, not redrawn. */ | |
| 57 | + loadImageBlob?: () => Promise<Blob>; | |
| 58 | + submitLabel?: string; | |
| 35 | 59 | onSubmit: (values: QuestionValues) => Promise<void>; |
| 36 | 60 | onCancel: () => void; |
| 37 | 61 | }) { |
| @@ -47,6 +71,9 @@ export function QuestionForm(props: { | ||
| 47 | 71 | const [drawing, setDrawing] = createSignal(false); |
| 48 | 72 | const [editScene, setEditScene] = createSignal<DrawScene | null>(null); |
| 49 | 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)); | |
| 50 | 77 | const [error, setError] = createSignal(""); |
| 51 | 78 | const [pending, setPending] = createSignal(false); |
| 52 | 79 | const [settings] = createResource(async () => { |
| @@ -58,19 +85,29 @@ export function QuestionForm(props: { | ||
| 58 | 85 | }); |
| 59 | 86 | const maxFileBytes = () => maxUploadBytes(settings()); |
| 60 | 87 | |
| 88 | + // Reset on a new `initial` only — `props.subjects` may arrive after the form is | |
| 89 | + // open (async course subjects), and re-running then would wipe what was typed. | |
| 61 | 90 | createEffect(() => { |
| 62 | 91 | const initial = props.initial; |
| 63 | - setText(initial?.text ?? ""); | |
| 64 | - setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? ""); | |
| 65 | - setKind(initial?.kind ?? "choice"); | |
| 66 | - setPoints(String(initial?.points ?? 1)); | |
| 67 | - setChoices(initial?.choices ?? ["", "", "", ""]); | |
| 68 | - setCorrect(initial?.correct ?? 0); | |
| 69 | - setImage(null); | |
| 70 | - setDrawing(false); | |
| 71 | - setEditScene(null); | |
| 72 | - setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); | |
| 73 | - setError(""); | |
| 92 | + untrack(() => { | |
| 93 | + setText(initial?.text ?? ""); | |
| 94 | + setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? ""); | |
| 95 | + setKind(initial?.kind ?? "choice"); | |
| 96 | + setPoints(String(initial?.points ?? 1)); | |
| 97 | + setChoices(initial?.choices ?? ["", "", "", ""]); | |
| 98 | + setCorrect(initial?.correct ?? 0); | |
| 99 | + setImage(null); | |
| 100 | + setDrawing(false); | |
| 101 | + setEditScene(null); | |
| 102 | + setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); | |
| 103 | + setChoiceSources((initial?.choices ?? ["", "", "", ""]).map((_, index) => (initial ? index : -1))); | |
| 104 | + setError(""); | |
| 105 | + }); | |
| 106 | + }); | |
| 107 | + | |
| 108 | + // Once subjects load, preselect the first one if nothing is chosen yet. | |
| 109 | + createEffect(() => { | |
| 110 | + if (!subjectId()) setSubjectId(props.subjects[0]?.id ?? ""); | |
| 74 | 111 | }); |
| 75 | 112 | |
| 76 | 113 | // Blank pad for a fresh drawing; reload the stored scene to edit an existing one. |
| @@ -80,11 +117,11 @@ export function QuestionForm(props: { | ||
| 80 | 117 | }; |
| 81 | 118 | |
| 82 | 119 | const editDrawing = async () => { |
| 83 | - const q = props.initial; | |
| 84 | - if (!q?.image) return; | |
| 120 | + const load = props.loadImageBlob; | |
| 121 | + if (!props.initial?.image || !load) return; | |
| 85 | 122 | setError(""); |
| 86 | 123 | try { |
| 87 | - const blob = await getExamQuestionImageBlob(q.exam, q.id); | |
| 124 | + const blob = await load(); | |
| 88 | 125 | const { pngBytesToScene } = await import("@/lib/drawing-file"); |
| 89 | 126 | setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); |
| 90 | 127 | } catch { |
| @@ -134,14 +171,24 @@ export function QuestionForm(props: { | ||
| 134 | 171 | }; |
| 135 | 172 | |
| 136 | 173 | const addChoice = () => { |
| 137 | - setChoices((current) => (current.length >= 10 ? current : [...current, ""])); | |
| 138 | - setChoiceImages((current) => (current.length >= 10 ? current : [...current, null])); | |
| 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])); | |
| 139 | 178 | }; |
| 140 | 179 | |
| 141 | 180 | const removeChoice = (index: number) => { |
| 181 | + const remaining = choices().length - 1; | |
| 142 | 182 | setChoices((current) => current.filter((_, i) => i !== index)); |
| 143 | 183 | setChoiceImages((current) => current.filter((_, i) => i !== index)); |
| 144 | - setCorrect((current) => Math.max(0, Math.min(current, choices().length - 2))); | |
| 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 | + }); | |
| 145 | 192 | }; |
| 146 | 193 | |
| 147 | 194 | const validate = (): QuestionValues | string => { |
| @@ -149,22 +196,35 @@ export function QuestionForm(props: { | ||
| 149 | 196 | const subject = subjectId().trim(); |
| 150 | 197 | if (!subject) return t("questions.subjectRequired"); |
| 151 | 198 | if (!body) return t("questions.textRequired"); |
| 152 | - if (body.length > 2000) return t("form.descriptionMax"); | |
| 199 | + if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax"); | |
| 153 | 200 | const p = Number(points()); |
| 154 | - if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange"); | |
| 201 | + if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange"); | |
| 155 | 202 | if (kind() === "text") { |
| 156 | - return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null }; | |
| 203 | + return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null, choice_sources: null }; | |
| 157 | 204 | } |
| 158 | - const indexedChoices = choices() | |
| 159 | - .map((choice, index) => ({ choice: choice.trim(), image: choiceImages()[index] ?? null })) | |
| 160 | - .filter((item) => item.choice); | |
| 161 | - const cleanChoices = indexedChoices.map((item) => item.choice); | |
| 162 | - if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) { | |
| 205 | + const compacted = compactChoices(choices(), choiceImages(), choiceSources(), correct()); | |
| 206 | + const cleanChoices = compacted.choices; | |
| 207 | + if ( | |
| 208 | + cleanChoices.length < BANK_QUESTION_LIMITS.minChoices || | |
| 209 | + cleanChoices.length > BANK_QUESTION_LIMITS.maxChoices || | |
| 210 | + cleanChoices.some((choice) => choice.length > BANK_QUESTION_LIMITS.choiceTextMaxLen) | |
| 211 | + ) { | |
| 163 | 212 | return t("questions.choicesRange"); |
| 164 | 213 | } |
| 165 | - const c = correct(); | |
| 166 | - if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange"); | |
| 167 | - return { subject_id: subject, text: body, kind: "choice", points: p, choices: cleanChoices, correct: c, image: image(), choice_images: indexedChoices.map((item) => item.image) }; | |
| 214 | + // The marked row survived compaction as `compacted.correct`; -1 means the user | |
| 215 | + // blanked the very choice they had marked, so make them pick again. | |
| 216 | + if (compacted.correct < 0) return t("questions.correctBlanked"); | |
| 217 | + return { | |
| 218 | + subject_id: subject, | |
| 219 | + text: body, | |
| 220 | + kind: "choice", | |
| 221 | + points: p, | |
| 222 | + choices: cleanChoices, | |
| 223 | + correct: compacted.correct, | |
| 224 | + image: image(), | |
| 225 | + choice_images: compacted.images, | |
| 226 | + choice_sources: compacted.sources, | |
| 227 | + }; | |
| 168 | 228 | }; |
| 169 | 229 | |
| 170 | 230 | const submit = async (e: SubmitEvent) => { |
| @@ -205,10 +265,10 @@ export function QuestionForm(props: { | ||
| 205 | 265 | }} |
| 206 | 266 | /> |
| 207 | 267 | <div class="flex items-center gap-3"> |
| 208 | - <Show when={props.initial?.image}> | |
| 268 | + <Show when={props.initial?.image && props.imageSrc}> | |
| 209 | 269 | <div class="relative shrink-0"> |
| 210 | 270 | <img |
| 211 | - src={`/api/exams/${props.initial!.exam}/questions/${props.initial!.id}/image`} | |
| 271 | + src={props.imageSrc} | |
| 212 | 272 | alt={t("questions.image")} |
| 213 | 273 | class="h-14 w-24 rounded border bg-muted/20 object-contain" |
| 214 | 274 | /> |
| @@ -235,7 +295,7 @@ export function QuestionForm(props: { | ||
| 235 | 295 | <IconEdit class="h-3.5 w-3.5" /> |
| 236 | 296 | {t("questions.draw")} |
| 237 | 297 | </button> |
| 238 | - <Show when={props.initial?.image}> | |
| 298 | + <Show when={props.initial?.image && props.loadImageBlob}> | |
| 239 | 299 | <button |
| 240 | 300 | type="button" |
| 241 | 301 | class="flex items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" |
| @@ -324,6 +384,10 @@ export function QuestionForm(props: { | ||
| 324 | 384 | <Index each={choices()}> |
| 325 | 385 | {(choice, index) => { |
| 326 | 386 | const isCorrect = () => correct() === index; |
| 387 | + // Stored images are keyed by the option's ORIGINAL index, which drifts | |
| 388 | + // from the display row once a choice is removed; -1 = added just now. | |
| 389 | + const storedIndex = () => choiceSources()[index] ?? -1; | |
| 390 | + const storedImage = () => (storedIndex() >= 0 ? props.initial?.choice_images?.[storedIndex()] : null); | |
| 327 | 391 | return ( |
| 328 | 392 | <div |
| 329 | 393 | class={cn( |
| @@ -364,9 +428,9 @@ export function QuestionForm(props: { | ||
| 364 | 428 | <IconFileImage class="h-3 w-3" /> |
| 365 | 429 | {choiceImages()[index]?.name ?? t("questions.choiceImage")} |
| 366 | 430 | </label> |
| 367 | - <Show when={props.initial?.choice_images?.[index]}> | |
| 431 | + <Show when={storedImage() && props.choiceImageSrc}> | |
| 368 | 432 | <img |
| 369 | - src={`/api/exams/${props.initial!.exam}/questions/${props.initial!.id}/choices/${index}/image`} | |
| 433 | + src={props.choiceImageSrc?.(storedIndex())} | |
| 370 | 434 | alt={t("questions.choiceImage")} |
| 371 | 435 | class="h-8 w-12 rounded border bg-muted/20 object-contain" |
| 372 | 436 | /> |
| @@ -395,7 +459,7 @@ export function QuestionForm(props: { | ||
| 395 | 459 | |
| 396 | 460 | <div class="flex flex-wrap items-center gap-2 pt-1"> |
| 397 | 461 | <Button type="submit" class="h-8 text-xs font-semibold" disabled={pending()}> |
| 398 | - {props.initial ? t("common.update") : t("common.create")} | |
| 462 | + {props.submitLabel ?? (props.initial ? t("common.update") : t("common.create"))} | |
| 399 | 463 | </Button> |
| 400 | 464 | <Button type="button" variant="outline" class="h-8 text-xs font-semibold" onClick={props.onCancel}> |
| 401 | 465 | {t("common.cancel")} |
src/components/layout/nav-items.tsmodified+2 -0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import type { Component } from "solid-js"; |
| 2 | 2 | import type { Role } from "@/api/client"; |
| 3 | 3 | import { |
| 4 | + IconArchive, | |
| 4 | 5 | IconBook, |
| 5 | 6 | IconBriefcase, |
| 6 | 7 | IconCalendar, |
| @@ -56,6 +57,7 @@ const NAV_GROUPS: NavGroup[] = [ | ||
| 56 | 57 | { to: "/clubs", labelKey: "nav.clubs", Icon: IconUsers }, |
| 57 | 58 | { to: "/homework", labelKey: "nav.homework", Icon: IconHomework }, |
| 58 | 59 | { to: "/exams", labelKey: "nav.exams", Icon: IconExam }, |
| 60 | + { to: "/question-bank", labelKey: "nav.questionBank", Icon: IconArchive, minRole: "teacher" }, | |
| 59 | 61 | { to: "/events", labelKey: "nav.events", Icon: IconCalendar }, |
| 60 | 62 | { to: "/calendar", labelKey: "nav.calendar", Icon: IconCalendarDays }, |
| 61 | 63 | { to: "/appointments", labelKey: "nav.appointments", Icon: IconClock }, |
src/i18n/messages.tsmodified+87 -0
| @@ -14,6 +14,7 @@ export type MessageKey = | ||
| 14 | 14 | | "nav.notes" |
| 15 | 15 | | "nav.events" |
| 16 | 16 | | "nav.exams" |
| 17 | + | "nav.questionBank" | |
| 17 | 18 | | "nav.homework" |
| 18 | 19 | | "nav.courses" |
| 19 | 20 | | "nav.studies" |
| @@ -431,6 +432,34 @@ export type MessageKey = | ||
| 431 | 432 | | "questions.pointsRange" |
| 432 | 433 | | "questions.choicesRange" |
| 433 | 434 | | "questions.correctRange" |
| 435 | + | "questions.correctBlanked" | |
| 436 | + | "questions.imagesLost" | |
| 437 | + | "bank.title" | |
| 438 | + | "bank.subtitle" | |
| 439 | + | "bank.empty" | |
| 440 | + | "bank.create" | |
| 441 | + | "bank.edit" | |
| 442 | + | "bank.owner" | |
| 443 | + | "bank.mine" | |
| 444 | + | "bank.created" | |
| 445 | + | "bank.copyNotice" | |
| 446 | + | "bank.courseHint" | |
| 447 | + | "bank.choiceImagesWarning" | |
| 448 | + | "bank.fromBank" | |
| 449 | + | "bank.pickTemplate" | |
| 450 | + | "bank.targetSubject" | |
| 451 | + | "bank.insert" | |
| 452 | + | "bank.inserted" | |
| 453 | + | "bank.saveToBank" | |
| 454 | + | "bank.saveCopyToBank" | |
| 455 | + | "bank.saveCopyTitle" | |
| 456 | + | "bank.saveCopyBody" | |
| 457 | + | "bank.saveCopyConfirm" | |
| 458 | + | "bank.savedToBank" | |
| 459 | + | "bank.inBankBadge" | |
| 460 | + | "bank.search" | |
| 461 | + | "bank.pickerEmpty" | |
| 462 | + | "bank.noSubjects" | |
| 434 | 463 | | "subjects.title" |
| 435 | 464 | | "subjects.item" |
| 436 | 465 | | "subjects.subject" |
| @@ -899,6 +928,7 @@ const en: Dict = { | ||
| 899 | 928 | "nav.notes": "Notes", |
| 900 | 929 | "nav.events": "Events", |
| 901 | 930 | "nav.exams": "Exams", |
| 931 | + "nav.questionBank": "Question bank", | |
| 902 | 932 | "nav.homework": "Homework", |
| 903 | 933 | "nav.courses": "Courses", |
| 904 | 934 | "nav.studies": "Study sessions", |
| @@ -1390,6 +1420,34 @@ const en: Dict = { | ||
| 1390 | 1420 | "questions.pointsRange": "Points must be an integer from 1 to 100", |
| 1391 | 1421 | "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters", |
| 1392 | 1422 | "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", | |
| 1426 | + "bank.subtitle": "Reusable question templates every teacher can use.", | |
| 1427 | + "bank.empty": "No templates yet.", | |
| 1428 | + "bank.create": "New template", | |
| 1429 | + "bank.edit": "Edit template", | |
| 1430 | + "bank.owner": "Added by", | |
| 1431 | + "bank.mine": "Mine", | |
| 1432 | + "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.", | |
| 1434 | + "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", | |
| 1437 | + "bank.pickTemplate": "Pick a template", | |
| 1438 | + "bank.targetSubject": "Subject in this exam", | |
| 1439 | + "bank.insert": "Add to exam", | |
| 1440 | + "bank.inserted": "Question copied from the bank.", | |
| 1441 | + "bank.saveToBank": "Save to bank", | |
| 1442 | + "bank.saveCopyToBank": "Save another copy to bank", | |
| 1443 | + "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.", | |
| 1445 | + "bank.saveCopyConfirm": "Save another copy", | |
| 1446 | + "bank.savedToBank": "Question copied to the bank.", | |
| 1447 | + "bank.inBankBadge": "In bank", | |
| 1448 | + "bank.search": "Search templates", | |
| 1449 | + "bank.pickerEmpty": "No matching template.", | |
| 1450 | + "bank.noSubjects": "This exam's course has no subjects yet. Add a subject to the course first.", | |
| 1393 | 1451 | "subjects.title": "Subjects", |
| 1394 | 1452 | "subjects.item": "Subject", |
| 1395 | 1453 | "subjects.subject": "Subject", |
| @@ -1796,6 +1854,7 @@ const tr: Dict = { | ||
| 1796 | 1854 | "nav.notes": "Defter", |
| 1797 | 1855 | "nav.events": "Etkinlikler", |
| 1798 | 1856 | "nav.exams": "Sınavlar", |
| 1857 | + "nav.questionBank": "Soru bankası", | |
| 1799 | 1858 | "nav.homework": "Ödevler", |
| 1800 | 1859 | "nav.courses": "Ders", |
| 1801 | 1860 | "nav.studies": "Etüt", |
| @@ -2287,6 +2346,34 @@ const tr: Dict = { | ||
| 2287 | 2346 | "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı", |
| 2288 | 2347 | "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı", |
| 2289 | 2348 | "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ı", | |
| 2352 | + "bank.subtitle": "Bütün öğretmenlerin kullanabildiği, yeniden kullanılabilir soru şablonları.", | |
| 2353 | + "bank.empty": "Henüz şablon yok.", | |
| 2354 | + "bank.create": "Yeni şablon", | |
| 2355 | + "bank.edit": "Şablonu düzenle", | |
| 2356 | + "bank.owner": "Ekleyen", | |
| 2357 | + "bank.mine": "Benimkiler", | |
| 2358 | + "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.", | |
| 2360 | + "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", | |
| 2363 | + "bank.pickTemplate": "Şablon seç", | |
| 2364 | + "bank.targetSubject": "Bu sınavdaki konu", | |
| 2365 | + "bank.insert": "Sınava ekle", | |
| 2366 | + "bank.inserted": "Soru bankadan kopyalandı.", | |
| 2367 | + "bank.saveToBank": "Bankaya kaydet", | |
| 2368 | + "bank.saveCopyToBank": "Bankaya yeni bir kopya kaydet", | |
| 2369 | + "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.", | |
| 2371 | + "bank.saveCopyConfirm": "Yeni kopya kaydet", | |
| 2372 | + "bank.savedToBank": "Soru bankaya kopyalandı.", | |
| 2373 | + "bank.inBankBadge": "Bankada", | |
| 2374 | + "bank.search": "Şablonlarda ara", | |
| 2375 | + "bank.pickerEmpty": "Eşleşen şablon yok.", | |
| 2376 | + "bank.noSubjects": "Bu sınavın dersinde henüz konu yok. Önce derse bir konu ekle.", | |
| 2290 | 2377 | "subjects.title": "Konular", |
| 2291 | 2378 | "subjects.item": "Konu", |
| 2292 | 2379 | "subjects.subject": "Konu", |
src/lib/choice-compaction.test.tsadded+57 -0
| @@ -0,0 +1,57 @@ | ||
| 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.tsadded+54 -0
| @@ -0,0 +1,54 @@ | ||
| 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/pages/question-bank-page.tsxadded+292 -0
| @@ -0,0 +1,292 @@ | ||
| 1 | +import { Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; | |
| 2 | +import type { ColumnDef } from "@tanstack/solid-table"; | |
| 3 | +import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions"; | |
| 4 | +import { getCourses } from "@/api/courses"; | |
| 5 | +import { getSubjectById } from "@/api/subjects"; | |
| 6 | +import { getUserById } from "@/api/users"; | |
| 7 | +import { formatApiError } from "@/api/client"; | |
| 8 | +import type { BankQuestion } from "@/api/client"; | |
| 9 | +import { BankQuestionForm } from "@/components/exams/bank-question-form"; | |
| 10 | +import { RouteGuard } from "@/components/layout/route-guard"; | |
| 11 | +import { Alert } from "@/components/ui/alert"; | |
| 12 | +import { Badge } from "@/components/ui/badge"; | |
| 13 | +import { Button } from "@/components/ui/button"; | |
| 14 | +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | |
| 15 | +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; | |
| 16 | +import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons"; | |
| 17 | +import { DropdownSelect } from "@/components/ui/select"; | |
| 18 | +import { SidePanel } from "@/components/ui/side-panel"; | |
| 19 | +import { TableRowActions } from "@/components/ui/table-row-actions"; | |
| 20 | +import { createFlash } from "@/lib/flash"; | |
| 21 | +import { formatDate } from "@/lib/format"; | |
| 22 | +import { hasMinRole } from "@/lib/roles"; | |
| 23 | +import { useAuth } from "@/stores/auth-context"; | |
| 24 | +import { usePreferences, useT } from "@/stores/preferences-context"; | |
| 25 | + | |
| 26 | +const BANK_PAGE_SIZE = 12; | |
| 27 | + | |
| 28 | +export default function QuestionBankPage() { | |
| 29 | + return ( | |
| 30 | + <RouteGuard minRole="teacher"> | |
| 31 | + <QuestionBankContent /> | |
| 32 | + </RouteGuard> | |
| 33 | + ); | |
| 34 | +} | |
| 35 | + | |
| 36 | +function QuestionBankContent() { | |
| 37 | + const auth = useAuth(); | |
| 38 | + const t = useT(); | |
| 39 | + const { locale } = usePreferences(); | |
| 40 | + const [ownerFilter, setOwnerFilter] = createSignal<"all" | "me">("all"); | |
| 41 | + const [subjectFilter, setSubjectFilter] = createSignal("all"); | |
| 42 | + const [createOpen, setCreateOpen] = createSignal(false); | |
| 43 | + const [editing, setEditing] = createSignal<BankQuestion | null>(null); | |
| 44 | + const [removing, setRemoving] = createSignal<BankQuestion | null>(null); | |
| 45 | + const [subjectNames, setSubjectNames] = createSignal<Record<string, string>>({}); | |
| 46 | + const [ownerNames, setOwnerNames] = createSignal<Record<string, string>>({}); | |
| 47 | + const [flash, setFlash] = createFlash(); | |
| 48 | + const [error, setError] = createSignal(""); | |
| 49 | + | |
| 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 | + () => ({ owner: ownerFilter(), subject: subjectFilter() }), | |
| 54 | + async (filters) => { | |
| 55 | + const items = ( | |
| 56 | + await getBankQuestions({ | |
| 57 | + limit: 100, | |
| 58 | + ...(filters.owner === "me" ? { owner: "me" } : {}), | |
| 59 | + ...(filters.subject !== "all" ? { subject: filters.subject } : {}), | |
| 60 | + }) | |
| 61 | + ).items; | |
| 62 | + const subjects = [...new Set(items.map((item) => item.subject))].filter((id) => !subjectNames()[id]); | |
| 63 | + const owners = [...new Set(items.map((item) => item.owner))].filter((id) => !ownerNames()[id]); | |
| 64 | + await Promise.all([ | |
| 65 | + ...subjects.map((id) => | |
| 66 | + getSubjectById(id) | |
| 67 | + .then((subject) => setSubjectNames((current) => ({ ...current, [id]: subject.name }))) | |
| 68 | + .catch(() => {}), | |
| 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 | + }, | |
| 83 | + ); | |
| 84 | + | |
| 85 | + // Only courses the teacher can author in supply subjects for a new template. | |
| 86 | + const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items); | |
| 87 | + const manageableCourses = createMemo(() => | |
| 88 | + (courses() ?? []).filter((course) => { | |
| 89 | + const user = auth.user(); | |
| 90 | + if (!user) return false; | |
| 91 | + return ( | |
| 92 | + course.creator.id === user.id || | |
| 93 | + (course.teachers ?? []).some((teacher) => teacher.id === user.id) || | |
| 94 | + hasMinRole(user.role, "manager") | |
| 95 | + ); | |
| 96 | + }), | |
| 97 | + ); | |
| 98 | + | |
| 99 | + const subjectName = (id: string) => subjectNames()[id] ?? id; | |
| 100 | + const ownerName = (id: string) => ownerNames()[id] ?? id; | |
| 101 | + const canEdit = (question: BankQuestion) => | |
| 102 | + question.owner === auth.user()?.id || hasMinRole(auth.user()?.role, "admin"); | |
| 103 | + | |
| 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>[]>(() => [ | |
| 111 | + { | |
| 112 | + accessorKey: "text", | |
| 113 | + header: t("questions.text"), | |
| 114 | + cell: (cell) => <p class="truncate font-medium">{cell.row.original.text}</p>, | |
| 115 | + }, | |
| 116 | + { | |
| 117 | + accessorKey: "kind", | |
| 118 | + header: t("questions.kind"), | |
| 119 | + meta: { headerClass: "text-center", cellClass: "text-center" }, | |
| 120 | + cell: (cell) => ( | |
| 121 | + <Badge variant="outline"> | |
| 122 | + {cell.row.original.kind === "choice" ? t("questions.kind.choice") : t("questions.kind.text")} | |
| 123 | + </Badge> | |
| 124 | + ), | |
| 125 | + }, | |
| 126 | + { | |
| 127 | + accessorKey: "points", | |
| 128 | + header: t("questions.points"), | |
| 129 | + meta: { headerClass: "text-center", cellClass: "mono text-center" }, | |
| 130 | + }, | |
| 131 | + { | |
| 132 | + id: "subject", | |
| 133 | + accessorFn: (question) => subjectName(question.subject), | |
| 134 | + header: t("subjects.subject"), | |
| 135 | + meta: { cellClass: "truncate text-muted-foreground" }, | |
| 136 | + }, | |
| 137 | + { | |
| 138 | + id: "owner", | |
| 139 | + accessorFn: (question) => ownerName(question.owner), | |
| 140 | + header: t("bank.owner"), | |
| 141 | + meta: { cellClass: "truncate text-muted-foreground" }, | |
| 142 | + }, | |
| 143 | + { | |
| 144 | + accessorKey: "created_at", | |
| 145 | + header: t("bank.created"), | |
| 146 | + meta: { cellClass: "mono whitespace-nowrap text-muted-foreground" }, | |
| 147 | + cell: (cell) => formatDate(cell.row.original.created_at, locale()), | |
| 148 | + }, | |
| 149 | + { | |
| 150 | + id: "actions", | |
| 151 | + header: t("common.actions"), | |
| 152 | + meta: { headerClass: "w-28 min-w-[7rem] text-center whitespace-nowrap", cellClass: "w-28 min-w-[7rem] text-center whitespace-nowrap" }, | |
| 153 | + cell: (cell) => ( | |
| 154 | + <Show when={canEdit(cell.row.original)}> | |
| 155 | + <TableRowActions | |
| 156 | + label={t("common.actions")} | |
| 157 | + actions={[ | |
| 158 | + { | |
| 159 | + label: t("common.edit"), | |
| 160 | + icon: <IconEdit class="h-4 w-4" />, | |
| 161 | + onSelect: () => setEditing(cell.row.original), | |
| 162 | + }, | |
| 163 | + { | |
| 164 | + label: t("common.delete"), | |
| 165 | + icon: <IconTrash class="h-4 w-4" />, | |
| 166 | + destructive: true, | |
| 167 | + onSelect: () => setRemoving(cell.row.original), | |
| 168 | + }, | |
| 169 | + ]} | |
| 170 | + /> | |
| 171 | + </Show> | |
| 172 | + ), | |
| 173 | + }, | |
| 174 | + ]); | |
| 175 | + | |
| 176 | + const subjectOptions = createMemo(() => [ | |
| 177 | + { value: "all", label: t("common.all") }, | |
| 178 | + ...Object.entries(subjectNames()).map(([id, name]) => ({ value: id, label: name })), | |
| 179 | + ]); | |
| 180 | + | |
| 181 | + return ( | |
| 182 | + <div class="space-y-6"> | |
| 183 | + <Show when={flash()}> | |
| 184 | + <Alert variant="success">{flash()}</Alert> | |
| 185 | + </Show> | |
| 186 | + <Show when={error()}> | |
| 187 | + <Alert variant="destructive">{error()}</Alert> | |
| 188 | + </Show> | |
| 189 | + | |
| 190 | + <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} />}> | |
| 192 | + <Show when={list.error}> | |
| 193 | + <Alert variant="destructive">{formatApiError(list.error)}</Alert> | |
| 194 | + </Show> | |
| 195 | + <DataTable | |
| 196 | + title={t("bank.title")} | |
| 197 | + description={t("bank.subtitle")} | |
| 198 | + actions={ | |
| 199 | + <Show when={manageableCourses().length > 0}> | |
| 200 | + <Button type="button" size="sm" class="min-w-30 rounded-lg" onClick={() => setCreateOpen(true)}> | |
| 201 | + <IconPlus class="h-4 w-4" /> | |
| 202 | + {t("bank.create")} | |
| 203 | + </Button> | |
| 204 | + </Show> | |
| 205 | + } | |
| 206 | + columns={columns()} | |
| 207 | + data={list() ?? []} | |
| 208 | + tableClass="table-fixed min-w-5xl" | |
| 209 | + filterPlaceholder={t("bank.search")} | |
| 210 | + searchPredicate={searchTemplate} | |
| 211 | + enablePagination | |
| 212 | + pageSize={BANK_PAGE_SIZE} | |
| 213 | + empty={t("bank.empty")} | |
| 214 | + filters={ | |
| 215 | + <div class="flex flex-wrap items-center gap-2.5"> | |
| 216 | + <DropdownSelect | |
| 217 | + labelPrefix={t("bank.owner")} | |
| 218 | + value={ownerFilter()} | |
| 219 | + onChange={(value) => setOwnerFilter(value as "all" | "me")} | |
| 220 | + options={[ | |
| 221 | + { value: "all", label: t("common.all") }, | |
| 222 | + { value: "me", label: t("bank.mine") }, | |
| 223 | + ]} | |
| 224 | + /> | |
| 225 | + <DropdownSelect | |
| 226 | + labelPrefix={t("subjects.subject")} | |
| 227 | + value={subjectFilter()} | |
| 228 | + onChange={(value) => setSubjectFilter(value)} | |
| 229 | + options={subjectOptions()} | |
| 230 | + /> | |
| 231 | + </div> | |
| 232 | + } | |
| 233 | + /> | |
| 234 | + </Suspense> | |
| 235 | + </section> | |
| 236 | + | |
| 237 | + <SidePanel | |
| 238 | + open={createOpen() || editing() != null} | |
| 239 | + onOpenChange={(open) => { | |
| 240 | + if (!open) { | |
| 241 | + setCreateOpen(false); | |
| 242 | + setEditing(null); | |
| 243 | + } | |
| 244 | + }} | |
| 245 | + title={editing() ? t("bank.edit") : t("bank.create")} | |
| 246 | + description={t("bank.title")} | |
| 247 | + size="wide" | |
| 248 | + > | |
| 249 | + <BankQuestionForm | |
| 250 | + initial={editing() ?? undefined} | |
| 251 | + courses={manageableCourses()} | |
| 252 | + onSaved={async (_question, imagesLost) => { | |
| 253 | + const wasEdit = editing() != null; | |
| 254 | + setCreateOpen(false); | |
| 255 | + setEditing(null); | |
| 256 | + setError(imagesLost ?? ""); | |
| 257 | + setFlash(wasEdit ? t("common.saved") : t("common.created")); | |
| 258 | + await refetch(); | |
| 259 | + }} | |
| 260 | + onCancel={() => { | |
| 261 | + setCreateOpen(false); | |
| 262 | + setEditing(null); | |
| 263 | + }} | |
| 264 | + /> | |
| 265 | + </SidePanel> | |
| 266 | + | |
| 267 | + <ConfirmDialog | |
| 268 | + open={removing() != null} | |
| 269 | + onOpenChange={(open) => { | |
| 270 | + if (!open) setRemoving(null); | |
| 271 | + }} | |
| 272 | + title={t("confirm.deleteTitle")} | |
| 273 | + variant="destructive" | |
| 274 | + summary={removing()?.text ?? ""} | |
| 275 | + onConfirm={async () => { | |
| 276 | + const question = removing(); | |
| 277 | + if (!question) return; | |
| 278 | + setError(""); | |
| 279 | + try { | |
| 280 | + await deleteBankQuestionById(question.id); | |
| 281 | + await refetch(); | |
| 282 | + setFlash(t("common.deleted")); | |
| 283 | + } catch (err) { | |
| 284 | + setError(formatApiError(err)); | |
| 285 | + } finally { | |
| 286 | + setRemoving(null); | |
| 287 | + } | |
| 288 | + }} | |
| 289 | + /> | |
| 290 | + </div> | |
| 291 | + ); | |
| 292 | +} |
src/routes/router.tsxmodified+8 -0
| @@ -32,6 +32,7 @@ const HomeworkDetailPage = lazyRoute(() => import("@/pages/homework-detail-page" | ||
| 32 | 32 | const ExamsPage = lazyRoute(() => import("@/pages/exams-page")); |
| 33 | 33 | const ExamDetailPage = lazyRoute(() => import("@/pages/exam-detail-page")); |
| 34 | 34 | const ExamRoomPage = lazyRoute(() => import("@/pages/exam-room-page")); |
| 35 | +const QuestionBankPage = lazyRoute(() => import("@/pages/question-bank-page")); | |
| 35 | 36 | const CoursesPage = lazyRoute(() => import("@/pages/courses-page")); |
| 36 | 37 | const CourseDetailPage = lazyRoute(() => import("@/pages/course-detail-page")); |
| 37 | 38 | const MarksPage = lazyRoute(() => import("@/pages/marks-page")); |
| @@ -144,6 +145,12 @@ const examRoomRoute = createRoute({ | ||
| 144 | 145 | component: ExamRoomPage, |
| 145 | 146 | }); |
| 146 | 147 | |
| 148 | +const questionBankRoute = createRoute({ | |
| 149 | + getParentRoute: () => rootRoute, | |
| 150 | + path: "/question-bank", | |
| 151 | + component: QuestionBankPage, | |
| 152 | +}); | |
| 153 | + | |
| 147 | 154 | const coursesRoute = createRoute({ |
| 148 | 155 | getParentRoute: () => rootRoute, |
| 149 | 156 | path: "/courses", |
| @@ -295,6 +302,7 @@ const routeTree = rootRoute.addChildren([ | ||
| 295 | 302 | examRoomRoute, |
| 296 | 303 | liveMonitorRoute, |
| 297 | 304 | examsRoute, |
| 305 | + questionBankRoute, | |
| 298 | 306 | coursesRoute, |
| 299 | 307 | studiesRoute, |
| 300 | 308 | clubsRoute, |