forge
Explore
Log in

Don't you dare go Hollow

✨ share exams with sibling sections, stop empty-id subject reads

Browse files at this commit

4d568179bd4b711b16828bce37657efd4639b479Burak BoduroğluParent: 877419e
  • feat
    • ✨ share exams with sibling sections, stop empty-id subject reads
Show full message
feat: ✨ share exams with sibling sections, stop empty-id subject reads
- exam audience endpoints return the audience array the API sends
  (POST/DELETE answered as a single row / void before), tests updated
- new "Paylaşılan şubeler" tab on exam detail: list the audience, share with
  a section teaching the same course in the same academic year, withdraw one
- ExamQuestionsPanel takes a nullable courseId and skips the subjects read
  until it resolves; Solid fetched `/courses//subjects` on the empty string
- a failed subjects read no longer throws into the page
src/api/__tests__/exams/exams.test.tsmodified+19 -11
@@ -146,34 +146,42 @@ describe("exams API - core", () => {
146146 expect(init?.method ?? "GET").toBe("GET");
147147 expect(init?.credentials).toBe("same-origin");
148148 });
149- it("getExamAudience calls /exams/:id/audience", async () => {
150- mockFetchSuccess({ items: [], total: 0 });
149+ it("getExamAudience reads the whole audience array", async () => {
150+ mockFetchSuccess([{ instance: "i1", class: "c1", course: "co1" }]);
151151
152- await getExamAudience("x1", { limit: 10 });
152+ const audience = await getExamAudience("x1");
153153
154- const [url] = lastFetchCall();
155- expect(url).toBe("/api/exams/x1/audience?limit=10");
154+ const [url, init] = lastFetchCall();
155+ expect(url).toBe("/api/exams/x1/audience");
156+ expect(init?.method ?? "GET").toBe("GET");
157+ expect(audience).toEqual([{ instance: "i1", class: "c1", course: "co1" }]);
156158 });
157159
158- it("postExamAudience announces the exam to another instance", async () => {
159- mockFetchSuccess({ instance: "i2", class: "c2", course: "co1" });
160+ it("postExamAudience announces the exam and returns the audience after the write", async () => {
161+ const after = [
162+ { instance: "i1", class: "c1", course: "co1" },
163+ { instance: "i2", class: "c2", course: "co1" },
164+ ];
165+ mockFetchSuccess(after);
160166
161- await postExamAudience("x1", "i2");
167+ const audience = await postExamAudience("x1", "i2");
162168
163169 const [url, init] = lastFetchCall();
164170 expect(url).toBe("/api/exams/x1/audience");
165171 expect(init?.method).toBe("POST");
166172 expect(init?.body).toBe(JSON.stringify({ instance: "i2" }));
173+ expect(audience).toEqual(after);
167174 });
168175
169- it("deleteExamAudienceByInstanceId calls /exams/:id/audience/:instance", async () => {
170- mockFetch204();
176+ it("deleteExamAudienceByInstanceId withdraws one instance and returns what is left", async () => {
177+ mockFetchSuccess([{ instance: "i1", class: "c1", course: "co1" }]);
171178
172- await deleteExamAudienceByInstanceId("x1", "i2");
179+ const audience = await deleteExamAudienceByInstanceId("x1", "i2");
173180
174181 const [url, init] = lastFetchCall();
175182 expect(url).toBe("/api/exams/x1/audience/i2");
176183 expect(init?.method).toBe("DELETE");
184+ expect(audience).toHaveLength(1);
177185 });
178186
179187 });
src/api/exams/deleteExamAudienceByInstanceId.tsmodified+4 -2
@@ -1,5 +1,7 @@
11 import { client } from "../client";
2+import type { ExamAudience } from "../client";
23
3-export function deleteExamAudienceByInstanceId(examId: string, instanceId: string): Promise<void> {
4- return client<void>(`/exams/${examId}/audience/${instanceId}`, { method: "DELETE" });
4+/** Withdraw the exam from one instance. Answers the audience left behind; the owner is not withdrawable (400). */
5+export function deleteExamAudienceByInstanceId(examId: string, instanceId: string): Promise<ExamAudience[]> {
6+ return client<ExamAudience[]>(`/exams/${examId}/audience/${instanceId}`, { method: "DELETE" });
57 }
src/api/exams/getExamAudience.tsmodified+6 -9
@@ -1,13 +1,10 @@
11 import { client } from "../client";
2-import { normalizePage, pageQuery, type Page, type PageParams } from "../client";
32 import type { ExamAudience } from "../client";
43
5-/** The instances this exam is announced to beyond the one that owns it. */
6-export async function getExamAudience(
7- examId: string,
8- params?: PageParams,
9- signal?: AbortSignal,
10-): Promise<Page<ExamAudience>> {
11- const data = await client<unknown>(`/exams/${examId}/audience${pageQuery(params)}`, { signal });
12- return normalizePage<ExamAudience>(data);
4+/**
5+ * Every instance the exam is announced to, its owner first, then in
6+ * announcement order. A plain array — the door takes no paging.
7+ */
8+export function getExamAudience(examId: string, signal?: AbortSignal): Promise<ExamAudience[]> {
9+ return client<ExamAudience[]>(`/exams/${examId}/audience`, { signal });
1310 }
src/api/exams/postExamAudience.tsmodified+4 -3
@@ -4,10 +4,11 @@ import type { ExamAudience } from "../client";
44 /**
55 * Announce the exam to another instance. It must teach the exam's own catalog
66 * course, sit under the same academic year, and be a different instance — the
7- * owner is refused with a 400.
7+ * owner is refused with a 400. Answers the whole audience after the write;
8+ * re-announcing a standing pair is a no-op.
89 */
9-export function postExamAudience(examId: string, instanceId: string): Promise<ExamAudience> {
10- return client<ExamAudience>(`/exams/${examId}/audience`, {
10+export function postExamAudience(examId: string, instanceId: string): Promise<ExamAudience[]> {
11+ return client<ExamAudience[]>(`/exams/${examId}/audience`, {
1112 method: "POST",
1213 body: { instance: instanceId },
1314 });
src/components/exams/exam-audience-panel.tsxadded+239 -0
@@ -0,0 +1,239 @@
1+import { Show, Suspense, createMemo, createSignal } from "solid-js";
2+import type { ColumnDef } from "@tanstack/solid-table";
3+import { createResource } from "@/lib/create-resource";
4+import { getClasses, getClassInstances } from "@/api/classes";
5+import { deleteExamAudienceByInstanceId, getExamAudience, postExamAudience } from "@/api/exams";
6+import { formatApiError, type ClassGroup, type ExamAudience } from "@/api/client";
7+import { Alert } from "@/components/ui/alert";
8+import { Badge } from "@/components/ui/badge";
9+import { Button } from "@/components/ui/button";
10+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
11+import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
12+import { IconPlus, IconTrash } from "@/components/ui/icons";
13+import { Label } from "@/components/ui/label";
14+import { SearchableSelect } from "@/components/ui/searchable-select";
15+import { SidePanel } from "@/components/ui/side-panel";
16+import { TableRowActions } from "@/components/ui/table-row-actions";
17+import { createFlash } from "@/lib/flash";
18+import { useT } from "@/stores/preferences-context";
19+
20+type AudienceRow = ExamAudience & { owner: boolean; label: string };
21+
22+/**
23+ * The sections a shared exam is announced to beyond its owner. Announcing puts
24+ * the exam — and its marks — into the sibling section's lists and report card;
25+ * the backend only accepts a section that teaches the same catalog course in
26+ * the same academic year, so the picker offers exactly those.
27+ */
28+export function ExamAudiencePanel(props: {
29+ examId: string;
30+ /** The exam's own instance (`class_course`). */
31+ ownerInstanceId: string;
32+ /** The catalog course the owner instance teaches; null while it resolves. */
33+ courseId: string | null;
34+ /** Announce/withdraw rights; the list itself is readable either way. */
35+ canManage: boolean;
36+}) {
37+ const t = useT();
38+ const [flash, setFlash] = createFlash();
39+ const [error, setError] = createSignal("");
40+ const [addOpen, setAddOpen] = createSignal(false);
41+ const [selected, setSelected] = createSignal("");
42+ const [saving, setSaving] = createSignal(false);
43+ const [removing, setRemoving] = createSignal<AudienceRow | null>(null);
44+
45+ const [audience, { mutate }] = createResource(() => props.examId, (examId) => getExamAudience(examId));
46+ // Section names label both the table and the picker. Teacher+ reads the
47+ // school's class list; one read covers every row.
48+ const [classes] = createResource(async () => {
49+ try {
50+ return (await getClasses({ limit: 200 })).items;
51+ } catch {
52+ return [] as ClassGroup[];
53+ }
54+ });
55+ const classById = createMemo(() => new Map((classes() ?? []).map((klass) => [klass.id, klass])));
56+ const className = (classId: string) => classById().get(classId)?.name ?? "—";
57+
58+ const rows = createMemo<AudienceRow[]>(() =>
59+ (audience() ?? []).map((row) => ({
60+ ...row,
61+ owner: row.instance === props.ownerInstanceId,
62+ label: className(row.class),
63+ })),
64+ );
65+
66+ // Candidates load only when the picker opens: one read per same-year şube.
67+ const [candidates] = createResource(
68+ () => (addOpen() && props.courseId && classes() ? props.courseId : null),
69+ async (courseId) => {
70+ const owner = (audience() ?? []).find((row) => row.instance === props.ownerInstanceId);
71+ const ownerYear = owner ? classById().get(owner.class)?.year ?? null : null;
72+ const siblings = (classes() ?? []).filter((klass) => klass.year === ownerYear);
73+ const perClass = await Promise.all(
74+ siblings.map(async (klass) => {
75+ try {
76+ return (await getClassInstances(klass.id, { limit: 200 })).items;
77+ } catch {
78+ return [];
79+ }
80+ }),
81+ );
82+ return perClass
83+ .flat()
84+ .filter((instance) => instance.course === courseId)
85+ .map((instance) => ({ value: instance.id, label: className(instance.class) }))
86+ .sort((a, b) => a.label.localeCompare(b.label, "tr"));
87+ },
88+ );
89+ const options = () => {
90+ const taken = new Set((audience() ?? []).map((row) => row.instance));
91+ return (candidates() ?? []).filter((option) => !taken.has(option.value));
92+ };
93+
94+ const add = async () => {
95+ const instanceId = selected();
96+ if (!instanceId || saving()) return;
97+ setSaving(true);
98+ setError("");
99+ try {
100+ mutate(await postExamAudience(props.examId, instanceId));
101+ setSelected("");
102+ setAddOpen(false);
103+ setFlash(t("exams.audience.added"));
104+ } catch (err) {
105+ setError(formatApiError(err));
106+ } finally {
107+ setSaving(false);
108+ }
109+ };
110+
111+ const remove = async () => {
112+ const row = removing();
113+ if (!row) return;
114+ setError("");
115+ try {
116+ mutate(await deleteExamAudienceByInstanceId(props.examId, row.instance));
117+ setFlash(t("exams.audience.removed"));
118+ } catch (err) {
119+ setError(formatApiError(err));
120+ } finally {
121+ setRemoving(null);
122+ }
123+ };
124+
125+ const columns = createMemo<ColumnDef<AudienceRow>[]>(() => [
126+ {
127+ accessorKey: "label",
128+ header: t("exams.audience.section"),
129+ meta: { cellClass: "font-medium" },
130+ },
131+ {
132+ id: "status",
133+ header: t("exams.audience.status"),
134+ cell: (cell) => (
135+ <Badge variant={cell.row.original.owner ? "default" : "secondary"}>
136+ {cell.row.original.owner ? t("exams.audience.owner") : t("exams.audience.shared")}
137+ </Badge>
138+ ),
139+ },
140+ ...(props.canManage
141+ ? [
142+ {
143+ id: "actions",
144+ header: t("common.actions"),
145+ meta: {
146+ headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap",
147+ cellClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap",
148+ },
149+ cell: (cell) => (
150+ <Show when={!cell.row.original.owner}>
151+ <TableRowActions
152+ label={t("common.actions")}
153+ actions={[
154+ {
155+ label: t("exams.audience.remove"),
156+ icon: <IconTrash class="h-4 w-4" />,
157+ destructive: true,
158+ onSelect: () => setRemoving(cell.row.original),
159+ },
160+ ]}
161+ />
162+ </Show>
163+ ),
164+ } satisfies ColumnDef<AudienceRow>,
165+ ]
166+ : []),
167+ ]);
168+
169+ return (
170+ <div class="space-y-3">
171+ <Show when={flash()}>
172+ <Alert variant="success">{flash()}</Alert>
173+ </Show>
174+ <Show when={error()}>
175+ <Alert variant="destructive">{error()}</Alert>
176+ </Show>
177+ <Suspense fallback={<DataTableSkeleton columns={2} rows={3} />}>
178+ <Show when={!audience.error} fallback={<Alert variant="destructive">{formatApiError(audience.error)}</Alert>}>
179+ <DataTable
180+ columns={columns()}
181+ data={rows()}
182+ title={t("exams.audience.tab")}
183+ description={t("exams.audience.description")}
184+ empty={t("exams.audience.empty")}
185+ enablePagination={false}
186+ enableColumnVisibility={false}
187+ actions={
188+ <Show when={props.canManage}>
189+ <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => setAddOpen(true)}>
190+ <IconPlus class="h-4 w-4" />
191+ {t("exams.audience.add")}
192+ </Button>
193+ </Show>
194+ }
195+ />
196+ </Show>
197+ </Suspense>
198+
199+ <SidePanel
200+ open={addOpen()}
201+ onOpenChange={(open) => {
202+ setAddOpen(open);
203+ if (!open) setSelected("");
204+ }}
205+ title={t("exams.audience.add")}
206+ description={t("exams.audience.addHelp")}
207+ >
208+ <div class="space-y-4 p-4">
209+ <Show
210+ when={!candidates.loading}
211+ fallback={<DataTableSkeleton columns={1} rows={3} />}
212+ >
213+ <Show when={options().length > 0} fallback={<p class="text-sm text-muted-foreground">{t("exams.audience.noCandidates")}</p>}>
214+ <div class="space-y-1.5">
215+ <Label for="exam-audience-section">{t("exams.audience.section")}</Label>
216+ <SearchableSelect id="exam-audience-section" value={selected()} onChange={setSelected} options={options()} />
217+ </div>
218+ <div class="flex justify-end">
219+ <Button type="button" size="sm" class="min-w-[7.5rem] rounded-lg" disabled={!selected() || saving()} onClick={() => void add()}>
220+ <IconPlus class="h-4 w-4" />
221+ {t("exams.audience.add")}
222+ </Button>
223+ </div>
224+ </Show>
225+ </Show>
226+ </div>
227+ </SidePanel>
228+
229+ <ConfirmDialog
230+ open={removing() !== null}
231+ onOpenChange={(open) => !open && setRemoving(null)}
232+ title={t("exams.audience.remove")}
233+ summary={t("exams.audience.removeConfirm", { section: removing()?.label ?? "" })}
234+ variant="destructive"
235+ onConfirm={remove}
236+ />
237+ </div>
238+ );
239+}
src/components/exams/exam-questions-panel.tsxmodified+15 -2
@@ -39,7 +39,8 @@ const QUESTION_PAGE_SIZE = 1;
3939
4040 export function ExamQuestionsPanel(props: {
4141 examId: string;
42- courseId: string;
42+ /** The exam's catalog course; null until the instance behind the exam resolves. */
43+ courseId: string | null;
4344 readOnly?: boolean;
4445 embedded?: boolean;
4546 createOpen?: boolean;
@@ -50,7 +51,19 @@ export function ExamQuestionsPanel(props: {
5051 const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher");
5152 const [bankOpen, setBankOpen] = createSignal(false);
5253 const [banking, setBanking] = createSignal("");
53- const [subjects] = createResource(() => props.courseId, async (courseId) => (await getCourseSubjects(courseId)).items);
54+ // Solid only skips a fetch on null/undefined/false — an empty string would
55+ // still ask for `/courses//subjects`. A subject list that cannot load only
56+ // costs the name lookup (ids stay readable), so it must not throw into the page.
57+ const [subjects] = createResource(
58+ () => props.courseId || null,
59+ async (courseId) => {
60+ try {
61+ return (await getCourseSubjects(courseId)).items;
62+ } catch {
63+ return [];
64+ }
65+ },
66+ );
5467 const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {
5568 try {
5669 return (await getExamQuestions(examId)).items;
src/pages/exam-detail-page.tsxmodified+13 -2
@@ -17,6 +17,7 @@ import { postExamResult } from "@/api/exams";
1717 import { ApiError, formatApiError } from "@/api/client";
1818 import type { ExamResult } from "@/api/client";
1919 import { ExamForm } from "@/components/exams/exam-form";
20+import { ExamAudiencePanel } from "@/components/exams/exam-audience-panel";
2021 import { ExamQuestionsPanel } from "@/components/exams/exam-questions-panel";
2122 import { AnswerSheetView } from "@/components/exams/answer-sheet-view";
2223 import { ExamResultBadge } from "@/components/exams/exam-result-badge";
@@ -30,7 +31,7 @@ import { Button } from "@/components/ui/button";
3031 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
3132 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
3233 import { EmptyState } from "@/components/ui/empty-state";
33-import { IconCalendarDays, IconChart, IconChevronDown, IconClipboardCheck, IconClock, IconEdit, IconExam, IconEye, IconRefresh, IconTrash } from "@/components/ui/icons";
34+import { IconCalendarDays, IconChart, IconChevronDown, IconClipboardCheck, IconClock, IconEdit, IconExam, IconEye, IconRefresh, IconSchool, IconTrash } from "@/components/ui/icons";
3435 import { Input } from "@/components/ui/input";
3536 import { PaginationControls } from "@/components/ui/pagination-controls";
3637 import { PageSpinner } from "@/components/ui/page-spinner";
@@ -663,6 +664,7 @@ function ExamDetailContent() {
663664 <TabsTrigger value="statistics"><IconChart class="h-4 w-4" />{t("exams.statistics")}</TabsTrigger>
664665 <TabsTrigger value="questions"><IconExam class="h-4 w-4" />{t("questions.title")}</TabsTrigger>
665666 <TabsTrigger value="results"><IconClipboardCheck class="h-4 w-4" />{t("exams.results")}</TabsTrigger>
667+ <TabsTrigger value="audience"><IconSchool class="h-4 w-4" />{t("exams.audience.tab")}</TabsTrigger>
666668 </TabsList>
667669
668670 <TabsContent value="statistics" forceMount class="data-shell p-4">
@@ -693,7 +695,7 @@ function ExamDetailContent() {
693695 </TabsContent>
694696
695697 <TabsContent value="questions" forceMount class="data-shell p-4">
696- <ExamQuestionsPanel examId={id()} courseId={instance()?.course ?? ""} readOnly={isFinished()} embedded />
698+ <ExamQuestionsPanel examId={id()} courseId={instance()?.course ?? null} readOnly={isFinished()} embedded />
697699 </TabsContent>
698700
699701 <TabsContent value="results" forceMount class="data-shell space-y-4 p-4">
@@ -740,6 +742,15 @@ function ExamDetailContent() {
740742 </Show>
741743 </Suspense>
742744 </TabsContent>
745+
746+ <TabsContent value="audience" class="data-shell p-4">
747+ <ExamAudiencePanel
748+ examId={id()}
749+ ownerInstanceId={ex().class_course}
750+ courseId={instance()?.course ?? null}
751+ canManage={hasCourseManagementRights()}
752+ />
753+ </TabsContent>
743754 </Tabs>
744755
745756 <SidePanel guardUnsaved
src/pages/exams-page.tsxmodified+2 -2
@@ -460,7 +460,7 @@ function ExamsContent() {
460460 <div class="space-y-4">
461461 <ExamQuestionsPanel
462462 examId={createdExam()!.id}
463- courseId={examCourseId(createdExam()!) ?? ""}
463+ courseId={examCourseId(createdExam()!)}
464464 embedded
465465 />
466466 <div class="flex justify-end border-t pt-3">
@@ -526,7 +526,7 @@ function ExamsContent() {
526526 <Show when={editTab() === "questions"}>
527527 <ExamQuestionsPanel
528528 examId={exam().id}
529- courseId={examCourseId(exam()) ?? ""}
529+ courseId={examCourseId(exam())}
530530 embedded
531531 />
532532 </Show>