forge
Explore
Log in

Don't you dare go Hollow

✨ add course subjects to exam questions

Browse files at this commit

4ec6b8abfc260fbb343cf3b88577c5beab3a5a2fBurak BoduroğluParent: 1c125f7
  • feat
    • ✨ add course subjects to exam questions
Show full message
feat: ✨ add course subjects to exam questions

- add course subject API helpers and frontend types

- manage subjects from the course detail page

- require a subject when creating or editing exam questions

- show question subject badges in the exam question list

- update docs for subject permissions and exam question tagging
README.mdmodified+3 -2
@@ -63,13 +63,13 @@ Dashboard and table summaries must use the same role scope as the related page.
63 | `/exams/:id/live` | Teacher+ | Live monitor / final state roster with pagination & sorting |63 | `/exams/:id/live` | Teacher+ | Live monitor / final state roster with pagination & sorting |
64 | `/exam-room/:id` | Student+ | WebSocket-based real-time exam room (auto-save, timer, local expiry close) |64 | `/exam-room/:id` | Student+ | WebSocket-based real-time exam room (auto-save, timer, local expiry close) |
65 | `/courses` | Student+ | Course table with search and term filters; create/edit flows for teacher+ |65 | `/courses` | Student+ | Course table with search and term filters; create/edit flows for teacher+ |
66-| `/courses/:id` | Student+ | Course detail, exams, roster, lesson sessions, and roll call tools |66+| `/courses/:id` | Student+ | Course detail, subjects, exams, roster, lesson sessions, and roll call tools |
67 | `/guide` | Authenticated | App usage guide |67 | `/guide` | Authenticated | App usage guide |
68 | `/admin/users` | Admin | User management |68 | `/admin/users` | Admin | User management |
69 69
70 ## Features70 ## Features
71 71
72-- **Exam lifecycle**: create (scheduled/async/unscheduled), automatic async duration from start/end, questions (multiple-choice / text), real-time WebSocket exam room, auto-close on expiry, teacher grading72+- **Exam lifecycle**: create (scheduled/async/unscheduled), automatic async duration from start/end, subject-tagged questions (multiple-choice / text), real-time WebSocket exam room, auto-close on expiry, teacher grading
73 - **Live monitor**: 2-second polling during active exams, static final state view after exam ends, pagination (10/page), column sorting73 - **Live monitor**: 2-second polling during active exams, static final state view after exam ends, pagination (10/page), column sorting
74 - **Statistics**: graded count, average/min/max marks on exam detail74 - **Statistics**: graded count, average/min/max marks on exam detail
75 - **Answer sheet**: teacher review of student answers with correct/wrong highlighting75 - **Answer sheet**: teacher review of student answers with correct/wrong highlighting
@@ -77,6 +77,7 @@ Dashboard and table summaries must use the same role scope as the related page.
77 - **Dense tables**: toolbar search/filter, subtle column separators, narrow centered three-dot row actions77 - **Dense tables**: toolbar search/filter, subtle column separators, narrow centered three-dot row actions
78 - **Side panels**: quick create/edit workflows without losing list context78 - **Side panels**: quick create/edit workflows without losing list context
79 - **Course sessions**: right-panel session creation and paginated roll call panels79 - **Course sessions**: right-panel session creation and paginated roll call panels
80+- **Course subjects**: course/study curriculum topics managed on the detail page; every exam question must pick one
80 - **Schedule validation**: event, exam, and lesson-session forms use `GET /time` for server-clock-aware past-date warnings before submit81 - **Schedule validation**: event, exam, and lesson-session forms use `GET /time` for server-clock-aware past-date warnings before submit
81 - **Notebook**: paper-style note cards; create in `SidePanel`; read in reader panel with attachments; three-dot card actions for edit/delete82 - **Notebook**: paper-style note cards; create in `SidePanel`; read in reader panel with attachments; three-dot card actions for edit/delete
82 - **Note files**: per-note upload/list/download/delete via native `FormData`; school `max_file_bytes` from settings83 - **Note files**: per-note upload/list/download/delete via native `FormData`; school `max_file_bytes` from settings
docs/frontend-next-steps.mdmodified+1 -1
@@ -9,7 +9,7 @@ Active backend-refresh work is tracked in
9 9
10 ## Completed State10 ## Completed State
11 11
12-- Backend alignment is complete for settings, terms, course sessions, attendance reports, work logs, exam attempts, and grade bands.12+- Backend alignment is complete for settings, terms, course subjects, course sessions, attendance reports, work logs, exam attempts, and grade bands.
13 - Shared UI primitives cover dense tables, data toolbars, row action menus, side panels, confirm dialogs, date picking, and animated disclosures.13 - Shared UI primitives cover dense tables, data toolbars, row action menus, side panels, confirm dialogs, date picking, and animated disclosures.
14 - Dashboard is a monochrome, role-aware, read-only status board: workspace portal cards (`Title | count` on desktop) + needs-attention / upcoming lists. No create CTAs, no vanity charts, no duplicate KPI strip. Admin sees global course/exam scope; other roles use own/enrolled/related scope where the backend supports it.14 - Dashboard is a monochrome, role-aware, read-only status board: workspace portal cards (`Title | count` on desktop) + needs-attention / upcoming lists. No create CTAs, no vanity charts, no duplicate KPI strip. Admin sees global course/exam scope; other roles use own/enrolled/related scope where the backend supports it.
15 - Table and card actions use narrow centered three-dot menus through `TableRowActions`.15 - Table and card actions use narrow centered three-dot menus through `TableRowActions`.
docs/role-scope-matrix.mdmodified+2 -1
@@ -66,6 +66,7 @@
66 | Enroll students / unenroll any enrollment | ❌ | ✅ (course creator) | ✅ | ✅ |66 | Enroll students / unenroll any enrollment | ❌ | ✅ (course creator) | ✅ | ✅ |
67 | Edit / delete courses | ❌ | ✅ (course creator) | ✅ | ✅ |67 | Edit / delete courses | ❌ | ✅ (course creator) | ✅ | ✅ |
68 | Create / edit / delete course sessions | ❌ | ✅ (course manager) | ✅ | ✅ |68 | Create / edit / delete course sessions | ❌ | ✅ (course manager) | ✅ | ✅ |
69+| Create / edit / delete course subjects | ❌ | ✅ (course manager) | ✅ | ✅ |
69 | Take session roll call | ❌ | ✅ (session teacher or course manager) | ✅ | ✅ |70 | Take session roll call | ❌ | ✅ (session teacher or course manager) | ✅ | ✅ |
70 | Mark session teacher's own presence | ❌ | ❌ | ✅ | ✅ |71 | Mark session teacher's own presence | ❌ | ❌ | ✅ | ✅ |
71 | Create exams | ❌ | ✅ (course manager) | ✅ | ✅ |72 | Create exams | ❌ | ✅ (course manager) | ✅ | ✅ |
@@ -87,7 +88,7 @@
87 ## Architectural Rules88 ## Architectural Rules
88 89
89 - **Hierarchical roles:** `student < teacher < manager < admin`. A higher role satisfies any lower requirement. The only exception is `exactRole` page guards (below), which are presentation filters — backend authorization never breaks the hierarchy.90 - **Hierarchical roles:** `student < teacher < manager < admin`. A higher role satisfies any lower requirement. The only exception is `exactRole` page guards (below), which are presentation filters — backend authorization never breaks the hierarchy.
90-- **Course management rights:** course creator or `manager+`. Required for enrollment, session CRUD, exam CRUD, grading, roster read.91+- **Course management rights:** course creator or `manager+`. Required for enrollment, subject/session CRUD, exam CRUD, grading, roster read.
91 - **Ownership edits:** event/note edit/delete respects creator id. Manager+ overrides creator gate.92 - **Ownership edits:** event/note edit/delete respects creator id. Manager+ overrides creator gate.
92 - **Student-only actions (BE-enforced):** enrolling, sitting exams (including the exam-room WebSocket — the role is re-checked on every answer save, so a mid-exam promotion closes the sheet), being graded, and being marked on lesson roll call all require the target's live role to be `student`. Unenroll, result removal, and roll-call removal stay role-free on the target, so stale rows left behind by a promotion remain removable.93 - **Student-only actions (BE-enforced):** enrolling, sitting exams (including the exam-room WebSocket — the role is re-checked on every answer save, so a mid-exam promotion closes the sheet), being graded, and being marked on lesson roll call all require the target's live role to be `student`. Unenroll, result removal, and roll-call removal stay role-free on the target, so stale rows left behind by a promotion remain removable.
93 - **Student-only pages (FE-only):** `/marks` (personal report card) is hidden from staff by `RouteGuard exactRole="student"` + router `beforeLoad` redirect as presentation, not security — the backend serves `GET /marks/me` and `GET /exams/{id}/result` to any authenticated user; a staff member's report is just permanently empty (staff cannot be enrolled or graded). Do not "fix" the backend to 403 these: a student promoted to staff must keep read access to their own history.94 - **Student-only pages (FE-only):** `/marks` (personal report card) is hidden from staff by `RouteGuard exactRole="student"` + router `beforeLoad` redirect as presentation, not security — the backend serves `GET /marks/me` and `GET /exams/{id}/result` to any authenticated user; a staff member's report is just permanently empty (staff cannot be enrolled or graded). Do not "fix" the backend to 403 these: a student promoted to staff must keep read access to their own history.
src/api/deleteSubjectById.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "./client";
2+
3+export function deleteSubjectById(subjectId: string): Promise<void> {
4+ return client<void>(`/subjects/${subjectId}`, { method: "DELETE" });
5+}
src/api/getCourseSubjects.tsadded+12 -0
@@ -0,0 +1,12 @@
1+import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
3+import type { Subject } from "./types";
4+
5+export async function getCourseSubjects(
6+ courseId: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<Subject>> {
10+ const data = await client<unknown>(`/courses/${courseId}/subjects${pageQuery(params)}`, { signal });
11+ return normalizePage<Subject>(data);
12+}
src/api/patchExamQuestionById.tsmodified+1 -0
@@ -2,6 +2,7 @@ import { client } from "./client";
2 import type { ExamQuestion, QuestionKind } from "./types";2 import type { ExamQuestion, QuestionKind } from "./types";
3 3
4 export type PatchExamQuestionBody = {4 export type PatchExamQuestionBody = {
5+ subject_id?: string;
5 text?: string | null;6 text?: string | null;
6 kind?: QuestionKind | null;7 kind?: QuestionKind | null;
7 points?: number | null;8 points?: number | null;
src/api/patchSubjectById.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "./client";
2+import type { Subject } from "./types";
3+
4+export type PatchSubjectBody = {
5+ name?: string;
6+ description?: string;
7+};
8+
9+export function patchSubjectById(subjectId: string, body: PatchSubjectBody): Promise<Subject> {
10+ return client<Subject>(`/subjects/${subjectId}`, { method: "PATCH", body });
11+}
src/api/postCourseSubject.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "./client";
2+import type { Subject } from "./types";
3+
4+export type PostCourseSubjectBody = {
5+ name: string;
6+ description?: string | null;
7+};
8+
9+export function postCourseSubject(courseId: string, body: PostCourseSubjectBody): Promise<Subject> {
10+ return client<Subject>(`/courses/${courseId}/subjects`, { method: "POST", body });
11+}
src/api/postExamQuestion.tsmodified+1 -0
@@ -2,6 +2,7 @@ import { client } from "./client";
2 import type { ExamQuestion, QuestionKind } from "./types";2 import type { ExamQuestion, QuestionKind } from "./types";
3 3
4 export type ExamQuestionBody = {4 export type ExamQuestionBody = {
5+ subject_id: string;
5 text: string;6 text: string;
6 kind: QuestionKind;7 kind: QuestionKind;
7 points: number;8 points: number;
src/api/types.tsmodified+9 -0
@@ -148,6 +148,7 @@ export type ExamResult = {
148 export type ExamQuestion = {148 export type ExamQuestion = {
149 id: string;149 id: string;
150 exam: string;150 exam: string;
151+ subject: string;
151 text: string;152 text: string;
152 kind: QuestionKind;153 kind: QuestionKind;
153 points: number;154 points: number;
@@ -181,6 +182,7 @@ export type AttemptAnswer = {
181 export type AttemptQuestion = {182 export type AttemptQuestion = {
182 id: string;183 id: string;
183 exam: string;184 exam: string;
185+ subject: string;
184 text: string;186 text: string;
185 kind: QuestionKind;187 kind: QuestionKind;
186 points: number;188 points: number;
@@ -188,6 +190,13 @@ export type AttemptQuestion = {
188 answer: AttemptAnswer | null;190 answer: AttemptAnswer | null;
189 };191 };
190 192
193+export type Subject = {
194+ id: string;
195+ course: string;
196+ name: string;
197+ description: string;
198+};
199+
191 export type MarkEntry = {200 export type MarkEntry = {
192 exam: string;201 exam: string;
193 title: string;202 title: string;
src/components/courses/course-subjects-panel.tsxadded+179 -0
@@ -0,0 +1,179 @@
1+import { For, Show, Suspense, createEffect, createResource, createSignal } from "solid-js";
2+import { deleteSubjectById } from "@/api/deleteSubjectById";
3+import { getCourseSubjects } from "@/api/getCourseSubjects";
4+import { patchSubjectById } from "@/api/patchSubjectById";
5+import { postCourseSubject } from "@/api/postCourseSubject";
6+import { formatApiError } from "@/api/client";
7+import type { Subject } from "@/api/types";
8+import { Alert } from "@/components/ui/alert";
9+import { Button } from "@/components/ui/button";
10+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
11+import { EmptyState } from "@/components/ui/empty-state";
12+import { IconEdit, 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 { SidePanel } from "@/components/ui/side-panel";
17+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
18+import { TableRowActions } from "@/components/ui/table-row-actions";
19+import { Textarea } from "@/components/ui/textarea";
20+import { createFlash } from "@/lib/flash";
21+import { useT } from "@/stores/preferences-context";
22+
23+export function CourseSubjectsPanel(props: { courseId: string; canManage: boolean; active: boolean }) {
24+ const t = useT();
25+ const [subjects, { refetch }] = createResource(
26+ () => (props.active ? props.courseId : null),
27+ async (courseId) => (courseId ? (await getCourseSubjects(courseId)).items : []),
28+ );
29+ const [panelOpen, setPanelOpen] = createSignal(false);
30+ const [editing, setEditing] = createSignal<Subject | null>(null);
31+ const [removeSubject, setRemoveSubject] = createSignal<Subject | null>(null);
32+ const [name, setName] = createSignal("");
33+ const [description, setDescription] = createSignal("");
34+ const [error, setError] = createSignal("");
35+ const [pending, setPending] = createSignal(false);
36+ const [flash, setFlash] = createFlash();
37+
38+ createEffect(() => {
39+ const subject = editing();
40+ setName(subject?.name ?? "");
41+ setDescription(subject?.description ?? "");
42+ });
43+
44+ const openCreate = () => {
45+ setEditing(null);
46+ setName("");
47+ setDescription("");
48+ setPanelOpen(true);
49+ };
50+
51+ const openEdit = (subject: Subject) => {
52+ setEditing(subject);
53+ setPanelOpen(true);
54+ };
55+
56+ const save = async (event: SubmitEvent) => {
57+ event.preventDefault();
58+ setError("");
59+ setPending(true);
60+ try {
61+ const body = { name: name().trim(), description: description().trim() };
62+ const subject = editing();
63+ if (subject) await patchSubjectById(subject.id, body);
64+ else await postCourseSubject(props.courseId, body);
65+ setPanelOpen(false);
66+ setEditing(null);
67+ await refetch();
68+ setFlash(subject ? t("common.saved") : t("common.created"));
69+ } catch (err) {
70+ setError(formatApiError(err));
71+ } finally {
72+ setPending(false);
73+ }
74+ };
75+
76+ return (
77+ <div class="space-y-4">
78+ <Show when={flash()}>
79+ <Alert variant="success">{flash()}</Alert>
80+ </Show>
81+ <Show when={props.canManage}>
82+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={openCreate}>
83+ <IconPlus class="h-4 w-4" />
84+ {t("subjects.add")}
85+ </Button>
86+ </Show>
87+
88+ <SidePanel open={panelOpen()} onOpenChange={setPanelOpen} title={editing() ? t("subjects.edit") : t("subjects.add")} description={t("subjects.help")}>
89+ <form class="space-y-3" onSubmit={(event) => void save(event)}>
90+ <div class="space-y-1.5">
91+ <Label for="subject-name">{t("subjects.name")}</Label>
92+ <Input id="subject-name" required maxlength={200} value={name()} onInput={(event) => setName(event.currentTarget.value)} />
93+ </div>
94+ <div class="space-y-1.5">
95+ <Label for="subject-description">{t("form.description")}</Label>
96+ <Textarea id="subject-description" maxlength={2000} rows={3} value={description()} onInput={(event) => setDescription(event.currentTarget.value)} />
97+ </div>
98+ {error() && <p class="text-sm text-destructive">{error()}</p>}
99+ <div class="flex flex-wrap gap-2">
100+ <Button type="submit" class="rounded-sm" disabled={pending()}>
101+ {editing() ? t("common.update") : t("common.create")}
102+ </Button>
103+ <Button type="button" variant="outline" class="rounded-sm" onClick={() => setPanelOpen(false)}>
104+ {t("common.cancel")}
105+ </Button>
106+ </div>
107+ </form>
108+ </SidePanel>
109+
110+ <ConfirmDialog
111+ open={removeSubject() != null}
112+ onOpenChange={(open) => {
113+ if (!open) setRemoveSubject(null);
114+ }}
115+ title={t("confirm.deleteTitle")}
116+ variant="destructive"
117+ summary={removeSubject()?.name ?? ""}
118+ onConfirm={async () => {
119+ const subject = removeSubject();
120+ if (!subject) return;
121+ setError("");
122+ try {
123+ await deleteSubjectById(subject.id);
124+ await refetch();
125+ setFlash(t("common.deleted"));
126+ } catch (err) {
127+ setError(formatApiError(err));
128+ } finally {
129+ setRemoveSubject(null);
130+ }
131+ }}
132+ />
133+
134+ {error() && <p class="rounded-sm bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}
135+
136+ <Suspense fallback={<PageSpinner />}>
137+ <Show when={(subjects() ?? []).length > 0} fallback={<EmptyState title={t("subjects.empty")} />}>
138+ <Table>
139+ <TableHeader>
140+ <TableRow>
141+ <TableHead>{t("subjects.name")}</TableHead>
142+ <TableHead>{t("form.description")}</TableHead>
143+ <Show when={props.canManage}>
144+ <TableHead class="w-14 text-center">{t("common.actions")}</TableHead>
145+ </Show>
146+ </TableRow>
147+ </TableHeader>
148+ <TableBody>
149+ <For each={subjects() ?? []}>
150+ {(subject) => (
151+ <TableRow>
152+ <TableCell class="font-medium">{subject.name}</TableCell>
153+ <TableCell class="text-sm text-muted-foreground">{subject.description || "—"}</TableCell>
154+ <Show when={props.canManage}>
155+ <TableCell class="px-1 text-center">
156+ <TableRowActions
157+ label={t("common.actions")}
158+ actions={[
159+ { label: t("common.edit"), icon: <IconEdit class="h-4 w-4" />, onSelect: () => openEdit(subject) },
160+ {
161+ label: t("common.remove"),
162+ icon: <IconTrash class="h-4 w-4" />,
163+ destructive: true,
164+ onSelect: () => setRemoveSubject(subject),
165+ },
166+ ]}
167+ />
168+ </TableCell>
169+ </Show>
170+ </TableRow>
171+ )}
172+ </For>
173+ </TableBody>
174+ </Table>
175+ </Show>
176+ </Suspense>
177+ </div>
178+ );
179+}
src/components/exams/exam-questions-panel.tsxmodified+6 -1
@@ -1,5 +1,6 @@
1 import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";1 import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";
2 import { deleteExamQuestionById } from "@/api/deleteExamQuestionById";2 import { deleteExamQuestionById } from "@/api/deleteExamQuestionById";
3+import { getCourseSubjects } from "@/api/getCourseSubjects";
3 import { getExamQuestions } from "@/api/getExamQuestions";4 import { getExamQuestions } from "@/api/getExamQuestions";
4 import { patchExamQuestionById } from "@/api/patchExamQuestionById";5 import { patchExamQuestionById } from "@/api/patchExamQuestionById";
5 import { postExamQuestion } from "@/api/postExamQuestion";6 import { postExamQuestion } from "@/api/postExamQuestion";
@@ -18,8 +19,9 @@ import { useT } from "@/stores/preferences-context";
18 19
19 const QUESTION_PAGE_SIZE = 5;20 const QUESTION_PAGE_SIZE = 5;
20 21
21-export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean; embedded?: boolean }) {22+export function ExamQuestionsPanel(props: { examId: string; courseId: string; readOnly?: boolean; embedded?: boolean }) {
22 const t = useT();23 const t = useT();
24+ const [subjects] = createResource(() => props.courseId, async (courseId) => (await getCourseSubjects(courseId)).items);
23 const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {25 const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {
24 try {26 try {
25 return (await getExamQuestions(examId)).items;27 return (await getExamQuestions(examId)).items;
@@ -37,6 +39,7 @@ export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean;
37 39
38 const formInitial = createMemo(() => editing() ?? undefined);40 const formInitial = createMemo(() => editing() ?? undefined);
39 const questionList = createMemo(() => questions() ?? []);41 const questionList = createMemo(() => questions() ?? []);
42+ const subjectName = (subjectId: string) => subjects()?.find((subject) => subject.id === subjectId)?.name ?? subjectId;
40 const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE)));43 const totalPages = createMemo(() => Math.max(1, Math.ceil(questionList().length / QUESTION_PAGE_SIZE)));
41 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));44 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
42 const pageItems = createMemo(() => {45 const pageItems = createMemo(() => {
@@ -115,6 +118,7 @@ export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean;
115 >118 >
116 <QuestionForm119 <QuestionForm
117 initial={formInitial()}120 initial={formInitial()}
121+ subjects={subjects() ?? []}
118 onCancel={() => {122 onCancel={() => {
119 setEditing(null);123 setEditing(null);
120 setShowForm(false);124 setShowForm(false);
@@ -142,6 +146,7 @@ export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean;
142 <Badge variant="outline" class="capitalize">146 <Badge variant="outline" class="capitalize">
143 {q.kind === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}147 {q.kind === "choice" ? t("questions.kind.choice") : t("questions.kind.text")}
144 </Badge>148 </Badge>
149+ <Badge variant="secondary">{subjectName(q.subject)}</Badge>
145 <Badge variant="outline">{q.points} {t("questions.points")}</Badge>150 <Badge variant="outline">{q.points} {t("questions.points")}</Badge>
146 </div>151 </div>
147 <p class="whitespace-pre-wrap text-sm font-medium">{q.text}</p>152 <p class="whitespace-pre-wrap text-sm font-medium">{q.text}</p>
src/components/exams/question-form.tsxmodified+16 -3
@@ -1,6 +1,6 @@
1 import { For, Index, Show, createEffect, createSignal } from "solid-js";1 import { For, Index, Show, createEffect, createSignal } from "solid-js";
2 import { formatApiError } from "@/api/client";2 import { formatApiError } from "@/api/client";
3-import type { ExamQuestion, QuestionKind } from "@/api/types";3+import type { ExamQuestion, QuestionKind, Subject } from "@/api/types";
4 import { QUESTION_KINDS } from "@/api/types";4 import { QUESTION_KINDS } from "@/api/types";
5 import { Button } from "@/components/ui/button";5 import { Button } from "@/components/ui/button";
6 import { IconCheck, IconPlus, IconTrash } from "@/components/ui/icons";6 import { IconCheck, IconPlus, IconTrash } from "@/components/ui/icons";
@@ -11,6 +11,7 @@ import { Textarea } from "@/components/ui/textarea";
11 import { useT } from "@/stores/preferences-context";11 import { useT } from "@/stores/preferences-context";
12 12
13 export type QuestionValues = {13 export type QuestionValues = {
14+ subject_id: string;
14 text: string;15 text: string;
15 kind: QuestionKind;16 kind: QuestionKind;
16 points: number;17 points: number;
@@ -20,12 +21,14 @@ export type QuestionValues = {
20 21
21 export function QuestionForm(props: {22 export function QuestionForm(props: {
22 initial?: ExamQuestion;23 initial?: ExamQuestion;
24+ subjects: Subject[];
23 onSubmit: (values: QuestionValues) => Promise<void>;25 onSubmit: (values: QuestionValues) => Promise<void>;
24 onCancel: () => void;26 onCancel: () => void;
25 }) {27 }) {
26 const t = useT();28 const t = useT();
27 let textAreaRef: HTMLTextAreaElement | undefined;29 let textAreaRef: HTMLTextAreaElement | undefined;
28 const [text, setText] = createSignal(props.initial?.text ?? "");30 const [text, setText] = createSignal(props.initial?.text ?? "");
31+ const [subjectId, setSubjectId] = createSignal(props.initial?.subject ?? props.subjects[0]?.id ?? "");
29 const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? "choice");32 const [kind, setKind] = createSignal<QuestionKind>(props.initial?.kind ?? "choice");
30 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));33 const [points, setPoints] = createSignal(String(props.initial?.points ?? 1));
31 const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]);34 const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]);
@@ -36,6 +39,7 @@ export function QuestionForm(props: {
36 createEffect(() => {39 createEffect(() => {
37 const initial = props.initial;40 const initial = props.initial;
38 setText(initial?.text ?? "");41 setText(initial?.text ?? "");
42+ setSubjectId(initial?.subject ?? props.subjects[0]?.id ?? "");
39 setKind(initial?.kind ?? "choice");43 setKind(initial?.kind ?? "choice");
40 setPoints(String(initial?.points ?? 1));44 setPoints(String(initial?.points ?? 1));
41 setChoices(initial?.choices ?? ["", "", "", ""]);45 setChoices(initial?.choices ?? ["", "", "", ""]);
@@ -69,12 +73,14 @@ export function QuestionForm(props: {
69 73
70 const validate = (): QuestionValues | string => {74 const validate = (): QuestionValues | string => {
71 const body = text().trim();75 const body = text().trim();
76+ const subject = subjectId().trim();
77+ if (!subject) return t("questions.subjectRequired");
72 if (!body) return t("questions.textRequired");78 if (!body) return t("questions.textRequired");
73 if (body.length > 2000) return t("form.descriptionMax");79 if (body.length > 2000) return t("form.descriptionMax");
74 const p = Number(points());80 const p = Number(points());
75 if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange");81 if (!Number.isInteger(p) || p < 1 || p > 100) return t("questions.pointsRange");
76 if (kind() === "text") {82 if (kind() === "text") {
77- return { text: body, kind: "text", points: p, choices: null, correct: null };83+ return { subject_id: subject, text: body, kind: "text", points: p, choices: null, correct: null };
78 }84 }
79 const cleanChoices = choices().map((choice) => choice.trim()).filter(Boolean);85 const cleanChoices = choices().map((choice) => choice.trim()).filter(Boolean);
80 if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) {86 if (cleanChoices.length < 2 || cleanChoices.length > 10 || cleanChoices.some((choice) => choice.length > 500)) {
@@ -82,7 +88,7 @@ export function QuestionForm(props: {
82 }88 }
83 const c = correct();89 const c = correct();
84 if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange");90 if (!Number.isInteger(c) || c < 0 || c >= cleanChoices.length) return t("questions.correctRange");
85- return { text: body, kind: "choice", points: p, choices: cleanChoices, correct: c };91+ return { subject_id: subject, text: body, kind: "choice", points: p, choices: cleanChoices, correct: c };
86 };92 };
87 93
88 const submit = async (e: SubmitEvent) => {94 const submit = async (e: SubmitEvent) => {
@@ -126,6 +132,13 @@ export function QuestionForm(props: {
126 <div class="space-y-1.5">132 <div class="space-y-1.5">
127 <Label for="question-kind" class="text-sm font-semibold">{t("questions.kind")}</Label>133 <Label for="question-kind" class="text-sm font-semibold">{t("questions.kind")}</Label>
128 <div class="flex h-[10rem] min-h-[10rem] flex-col justify-between rounded-md border bg-background p-3">134 <div class="flex h-[10rem] min-h-[10rem] flex-col justify-between rounded-md border bg-background p-3">
135+ <div class="space-y-1.5">
136+ <Label for="question-subject">{t("subjects.subject")}</Label>
137+ <Select id="question-subject" value={subjectId()} required onChange={(e) => setSubjectId(e.currentTarget.value)}>
138+ <option value="">{t("subjects.select")}</option>
139+ <For each={props.subjects}>{(subject) => <option value={subject.id}>{subject.name}</option>}</For>
140+ </Select>
141+ </div>
129 <div class="space-y-1.5">142 <div class="space-y-1.5">
130 <Select id="question-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as QuestionKind)}>143 <Select id="question-kind" value={kind()} onChange={(e) => setKind(e.currentTarget.value as QuestionKind)}>
131 <For each={QUESTION_KINDS}>144 <For each={QUESTION_KINDS}>
src/i18n/messages.tsmodified+27 -0
@@ -289,10 +289,19 @@ export type MessageKey =
289 | "questions.correctHint"289 | "questions.correctHint"
290 | "questions.kind.choice"290 | "questions.kind.choice"
291 | "questions.kind.text"291 | "questions.kind.text"
292+ | "questions.subjectRequired"
292 | "questions.textRequired"293 | "questions.textRequired"
293 | "questions.pointsRange"294 | "questions.pointsRange"
294 | "questions.choicesRange"295 | "questions.choicesRange"
295 | "questions.correctRange"296 | "questions.correctRange"
297+ | "subjects.title"
298+ | "subjects.subject"
299+ | "subjects.name"
300+ | "subjects.add"
301+ | "subjects.edit"
302+ | "subjects.empty"
303+ | "subjects.select"
304+ | "subjects.help"
296 | "attempt.title"305 | "attempt.title"
297 | "attempt.openRoom"306 | "attempt.openRoom"
298 | "attempt.start"307 | "attempt.start"
@@ -835,10 +844,19 @@ const en: Dict = {
835 "questions.correctHint": "Zero-based: first choice is 0.",844 "questions.correctHint": "Zero-based: first choice is 0.",
836 "questions.kind.choice": "Choice",845 "questions.kind.choice": "Choice",
837 "questions.kind.text": "Text",846 "questions.kind.text": "Text",
847+ "questions.subjectRequired": "Select a subject for this question",
838 "questions.textRequired": "Question text is required",848 "questions.textRequired": "Question text is required",
839 "questions.pointsRange": "Points must be an integer from 1 to 100",849 "questions.pointsRange": "Points must be an integer from 1 to 100",
840 "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters",850 "questions.choicesRange": "Choice questions need 2–10 choices, each at most 500 characters",
841 "questions.correctRange": "Correct index must point to one of the choices",851 "questions.correctRange": "Correct index must point to one of the choices",
852+ "subjects.title": "Subjects",
853+ "subjects.subject": "Subject",
854+ "subjects.name": "Subject name",
855+ "subjects.add": "Add subject",
856+ "subjects.edit": "Edit subject",
857+ "subjects.empty": "No subjects yet.",
858+ "subjects.select": "Select subject",
859+ "subjects.help": "Curriculum topics for this education item. Every exam question must be tagged with one.",
842 "attempt.title": "Exam room",860 "attempt.title": "Exam room",
843 "attempt.openRoom": "Open exam room",861 "attempt.openRoom": "Open exam room",
844 "attempt.start": "Start exam",862 "attempt.start": "Start exam",
@@ -1391,10 +1409,19 @@ const tr: Dict = {
1391 "questions.correctHint": "Sıfırdan başlar: ilk seçenek 0.",1409 "questions.correctHint": "Sıfırdan başlar: ilk seçenek 0.",
1392 "questions.kind.choice": "Seçmeli",1410 "questions.kind.choice": "Seçmeli",
1393 "questions.kind.text": "Metin",1411 "questions.kind.text": "Metin",
1412+ "questions.subjectRequired": "Bu soru için konu seç",
1394 "questions.textRequired": "Soru metni gerekli",1413 "questions.textRequired": "Soru metni gerekli",
1395 "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı",1414 "questions.pointsRange": "Puan 1–100 arası tam sayı olmalı",
1396 "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı",1415 "questions.choicesRange": "Seçmeli soruda 2–10 seçenek gerekir; her biri en fazla 500 karakter olmalı",
1397 "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",1416 "questions.correctRange": "Doğru indeks seçeneklerden birini göstermeli",
1417+ "subjects.title": "Konular",
1418+ "subjects.subject": "Konu",
1419+ "subjects.name": "Konu adı",
1420+ "subjects.add": "Konu ekle",
1421+ "subjects.edit": "Konuyu düzenle",
1422+ "subjects.empty": "Henüz konu yok.",
1423+ "subjects.select": "Konu seç",
1424+ "subjects.help": "Bu eğitim kaydının müfredat konuları. Her sınav sorusu bir konuya bağlanmalı.",
1398 "attempt.title": "Sınav odası",1425 "attempt.title": "Sınav odası",
1399 "attempt.openRoom": "Sınav odasını aç",1426 "attempt.openRoom": "Sınav odasını aç",
1400 "attempt.start": "Sınava başla",1427 "attempt.start": "Sınava başla",
src/pages/course-detail-page.tsxmodified+13 -2
@@ -15,6 +15,7 @@ import { formatApiError } from "@/api/client";
15 import type { CourseKind } from "@/api/types";15 import type { CourseKind } from "@/api/types";
16 import { ExamLink } from "@/components/exams/exam-link";16 import { ExamLink } from "@/components/exams/exam-link";
17 import { ExamForm } from "@/components/exams/exam-form";17 import { ExamForm } from "@/components/exams/exam-form";
18+import { CourseSubjectsPanel } from "@/components/courses/course-subjects-panel";
18 import { CourseSessionsPanel } from "@/components/sessions/course-sessions-panel";19 import { CourseSessionsPanel } from "@/components/sessions/course-sessions-panel";
19 import { RouteGuard } from "@/components/layout/route-guard";20 import { RouteGuard } from "@/components/layout/route-guard";
20 import { PageHeader } from "@/components/layout/page-header";21 import { PageHeader } from "@/components/layout/page-header";
@@ -98,7 +99,7 @@ function CourseDetailContent() {
98 const [showExamForm, setShowExamForm] = createSignal(false);99 const [showExamForm, setShowExamForm] = createSignal(false);
99 const [showSessionForm, setShowSessionForm] = createSignal(false);100 const [showSessionForm, setShowSessionForm] = createSignal(false);
100 const [showEnrollPanel, setShowEnrollPanel] = createSignal(false);101 const [showEnrollPanel, setShowEnrollPanel] = createSignal(false);
101- const [openSections, setOpenSections] = createSignal({ exams: true, sessions: false, roster: false });102+ const [openSections, setOpenSections] = createSignal({ subjects: true, exams: true, sessions: false, roster: false });
102 const [enrollUserId, setEnrollUserId] = createSignal("");103 const [enrollUserId, setEnrollUserId] = createSignal("");
103 const [error, setError] = createSignal("");104 const [error, setError] = createSignal("");
104 const [pending, setPending] = createSignal(false);105 const [pending, setPending] = createSignal(false);
@@ -131,7 +132,7 @@ function CourseDetailContent() {
131 const examKindCount = createMemo(() => new Set((exams() ?? []).map((exam) => exam.kind)).size);132 const examKindCount = createMemo(() => new Set((exams() ?? []).map((exam) => exam.kind)).size);
132 133
133 const enrolledUserIds = () => (roster() ?? []).map((row) => row.user.id);134 const enrolledUserIds = () => (roster() ?? []).map((row) => row.user.id);
134- const toggleSection = (section: "exams" | "sessions" | "roster") => {135+ const toggleSection = (section: "subjects" | "exams" | "sessions" | "roster") => {
135 setOpenSections((current) => ({ ...current, [section]: !current[section] }));136 setOpenSections((current) => ({ ...current, [section]: !current[section] }));
136 };137 };
137 138
@@ -406,6 +407,16 @@ function CourseDetailContent() {
406 </div>407 </div>
407 </section>408 </section>
408 409
410+ <SectionDisclosure
411+ open={openSections().subjects}
412+ onToggle={() => toggleSection("subjects")}
413+ title={t("subjects.title")}
414+ description={t("subjects.help")}
415+ meta={<Badge variant="secondary" class="rounded-lg px-3 py-1">{t("subjects.title")}</Badge>}
416+ >
417+ <CourseSubjectsPanel courseId={id()} canManage={canManage()} active={openSections().subjects} />
418+ </SectionDisclosure>
419+
409 <SectionDisclosure420 <SectionDisclosure
410 open={openSections().exams}421 open={openSections().exams}
411 onToggle={() => toggleSection("exams")}422 onToggle={() => toggleSection("exams")}
src/pages/exam-detail-page.tsxmodified+1 -1
@@ -445,7 +445,7 @@ function ExamDetailContent() {
445 description={t("exams.examQuestions")}445 description={t("exams.examQuestions")}
446 >446 >
447 <Show when={openSections().questions}>447 <Show when={openSections().questions}>
448- <ExamQuestionsPanel examId={id()} readOnly={isFinished() || isUpcoming()} embedded />448+ <ExamQuestionsPanel examId={id()} courseId={ex().course} readOnly={isFinished() || isUpcoming()} embedded />
449 </Show>449 </Show>
450 </SectionDisclosure>450 </SectionDisclosure>
451 451