From 8aa8ff23dc1de04f2c3e552958f0a575b9d43e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 20 Jul 2026 00:36:22 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20nginx=20API=20whitelist,?= =?UTF-8?q?=20answer-sheet=20join,=20prefs=20clear;=20contract=20tests=20-?= =?UTF-8?q?=20nginx.conf:=20proxy=20whitelist=20gains=20sessions/work/pomo?= =?UTF-8?q?doro/attendance/=20=20=20settings/subjects/terms=20=E2=80=94=20?= =?UTF-8?q?containerized=20frontend=20served=20index.html=20for=20=20=20th?= =?UTF-8?q?ose=20APIs;=20new=20nginx.conf.test.ts=20(bun=20test)=20guards?= =?UTF-8?q?=20the=20list=20-=20teacher=20answer=20sheet:=20join=20via=20te?= =?UTF-8?q?sted=20lib/answer-sheet.ts=20and=20list=20every=20=20=20questio?= =?UTF-8?q?n,=20showing=20unanswered=20ones=20too=20(answers-only=20merge?= =?UTF-8?q?=20hid=20them)=20-=20admin=20user=20preferences:=20send=20""=20?= =?UTF-8?q?(not=20null)=20to=20clear=20theme/language=20=E2=80=94=20=20=20?= =?UTF-8?q?backend=20keeps=20on=20null;=20body=20types=20now=20forbid=20nu?= =?UTF-8?q?ll=20-=20live=20monitor:=20attemptLabel=20moved=20to=20lib/exam?= =?UTF-8?q?-labels.ts=20with=20a=20real=20=20=20unlimited-attempts=20guard?= =?UTF-8?q?=20(max=5Fattempts=200=20no=20longer=20renders=20"n=20/=200")?= =?UTF-8?q?=20-=20PATCH=20body=20types=20stop=20offering=20null-clears=20t?= =?UTF-8?q?he=20backend=20ignores=20=20=20(session/event/course/note/work)?= =?UTF-8?q?;=20only=20true=20set=5For=5Fclear=20fields=20stay=20=20=20null?= =?UTF-8?q?able=20-=20course=20edit=20form=20gains=20maxlength=20hints=20m?= =?UTF-8?q?atching=20backend=20limits=20-=20unit=20tests=20for=20answer-sh?= =?UTF-8?q?eet=20join,=20exam=20weight,=20attempt=20label;=20=20=20tsconfi?= =?UTF-8?q?g=20excludes=20src/**/*.test.ts=20from=20app=20typecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nginx.conf | 2 +- nginx.conf.test.ts | 33 ++++++++ src/api/patchCourseById.ts | 7 +- src/api/patchEventById.ts | 8 +- src/api/patchNoteById.ts | 5 +- src/api/patchSessionById.ts | 7 +- src/api/patchUserPreferences.ts | 6 +- src/api/patchWorkEntryById.ts | 5 +- src/components/exams/answer-sheet-view.tsx | 79 ++++++------------- .../users/user-preferences-actions.tsx | 5 +- src/components/users/user-table.tsx | 2 +- src/lib/answer-sheet.test.ts | 58 ++++++++++++++ src/lib/answer-sheet.ts | 16 ++++ src/lib/exam-labels.test.ts | 14 ++++ src/lib/exam-labels.ts | 14 ++++ src/lib/exam-weight.test.ts | 20 +++++ src/pages/admin-users-page.tsx | 2 +- src/pages/course-detail-page.tsx | 2 + src/pages/live-monitor-page.tsx | 8 +- tsconfig.app.json | 3 +- tsconfig.json | 3 +- 21 files changed, 216 insertions(+), 83 deletions(-) create mode 100644 nginx.conf.test.ts create mode 100644 src/lib/answer-sheet.test.ts create mode 100644 src/lib/answer-sheet.ts create mode 100644 src/lib/exam-labels.test.ts create mode 100644 src/lib/exam-weight.test.ts diff --git a/nginx.conf b/nginx.conf index b83e326..453c7f4 100644 --- a/nginx.conf +++ b/nginx.conf @@ -3,7 +3,7 @@ server { root /usr/share/nginx/html; index index.html; - location ~ ^/api/(auth|users|notes|events|exams|courses|marks|health|time)(/|$) { + location ~ ^/api/(auth|users|notes|events|exams|courses|sessions|marks|attendance|work|pomodoro|settings|subjects|terms|health|time)(/|$) { rewrite ^/api(/.*)$ $1 break; proxy_pass http://hezarfen-backend:8080; proxy_http_version 1.1; diff --git a/nginx.conf.test.ts b/nginx.conf.test.ts new file mode 100644 index 0000000..ac6c078 --- /dev/null +++ b/nginx.conf.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; + +// Mirror of backend route mounts (hezarfen_backend src/lib.rs .nest calls + /health, /time). +// Backend adds a prefix → add it here AND in nginx.conf's proxy location. +const BACKEND_PREFIXES = [ + "auth", + "users", + "notes", + "events", + "courses", + "sessions", + "exams", + "marks", + "work", + "pomodoro", + "attendance", + "settings", + "subjects", + "terms", + "health", + "time", +]; + +test("nginx proxy whitelist covers every backend route prefix", () => { + const conf = readFileSync(new URL("./nginx.conf", import.meta.url), "utf8"); + const match = conf.match(/\^\/api\/\(([^)]+)\)/); + expect(match).not.toBeNull(); + const listed = match![1].split("|"); + for (const prefix of BACKEND_PREFIXES) { + expect(listed).toContain(prefix); + } +}); diff --git a/src/api/patchCourseById.ts b/src/api/patchCourseById.ts index b1d4eb5..be68f03 100644 --- a/src/api/patchCourseById.ts +++ b/src/api/patchCourseById.ts @@ -1,10 +1,11 @@ import { client } from "./client"; import type { Course, CourseKind } from "./types"; +/** Omitted fields keep their value. Only `term_id`/`capacity` clear on explicit null. */ export type PatchCourseBody = { - title?: string | null; - description?: string | null; - kind?: CourseKind | null; + title?: string; + description?: string; + kind?: CourseKind; term_id?: string | null; capacity?: number | null; }; diff --git a/src/api/patchEventById.ts b/src/api/patchEventById.ts index 29c7c44..7461d59 100644 --- a/src/api/patchEventById.ts +++ b/src/api/patchEventById.ts @@ -1,11 +1,11 @@ import { client } from "./client"; import type { Event, EventAudience } from "./types"; -/** Omitted time fields keep their value; explicit null clears them. */ +/** Omitted fields keep their value. Only the time fields clear on explicit null. */ export type PatchEventBody = { - title?: string | null; - description?: string | null; - audience?: EventAudience | null; + title?: string; + description?: string; + audience?: EventAudience; starts_at?: number | null; ends_at?: number | null; }; diff --git a/src/api/patchNoteById.ts b/src/api/patchNoteById.ts index e1b9601..2592b4f 100644 --- a/src/api/patchNoteById.ts +++ b/src/api/patchNoteById.ts @@ -1,9 +1,10 @@ import { client } from "./client"; import type { Note } from "./types"; +/** Omitted fields keep their value; null never clears here. */ export type PatchNoteBody = { - title?: string | null; - content?: string | null; + title?: string; + content?: string; }; export function patchNoteById(id: string, body: PatchNoteBody): Promise { diff --git a/src/api/patchSessionById.ts b/src/api/patchSessionById.ts index f279f2b..56d03e7 100644 --- a/src/api/patchSessionById.ts +++ b/src/api/patchSessionById.ts @@ -1,10 +1,11 @@ import { client } from "./client"; import type { CourseSession } from "./types"; +/** Omitted fields keep their value. Only `ends_at` clears on explicit null. */ export type PatchSessionBody = { - topic?: string | null; - teacher_id?: string | null; - starts_at?: number | null; + topic?: string; + teacher_id?: string; + starts_at?: number; ends_at?: number | null; }; diff --git a/src/api/patchUserPreferences.ts b/src/api/patchUserPreferences.ts index 01b826b..33c0b48 100644 --- a/src/api/patchUserPreferences.ts +++ b/src/api/patchUserPreferences.ts @@ -1,9 +1,11 @@ import { client } from "./client"; import type { User, UserLanguage, UserTheme } from "./types"; +/** Omit to keep; empty string clears back to the device default. Null also + * means keep on the backend, so it is deliberately not allowed here. */ export type PatchUserPreferencesBody = { - theme?: UserTheme | null; - language?: UserLanguage | null; + theme?: UserTheme | ""; + language?: UserLanguage | ""; }; export function patchUserPreferences(id: string, body: PatchUserPreferencesBody): Promise { diff --git a/src/api/patchWorkEntryById.ts b/src/api/patchWorkEntryById.ts index 20a3aa9..931721a 100644 --- a/src/api/patchWorkEntryById.ts +++ b/src/api/patchWorkEntryById.ts @@ -1,9 +1,10 @@ import { client } from "./client"; import type { WorkEntry } from "./types"; +/** Omitted fields keep their value; null never clears here. */ export type PatchWorkEntryBody = { - check_in?: number | null; - check_out?: number | null; + check_in?: number; + check_out?: number; }; export function patchWorkEntryById(id: string, body: PatchWorkEntryBody): Promise { diff --git a/src/components/exams/answer-sheet-view.tsx b/src/components/exams/answer-sheet-view.tsx index 748671f..2b0223f 100644 --- a/src/components/exams/answer-sheet-view.tsx +++ b/src/components/exams/answer-sheet-view.tsx @@ -1,90 +1,80 @@ import { For, Show, Suspense, createResource } from "solid-js"; import { getExamQuestions } from "@/api/getExamQuestions"; import { getStudentAnswers } from "@/api/getStudentAnswers"; -import type { ExamQuestion, StudentAnswer } from "@/api/types"; import { Badge } from "@/components/ui/badge"; import { PageSpinner } from "@/components/ui/page-spinner"; +import { joinAnswerSheet } from "@/lib/answer-sheet"; import { personLabelWithId } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; export function AnswerSheetView(props: { examId: string; userId: string }) { const t = useT(); - const [sheet] = createResource( + const [data] = createResource( () => [props.examId, props.userId] as const, async ([examId, userId]) => { - const [answers, questions] = await Promise.all([getStudentAnswers(examId, userId), getExamQuestions(examId)]); - const byId = new Map(questions.items.map((question) => [question.id, question])); - return { - ...answers, - rows: answers.answers.flatMap((answer) => { - const question = byId.get(answer.question); - return question ? [answerRow(answer, question)] : []; - }), - }; + const [questions, sheet] = await Promise.all([getExamQuestions(examId), getStudentAnswers(examId, userId)]); + return { sheet, rows: joinAnswerSheet(questions.items, sheet.answers) }; }, ); return ( }> - - {(s) => ( + + {(d) => (
-

{personLabelWithId(s().user)}

+

{personLabelWithId(d().sheet.user)}

- {t("exams.autoScore")}: {s().auto_score.earned}/{s().auto_score.possible} + {t("exams.autoScore")}: {d().sheet.auto_score.earned}/{d().sheet.auto_score.possible}
- - {(answer, idx) => ( + + {(row, idx) => (
#{idx() + 1} - {answer.points} {t("questions.points")} - - {answer.is_correct === true ? t("exams.isCorrect") : - answer.is_correct === false ? "✗" : - answer.kind === "text" ? t("questions.kind.text") : "—"} + {row.question.points} {t("questions.points")} + + {row.answer?.is_correct === true ? t("exams.isCorrect") : + row.answer?.is_correct === false ? "✗" : + row.question.kind === "text" ? t("questions.kind.text") : "—"} - {t("exams.autoScore")}: {answer.auto_score.earned}/{answer.auto_score.possible}
-

{answer.text}

+

{row.question.text}

{t("exams.textAnswer")}

-

{answer.text_answer || "—"}

+

{row.answer?.text || "—"}

} >
- + {(choice, ci) => (
- {ci() === answer.correct || ci() === answer.selected - ? ci() === answer.correct && ci() === answer.selected + {ci() === row.question.correct || ci() === row.answer?.selected + ? ci() === row.question.correct ? "✓" - : ci() === answer.correct - ? "✓" - : "✗" + : "✗" : String.fromCharCode(65 + ci())} {choice} - {ci() === answer.correct && {t("questions.correct")}} + {ci() === row.question.correct && {t("questions.correct")}}
)}
@@ -99,20 +89,3 @@ export function AnswerSheetView(props: { examId: string; userId: string }) { ); } - -function answerRow(answer: StudentAnswer, question: ExamQuestion) { - const isChoice = question.kind === "choice"; - const possible = isChoice ? question.points : 0; - return { - question_id: answer.question, - text: question.text, - kind: question.kind, - points: question.points, - choices: question.choices, - correct: question.correct, - selected: answer.selected, - text_answer: answer.text, - is_correct: answer.is_correct, - auto_score: { earned: answer.is_correct ? question.points : 0, possible }, - }; -} diff --git a/src/components/users/user-preferences-actions.tsx b/src/components/users/user-preferences-actions.tsx index b92e3ca..48341df 100644 --- a/src/components/users/user-preferences-actions.tsx +++ b/src/components/users/user-preferences-actions.tsx @@ -7,7 +7,7 @@ import { useT } from "@/stores/preferences-context"; export function UserPreferencesActions(props: { user: User; - onPreferencesChange: (userId: string, body: { theme?: UserTheme | null; language?: UserLanguage | null }) => Promise; + onPreferencesChange: (userId: string, body: { theme?: UserTheme | ""; language?: UserLanguage | "" }) => Promise; }) { const t = useT(); const [theme, setTheme] = createSignal(props.user.theme ?? ""); @@ -29,7 +29,8 @@ export function UserPreferencesActions(props: {
- diff --git a/src/components/users/user-table.tsx b/src/components/users/user-table.tsx index ae6a126..aa535f4 100644 --- a/src/components/users/user-table.tsx +++ b/src/components/users/user-table.tsx @@ -75,7 +75,7 @@ export function UserTable(props: { users: User[]; currentUserId: string; onRoleChange: (userId: string, role: Role) => Promise; - onPreferencesChange?: (userId: string, body: { theme?: UserTheme | null; language?: UserLanguage | null }) => Promise; + onPreferencesChange?: (userId: string, body: { theme?: UserTheme | ""; language?: UserLanguage | "" }) => Promise; }) { const t = useT(); const searchUser = (user: User, query: string) => diff --git a/src/lib/answer-sheet.test.ts b/src/lib/answer-sheet.test.ts new file mode 100644 index 0000000..af490dd --- /dev/null +++ b/src/lib/answer-sheet.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from "bun:test"; +import type { ExamQuestion, StudentAnswer } from "@/api/types"; +import { joinAnswerSheet } from "./answer-sheet"; + +function question(id: string, overrides: Partial = {}): ExamQuestion { + return { + id, + exam: "e1", + subject: "s1", + text: `Question ${id}`, + kind: "choice", + points: 10, + choices: ["a", "b"], + correct: 0, + ...overrides, + }; +} + +function answer(questionId: string, overrides: Partial = {}): StudentAnswer { + return { + question: questionId, + selected: 0, + text: null, + updated_at: 1, + is_correct: true, + ...overrides, + }; +} + +test("pairs each question with its answer by id, keeping question order", () => { + const rows = joinAnswerSheet( + [question("q1"), question("q2")], + [answer("q2", { selected: 1, is_correct: false }), answer("q1")], + ); + expect(rows.map((r) => r.question.id)).toEqual(["q1", "q2"]); + expect(rows[0].answer?.is_correct).toBe(true); + expect(rows[1].answer?.selected).toBe(1); +}); + +test("unanswered question yields a null answer", () => { + const rows = joinAnswerSheet([question("q1")], []); + expect(rows).toHaveLength(1); + expect(rows[0].answer).toBeNull(); +}); + +test("answers for deleted questions are dropped", () => { + const rows = joinAnswerSheet([question("q1")], [answer("gone")]); + expect(rows).toHaveLength(1); + expect(rows[0].answer).toBeNull(); +}); + +test("text answers carry the student's text through", () => { + const rows = joinAnswerSheet( + [question("q1", { kind: "text", choices: null, correct: null })], + [answer("q1", { selected: null, text: "my essay", is_correct: null })], + ); + expect(rows[0].answer?.text).toBe("my essay"); +}); diff --git a/src/lib/answer-sheet.ts b/src/lib/answer-sheet.ts new file mode 100644 index 0000000..27f8c31 --- /dev/null +++ b/src/lib/answer-sheet.ts @@ -0,0 +1,16 @@ +import type { ExamQuestion, StudentAnswer } from "@/api/types"; + +export type AnswerSheetRow = { + question: ExamQuestion; + answer: StudentAnswer | null; +}; + +/** Pair the exam's questions with a student's answers (`answer.question` → `question.id`). + * Unanswered questions get `answer: null`; answers to deleted questions are dropped. */ +export function joinAnswerSheet(questions: ExamQuestion[], answers: StudentAnswer[]): AnswerSheetRow[] { + const byQuestion = new Map(answers.map((answer) => [answer.question, answer])); + return questions.map((question) => ({ + question, + answer: byQuestion.get(question.id) ?? null, + })); +} diff --git a/src/lib/exam-labels.test.ts b/src/lib/exam-labels.test.ts new file mode 100644 index 0000000..e6414b7 --- /dev/null +++ b/src/lib/exam-labels.test.ts @@ -0,0 +1,14 @@ +import { expect, test } from "bun:test"; +import { attemptLabel } from "./exam-labels"; + +test("shows used/max when the exam caps attempts", () => { + expect(attemptLabel({ attempts_used: 1, attempt: 1 }, 3)).toBe("1 / 3"); +}); + +test("unlimited attempts (max 0) falls back to the attempt count", () => { + expect(attemptLabel({ attempts_used: 2, attempt: 2 }, 0)).toBe("2"); +}); + +test("no attempt data renders a dash", () => { + expect(attemptLabel({}, 3)).toBe("—"); +}); diff --git a/src/lib/exam-labels.ts b/src/lib/exam-labels.ts index b5bfe6a..e3decb8 100644 --- a/src/lib/exam-labels.ts +++ b/src/lib/exam-labels.ts @@ -15,3 +15,17 @@ const EXAM_KIND_LABELS: Record = { export function examKindLabel(kind: string, t: T): string { return kind in EXAM_KIND_LABELS ? t(EXAM_KIND_LABELS[kind as KnownExamKind]) : kind; } + +/** Attempts cell for the live monitor. `maxAttempts` comes from the monitored + * exam itself (the roster rows don't carry it); `0` means unlimited. */ +export function attemptLabel( + entry: { attempt?: number | null; attempts_used?: number | null }, + maxAttempts: number | null | undefined, +): string { + if (entry.attempts_used != null && maxAttempts != null && maxAttempts > 0) { + return `${entry.attempts_used} / ${maxAttempts}`; + } + if (entry.attempt != null) return String(entry.attempt); + if (entry.attempts_used != null) return String(entry.attempts_used); + return "—"; +} diff --git a/src/lib/exam-weight.test.ts b/src/lib/exam-weight.test.ts new file mode 100644 index 0000000..29fdfcb --- /dev/null +++ b/src/lib/exam-weight.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "bun:test"; +import { examWeight } from "./exam-weight"; + +const kinds = [ + { name: "quiz", weight: 2 }, + { name: "final", weight: 5 }, +]; + +test("a direct weight (marks report) wins over the settings lookup", () => { + expect(examWeight({ kind: "quiz", weight: 7 }, kinds)).toBe(7); +}); + +test("without a direct weight, the exam kind resolves through settings", () => { + expect(examWeight({ kind: "final" }, kinds)).toBe(5); +}); + +test("unknown kind and no weight yields null", () => { + expect(examWeight({ kind: "custom" }, kinds)).toBeNull(); + expect(examWeight({}, undefined)).toBeNull(); +}); diff --git a/src/pages/admin-users-page.tsx b/src/pages/admin-users-page.tsx index c4b2e9c..8b1d8a2 100644 --- a/src/pages/admin-users-page.tsx +++ b/src/pages/admin-users-page.tsx @@ -46,7 +46,7 @@ function AdminUsersContent() { } }; - const onPreferencesChange = async (userId: string, body: { theme?: UserTheme | null; language?: UserLanguage | null }) => { + const onPreferencesChange = async (userId: string, body: { theme?: UserTheme | ""; language?: UserLanguage | "" }) => { setError(""); try { await patchUserPreferences(userId, body); diff --git a/src/pages/course-detail-page.tsx b/src/pages/course-detail-page.tsx index c0b65ec..5f8cbd3 100644 --- a/src/pages/course-detail-page.tsx +++ b/src/pages/course-detail-page.tsx @@ -359,6 +359,7 @@ function CourseDetailContent() { id="edit-course-title" value={title()} required + maxlength={200} onInput={(e) => setTitle(e.currentTarget.value)} />
@@ -368,6 +369,7 @@ function CourseDetailContent() { id="edit-course-desc" value={description()} rows={3} + maxlength={2000} onInput={(e) => setDescription(e.currentTarget.value)} /> diff --git a/src/pages/live-monitor-page.tsx b/src/pages/live-monitor-page.tsx index 3933cbb..fd39f1b 100644 --- a/src/pages/live-monitor-page.tsx +++ b/src/pages/live-monitor-page.tsx @@ -17,6 +17,7 @@ import { IconChevronLeft } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import { usePreferences, useT } from "@/stores/preferences-context"; import { createNow } from "@/lib/create-now"; +import { attemptLabel } from "@/lib/exam-labels"; import { formatDateTime } from "@/lib/format"; const PAGE_SIZE = 10; @@ -84,13 +85,6 @@ function isLowRemaining(entry: LiveRosterEntry): boolean { return entry.status === "in_progress" && remaining <= 5 * 60 * 1000; } -function attemptLabel(entry: LiveRosterEntry, maxAttempts: number | null): string { - if (entry.attempts_used != null && maxAttempts != null) return `${entry.attempts_used} / ${maxAttempts}`; - if (entry.attempt != null) return String(entry.attempt); - if (entry.attempts_used != null) return String(entry.attempts_used); - return "—"; -} - function LiveMonitorContent() { const location = useLocation(); const params = useParams({ from: "/exams/$id/live" }); diff --git a/tsconfig.app.json b/tsconfig.app.json index fadb520..7fe3fe6 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -23,5 +23,6 @@ "@/*": ["./src/*"] } }, - "include": ["src"] + "include": ["src"], + "exclude": ["src/**/*.test.ts"] } diff --git a/tsconfig.json b/tsconfig.json index 5d48c38..a2e4d89 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,5 +22,6 @@ "@/*": ["./src/*"] } }, - "include": ["src"] + "include": ["src"], + "exclude": ["src/**/*.test.ts"] }