forge
Explore
Log in

Don't you dare go Hollow

🔧 type hardening, date-picker locale, answer sheet merge, cleanup

Browse files at this commit

e00544e71550996326017f7d2145797af494b2fcBurak BoduroğluParent: 3790224
  • refactor
    • 🔧 type hardening, date-picker locale, answer sheet merge, cleanup
Show full message
refactor: 🔧 type hardening, date-picker locale, answer sheet merge, cleanup

- types: Exam/ExamAttempt/LiveMonitor fields required instead of optional,
  remove legacy weight variants (kind_weight, type_weight, exam_type_weight)
- AttemptQuestion: split into AttemptQuestionResponse + mapped AttemptQuestion
- StudentAnswer replaces GradedAnswer, matches backend shape exactly
- getExamAttemptQuestions: adds exam field via map (backend omits it)
- answer-sheet-view: fetch questions + answers, merge client-side for display
- date-picker: locale-aware day headers via Intl, Portal for overlay,
  selected-day label, improved outside-click detection
- createNow interval: 1000ms -> 30000ms (reduce polling)
- exam-weight: remove legacy field fallbacks
- live-monitor: pass maxAttempts from exam to attemptLabel
- cleanup: delete getSessionById, getSubjectById, getTermById (unused)
src/api/getExamAttemptQuestions.tsmodified+4 -3
@@ -1,6 +1,7 @@
1 import { client } from "./client";1 import { client } from "./client";
2-import type { AttemptQuestion } from "./types";2+import type { AttemptQuestion, AttemptQuestionResponse } from "./types";
3 3
4-export function getExamAttemptQuestions(examId: string, signal?: AbortSignal): Promise<AttemptQuestion[]> {4+export async function getExamAttemptQuestions(examId: string, signal?: AbortSignal): Promise<AttemptQuestion[]> {
5- return client<AttemptQuestion[]>(`/exams/${examId}/attempt/questions`, { signal });5+ const questions = await client<AttemptQuestionResponse[]>(`/exams/${examId}/attempt/questions`, { signal });
6+ return questions.map((question) => ({ ...question, exam: examId }));
6 }7 }
src/api/getSessionById.tsdeleted+0 -6
@@ -1,6 +0,0 @@
1-import { client } from "./client";
2-import type { CourseSession } from "./types";
3-
4-export function getSessionById(id: string, signal?: AbortSignal): Promise<CourseSession> {
5- return client<CourseSession>(`/sessions/${id}`, { signal });
6-}
src/api/getSubjectById.tsdeleted+0 -6
@@ -1,6 +0,0 @@
1-import { client } from "./client";
2-import type { Subject } from "./types";
3-
4-export function getSubjectById(id: string, signal?: AbortSignal): Promise<Subject> {
5- return client<Subject>(`/subjects/${id}`, { signal });
6-}
src/api/getTermById.tsdeleted+0 -6
@@ -1,6 +0,0 @@
1-import { client } from "./client";
2-import type { Term } from "./types";
3-
4-export function getTermById(id: string, signal?: AbortSignal): Promise<Term> {
5- return client<Term>(`/terms/${id}`, { signal });
6-}
src/api/types.tsmodified+33 -42
@@ -94,9 +94,8 @@ export type Course = {
94 title: string;94 title: string;
95 description: string;95 description: string;
96 kind: CourseKind;96 kind: CourseKind;
97- /** Academic term id from API (`CourseResponse.term`). */97+ term: string | null;
98- term?: string | null;98+ capacity: number | null;
99- capacity?: number | null;
100 };99 };
101 100
102 export type Term = {101 export type Term = {
@@ -138,17 +137,13 @@ export type Exam = {
138 title: string;137 title: string;
139 description: string;138 description: string;
140 kind: ExamKind | string;139 kind: ExamKind | string;
141- weight?: number | null;
142- kind_weight?: number | null;
143- type_weight?: number | null;
144- exam_type_weight?: number | null;
145 mode: ExamMode | string | null;140 mode: ExamMode | string | null;
146 starts_at: number | null;141 starts_at: number | null;
147 ends_at: number | null;142 ends_at: number | null;
148 duration_ms: number | null;143 duration_ms: number | null;
149- max_attempts?: number | null;144+ max_attempts: number;
150- allow_rejoin?: boolean | null;145+ allow_rejoin: boolean;
151- draft?: boolean | null;146+ draft: boolean;
152 };147 };
153 148
154 export type ImageMeta = {149 export type ImageMeta = {
@@ -178,16 +173,18 @@ export type ExamQuestion = {
178 };173 };
179 174
180 export type ExamAttempt = {175 export type ExamAttempt = {
181- id?: string;176+ id: string;
182- exam?: string;177+ exam: string;
183- user?: PersonRef;178+ user: PersonRef;
184 status: AttemptStatus;179 status: AttemptStatus;
185- attempt?: number;180+ attempt: number;
186- attempts_used?: number;181+ attempts_used: number;
187- max_attempts?: number;182+ max_attempts: number;
183+ started_at: number;
184+ finished_at: number | null;
188 deadline: number | null;185 deadline: number | null;
189 remaining_ms: number | null;186 remaining_ms: number | null;
190- left_at?: number | null;187+ left_at: number | null;
191 mark: number | null;188 mark: number | null;
192 answered: number;189 answered: number;
193 question_count: number;190 question_count: number;
@@ -200,9 +197,8 @@ export type AttemptAnswer = {
200 updated_at?: number;197 updated_at?: number;
201 };198 };
202 199
203-export type AttemptQuestion = {200+export type AttemptQuestionResponse = {
204 id: string;201 id: string;
205- exam: string;
206 subject: string;202 subject: string;
207 text: string;203 text: string;
208 kind: QuestionKind;204 kind: QuestionKind;
@@ -213,6 +209,8 @@ export type AttemptQuestion = {
213 answer: AttemptAnswer | null;209 answer: AttemptAnswer | null;
214 };210 };
215 211
212+export type AttemptQuestion = AttemptQuestionResponse & { exam: string };
213+
216 export type PomodoroSession = {214 export type PomodoroSession = {
217 id: string;215 id: string;
218 user: string;216 user: string;
@@ -240,10 +238,7 @@ export type MarkEntry = {
240 exam: string;238 exam: string;
241 title: string;239 title: string;
242 kind: string;240 kind: string;
243- weight?: number | null;241+ weight: number;
244- kind_weight?: number | null;
245- type_weight?: number | null;
246- exam_type_weight?: number | null;
247 mark: number;242 mark: number;
248 grade?: string | null;243 grade?: string | null;
249 graded_by: string;244 graded_by: string;
@@ -294,44 +289,40 @@ export type MarksReport = {
294 };289 };
295 290
296 export type ExamStatistics = {291 export type ExamStatistics = {
292+ exam: string;
297 graded: number;293 graded: number;
298 average: number | null;294 average: number | null;
299 min: number | null;295 min: number | null;
300 max: number | null;296 max: number | null;
301 };297 };
302 298
303-export type GradedAnswer = {299+export type StudentAnswer = {
304- question_id: string;300+ question: string;
305- text: string;
306- kind: QuestionKind;
307- points: number;
308- choices: string[] | null;
309- correct: number | null;
310 selected: number | null;301 selected: number | null;
311- text_answer: string | null;302+ text: string | null;
303+ updated_at: number;
312 is_correct: boolean | null;304 is_correct: boolean | null;
313- auto_score: { earned: number; possible: number };
314 };305 };
315 306
316 export type StudentAnswerSheet = {307 export type StudentAnswerSheet = {
308+ exam: string;
317 user: PersonRef;309 user: PersonRef;
318- answers: GradedAnswer[];310+ answers: StudentAnswer[];
319 auto_score: { earned: number; possible: number };311 auto_score: { earned: number; possible: number };
320 };312 };
321 313
322 export type LiveRosterEntry = {314 export type LiveRosterEntry = {
323 user: PersonRef;315 user: PersonRef;
324 status: AttemptStatus | "not_started" | "absent";316 status: AttemptStatus | "not_started" | "absent";
325- attempt?: number | null;317+ attempt: number | null;
326- attempts_used?: number | null;318+ attempts_used: number;
327- max_attempts?: number | null;
328 deadline: number | null;319 deadline: number | null;
329 remaining_ms: number | null;320 remaining_ms: number | null;
330- left_at?: number | null;321+ left_at: number | null;
331 mark: number | null;322 mark: number | null;
332 answered: number;323 answered: number;
333- started_at?: number | null;324+ started_at: number | null;
334- finished_at?: number | null;325+ finished_at: number | null;
335 last_activity: number | null;326 last_activity: number | null;
336 };327 };
337 328
@@ -341,13 +332,13 @@ export type LiveMonitor = {
341 question_count: number;332 question_count: number;
342 students: LiveRosterEntry[];333 students: LiveRosterEntry[];
343 counts: {334 counts: {
344- enrolled?: number;335+ enrolled: number;
345 not_started: number;336 not_started: number;
346- absent?: number;337+ absent: number;
347 in_progress: number;338 in_progress: number;
348 submitted: number;339 submitted: number;
349 expired: number;340 expired: number;
350- graded?: number;341+ graded: number;
351 };342 };
352 };343 };
353 344
src/components/exams/answer-sheet-view.tsxmodified+31 -2
@@ -1,5 +1,7 @@
1 import { For, Show, Suspense, createResource } from "solid-js";1 import { For, Show, Suspense, createResource } from "solid-js";
2+import { getExamQuestions } from "@/api/getExamQuestions";
2 import { getStudentAnswers } from "@/api/getStudentAnswers";3 import { getStudentAnswers } from "@/api/getStudentAnswers";
4+import type { ExamQuestion, StudentAnswer } from "@/api/types";
3 import { Badge } from "@/components/ui/badge";5 import { Badge } from "@/components/ui/badge";
4 import { PageSpinner } from "@/components/ui/page-spinner";6 import { PageSpinner } from "@/components/ui/page-spinner";
5 import { personLabelWithId } from "@/lib/person";7 import { personLabelWithId } from "@/lib/person";
@@ -9,7 +11,17 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
9 const t = useT();11 const t = useT();
10 const [sheet] = createResource(12 const [sheet] = createResource(
11 () => [props.examId, props.userId] as const,13 () => [props.examId, props.userId] as const,
12- async ([examId, userId]) => getStudentAnswers(examId, userId),14+ async ([examId, userId]) => {
15+ const [answers, questions] = await Promise.all([getStudentAnswers(examId, userId), getExamQuestions(examId)]);
16+ const byId = new Map(questions.items.map((question) => [question.id, question]));
17+ return {
18+ ...answers,
19+ rows: answers.answers.flatMap((answer) => {
20+ const question = byId.get(answer.question);
21+ return question ? [answerRow(answer, question)] : [];
22+ }),
23+ };
24+ },
13 );25 );
14 26
15 return (27 return (
@@ -24,7 +36,7 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
24 </Badge>36 </Badge>
25 </div>37 </div>
26 38
27- <For each={s().answers}>39+ <For each={s().rows}>
28 {(answer, idx) => (40 {(answer, idx) => (
29 <div class="rounded-md border p-4">41 <div class="rounded-md border p-4">
30 <div class="mb-2 flex flex-wrap items-center gap-2">42 <div class="mb-2 flex flex-wrap items-center gap-2">
@@ -87,3 +99,20 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
87 </Suspense>99 </Suspense>
88 );100 );
89 }101 }
102+
103+function answerRow(answer: StudentAnswer, question: ExamQuestion) {
104+ const isChoice = question.kind === "choice";
105+ const possible = isChoice ? question.points : 0;
106+ return {
107+ question_id: answer.question,
108+ text: question.text,
109+ kind: question.kind,
110+ points: question.points,
111+ choices: question.choices,
112+ correct: question.correct,
113+ selected: answer.selected,
114+ text_answer: answer.text,
115+ is_correct: answer.is_correct,
116+ auto_score: { earned: answer.is_correct ? question.points : 0, possible },
117+ };
118+}
src/components/exams/exam-room-ws.tsxmodified+1 -11
@@ -89,17 +89,7 @@ export function ExamRoomWS(props: { exam: Exam }) {
89 setAttempt((prev) =>89 setAttempt((prev) =>
90 prev90 prev
91 ? { ...prev, status: msg.status as any, deadline: msg.deadline, remaining_ms: msg.remaining_ms, answered: msg.answered, question_count: msg.question_count, now: msg.now }91 ? { ...prev, status: msg.status as any, deadline: msg.deadline, remaining_ms: msg.remaining_ms, answered: msg.answered, question_count: msg.question_count, now: msg.now }
92- : {92+ : prev,
93- id: undefined,
94- exam: props.exam.id,
95- status: msg.status as any,
96- deadline: msg.deadline,
97- remaining_ms: msg.remaining_ms,
98- mark: null,
99- answered: msg.answered,
100- question_count: msg.question_count,
101- now: msg.now,
102- },
103 );93 );
104 setRemainingMs(msg.remaining_ms);94 setRemainingMs(msg.remaining_ms);
105 break;95 break;
src/components/ui/date-picker.tsxmodified+60 -43
@@ -1,8 +1,10 @@
1 import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";1 import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2+import { Portal } from "solid-js/web";
2 import { Button } from "@/components/ui/button";3 import { Button } from "@/components/ui/button";
3 import { IconCalendar, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";4 import { IconCalendar, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";
4 import { Input } from "@/components/ui/input";5 import { Input } from "@/components/ui/input";
5 import { cn } from "@/lib/cn";6 import { cn } from "@/lib/cn";
7+import { usePreferences } from "@/stores/preferences-context";
6 8
7 function pad(value: number): string {9 function pad(value: number): string {
8 return String(value).padStart(2, "0");10 return String(value).padStart(2, "0");
@@ -47,15 +49,29 @@ export function DatePicker(props: {
47 class?: string;49 class?: string;
48 onChange: (value: string) => void;50 onChange: (value: string) => void;
49 }) {51 }) {
52+ const { locale } = usePreferences();
50 let root: HTMLDivElement | undefined;53 let root: HTMLDivElement | undefined;
54+ let panel: HTMLDivElement | undefined;
51 const [open, setOpen] = createSignal(false);55 const [open, setOpen] = createSignal(false);
52 const [position, setPosition] = createSignal({ left: 0, top: 0, width: 288 });56 const [position, setPosition] = createSignal({ left: 0, top: 0, width: 288 });
53 const selected = createMemo(() => parseDate(props.value));57 const selected = createMemo(() => parseDate(props.value));
54 const [month, setMonth] = createSignal(selected() ?? new Date());58 const [month, setMonth] = createSignal(selected() ?? new Date());
55 const days = createMemo(() => monthDays(month()));59 const days = createMemo(() => monthDays(month()));
56 const monthLabel = createMemo(() =>60 const monthLabel = createMemo(() =>
57- new Intl.DateTimeFormat(undefined, { month: "long", year: "numeric" }).format(month()),61+ new Intl.DateTimeFormat(locale(), { month: "long", year: "numeric" }).format(month()),
58 );62 );
63+ const selectedDayLabel = createMemo(() => {
64+ const date = selected();
65+ return date ? new Intl.DateTimeFormat(locale(), { weekday: "long" }).format(date) : "";
66+ });
67+ const dayHeaders = createMemo(() => {
68+ const base = new Date(2024, 0, 1);
69+ return Array.from({ length: 7 }, (_, i) => {
70+ const d = new Date(base);
71+ d.setDate(base.getDate() + i);
72+ return new Intl.DateTimeFormat(locale(), { weekday: "short" }).format(d);
73+ });
74+ });
59 75
60 createEffect(() => {76 createEffect(() => {
61 const date = selected();77 const date = selected();
@@ -81,7 +97,8 @@ export function DatePicker(props: {
81 };97 };
82 updatePosition();98 updatePosition();
83 const closeOnOutside = (event: MouseEvent) => {99 const closeOnOutside = (event: MouseEvent) => {
84- if (root && !root.contains(event.target as Node)) setOpen(false);100+ const target = event.target as Node;
101+ if (root && !root.contains(target) && panel && !panel.contains(target)) setOpen(false);
85 };102 };
86 window.addEventListener("resize", updatePosition);103 window.addEventListener("resize", updatePosition);
87 window.addEventListener("scroll", updatePosition, true);104 window.addEventListener("scroll", updatePosition, true);
@@ -119,49 +136,49 @@ export function DatePicker(props: {
119 />136 />
120 <IconCalendar class="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />137 <IconCalendar class="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
121 </div>138 </div>
139+ <Show when={selectedDayLabel()}>
140+ {(day) => <p class="mt-1 text-xs font-medium capitalize text-muted-foreground">{day()}</p>}
141+ </Show>
122 <Show when={open()}>142 <Show when={open()}>
123- <div143+ <Portal>
124- class="fixed z-[80] rounded-xl border border-border/80 bg-popover p-2.5 text-popover-foreground shadow-xl"144+ <div
125- style={{ left: `${position().left}px`, top: `${position().top}px`, width: `${position().width}px` }}145+ ref={panel}
126- >146+ class="fixed z-[80] rounded-xl border border-border/80 bg-popover p-2.5 text-popover-foreground shadow-xl"
127- <div class="mb-3 flex items-center justify-between gap-2">147+ style={{ left: `${position().left}px`, top: `${position().top}px`, width: `${position().width}px` }}
128- <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={() => moveMonth(-1)}>148+ >
129- <IconChevronLeft class="h-4 w-4" />149+ <div class="mb-3 flex items-center justify-between gap-2">
130- </Button>150+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={() => moveMonth(-1)}>
131- <p class="min-w-0 truncate px-2 text-sm font-semibold capitalize">{monthLabel()}</p>151+ <IconChevronLeft class="h-4 w-4" />
132- <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={() => moveMonth(1)}>152+ </Button>
133- <IconChevronRight class="h-4 w-4" />153+ <p class="min-w-0 truncate px-2 text-sm font-semibold capitalize">{monthLabel()}</p>
134- </Button>154+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={() => moveMonth(1)}>
135- </div>155+ <IconChevronRight class="h-4 w-4" />
136- <div class="grid grid-cols-7 gap-1 text-center text-[11px] font-medium text-muted-foreground">156+ </Button>
137- <span>Pzt</span>157+ </div>
138- <span>Sal</span>158+ <div class="grid grid-cols-7 gap-1 text-center text-[11px] font-medium text-muted-foreground">
139- <span>Çar</span>159+ <For each={dayHeaders()}>{(day) => <span>{day}</span>}</For>
140- <span>Per</span>160+ </div>
141- <span>Cum</span>161+ <div class="mt-1 grid grid-cols-7 gap-0.5">
142- <span>Cmt</span>162+ <For each={days()}>
143- <span>Paz</span>163+ {(date) => (
144- </div>164+ <Show when={date} fallback={<span class="h-8" />}>
145- <div class="mt-1 grid grid-cols-7 gap-0.5">165+ {(day) => (
146- <For each={days()}>166+ <Button
147- {(date) => (167+ type="button"
148- <Show when={date} fallback={<span class="h-8" />}>168+ variant={sameDay(selected(), day()) ? "default" : "ghost"}
149- {(day) => (169+ size="sm"
150- <Button170+ class="h-8 rounded-lg p-0 text-xs"
151- type="button"171+ onClick={() => pick(day())}
152- variant={sameDay(selected(), day()) ? "default" : "ghost"}172+ >
153- size="sm"173+ {day().getDate()}
154- class="h-8 rounded-lg p-0 text-xs"174+ </Button>
155- onClick={() => pick(day())}175+ )}
156- >176+ </Show>
157- {day().getDate()}177+ )}
158- </Button>178+ </For>
159- )}179+ </div>
160- </Show>
161- )}
162- </For>
163 </div>180 </div>
164- </div>181+ </Portal>
165 </Show>182 </Show>
166 </div>183 </div>
167 );184 );
src/lib/create-now.tsmodified+1 -1
@@ -1,7 +1,7 @@
1 import { createSignal, onCleanup } from "solid-js";1 import { createSignal, onCleanup } from "solid-js";
2 import { getTime } from "@/api/getTime";2 import { getTime } from "@/api/getTime";
3 3
4-export function createNow(intervalMs = 1000) {4+export function createNow(intervalMs = 30000) {
5 let offset = 0;5 let offset = 0;
6 const serverNow = () => Date.now() + offset;6 const serverNow = () => Date.now() + offset;
7 const [now, setNow] = createSignal(serverNow());7 const [now, setNow] = createSignal(serverNow());
src/lib/exam-weight.tsmodified+1 -4
@@ -1,9 +1,6 @@
1 type ExamWeightSource = {1 type ExamWeightSource = {
2 kind?: string | null;2 kind?: string | null;
3 weight?: number | null;3 weight?: number | null;
4- kind_weight?: number | null;
5- type_weight?: number | null;
6- exam_type_weight?: number | null;
7 };4 };
8 5
9 type KindWeight = {6 type KindWeight = {
@@ -15,7 +12,7 @@ export function examWeight(
15 source: ExamWeightSource,12 source: ExamWeightSource,
16 kinds?: readonly KindWeight[] | null,13 kinds?: readonly KindWeight[] | null,
17 ): number | null {14 ): number | null {
18- const direct = source.kind_weight ?? source.type_weight ?? source.exam_type_weight ?? source.weight ?? null;15+ const direct = source.weight ?? null;
19 if (typeof direct === "number" && Number.isFinite(direct)) return direct;16 if (typeof direct === "number" && Number.isFinite(direct)) return direct;
20 if (source.kind != null && kinds?.length) {17 if (source.kind != null && kinds?.length) {
21 const match = kinds.find((item) => item.name === String(source.kind));18 const match = kinds.find((item) => item.name === String(source.kind));
src/pages/live-monitor-page.tsxmodified+3 -3
@@ -84,8 +84,8 @@ function isLowRemaining(entry: LiveRosterEntry): boolean {
84 return entry.status === "in_progress" && remaining <= 5 * 60 * 1000;84 return entry.status === "in_progress" && remaining <= 5 * 60 * 1000;
85 }85 }
86 86
87-function attemptLabel(entry: LiveRosterEntry): string {87+function attemptLabel(entry: LiveRosterEntry, maxAttempts: number | null): string {
88- if (entry.attempts_used != null && entry.max_attempts != null) return `${entry.attempts_used} / ${entry.max_attempts}`;88+ if (entry.attempts_used != null && maxAttempts != null) return `${entry.attempts_used} / ${maxAttempts}`;
89 if (entry.attempt != null) return String(entry.attempt);89 if (entry.attempt != null) return String(entry.attempt);
90 if (entry.attempts_used != null) return String(entry.attempts_used);90 if (entry.attempts_used != null) return String(entry.attempts_used);
91 return "—";91 return "—";
@@ -246,7 +246,7 @@ function LiveMonitorContent() {
246 accessorFn: (entry) => entry.attempts_used ?? entry.attempt ?? 0,246 accessorFn: (entry) => entry.attempts_used ?? entry.attempt ?? 0,
247 header: t("attempt.attempt"),247 header: t("attempt.attempt"),
248 meta: { headerClass: "text-center", cellClass: "text-center tabular-nums" },248 meta: { headerClass: "text-center", cellClass: "text-center tabular-nums" },
249- cell: (cell) => attemptLabel(cell.row.original),249+ cell: (cell) => attemptLabel(cell.row.original, m.exam.max_attempts),
250 },250 },
251 {251 {
252 id: "progress",252 id: "progress",