forge
Explore
Log in

Don't you dare go Hollow

✨ add exam question management

Browse files at this commit

5e20cbcd342ff2207c0a836db8f8b7009f80d751Burak BoduroğluParent: b8c369a
  • feat
    • ✨ add exam question management
Show full message
feat: ✨ add exam question management
src/api/deleteExamQuestionById.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "./client";
2+
3+export function deleteExamQuestionById(examId: string, questionId: string): Promise<void> {
4+ return client<void>(`/exams/${examId}/questions/${questionId}`, { method: "DELETE" });
5+}
src/api/getExamQuestions.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "./client";
2+import type { ExamQuestion } from "./types";
3+
4+export function getExamQuestions(examId: string, signal?: AbortSignal): Promise<ExamQuestion[]> {
5+ return client<ExamQuestion[]>(`/exams/${examId}/questions`, { signal });
6+}
src/api/patchExamQuestionById.tsadded+18 -0
@@ -0,0 +1,18 @@
1+import { client } from "./client";
2+import type { ExamQuestion, QuestionKind } from "./types";
3+
4+export type PatchExamQuestionBody = {
5+ text?: string;
6+ kind?: QuestionKind;
7+ points?: number;
8+ choices?: string[] | null;
9+ correct?: number | null;
10+};
11+
12+export function patchExamQuestionById(
13+ examId: string,
14+ questionId: string,
15+ body: PatchExamQuestionBody,
16+): Promise<ExamQuestion> {
17+ return client<ExamQuestion>(`/exams/${examId}/questions/${questionId}`, { method: "PATCH", body });
18+}
src/api/postExamQuestion.tsadded+14 -0
@@ -0,0 +1,14 @@
1+import { client } from "./client";
2+import type { ExamQuestion, QuestionKind } from "./types";
3+
4+export type ExamQuestionBody = {
5+ text: string;
6+ kind: QuestionKind;
7+ points: number;
8+ choices?: string[] | null;
9+ correct?: number | null;
10+};
11+
12+export function postExamQuestion(examId: string, body: ExamQuestionBody): Promise<ExamQuestion> {
13+ return client<ExamQuestion>(`/exams/${examId}/questions`, { method: "POST", body });
14+}
src/api/types.tsmodified+13 -0
@@ -2,6 +2,7 @@ export type Role = "student" | "teacher" | "manager" | "admin";
2 export type AttendanceStatus = "present" | "absent" | "late" | "excused";2 export type AttendanceStatus = "present" | "absent" | "late" | "excused";
3 export type ExamKind = "homework" | "quiz" | "midterm" | "final" | "project" | "oral";3 export type ExamKind = "homework" | "quiz" | "midterm" | "final" | "project" | "oral";
4 export type ExamMode = "sync" | "async";4 export type ExamMode = "sync" | "async";
5+export type QuestionKind = "choice" | "text";
5 6
6 export type User = {7 export type User = {
7 id: string;8 id: string;
@@ -74,6 +75,16 @@ export type ExamResult = {
74 graded_by: string;75 graded_by: string;
75 };76 };
76 77
78+export type ExamQuestion = {
79+ id: string;
80+ exam: string;
81+ text: string;
82+ kind: QuestionKind;
83+ points: number;
84+ choices: string[] | null;
85+ correct: number | null;
86+};
87+
77 export type MarkEntry = {88 export type MarkEntry = {
78 exam: string;89 exam: string;
79 title: string;90 title: string;
@@ -105,3 +116,5 @@ export const EXAM_KINDS: ExamKind[] = [
105 ];116 ];
106 117
107 export const EXAM_MODES: ExamMode[] = ["sync", "async"];118 export const EXAM_MODES: ExamMode[] = ["sync", "async"];
119+
120+export const QUESTION_KINDS: QuestionKind[] = ["choice", "text"];
src/components/exams/exam-questions-panel.tsxadded+271 -0
@@ -0,0 +1,271 @@
1+import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";
2+import { deleteExamQuestionById } from "@/api/deleteExamQuestionById";
3+import { getExamQuestions } from "@/api/getExamQuestions";
4+import { patchExamQuestionById } from "@/api/patchExamQuestionById";
5+import { postExamQuestion } from "@/api/postExamQuestion";
6+import { ApiError, formatApiError } from "@/api/client";
7+import type { ExamQuestion, QuestionKind } from "@/api/types";
8+import { QUESTION_KINDS } from "@/api/types";
9+import { Badge } from "@/components/ui/badge";
10+import { Button } from "@/components/ui/button";
11+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
12+import { IconPlus, IconTrash } from "@/components/ui/icons";
13+import { Input } from "@/components/ui/input";
14+import { Label } from "@/components/ui/label";
15+import { PageSpinner } from "@/components/ui/page-spinner";
16+import { Select } from "@/components/ui/select";
17+import { Textarea } from "@/components/ui/textarea";
18+import { useT } from "@/stores/preferences-context";
19+
20+type QuestionValues = {
21+ text: string;
22+ kind: QuestionKind;
23+ points: number;
24+ choices: string[] | null;
25+ correct: number | null;
26+};
27+
28+export function ExamQuestionsPanel(props: { examId: string }) {
29+ const t = useT();
30+ const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {
31+ try {
32+ return await getExamQuestions(examId);
33+ } catch (err) {
34+ if (err instanceof ApiError && err.status === 404) return [];
35+ throw err;
36+ }
37+ });
38+ const [showForm, setShowForm] = createSignal(false);
39+ const [editing, setEditing] = createSignal<ExamQuestion | null>(null);
40+ const [removeQuestion, setRemoveQuestion] = createSignal<ExamQuestion | null>(null);
41+ const [error, setError] = createSignal("");
42+
43+ const formInitial = createMemo(() => editing() ?? undefined);
44+
45+ const submit = async (values: QuestionValues) => {
46+ setError("");
47+ try {
48+ const q = editing();
49+ if (q) {
50+ await patchExamQuestionById(props.examId, q.id, values);
51+ } else {
52+ await postExamQuestion(props.examId, values);
53+ }
54+ setEditing(null);
55+ setShowForm(false);
56+ await refetch();
57+ } catch (err) {
58+ setError(formatApiError(err));
59+ }
60+ };
61+
62+ return (
63+ <section class="surface-card space-y-4 p-5">
64+ <div class="flex flex-wrap items-center justify-between gap-2">
65+ <h2 class="font-display text-lg font-semibold">{t("questions.title")}</h2>
66+ <Button
67+ type="button"
68+ variant="outline"
69+ size="sm"
70+ onClick={() => {
71+ setEditing(null);
72+ setShowForm((v) => !v);
73+ }}
74+ >
75+ <IconPlus class="h-4 w-4" />
76+ {t("questions.add")}
77+ </Button>
78+ </div>
79+
80+ <Show when={showForm() || editing()}>
81+ <QuestionForm
82+ initial={formInitial()}
83+ onCancel={() => {
84+ setEditing(null);
85+ setShowForm(false);
86+ }}
87+ onSubmit={submit}
88+ />
89+ </Show>
90+
91+ {error() && <p class="rounded-sm bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}
92+
93+ <Suspense fallback={<PageSpinner />}>
94+ <Show
95+ when={(questions() ?? []).length > 0}
96+ fallback={<p class="rounded-sm bg-muted/40 px-3 py-4 text-sm text-muted-foreground">{t("questions.empty")}</p>}
97+ >
98+ <ol class="space-y-3">
99+ <For each={questions() ?? []}>
100+ {(q, index) => (
101+ <li class="rounded-md border p-4">
102+ <div class="flex flex-wrap items-start justify-between gap-3">
103+ <div class="min-w-0 space-y-2">
104+ <div class="flex flex-wrap items-center gap-2">
105+ <span class="text-xs font-semibold text-muted-foreground">#{index() + 1}</span>
106+ <Badge variant="outline" class="capitalize">
107+ {q.kind === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}
108+ </Badge>
109+ <Badge variant="outline">{q.points} {t("questions.points")}</Badge>
110+ </div>
111+ <p class="whitespace-pre-wrap text-sm font-medium">{q.text}</p>
112+ <Show when={q.kind === "choice" && q.choices}>
113+ <ol class="grid gap-1 text-sm text-muted-foreground">
114+ <For each={q.choices ?? []}>
115+ {(choice, choiceIndex) => (
116+ <li class={choiceIndex() === q.correct ? "font-medium text-foreground" : undefined}>
117+ {choiceIndex()}. {choice}
118+ </li>
119+ )}
120+ </For>
121+ </ol>
122+ </Show>
123+ </div>
124+ <div class="flex gap-2">
125+ <Button type="button" variant="outline" size="sm" onClick={() => setEditing(q)}>
126+ {t("common.edit")}
127+ </Button>
128+ <Button type="button" variant="ghost" size="sm" class="text-destructive" onClick={() => setRemoveQuestion(q)}>
129+ <IconTrash class="h-4 w-4" />
130+ </Button>
131+ </div>
132+ </div>
133+ </li>
134+ )}
135+ </For>
136+ </ol>
137+ </Show>
138+ </Suspense>
139+
140+ <ConfirmDialog
141+ open={removeQuestion() != null}
142+ onOpenChange={(open) => {
143+ if (!open) setRemoveQuestion(null);
144+ }}
145+ title={t("confirm.deleteTitle")}
146+ variant="destructive"
147+ summary={removeQuestion()?.text ?? ""}
148+ onConfirm={async () => {
149+ const q = removeQuestion();
150+ if (!q) return;
151+ setError("");
152+ try {
153+ await deleteExamQuestionById(props.examId, q.id);
154+ await refetch();
155+ } catch (err) {
156+ setError(formatApiError(err));
157+ } finally {
158+ setRemoveQuestion(null);
159+ }
160+ }}
161+ />
162+ </section>
163+ );
164+}
165+
166+function QuestionForm(props: {
167+ initial?: ExamQuestion;
168+ onSubmit: (values: QuestionValues) => Promise<void>;
169+ onCancel: () => void;
170+}) {
171+ const t = useT();
172+ const [text, setText] = createSignal(props.initial?.text ?? "");
173+ const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? "choice");
174+ const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));
175+ const [choicesText, setChoicesText] = createSignal((props.initial?.choices ?? ["", ""]).join("\n"));
176+ const [correct, setCorrect] = createSignal(props.initial?.correct != null ? String(props.initial.correct) : "0");
177+ const [error, setError] = createSignal("");
178+ const [pending, setPending] = createSignal(false);
179+
180+ createEffect(() => {
181+ const initial = props.initial;
182+ setText(initial?.text ?? "");
183+ setKind(initial?.kind ?? "choice");
184+ setPoints(String(initial?.points ?? 1));
185+ setChoicesText((initial?.choices ?? ["", ""]).join("\n"));
186+ setCorrect(initial?.correct != null ? String(initial.correct) : "0");
187+ setError("");
188+ });
189+
190+ const validate = (): QuestionValues | string => {
191+ const body = text().trim();
192+ if (!body) return t("questions.textRequired");
193+ if (body.length > 2000) return t("form.descriptionMax");
194+ const p = Number(points());
195+ if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange");
196+ if (kind() === "text") {
197+ return { text: body, kind: "text", points: p, choices: null, correct: null };
198+ }
199+ const choices = choicesText().split("\n").map((choice) => choice.trim()).filter(Boolean);
200+ if (choices.length < 2 || choices.length > 10 || choices.some((choice) => choice.length > 500)) {
201+ return t("questions.choicesRange");
202+ }
203+ const c = Number(correct());
204+ if (!Number.isInteger(c) || c < 0 || c >= choices.length) return t("questions.correctRange");
205+ return { text: body, kind: "choice", points: p, choices, correct: c };
206+ };
207+
208+ const submit = async (e: SubmitEvent) => {
209+ e.preventDefault();
210+ const values = validate();
211+ if (typeof values === "string") {
212+ setError(values);
213+ return;
214+ }
215+ setError("");
216+ setPending(true);
217+ try {
218+ await props.onSubmit(values);
219+ } catch (err) {
220+ setError(formatApiError(err));
221+ } finally {
222+ setPending(false);
223+ }
224+ };
225+
226+ return (
227+ <form class="space-y-3 rounded-md border p-4" onSubmit={(e) => void submit(e)}>
228+ <div class="space-y-1.5">
229+ <Label for="question-text">{t("questions.text")}</Label>
230+ <Textarea id="question-text" value={text()} maxlength={2000} rows={4} required onInput={(e) => setText(e.currentTarget.value)} />
231+ </div>
232+ <div class="grid gap-3 sm:grid-cols-3">
233+ <div class="space-y-1.5">
234+ <Label for="question-kind">{t("questions.kind")}</Label>
235+ <Select id="question-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as QuestionKind)}>
236+ <For each={QUESTION_KINDS}>
237+ {(k) => <option value={k}>{k === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}</option>}
238+ </For>
239+ </Select>
240+ </div>
241+ <div class="space-y-1.5">
242+ <Label for="question-points">{t("questions.points")}</Label>
243+ <Input id="question-points" type="number" min={1} max={100} value={points()} required onInput={(e) => setPoints(e.currentTarget.value)} />
244+ </div>
245+ <Show when={kind() === "choice"}>
246+ <div class="space-y-1.5">
247+ <Label for="question-correct">{t("questions.correct")}</Label>
248+ <Input id="question-correct" type="number" min={0} value={correct()} required onInput={(e) => setCorrect(e.currentTarget.value)} />
249+ <p class="text-xs text-muted-foreground">{t("questions.correctHint")}</p>
250+ </div>
251+ </Show>
252+ </div>
253+ <Show when={kind() === "choice"}>
254+ <div class="space-y-1.5">
255+ <Label for="question-choices">{t("questions.choices")}</Label>
256+ <Textarea id="question-choices" value={choicesText()} rows={5} onInput={(e) => setChoicesText(e.currentTarget.value)} />
257+ <p class="text-xs text-muted-foreground">{t("questions.choicesHint")}</p>
258+ </div>
259+ </Show>
260+ {error() && <p class="text-sm text-destructive">{error()}</p>}
261+ <div class="flex flex-wrap items-center gap-2">
262+ <Button type="submit" disabled={pending()}>
263+ {props.initial ? t("common.update") : t("common.create")}
264+ </Button>
265+ <Button type="button" variant="outline" onClick={props.onCancel}>
266+ {t("common.cancel")}
267+ </Button>
268+ </div>
269+ </form>
270+ );
271+}
src/i18n/messages.tsmodified+51 -0
@@ -159,6 +159,23 @@ export type MessageKey =
159 | "exams.durationRequired"159 | "exams.durationRequired"
160 | "exams.durationRange"160 | "exams.durationRange"
161 | "exams.scheduleRequired"161 | "exams.scheduleRequired"
162+ | "questions.title"
163+ | "questions.add"
164+ | "questions.edit"
165+ | "questions.empty"
166+ | "questions.text"
167+ | "questions.kind"
168+ | "questions.points"
169+ | "questions.choices"
170+ | "questions.choicesHint"
171+ | "questions.correct"
172+ | "questions.correctHint"
173+ | "questions.kind.choice"
174+ | "questions.kind.text"
175+ | "questions.textRequired"
176+ | "questions.pointsRange"
177+ | "questions.choicesRange"
178+ | "questions.correctRange"
162 | "exams.helpTitle"179 | "exams.helpTitle"
163 | "exams.helpBody"180 | "exams.helpBody"
164 | "admin.title"181 | "admin.title"
@@ -409,6 +426,23 @@ const en: Dict = {
409 "exams.durationRequired": "Async exams need a duration",426 "exams.durationRequired": "Async exams need a duration",
410 "exams.durationRange": "Duration must be from 1 minute to 24 hours",427 "exams.durationRange": "Duration must be from 1 minute to 24 hours",
411 "exams.scheduleRequired": "Scheduled exams need start and end times",428 "exams.scheduleRequired": "Scheduled exams need start and end times",
429+ "questions.title": "Questions",
430+ "questions.add": "Add question",
431+ "questions.edit": "Edit question",
432+ "questions.empty": "No questions yet.",
433+ "questions.text": "Question text",
434+ "questions.kind": "Question kind",
435+ "questions.points": "Points",
436+ "questions.choices": "Choices",
437+ "questions.choicesHint": "One choice per line, 2–10 choices.",
438+ "questions.correct": "Correct choice index",
439+ "questions.correctHint": "Zero-based: first choice is 0.",
440+ "questions.kind.choice": "Choice",
441+ "questions.kind.text": "Text",
442+ "questions.textRequired": "Question text is required",
443+ "questions.pointsRange": "Points must be an integer from 1 to 100",
444+ "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters",
445+ "questions.correctRange": "Correct index must point to one of the choices",
412 "exams.helpTitle": "About exams",446 "exams.helpTitle": "About exams",
413 "exams.helpBody":447 "exams.helpBody":
414 "Exams belong to a course. Teachers add them from the course page with a kind and weight (1–100). Students only see their own mark (or “not graded yet”). Weighted averages appear on the report card.",448 "Exams belong to a course. Teachers add them from the course page with a kind and weight (1–100). Students only see their own mark (or “not graded yet”). Weighted averages appear on the report card.",
@@ -669,6 +703,23 @@ const tr: Dict = {
669 "exams.durationRequired": "Asenkron sınav için süre gerekli",703 "exams.durationRequired": "Asenkron sınav için süre gerekli",
670 "exams.durationRange": "Süre 1 dakika ile 24 saat arasında olmalı",704 "exams.durationRange": "Süre 1 dakika ile 24 saat arasında olmalı",
671 "exams.scheduleRequired": "Zamanlı sınav için başlangıç ve bitiş gerekli",705 "exams.scheduleRequired": "Zamanlı sınav için başlangıç ve bitiş gerekli",
706+ "questions.title": "Sorular",
707+ "questions.add": "Soru ekle",
708+ "questions.edit": "Soruyu düzenle",
709+ "questions.empty": "Henüz soru yok.",
710+ "questions.text": "Soru metni",
711+ "questions.kind": "Soru türü",
712+ "questions.points": "Puan",
713+ "questions.choices": "Seçenekler",
714+ "questions.choicesHint": "Her satıra bir seçenek, 2–10 seçenek.",
715+ "questions.correct": "Doğru seçenek indeksi",
716+ "questions.correctHint": "Sıfırdan başlar: ilk seçenek 0.",
717+ "questions.kind.choice": "Seçmeli",
718+ "questions.kind.text": "Metin",
719+ "questions.textRequired": "Soru metni gerekli",
720+ "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı",
721+ "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı",
722+ "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",
672 "exams.helpTitle": "Sınavlar hakkında",723 "exams.helpTitle": "Sınavlar hakkında",
673 "exams.helpBody":724 "exams.helpBody":
674 "Sınavlar bir derse aittir. Öğretmenler ders sayfasından tür ve ağırlık (1–100) ile ekler. Öğrenciler yalnızca kendi notunu görür. Ağırlıklı ortalamalar Karnem’dedir.",725 "Sınavlar bir derse aittir. Öğretmenler ders sayfasından tür ve ağırlık (1–100) ile ekler. Öğrenciler yalnızca kendi notunu görür. Ağırlıklı ortalamalar Karnem’dedir.",
src/pages/exam-detail-page.tsxmodified+3 -0
@@ -9,6 +9,7 @@ import { patchExamById } from "@/api/patchExamById";
9 import { postExamResult } from "@/api/postExamResult";9 import { postExamResult } from "@/api/postExamResult";
10 import { ApiError, formatApiError } from "@/api/client";10 import { ApiError, formatApiError } from "@/api/client";
11 import { ExamForm } from "@/components/exams/exam-form";11 import { ExamForm } from "@/components/exams/exam-form";
12+import { ExamQuestionsPanel } from "@/components/exams/exam-questions-panel";
12 import { ExamResultBadge } from "@/components/exams/exam-result-badge";13 import { ExamResultBadge } from "@/components/exams/exam-result-badge";
13 import { GradeForm } from "@/components/exams/grade-form";14 import { GradeForm } from "@/components/exams/grade-form";
14 import { RouteGuard } from "@/components/layout/route-guard";15 import { RouteGuard } from "@/components/layout/route-guard";
@@ -218,6 +219,8 @@ function ExamDetailContent() {
218 </Show>219 </Show>
219 220
220 <Show when={isTeacherPlus()}>221 <Show when={isTeacherPlus()}>
222+ <ExamQuestionsPanel examId={id()} />
223+
221 <section class="surface-card p-5">224 <section class="surface-card p-5">
222 <h2 class="mb-4 font-display text-lg font-semibold">{t("exams.gradeStudent")}</h2>225 <h2 class="mb-4 font-display text-lg font-semibold">{t("exams.gradeStudent")}</h2>
223 <GradeForm226 <GradeForm