diff --git a/src/api/__tests__/bank-questions/bank-questions.test.ts b/src/api/__tests__/bank-questions/bank-questions.test.ts new file mode 100644 index 0000000..5d76ac8 --- /dev/null +++ b/src/api/__tests__/bank-questions/bank-questions.test.ts @@ -0,0 +1,161 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + deleteBankChoiceImage, + deleteBankQuestionById, + deleteBankQuestionImage, + getBankChoiceImageBlob, + getBankQuestionById, + getBankQuestionImageBlob, + getBankQuestions, + patchBankQuestionById, + postBankChoiceImage, + postBankQuestion, + postBankQuestionImage, +} from "../../bank-questions"; +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; + +describe("bank-questions API", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("postBankQuestion calls /bank-questions with data", async () => { + const mockQuestion = { id: "b1" }; + mockFetchSuccess(mockQuestion, 201); + + const data = { subject_id: "sub1", text: "Q?", kind: "choice" as const, points: 10 }; + const result = await postBankQuestion(data); + expect(result).toEqual(mockQuestion); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify(data)); + }); + + it("getBankQuestions calls /bank-questions without a query when unfiltered", async () => { + const mockPage = { items: [{ id: "b1" }], total: 1 }; + mockFetchSuccess(mockPage); + + const result = await getBankQuestions(); + expect(result).toEqual({ ...mockPage, limit: null, offset: 0 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions"); + expect(init?.method).toBe("GET"); + }); + + it("getBankQuestions passes subject, owner and page params", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getBankQuestions({ subject: "sub1", owner: "me", limit: 20, offset: 40 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/bank-questions?subject=sub1&owner=me&limit=20&offset=40"); + }); + + it("getBankQuestionById calls /bank-questions/:bid", async () => { + const mockQuestion = { id: "b1" }; + mockFetchSuccess(mockQuestion); + + const result = await getBankQuestionById("b1"); + expect(result).toEqual(mockQuestion); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1"); + expect(init?.method).toBe("GET"); + }); + + it("patchBankQuestionById calls /bank-questions/:bid with updates", async () => { + const mockQuestion = { id: "b1", text: "Updated" }; + mockFetchSuccess(mockQuestion); + + const updates = { text: "Updated" }; + const result = await patchBankQuestionById("b1", updates); + expect(result).toEqual(mockQuestion); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1"); + expect(init?.method).toBe("PATCH"); + expect(init?.body).toBe(JSON.stringify(updates)); + }); + + it("deleteBankQuestionById calls /bank-questions/:bid", async () => { + mockFetch204(); + + await deleteBankQuestionById("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1"); + expect(init?.method).toBe("DELETE"); + }); + + it("postBankQuestionImage calls /bank-questions/:bid/image with FormData", async () => { + const mockMeta = { content_type: "image/png", size: 100 }; + mockFetchSuccess(mockMeta, 201); + + const file = new File(["test"], "test.png", { type: "image/png" }); + const result = await postBankQuestionImage("b1", file); + expect(result).toEqual(mockMeta); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/image"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeInstanceOf(FormData); + }); + + it("getBankQuestionImageBlob calls /bank-questions/:bid/image", async () => { + mockFetchBlob(new Blob(["img"], { type: "image/png" })); + + const result = await getBankQuestionImageBlob("b1"); + expect(result).toBeInstanceOf(Blob); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/image"); + expect(init?.method).toBeUndefined(); + }); + + it("deleteBankQuestionImage calls /bank-questions/:bid/image", async () => { + mockFetch204(); + + await deleteBankQuestionImage("b1"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/image"); + expect(init?.method).toBe("DELETE"); + }); + + it("postBankChoiceImage calls /bank-questions/:bid/choices/:index/image with FormData", async () => { + const mockMeta = { content_type: "image/png", size: 100 }; + mockFetchSuccess(mockMeta, 201); + + const file = new File(["test"], "test.png", { type: "image/png" }); + const result = await postBankChoiceImage("b1", 2, file); + expect(result).toEqual(mockMeta); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeInstanceOf(FormData); + }); + + it("getBankChoiceImageBlob calls /bank-questions/:bid/choices/:index/image", async () => { + mockFetchBlob(new Blob(["img"], { type: "image/png" })); + + const result = await getBankChoiceImageBlob("b1", 2); + expect(result).toBeInstanceOf(Blob); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + }); + + it("deleteBankChoiceImage calls /bank-questions/:bid/choices/:index/image", async () => { + mockFetch204(); + + await deleteBankChoiceImage("b1", 2); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/bank-questions/b1/choices/2/image"); + expect(init?.method).toBe("DELETE"); + }); +}); diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index e98fd62..773e2cf 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -139,6 +139,22 @@ describe("client", () => { ); }); + it("localizes question-bank permission and attempt conflicts", () => { + // exact backend strings from web/bank_questions.rs + web/exams.rs + expect(formatApiErrorMessage("only the template's owner or an admin can change it", "tr")).toBe( + "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", + ); + expect( + formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", "en"), + ).toBe("Only this course's teachers or a manager can save this question to the bank."); + expect(formatApiError(new ApiError(409, "cannot change questions after attempts have started"), "tr")).toBe( + "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", + ); + expect( + formatApiErrorMessage("only the course creator, an assigned teacher, or a manager/admin can author questions", "tr"), + ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir."); + }); + it("handles unknown messages with sentence case", () => { expect(formatApiErrorMessage("custom error occurred", "en")).toBe("Custom error occurred"); expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı: Custom error occurred"); diff --git a/src/api/__tests__/exams/exam-questions.test.ts b/src/api/__tests__/exams/exam-questions.test.ts index ecf6c71..58d9cd1 100644 --- a/src/api/__tests__/exams/exam-questions.test.ts +++ b/src/api/__tests__/exams/exam-questions.test.ts @@ -7,6 +7,8 @@ import { postExamQuestionImage } from "../../exams"; import { deleteExamQuestionImage } from "../../exams"; import { postExamChoiceImage } from "../../exams"; import { deleteExamChoiceImage } from "../../exams"; +import { postExamQuestionFromBank } from "../../exams"; +import { postExamQuestionToBank } from "../../exams"; import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; describe("exams API - questions", () => { @@ -111,4 +113,30 @@ describe("exams API - questions", () => { expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); expect(init?.method).toBe("DELETE"); }); + + it("postExamQuestionFromBank calls /exams/:id/questions/from-bank/:bid with subject_id", async () => { + const mockQuestion = { id: "q9", source_bank: "b1" }; + mockFetchSuccess(mockQuestion, 201); + + const result = await postExamQuestionFromBank("ex1", "b1", "sub1"); + expect(result).toEqual(mockQuestion); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/ex1/questions/from-bank/b1"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBe(JSON.stringify({ subject_id: "sub1" })); + }); + + it("postExamQuestionToBank calls /exams/:id/questions/:qid/to-bank with no body", async () => { + const mockBankQuestion = { id: "b1", source_exam: "ex1" }; + mockFetchSuccess(mockBankQuestion, 201); + + const result = await postExamQuestionToBank("ex1", "q1"); + expect(result).toEqual(mockBankQuestion); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/ex1/questions/q1/to-bank"); + expect(init?.method).toBe("POST"); + expect(init?.body).toBeUndefined(); + }); }); diff --git a/src/api/__tests__/exams/exams.test.ts b/src/api/__tests__/exams/exams.test.ts index ac71cb4..1c9df5b 100644 --- a/src/api/__tests__/exams/exams.test.ts +++ b/src/api/__tests__/exams/exams.test.ts @@ -4,6 +4,7 @@ import { getExamById } from "../../exams"; import { patchExamById } from "../../exams"; import { deleteExamById } from "../../exams"; import { getExamQuestionImageBlob } from "../../exams"; +import { getExamChoiceImageBlob } from "../../exams"; import { postExamAttemptAnswerImage } from "../../exams"; import { deleteExamAttemptAnswerImage } from "../../exams"; import { getExamAnswerImageBlob } from "../../exams"; @@ -26,6 +27,17 @@ describe("exams API - core", () => { expect(init?.method).toBe("GET"); }); + it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:index/image", async () => { + mockFetchBlob(new Blob(["img"], { type: "image/png" })); + + const result = await getExamChoiceImageBlob("ex1", "q1", 2); + expect(result).toBeInstanceOf(Blob); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/exams/ex1/questions/q1/choices/2/image"); + expect(init?.method).toBeUndefined(); + }); + it("getExamById calls /exams/:id", async () => { const mockExam = { id: "ex1", title: "Exam" }; mockFetchSuccess(mockExam); diff --git a/src/api/bank-questions/deleteBankChoiceImage.ts b/src/api/bank-questions/deleteBankChoiceImage.ts new file mode 100644 index 0000000..cc4e60f --- /dev/null +++ b/src/api/bank-questions/deleteBankChoiceImage.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteBankChoiceImage(bankQuestionId: string, index: number): Promise { + return client(`/bank-questions/${bankQuestionId}/choices/${index}/image`, { method: "DELETE" }); +} diff --git a/src/api/bank-questions/deleteBankQuestionById.ts b/src/api/bank-questions/deleteBankQuestionById.ts new file mode 100644 index 0000000..a463401 --- /dev/null +++ b/src/api/bank-questions/deleteBankQuestionById.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteBankQuestionById(bankQuestionId: string): Promise { + return client(`/bank-questions/${bankQuestionId}`, { method: "DELETE" }); +} diff --git a/src/api/bank-questions/deleteBankQuestionImage.ts b/src/api/bank-questions/deleteBankQuestionImage.ts new file mode 100644 index 0000000..e050516 --- /dev/null +++ b/src/api/bank-questions/deleteBankQuestionImage.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; + +export function deleteBankQuestionImage(bankQuestionId: string): Promise { + return client(`/bank-questions/${bankQuestionId}/image`, { method: "DELETE" }); +} diff --git a/src/api/bank-questions/getBankChoiceImageBlob.ts b/src/api/bank-questions/getBankChoiceImageBlob.ts new file mode 100644 index 0000000..eb834d1 --- /dev/null +++ b/src/api/bank-questions/getBankChoiceImageBlob.ts @@ -0,0 +1,5 @@ +import { blobClient } from "../client"; + +export function getBankChoiceImageBlob(bankQuestionId: string, index: number, signal?: AbortSignal): Promise { + return blobClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, signal); +} diff --git a/src/api/bank-questions/getBankQuestionById.ts b/src/api/bank-questions/getBankQuestionById.ts new file mode 100644 index 0000000..761c574 --- /dev/null +++ b/src/api/bank-questions/getBankQuestionById.ts @@ -0,0 +1,6 @@ +import { client } from "../client"; +import type { BankQuestion } from "../client"; + +export function getBankQuestionById(bankQuestionId: string, signal?: AbortSignal): Promise { + return client(`/bank-questions/${bankQuestionId}`, { signal }); +} diff --git a/src/api/bank-questions/getBankQuestionImageBlob.ts b/src/api/bank-questions/getBankQuestionImageBlob.ts new file mode 100644 index 0000000..1625c64 --- /dev/null +++ b/src/api/bank-questions/getBankQuestionImageBlob.ts @@ -0,0 +1,5 @@ +import { blobClient } from "../client"; + +export function getBankQuestionImageBlob(bankQuestionId: string, signal?: AbortSignal): Promise { + return blobClient(`/bank-questions/${bankQuestionId}/image`, signal); +} diff --git a/src/api/bank-questions/getBankQuestions.ts b/src/api/bank-questions/getBankQuestions.ts new file mode 100644 index 0000000..650f894 --- /dev/null +++ b/src/api/bank-questions/getBankQuestions.ts @@ -0,0 +1,19 @@ +import { client } from "../client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; +import type { BankQuestion } from "../client"; + +/** `owner` takes a user id or the literal "me". */ +export type BankQuestionFilters = PageParams & { subject?: string; owner?: string }; + +export async function getBankQuestions( + params?: BankQuestionFilters, + signal?: AbortSignal, +): Promise> { + const query = new URLSearchParams(); + if (params?.subject) query.set("subject", params.subject); + if (params?.owner) query.set("owner", params.owner); + appendPageParams(query, params); + const value = query.toString(); + const data = await client(`/bank-questions${value ? `?${value}` : ""}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/bank-questions/index.ts b/src/api/bank-questions/index.ts new file mode 100644 index 0000000..05aaae9 --- /dev/null +++ b/src/api/bank-questions/index.ts @@ -0,0 +1,11 @@ +export * from "./postBankQuestion"; +export * from "./getBankQuestions"; +export * from "./getBankQuestionById"; +export * from "./patchBankQuestionById"; +export * from "./deleteBankQuestionById"; +export * from "./postBankQuestionImage"; +export * from "./getBankQuestionImageBlob"; +export * from "./deleteBankQuestionImage"; +export * from "./postBankChoiceImage"; +export * from "./getBankChoiceImageBlob"; +export * from "./deleteBankChoiceImage"; diff --git a/src/api/bank-questions/patchBankQuestionById.ts b/src/api/bank-questions/patchBankQuestionById.ts new file mode 100644 index 0000000..4dafd6b --- /dev/null +++ b/src/api/bank-questions/patchBankQuestionById.ts @@ -0,0 +1,18 @@ +import { client } from "../client"; +import type { BankQuestion, QuestionKind } from "../client"; + +export type PatchBankQuestionBody = { + subject_id?: string; + text?: string; + kind?: QuestionKind; + points?: number; + choices?: string[] | null; + correct?: number | null; +}; + +export function patchBankQuestionById( + bankQuestionId: string, + body: PatchBankQuestionBody, +): Promise { + return client(`/bank-questions/${bankQuestionId}`, { method: "PATCH", body }); +} diff --git a/src/api/bank-questions/postBankChoiceImage.ts b/src/api/bank-questions/postBankChoiceImage.ts new file mode 100644 index 0000000..104a7f2 --- /dev/null +++ b/src/api/bank-questions/postBankChoiceImage.ts @@ -0,0 +1,8 @@ +import { formClient } from "../client"; +import type { ImageMeta } from "../client"; + +export function postBankChoiceImage(bankQuestionId: string, index: number, file: File, signal?: AbortSignal): Promise { + const body = new FormData(); + body.append("file", file); + return formClient(`/bank-questions/${bankQuestionId}/choices/${index}/image`, body, signal); +} diff --git a/src/api/bank-questions/postBankQuestion.ts b/src/api/bank-questions/postBankQuestion.ts new file mode 100644 index 0000000..44a1a0c --- /dev/null +++ b/src/api/bank-questions/postBankQuestion.ts @@ -0,0 +1,15 @@ +import { client } from "../client"; +import type { BankQuestion, QuestionKind } from "../client"; + +export type BankQuestionBody = { + subject_id: string; + text: string; + kind: QuestionKind; + points: number; + choices?: string[] | null; + correct?: number | null; +}; + +export function postBankQuestion(body: BankQuestionBody): Promise { + return client(`/bank-questions`, { method: "POST", body }); +} diff --git a/src/api/bank-questions/postBankQuestionImage.ts b/src/api/bank-questions/postBankQuestionImage.ts new file mode 100644 index 0000000..499d5ae --- /dev/null +++ b/src/api/bank-questions/postBankQuestionImage.ts @@ -0,0 +1,8 @@ +import { formClient } from "../client"; +import type { ImageMeta } from "../client"; + +export function postBankQuestionImage(bankQuestionId: string, file: File, signal?: AbortSignal): Promise { + const body = new FormData(); + body.append("file", file); + return formClient(`/bank-questions/${bankQuestionId}/image`, body, signal); +} diff --git a/src/api/client/client.ts b/src/api/client/client.ts index 0e477d7..c803523 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -90,6 +90,26 @@ const API_ERROR_MESSAGES: Record> = { en: "The repeated slots overlap each other.", tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", }, + "only the template's owner or an admin can change it": { + en: "Only the teacher who created this template (or an admin) can change it.", + tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", + }, + "only the course creator, an assigned teacher, or a manager/admin can author questions": { + en: "Only this course's teachers or a manager can add questions to this exam.", + tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.", + }, + "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": { + en: "Only this course's teachers or a manager can save this question to the bank.", + tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.", + }, + "cannot change questions after attempts have started": { + en: "Students have already started this exam, so its questions can no longer change.", + tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", + }, + "bank questions still reference this subject — re-tag or delete them first": { + en: "Question bank templates still use this subject. Re-tag or delete them first.", + tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.", + }, "course not found": { en: "Course not found.", tr: "Ders bulunamadı.", diff --git a/src/api/client/types.ts b/src/api/client/types.ts index 78e3783..bc5dbce 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -125,6 +125,15 @@ export const APPOINTMENT_LIMITS = { maxSlotOccurrences: 52, // MAX_SLOT_OCCURRENCES for repeat_weekly } as const; +export const BANK_QUESTION_LIMITS = { + textMaxLen: 2000, // MAX_QUESTION_TEXT_LEN + choiceTextMaxLen: 500, // MAX_CHOICE_TEXT_LEN + minPoints: 1, // MIN_QUESTION_POINTS + maxPoints: 100, // MAX_QUESTION_POINTS + minChoices: 2, // MIN_QUESTION_CHOICES + maxChoices: 10, // MAX_QUESTION_CHOICES +} as const; + export type Course = { id: string; creator: PersonRef; @@ -209,6 +218,23 @@ export type ExamQuestion = { correct: number | null; image?: ImageMeta | null; choice_images?: (ImageMeta | null)[] | null; + source_bank?: string | null; // bank question this was copied from, if any +}; + +/** Reusable question stored in the school-wide question bank, outside any exam. */ +export type BankQuestion = { + id: string; + owner: string; // user id + subject: string; // subject id (origin metadata) + text: string; + kind: QuestionKind; + points: number; + choices: string[] | null; + correct: number | null; + image?: ImageMeta | null; + choice_images?: (ImageMeta | null)[] | null; + source_exam?: string | null; + created_at: number; // UTC unix ms }; export type ExamAttempt = { diff --git a/src/api/exams/getExamChoiceImageBlob.ts b/src/api/exams/getExamChoiceImageBlob.ts new file mode 100644 index 0000000..ad09223 --- /dev/null +++ b/src/api/exams/getExamChoiceImageBlob.ts @@ -0,0 +1,5 @@ +import { blobClient } from "../client"; + +export function getExamChoiceImageBlob(examId: string, questionId: string, index: number, signal?: AbortSignal): Promise { + return blobClient(`/exams/${examId}/questions/${questionId}/choices/${index}/image`, signal); +} diff --git a/src/api/exams/index.ts b/src/api/exams/index.ts index 570188c..b9d13ee 100644 --- a/src/api/exams/index.ts +++ b/src/api/exams/index.ts @@ -8,6 +8,7 @@ export * from "./patchExamQuestionById"; export * from "./deleteExamQuestionById"; export * from "./postExamQuestionImage"; export * from "./getExamQuestionImageBlob"; +export * from "./getExamChoiceImageBlob"; export * from "./deleteExamQuestionImage"; export * from "./postExamChoiceImage"; export * from "./deleteExamChoiceImage"; @@ -35,3 +36,5 @@ export * from "./getExamReviewAttempts"; export * from "./getExamReviewAttemptAnswers"; export * from "./getExamReviewAttemptAnswerImage"; export * from "./getStudentMarksHistory"; +export * from "./postExamQuestionFromBank"; +export * from "./postExamQuestionToBank"; diff --git a/src/api/exams/postExamQuestionFromBank.ts b/src/api/exams/postExamQuestionFromBank.ts new file mode 100644 index 0000000..cc7de43 --- /dev/null +++ b/src/api/exams/postExamQuestionFromBank.ts @@ -0,0 +1,14 @@ +import { client } from "../client"; +import type { ExamQuestion } from "../client"; + +/** Copy a bank question into this exam; `subjectId` is the exam-side subject. */ +export function postExamQuestionFromBank( + examId: string, + bankQuestionId: string, + subjectId: string, +): Promise { + return client(`/exams/${examId}/questions/from-bank/${bankQuestionId}`, { + method: "POST", + body: { subject_id: subjectId }, + }); +} diff --git a/src/api/exams/postExamQuestionToBank.ts b/src/api/exams/postExamQuestionToBank.ts new file mode 100644 index 0000000..3e868b3 --- /dev/null +++ b/src/api/exams/postExamQuestionToBank.ts @@ -0,0 +1,7 @@ +import { client } from "../client"; +import type { BankQuestion } from "../client"; + +/** Copy an exam question into the caller's question bank. */ +export function postExamQuestionToBank(examId: string, questionId: string): Promise { + return client(`/exams/${examId}/questions/${questionId}/to-bank`, { method: "POST" }); +} diff --git a/src/components/exams/bank-question-form.tsx b/src/components/exams/bank-question-form.tsx new file mode 100644 index 0000000..237c2d3 --- /dev/null +++ b/src/components/exams/bank-question-form.tsx @@ -0,0 +1,127 @@ +import { For, Show, createResource, createSignal } from "solid-js"; +import type { BankQuestion, Course } from "@/api/client"; +import { + getBankChoiceImageBlob, + patchBankQuestionById, + postBankChoiceImage, + postBankQuestion, + postBankQuestionImage, +} from "@/api/bank-questions"; +import { getBankQuestionImageBlob } from "@/api/bank-questions"; +import { getCourseSubjects } from "@/api/courses"; +import { getSubjectById } from "@/api/subjects"; +import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; +import { planChoiceImageRestore } from "@/lib/choice-compaction"; +import { Label } from "@/components/ui/label"; +import { Select } from "@/components/ui/select"; +import { useT } from "@/stores/preferences-context"; + +/** + * Create/edit a bank template. Wraps the shared `QuestionForm` with the + * course→subject pick the bank needs (a template carries a subject id, but the + * backend has no school-wide subject list — subjects are reached through a course). + */ +export function BankQuestionForm(props: { + initial?: BankQuestion; + courses: Course[]; + /** `imagesLost` is set when an option image could not be carried over the edit. */ + onSaved: (question: BankQuestion, imagesLost?: string) => void; + onCancel: () => void; +}) { + const t = useT(); + // Editing: resolve the template's subject to learn which course to preselect. + const [initialCourse] = createResource( + () => props.initial?.subject ?? null, + async (subjectId) => (await getSubjectById(subjectId).catch(() => null))?.course ?? "", + ); + const [courseId, setCourseId] = createSignal(""); + const selectedCourse = () => courseId() || initialCourse() || props.courses[0]?.id || ""; + const [subjects] = createResource( + () => selectedCourse() || null, + async (id) => (await getCourseSubjects(id)).items, + ); + + const imageBase = () => `/api/bank-questions/${props.initial?.id}`; + + const submit = async (values: QuestionValues) => { + const { image, choice_images, choice_sources, ...body } = values; + const existing = props.initial; + + // PATCH with a `choices` key wipes every stored option image server-side, so + // fetch the ones the user is keeping first and put them back afterwards. + // `choice_sources` maps each surviving choice to the option it came from, + // because blank choices are dropped and would otherwise shift the indices. + const lost: number[] = []; + const keep: { index: number; file: File }[] = []; + if (existing && body.kind === "choice") { + const plan = planChoiceImageRestore(choice_sources ?? [], existing.choice_images ?? [], choice_images); + for (const slot of plan) { + try { + const blob = await getBankChoiceImageBlob(existing.id, slot.source); + keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) }); + } catch { + lost.push(slot.index); // the PATCH below deletes it regardless — say so + } + } + } + + const saved = existing + ? await patchBankQuestionById(existing.id, body) + : await postBankQuestion(body); + if (image) await postBankQuestionImage(saved.id, image); + for (const [index, file] of (choice_images ?? []).entries()) { + if (file) await postBankChoiceImage(saved.id, index, file); + } + // One failed restore must not abandon the rest: upload each independently. + for (const slot of keep) { + try { + await postBankChoiceImage(saved.id, slot.index, slot.file); + } catch { + lost.push(slot.index); + } + } + props.onSaved( + saved, + lost.length > 0 + ? t("questions.imagesLost", { options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", ") }) + : undefined, + ); + }; + + return ( +
+

+ {t("bank.copyNotice")} +

+ +
+ + +

{t("bank.courseHint")}

+
+ + +

+ {t("bank.choiceImagesWarning")} +

+
+ + `${imageBase()}/choices/${index}/image`} + loadImageBlob={props.initial ? () => getBankQuestionImageBlob(props.initial!.id) : undefined} + onSubmit={submit} + onCancel={props.onCancel} + /> +
+ ); +} diff --git a/src/components/exams/bank-question-picker.tsx b/src/components/exams/bank-question-picker.tsx new file mode 100644 index 0000000..6e0d8b1 --- /dev/null +++ b/src/components/exams/bank-question-picker.tsx @@ -0,0 +1,167 @@ +import { For, Show, createMemo, createResource, createSignal } from "solid-js"; +import type { BankQuestion, Subject } from "@/api/client"; +import { formatApiError } from "@/api/client"; +import { getBankQuestions } from "@/api/bank-questions"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select } from "@/components/ui/select"; +import { cn } from "@/lib/cn"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +const BANK_LIMIT = 100; + +/** Pick a bank template and copy it into an exam under one of that exam's subjects. */ +export function BankQuestionPicker(props: { + subjects: Subject[]; + onInsert: (bankQuestionId: string, subjectId: string) => Promise; + onCancel: () => void; +}) { + const t = useT(); + const { locale } = usePreferences(); + const [query, setQuery] = createSignal(""); + const [selected, setSelected] = createSignal(null); + const [subjectId, setSubjectId] = createSignal(""); + const [error, setError] = createSignal(""); + const [pending, setPending] = createSignal(false); + // ponytail: first 100 templates, narrowed client-side — the bank has no text + // search endpoint. Swap for a server query when the bank outgrows one page. + const [templates] = createResource(async () => (await getBankQuestions({ limit: BANK_LIMIT })).items); + + const targetSubject = () => subjectId() || props.subjects[0]?.id || ""; + const visible = createMemo(() => { + const q = query().trim().toLocaleLowerCase(locale()); + const items = templates() ?? []; + return q ? items.filter((item) => item.text.toLocaleLowerCase(locale()).includes(q)) : items; + }); + + const insert = async () => { + const template = selected(); + const subject = targetSubject(); + if (!template || !subject || pending()) return; + setError(""); + setPending(true); + try { + await props.onInsert(template.id, subject); + } catch (err) { + setError(formatApiError(err)); + } finally { + setPending(false); + } + }; + + return ( +
+

+ {t("bank.copyNotice")} +

+ + setQuery(event.currentTarget.value)} + /> + +
+ 0} + fallback={

{t("bank.pickerEmpty")}

} + > + + {(template) => ( + + )} + +
+
+ + + {(template) => ( +
+

{template().text}

+ + {t("questions.image")} + + +
    + + {(choice, index) => ( +
  1. + {String.fromCharCode(65 + index())} + {choice} +
  2. + )} +
    +
+
+
+ )} +
+ +
+ + 0} + fallback={

{t("bank.noSubjects")}

} + > + +
+
+ + {error() &&

{error()}

} + +
+ + +
+
+ ); +} diff --git a/src/components/exams/exam-questions-panel.tsx b/src/components/exams/exam-questions-panel.tsx index ef7a38e..ad8c7bc 100644 --- a/src/components/exams/exam-questions-panel.tsx +++ b/src/components/exams/exam-questions-panel.tsx @@ -3,7 +3,11 @@ import { deleteExamChoiceImage } from "@/api/exams"; import { deleteExamQuestionImage } from "@/api/exams"; import { deleteExamQuestionById } from "@/api/exams"; import { getCourseSubjects } from "@/api/courses"; +import { getExamChoiceImageBlob } from "@/api/exams"; +import { getExamQuestionImageBlob } from "@/api/exams"; import { getExamQuestions } from "@/api/exams"; +import { postExamQuestionFromBank } from "@/api/exams"; +import { postExamQuestionToBank } from "@/api/exams"; import { patchExamQuestionById } from "@/api/exams"; import { postExamChoiceImage } from "@/api/exams"; import { postExamQuestionImage } from "@/api/exams"; @@ -15,10 +19,14 @@ import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { FormDialog } from "@/components/ui/form-dialog"; +import { BankQuestionPicker } from "@/components/exams/bank-question-picker"; import { QuestionForm, type QuestionValues } from "@/components/exams/question-form"; -import { IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; +import { IconArchive, IconChevronLeft, IconChevronRight, IconPlus, IconTrash } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; +import { planChoiceImageRestore } from "@/lib/choice-compaction"; import { createFlash } from "@/lib/flash"; +import { hasMinRole } from "@/lib/roles"; +import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; const QUESTION_PAGE_SIZE = 1; @@ -32,6 +40,10 @@ export function ExamQuestionsPanel(props: { onCreateOpenChange?: (open: boolean) => void; }) { const t = useT(); + const auth = useAuth(); + const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher"); + const [bankOpen, setBankOpen] = createSignal(false); + const [banking, setBanking] = createSignal(""); const [subjects] = createResource(() => props.courseId, async (courseId) => (await getCourseSubjects(courseId)).items); const [questions, { refetch }] = createResource(() => props.examId, async (examId) => { try { @@ -44,6 +56,10 @@ export function ExamQuestionsPanel(props: { const [showForm, setShowForm] = createSignal(false); const [editing, setEditing] = createSignal(null); const [removeQuestion, setRemoveQuestion] = createSignal(null); + const [confirmBank, setConfirmBank] = createSignal(null); + // Older backends never write `source_bank` back onto the exam question after a + // to-bank save, so remember what this session banked and treat both as "banked". + const [bankedIds, setBankedIds] = createSignal([]); const [error, setError] = createSignal(""); const [imagePending, setImagePending] = createSignal(""); const [flash, setFlash] = createFlash(); @@ -57,6 +73,11 @@ export function ExamQuestionsPanel(props: { const formInitial = createMemo(() => editing() ?? undefined); const questionList = createMemo(() => questions() ?? []); + // The header badge renders outside the below, so it must read + // `.latest` — a bare read there re-suspends on every refetch (insert-from-bank, + // save, delete) and blanks the surrounding page for the whole fetch. + const questionCount = () => questions.latest?.length ?? 0; + const isBanked = (question: ExamQuestion) => Boolean(question.source_bank) || bankedIds().includes(question.id); const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId; const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE))); const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); @@ -82,7 +103,24 @@ export function ExamQuestionsPanel(props: { try { const q = editing(); const isNewQuestion = !q; - const { image, choice_images, ...body } = values; + // choice_sources is form-only bookkeeping — never send it to the backend. + const { image, choice_images, choice_sources, ...body } = values; + + // A PATCH carrying `choices` wipes every stored option image, so pull the + // ones the user kept first and put them back under their new indices. + const lost: number[] = []; + const keep: { index: number; file: File }[] = []; + if (q && body.kind === "choice") { + for (const slot of planChoiceImageRestore(choice_sources ?? [], q.choice_images ?? [], choice_images)) { + try { + const blob = await getExamChoiceImageBlob(props.examId, q.id, slot.source); + keep.push({ index: slot.index, file: new File([blob], `choice-${slot.source}`, { type: blob.type }) }); + } catch { + lost.push(slot.index); // the write below drops it either way — report it + } + } + } + const saved = q ? await patchExamQuestionById(props.examId, q.id, body) : await postExamQuestion(props.examId, body); @@ -90,6 +128,19 @@ export function ExamQuestionsPanel(props: { for (const [index, file] of (choice_images ?? []).entries()) { if (file) await postExamChoiceImage(props.examId, saved.id, index, file); } + // Independent uploads: one failure must not strand the remaining images. + for (const slot of keep) { + try { + await postExamChoiceImage(props.examId, saved.id, slot.index, slot.file); + } catch { + lost.push(slot.index); + } + } + if (lost.length > 0) { + setError(t("questions.imagesLost", { + options: lost.sort((a, b) => a - b).map((index) => String.fromCharCode(65 + index)).join(", "), + })); + } if (q) { setFlash(t("common.saved")); } else { @@ -104,6 +155,29 @@ export function ExamQuestionsPanel(props: { } }; + const insertFromBank = async (bankQuestionId: string, subjectId: string) => { + await postExamQuestionFromBank(props.examId, bankQuestionId, subjectId); + setBankOpen(false); + setFlash(t("bank.inserted")); + await refetch(); + }; + + const saveToBank = async (question: ExamQuestion) => { + if (banking()) return; + setError(""); + setBanking(question.id); + try { + await postExamQuestionToBank(props.examId, question.id); + setBankedIds((ids) => (ids.includes(question.id) ? ids : [...ids, question.id])); + setFlash(t("bank.savedToBank")); + await refetch(); + } catch (err) { + setError(formatApiError(err)); + } finally { + setBanking(""); + } + }; + const removeQuestionImage = async (question: ExamQuestion) => { if (props.readOnly) return; setError(""); @@ -144,26 +218,53 @@ export function ExamQuestionsPanel(props: {

{t("questions.title")}

- {questionList().length} + {questionCount()}
- +
+ + + + +
+ + setBankOpen(false)} + /> + + { @@ -178,6 +279,9 @@ export function ExamQuestionsPanel(props: { `/api/exams/${props.examId}/questions/${editing()?.id}/choices/${index}/image`} + loadImageBlob={editing() ? () => getExamQuestionImageBlob(props.examId, editing()!.id) : undefined} onCancel={() => { setEditing(null); setFormOpen(false); @@ -230,6 +334,14 @@ export function ExamQuestionsPanel(props: { {q.points} {t("questions.points")} + {/* `source_bank` is set in both directions (inserted from the + bank, or saved to it), so the badge stays origin-neutral. */} + + + + {t("bank.inBankBadge")} + + - + {/* Saving to the bank copies the question out; it never touches the + exam, so it stays available on a finished/read-only exam. */} +
- - + + + + + + +
@@ -354,6 +483,24 @@ export function ExamQuestionsPanel(props: {
+ { + if (!open) setConfirmBank(null); + }} + title={t("bank.saveCopyTitle")} + description={t("bank.saveCopyBody")} + confirmLabel={t("bank.saveCopyConfirm")} + icon={} + summary={confirmBank()?.text ?? ""} + onConfirm={async () => { + const q = confirmBank(); + if (!q) return; + setConfirmBank(null); + await saveToBank(q); + }} + /> + { diff --git a/src/components/exams/question-form.tsx b/src/components/exams/question-form.tsx index e5d1fe8..418a45c 100644 --- a/src/components/exams/question-form.tsx +++ b/src/components/exams/question-form.tsx @@ -1,8 +1,7 @@ -import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy } from "solid-js"; +import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy, untrack } from "solid-js"; import { formatApiError } from "@/api/client"; -import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; -import { QUESTION_KINDS } from "@/api/client"; -import { getExamQuestionImageBlob } from "@/api/exams"; +import type { ImageMeta, QuestionKind, Subject } from "@/api/client"; +import { BANK_QUESTION_LIMITS, QUESTION_KINDS } from "@/api/client"; import { getSettings } from "@/api/settings"; import type { DrawScene } from "@/lib/draw-stroke"; import { Button } from "@/components/ui/button"; @@ -11,6 +10,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; +import { compactChoices } from "@/lib/choice-compaction"; import { cn } from "@/lib/cn"; import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { useT } from "@/stores/preferences-context"; @@ -27,11 +27,35 @@ export type QuestionValues = { correct: number | null; image: File | null; choice_images: (File | null)[] | null; + /** + * For each surviving choice, the index it had in `initial.choices` (or -1 when + * it was added in this edit). Blank choices are dropped on submit, so callers + * that must re-attach per-choice server state need this old→new map. + */ + choice_sources: number[] | null; +}; + +/** Shape both `ExamQuestion` and `BankQuestion` satisfy — the form only needs these. */ +export type QuestionFormInitial = { + subject: string; + text: string; + kind: QuestionKind; + points: number; + choices: string[] | null; + correct: number | null; + image?: ImageMeta | null; + choice_images?: (ImageMeta | null)[] | null; }; export function QuestionForm(props: { - initial?: ExamQuestion; + initial?: QuestionFormInitial; subjects: Subject[]; + /** Existing stored image, as a URL the browser can GET (exam or bank path). */ + imageSrc?: string; + choiceImageSrc?: (index: number) => string; + /** Reload the stored image so an existing drawing can be edited, not redrawn. */ + loadImageBlob?: () => Promise; + submitLabel?: string; onSubmit: (values: QuestionValues) => Promise; onCancel: () => void; }) { @@ -47,6 +71,9 @@ export function QuestionForm(props: { const [drawing, setDrawing] = createSignal(false); const [editScene, setEditScene] = createSignal(null); const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); + // Index each row still holds in `initial.choices` (-1 once added here), so a + // caller can map surviving choices back to the server-side option they came from. + const [choiceSources, setChoiceSources] = createSignal(choices().map((_, index) => index)); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [settings] = createResource(async () => { @@ -58,19 +85,29 @@ export function QuestionForm(props: { }); const maxFileBytes = () => maxUploadBytes(settings()); + // Reset on a new `initial` only — `props.subjects` may arrive after the form is + // open (async course subjects), and re-running then would wipe what was typed. createEffect(() => { const initial = props.initial; - setText(initial?.text ?? ""); - setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? ""); - setKind(initial?.kind ?? "choice"); - setPoints(String(initial?.points ?? 1)); - setChoices(initial?.choices ?? ["", "", "", ""]); - setCorrect(initial?.correct ?? 0); - setImage(null); - setDrawing(false); - setEditScene(null); - setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); - setError(""); + untrack(() => { + setText(initial?.text ?? ""); + setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? ""); + setKind(initial?.kind ?? "choice"); + setPoints(String(initial?.points ?? 1)); + setChoices(initial?.choices ?? ["", "", "", ""]); + setCorrect(initial?.correct ?? 0); + setImage(null); + setDrawing(false); + setEditScene(null); + setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); + setChoiceSources((initial?.choices ?? ["", "", "", ""]).map((_, index) => (initial ? index : -1))); + setError(""); + }); + }); + + // Once subjects load, preselect the first one if nothing is chosen yet. + createEffect(() => { + if (!subjectId()) setSubjectId(props.subjects[0]?.id ?? ""); }); // Blank pad for a fresh drawing; reload the stored scene to edit an existing one. @@ -80,11 +117,11 @@ export function QuestionForm(props: { }; const editDrawing = async () => { - const q = props.initial; - if (!q?.image) return; + const load = props.loadImageBlob; + if (!props.initial?.image || !load) return; setError(""); try { - const blob = await getExamQuestionImageBlob(q.exam, q.id); + const blob = await load(); const { pngBytesToScene } = await import("@/lib/drawing-file"); setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); } catch { @@ -134,14 +171,24 @@ export function QuestionForm(props: { }; const addChoice = () => { - setChoices((current) => (current.length >= 10 ? current : [...current, ""])); - setChoiceImages((current) => (current.length >= 10 ? current : [...current, null])); + const max = BANK_QUESTION_LIMITS.maxChoices; + setChoices((current) => (current.length >= max ? current : [...current, ""])); + setChoiceImages((current) => (current.length >= max ? current : [...current, null])); + setChoiceSources((current) => (current.length >= max ? current : [...current, -1])); }; const removeChoice = (index: number) => { + const remaining = choices().length - 1; setChoices((current) => current.filter((_, i) => i !== index)); setChoiceImages((current) => current.filter((_, i) => i !== index)); - setCorrect((current) => Math.max(0, Math.min(current, choices().length - 2))); + setChoiceSources((current) => current.filter((_, i) => i !== index)); + // Deleting a row above the answer shifts it down; deleting the answer row + // itself moves the mark to the row that took its place (visible in the UI). + setCorrect((current) => { + if (index < current) return Math.max(0, current - 1); + if (index > current) return current; + return Math.max(0, Math.min(current, remaining - 1)); + }); }; const validate = (): QuestionValues | string => { @@ -149,22 +196,35 @@ export function QuestionForm(props: { const subject = subjectId().trim(); if (!subject) return t("questions.subjectRequired"); if (!body) return t("questions.textRequired"); - if (body.length > 2000) return t("form.descriptionMax"); + if (body.length > BANK_QUESTION_LIMITS.textMaxLen) return t("form.descriptionMax"); const p = Number(points()); - if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange"); + if (!Number.isInteger(p) || p < BANK_QUESTION_LIMITS.minPoints || p > BANK_QUESTION_LIMITS.maxPoints) return t("questions.pointsRange"); if (kind() === "text") { - return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null }; + return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null, image: image(), choice_images: null, choice_sources: null }; } - const indexedChoices = choices() - .map((choice, index) => ({ choice: choice.trim(), image: choiceImages()[index] ?? null })) - .filter((item) => item.choice); - const cleanChoices = indexedChoices.map((item) => item.choice); - if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) { + const compacted = compactChoices(choices(), choiceImages(), choiceSources(), correct()); + const cleanChoices = compacted.choices; + if ( + cleanChoices.length < BANK_QUESTION_LIMITS.minChoices || + cleanChoices.length > BANK_QUESTION_LIMITS.maxChoices || + cleanChoices.some((choice) => choice.length > BANK_QUESTION_LIMITS.choiceTextMaxLen) + ) { return t("questions.choicesRange"); } - const c = correct(); - if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange"); - return { subject_id: subject, text: body, kind: "choice", points: p, choices: cleanChoices, correct: c, image: image(), choice_images: indexedChoices.map((item) => item.image) }; + // The marked row survived compaction as `compacted.correct`; -1 means the user + // blanked the very choice they had marked, so make them pick again. + if (compacted.correct < 0) return t("questions.correctBlanked"); + return { + subject_id: subject, + text: body, + kind: "choice", + points: p, + choices: cleanChoices, + correct: compacted.correct, + image: image(), + choice_images: compacted.images, + choice_sources: compacted.sources, + }; }; const submit = async (e: SubmitEvent) => { @@ -205,10 +265,10 @@ export function QuestionForm(props: { }} />
- +
{t("questions.image")} @@ -235,7 +295,7 @@ export function QuestionForm(props: { {t("questions.draw")} - + + + } + columns={columns()} + data={list() ?? []} + tableClass="table-fixed min-w-5xl" + filterPlaceholder={t("bank.search")} + searchPredicate={searchTemplate} + enablePagination + pageSize={BANK_PAGE_SIZE} + empty={t("bank.empty")} + filters={ +
+ setOwnerFilter(value as "all" | "me")} + options={[ + { value: "all", label: t("common.all") }, + { value: "me", label: t("bank.mine") }, + ]} + /> + setSubjectFilter(value)} + options={subjectOptions()} + /> +
+ } + /> + + + + { + if (!open) { + setCreateOpen(false); + setEditing(null); + } + }} + title={editing() ? t("bank.edit") : t("bank.create")} + description={t("bank.title")} + size="wide" + > + { + const wasEdit = editing() != null; + setCreateOpen(false); + setEditing(null); + setError(imagesLost ?? ""); + setFlash(wasEdit ? t("common.saved") : t("common.created")); + await refetch(); + }} + onCancel={() => { + setCreateOpen(false); + setEditing(null); + }} + /> + + + { + if (!open) setRemoving(null); + }} + title={t("confirm.deleteTitle")} + variant="destructive" + summary={removing()?.text ?? ""} + onConfirm={async () => { + const question = removing(); + if (!question) return; + setError(""); + try { + await deleteBankQuestionById(question.id); + await refetch(); + setFlash(t("common.deleted")); + } catch (err) { + setError(formatApiError(err)); + } finally { + setRemoving(null); + } + }} + /> +
+ ); +} diff --git a/src/routes/router.tsx b/src/routes/router.tsx index 4187e1c..abba201 100644 --- a/src/routes/router.tsx +++ b/src/routes/router.tsx @@ -32,6 +32,7 @@ const HomeworkDetailPage = lazyRoute(() => import("@/pages/homework-detail-page" const ExamsPage = lazyRoute(() => import("@/pages/exams-page")); const ExamDetailPage = lazyRoute(() => import("@/pages/exam-detail-page")); const ExamRoomPage = lazyRoute(() => import("@/pages/exam-room-page")); +const QuestionBankPage = lazyRoute(() => import("@/pages/question-bank-page")); const CoursesPage = lazyRoute(() => import("@/pages/courses-page")); const CourseDetailPage = lazyRoute(() => import("@/pages/course-detail-page")); const MarksPage = lazyRoute(() => import("@/pages/marks-page")); @@ -144,6 +145,12 @@ const examRoomRoute = createRoute({ component: ExamRoomPage, }); +const questionBankRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/question-bank", + component: QuestionBankPage, +}); + const coursesRoute = createRoute({ getParentRoute: () => rootRoute, path: "/courses", @@ -295,6 +302,7 @@ const routeTree = rootRoute.addChildren([ examRoomRoute, liveMonitorRoute, examsRoute, + questionBankRoute, coursesRoute, studiesRoute, clubsRoute,