diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index c9f3232..ea65285 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -126,7 +126,7 @@ describe("client", () => { it("handles unknown messages with sentence case", () => { expect(formatApiErrorMessage("custom error occurred", "en")).toBe("Custom error occurred"); - expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı. Lütfen tekrar dene."); + expect(formatApiErrorMessage("custom error occurred", "tr")).toBe("İşlem tamamlanamadı: Custom error occurred"); }); }); @@ -150,7 +150,7 @@ describe("client", () => { it("formats generic Error", () => { expect(formatApiError(new Error("generic"), "en")).toBe("Generic"); - expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı. Lütfen tekrar dene."); + expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı: Generic"); }); }); }); diff --git a/src/api/client/client.ts b/src/api/client/client.ts index da96b3d..0e5c796 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -46,6 +46,38 @@ const API_ERROR_MESSAGES: Record> = { en: "This username is already in use.", tr: "Bu kullanıcı adı zaten kullanılıyor.", }, + "file too large": { + en: "This file is larger than the allowed upload limit.", + tr: "Bu dosya izin verilen yükleme sınırından büyük.", + }, + "payload too large": { + en: "This upload is too large. Choose a smaller file and try again.", + tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", + }, + "request entity too large": { + en: "This upload is too large. Choose a smaller file and try again.", + tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", + }, + "unsupported file type": { + en: "This file type is not supported.", + tr: "Bu dosya türü desteklenmiyor.", + }, + "unsupported image type": { + en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.", + tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.", + }, + "invalid image": { + en: "The image could not be read. Choose another image and try again.", + tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.", + }, + "too many files": { + en: "This note already has the maximum number of files.", + tr: "Bu notta en fazla dosya sayısına ulaşılmış.", + }, + "note file limit reached": { + en: "This note already has the maximum number of files.", + tr: "Bu notta en fazla dosya sayısına ulaşılmış.", + }, "course not found": { en: "Course not found.", tr: "Ders bulunamadı.", @@ -74,6 +106,22 @@ const API_ERROR_MESSAGES: Record> = { en: "This attempt is closed. Answers are read-only.", tr: "Bu oturum kapalı. Cevaplar salt okunur.", }, + "exam has not started": { + en: "This exam has not started yet.", + tr: "Bu sınav henüz başlamadı.", + }, + "exam has ended": { + en: "This exam has ended.", + tr: "Bu sınav sona erdi.", + }, + "no attempts left": { + en: "No attempts left for this exam.", + tr: "Bu sınav için deneme hakkı kalmadı.", + }, + "answer is required": { + en: "Enter an answer before saving.", + tr: "Kaydetmeden önce cevap gir.", + }, "only students can sit exams": { en: "Only students can take exams.", tr: "Sınava yalnızca öğrenciler girebilir.", @@ -90,6 +138,30 @@ const API_ERROR_MESSAGES: Record> = { en: "Only students can be marked on a lesson roll call.", tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.", }, + "event is full": { + en: "This event is full.", + tr: "Bu etkinlik dolu.", + }, + "registration is closed": { + en: "Registration is closed for this event.", + tr: "Bu etkinlik için kayıt kapalı.", + }, + "already registered": { + en: "This student is already registered.", + tr: "Bu öğrenci zaten kayıtlı.", + }, + "already enrolled": { + en: "This student is already enrolled.", + tr: "Bu öğrenci zaten kayıtlı.", + }, + "active pomodoro session already exists": { + en: "You already have a focus session running.", + tr: "Zaten devam eden bir odak oturumun var.", + }, + "no active pomodoro session": { + en: "There is no active focus session to finish.", + tr: "Bitirilecek aktif odak oturumu yok.", + }, }; function currentLocale(): Locale { @@ -118,6 +190,28 @@ function sentenceCase(message: string): string { return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); } +function errorMessageFromPayload(data: unknown, fallback: string): string { + if (!data || typeof data !== "object") return fallback; + const record = data as Record; + if (typeof record.error === "string") return record.error; + if (typeof record.message === "string") return record.message; + const detail = record.detail; + if (typeof detail === "string") return detail; + if (Array.isArray(detail)) { + return detail + .map((item) => { + if (!item || typeof item !== "object") return ""; + const row = item as Record; + const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : ""; + const msg = typeof row.msg === "string" ? row.msg : ""; + return loc && msg ? `${loc}: ${msg}` : msg; + }) + .filter(Boolean) + .join("; ") || fallback; + } + return fallback; +} + export async function client(path: string, options: RequestOptions = {}): Promise { const headers: Record = {}; let body: string | undefined; @@ -151,12 +245,7 @@ export async function client(path: string, options: RequestOptions = {}): Pro } if (!res.ok) { - const message = - data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" - ? (data as { error: string }).error - : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" - ? (data as { message: string }).message - : res.statusText || "Request failed"; + const message = errorMessageFromPayload(data, res.statusText || "Request failed"); let retryAfter: number | null = null; if (res.status === 429) { @@ -192,12 +281,7 @@ export async function formClient(path: string, body: FormData, signal?: Abort } if (!res.ok) { - const message = - data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" - ? (data as { error: string }).error - : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" - ? (data as { message: string }).message - : res.statusText || "Request failed"; + const message = errorMessageFromPayload(data, res.statusText || "Request failed"); throw new ApiError(res.status, message); } @@ -215,9 +299,7 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; return formatApiErrorMessage(err.message, locale); } diff --git a/src/components/exams/exam-room-ws.tsx b/src/components/exams/exam-room-ws.tsx index a1400b5..8ae6246 100644 --- a/src/components/exams/exam-room-ws.tsx +++ b/src/components/exams/exam-room-ws.tsx @@ -1,6 +1,7 @@ -import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createSignal, lazy, onCleanup } from "solid-js"; +import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createResource, createSignal, lazy, onCleanup } from "solid-js"; import { getExamAttempt } from "@/api/exams"; import { getExamAttemptQuestions } from "@/api/exams"; +import { getSettings } from "@/api/settings"; import { postExamAttempt } from "@/api/exams"; import { postExamAttemptAnswer } from "@/api/exams"; import { postExamAttemptFinish } from "@/api/exams"; @@ -20,6 +21,7 @@ import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/cn"; import { createNow } from "@/lib/create-now"; import { formatDateTime } from "@/lib/format"; +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { usePreferences, useT } from "@/stores/preferences-context"; // Lazy so the drawing pad rides its own chunk, off the exam room's initial load. @@ -56,7 +58,15 @@ export function ExamRoomWS(props: { exam: Exam }) { const [activeQuestionIndex, setActiveQuestionIndex] = createSignal(0); const [remainingMs, setRemainingMs] = createSignal(0); const [wsState, setWsState] = createSignal("disconnected"); + const [settings] = createResource(async () => { + try { + return await getSettings(); + } catch { + return null; + } + }); const now = createNow(); + const maxFileBytes = () => maxUploadBytes(settings()); const scheduled = createMemo(() => props.exam.mode === "sync" || props.exam.mode === "async" || props.exam.mode === "open"); const attemptStatus = createMemo(() => { const current = attempt(); @@ -238,6 +248,10 @@ export function ExamRoomWS(props: { exam: Exam }) { const saveAnswerImage = async (question: AttemptQuestion, file: File) => { setError(""); + if (file.size > maxFileBytes()) { + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); + return; + } setPending(true); try { await postExamAttemptAnswerImage(props.exam.id, question.id, file); diff --git a/src/components/exams/question-form.tsx b/src/components/exams/question-form.tsx index a7864a7..ab5c2a5 100644 --- a/src/components/exams/question-form.tsx +++ b/src/components/exams/question-form.tsx @@ -1,8 +1,9 @@ -import { For, Index, Show, Suspense, createEffect, createSignal, lazy } from "solid-js"; +import { For, Index, Show, Suspense, createEffect, createResource, createSignal, lazy } from "solid-js"; import { formatApiError } from "@/api/client"; import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; import { QUESTION_KINDS } from "@/api/client"; import { getExamQuestionImageBlob } from "@/api/exams"; +import { getSettings } from "@/api/settings"; import type { DrawScene } from "@/lib/draw-stroke"; import { Button } from "@/components/ui/button"; import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons"; @@ -11,6 +12,7 @@ import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/cn"; +import { formatBytes, maxUploadBytes } from "@/lib/upload-limits"; import { useT } from "@/stores/preferences-context"; // Lazy so the drawing pad rides its own chunk, off the exam editor's initial load. @@ -47,6 +49,14 @@ export function QuestionForm(props: { const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); + const [settings] = createResource(async () => { + try { + return await getSettings(); + } catch { + return null; + } + }); + const maxFileBytes = () => maxUploadBytes(settings()); createEffect(() => { const initial = props.initial; @@ -99,7 +109,27 @@ export function QuestionForm(props: { setChoices((current) => current.map((choice, i) => (i === index ? value : choice))); }; + const validImage = (file: File | null): file is File => { + if (!file) return false; + if (file.size <= maxFileBytes()) return true; + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); + return false; + }; + + const setQuestionImage = (file: File | null) => { + if (!file) { + setImage(null); + return; + } + setError(""); + if (validImage(file)) setImage(file); + }; + const setChoiceImage = (index: number, file: File | null) => { + if (file) { + setError(""); + if (!validImage(file)) return; + } setChoiceImages((current) => choices().map((_, i) => (i === index ? file : current[i] ?? null))); }; @@ -190,7 +220,7 @@ export function QuestionForm(props: { type="file" accept="image/png,image/jpeg,image/webp,image/gif" class="sr-only" - onChange={(event) => setImage(event.currentTarget.files?.[0] ?? null)} + onChange={(event) => setQuestionImage(event.currentTarget.files?.[0] ?? null)} />