diff --git a/docs/navigation-patterns.md b/docs/navigation-patterns.md index e602535..36c0910 100644 --- a/docs/navigation-patterns.md +++ b/docs/navigation-patterns.md @@ -50,6 +50,13 @@ Pagination and request rules: - If a page intentionally fetches the full list and paginates in memory, document that the expected dataset is small or temporary. - Search/filter/sort UI should match the request model: server-side controls for server-paginated lists, client-side controls only for accepted small lists. +Question bank rules: + +- The question bank (`/question-bank`, teacher+) lives in the **classes** nav group next to Exams, and is a full page because it is a durable, browsable school-wide resource. +- Its list is server-paginated/filtered (`limit`/`offset`, owner/subject/visibility/`q`); every filter or search change resets to the first page, and a delete that empties the last page clamps the page index back so the user is never left on a page with no pagination controls. +- Creating and editing a template uses a `SidePanel` from the table header; deleting uses a confirm dialog. +- Templates are private by default; exam ↔ bank transfers are copies, never links. + Table action rules: - Row actions use `TableRowActions` with a centered three-dot trigger. diff --git a/docs/role-scope-matrix.md b/docs/role-scope-matrix.md index 44d4bf8..03cea9f 100644 --- a/docs/role-scope-matrix.md +++ b/docs/role-scope-matrix.md @@ -14,6 +14,7 @@ | Exam detail `/exams/:id` | ✅ | ✅ | ✅ | ✅ | | Exam room `/exam-room/:id` | ✅ | ❌ | ❌ | ❌ | | Live monitor `/exams/:id/live` | ❌ | ✅ | ✅ | ✅ | +| Question bank `/question-bank` | ❌ | ✅ | ✅ | ✅ | | Events `/events` | ✅ | ✅ | ✅ | ✅ | | Event detail `/events/:id` | ✅ | ✅ | ✅ | ✅ | | Appointments `/appointments` | ✅ (book + own) | ✅ (publish/manage own) | ✅ (manage all) | ✅ (manage all) | @@ -32,6 +33,7 @@ | Sidebar group / item | Student | Teacher | Manager | Admin | |---|---|---|---|---| | **classes** — Courses / Exams / Events / exam grades | ✅ | ✅ | ✅ | ✅ | +| **classes** — Question bank (`/question-bank`) | ❌ | ✅ | ✅ | ✅ | | **grades** — Defter (`/notes`) | ✅ | ✅ | ✅ | ✅ | | **community** — Messages / Question pool | ✅ | ✅ | ✅ | ✅ | | **students** — My attendance (`/attendance`) | ✅ | ✅ | ✅ | ✅ | @@ -82,6 +84,8 @@ | Write exam questions | ❌ | ✅ (course manager) | ✅ | ✅ | +| Create bank templates | ❌ | ✅ (course manager) | ✅ | ✅ | +| Edit / delete bank templates | ❌ | ✅ (own only) | ✅ (own only) | ✅ (any) | | Start / finish own pomodoro focus session | ✅ | ❌ | ❌ | ❌ | | Read answer sheets | ❌ | ✅ (course manager) | ✅ | ✅ | | Watch live monitor | ❌ | ✅ (course manager) | ✅ | ✅ | diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index 513adf1..962d32a 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -64,6 +64,76 @@ describe("client", () => { }); }); + describe("client() timeout", () => { + // hang until whatever signal fetch was given aborts + const hangingFetch = () => + vi.spyOn(globalThis, "fetch").mockImplementation( + (_url, init?: RequestInit) => + new Promise((_resolve, reject) => { + const signal = init?.signal; + if (!signal) return; // no deadline at all -> test times out, which is the bug + signal.addEventListener("abort", () => reject(signal.reason)); + }), + ); + + it("fails a hung request as a localized ApiError instead of hanging forever", async () => { + // shrink the real deadline; everything else (AbortSignal.any, the catch) runs for real + const realTimeout = AbortSignal.timeout.bind(AbortSignal); + vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5)); + hangingFetch(); + await expect(client("/slow")).rejects.toMatchObject({ name: "ApiError", status: 408 }); + try { + await client("/slow"); + } catch (err) { + expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene."); + expect(formatApiError(err, "en")).toBe("The server did not respond in time. Check your connection and try again."); + } + }); + + // headers arrive promptly, the body stalls — the multi-MB shell feed on a + // school connection. The deadline lands while res.text() is streaming. + const stallingBodyFetch = () => + vi.spyOn(globalThis, "fetch").mockImplementation((_url, init?: RequestInit) => { + const signal = init?.signal; + const stream = new ReadableStream({ + start(ctrl) { + ctrl.enqueue(new TextEncoder().encode('{"items":[')); + signal?.addEventListener("abort", () => ctrl.error(signal.reason)); + }, + }); + return Promise.resolve(new Response(stream, { status: 200 })); + }); + + it("fails a timeout during body streaming as ApiError 408, not a raw DOMException", async () => { + const realTimeout = AbortSignal.timeout.bind(AbortSignal); + vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5)); + stallingBodyFetch(); + await expect(client("/big-feed")).rejects.toMatchObject({ name: "ApiError", status: 408 }); + try { + await client("/big-feed"); + } catch (err) { + expect(formatApiError(err, "tr")).toBe("Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene."); + } + }); + + it("still surfaces a caller abort mid-body as AbortError, not a timeout", async () => { + stallingBodyFetch(); + const ctrl = new AbortController(); + const pending = client("/big-feed", { signal: ctrl.signal }); + await Promise.resolve(); + ctrl.abort(); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); + }); + + it("still surfaces a caller abort as AbortError, not a timeout", async () => { + hangingFetch(); + const ctrl = new AbortController(); + const pending = client("/slow", { signal: ctrl.signal }); + ctrl.abort(); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); + }); + }); + describe("formClient()", () => { it("makes POST request with FormData", async () => { mockFetchSuccess({ ok: true }); @@ -197,6 +267,58 @@ describe("client", () => { expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found."); }); + it("prefers the table entry over the per-status generic message", () => { + // the whole 403 table was dead code: every 403 rendered "forbidden" + expect(formatApiError(new ApiError(403, "only the template's owner or an admin can change it"), "tr")).toBe( + "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", + ); + expect( + formatApiError(new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can author questions"), "tr"), + ).toBe("Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir."); + expect( + formatApiError( + new ApiError(403, "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank"), + "en", + ), + ).toBe("Only this course's teachers or a manager can save this question to the bank."); + // same ordering bug shape for 404 ("course not found" / "exam not found") + expect(formatApiError(new ApiError(404, "exam not found"), "tr")).toBe("Sınav bulunamadı."); + expect(formatApiError(new ApiError(404, "course not found"), "en")).toBe("Course not found."); + // unmatched messages still fall back to the generic per-status message + expect(formatApiError(new ApiError(403, "some brand new refusal"), "tr")).toBe("Bu işlem için yetkin yok."); + expect(formatApiError(new ApiError(404, ""), "en")).toBe("The requested record was not found."); + }); + + it("localizes appointment booking and decision conflicts", () => { + // exact backend strings from domain/appointment.rs — a miss renders + // "İşlem tamamlanamadı: " + const cases: Array<[string, string]> = [ + ["the slot is already booked", "Bu saati senden önce başkası aldı."], + ["the slot has already started", "Bu saat başladığı için artık randevu alınamaz."], + ["you already have an appointment at that time", "O saatte zaten bir randevun var."], + ["the appointment is already settled", "Bu randevu zaten sonuçlanmış."], + ["the appointment has already started", "Bu randevu çoktan başladı."], + ["that time has already started", "O saat çoktan başladı. Daha ileri bir saat seç."], + ["no time has been proposed", "Bu randevu için henüz bir saat önerilmedi."], + ["the appointment is no longer pending", "Bu randevu artık yanıt bekliyor değil."], + ]; + for (const [backend, turkish] of cases) { + expect(formatApiError(new ApiError(409, backend), "tr")).toBe(turkish); + expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/^İşlem/); + expect(formatApiErrorMessage(backend, "en")).toMatch(/\.$/); + } + }); + + it("localizes the refresh-from-bank validation error", () => { + // ValidationError::Invalid renders "{field}: {reason}" (web/exams.rs:2013) + expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "tr")).toBe( + "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.", + ); + expect(formatApiError(new ApiError(400, "question: this question did not come from a bank template"), "en")).toBe( + "This question was not copied from a bank template, so there is nothing to refresh it from.", + ); + }); + it("formats 500+", () => { expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again."); expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene."); diff --git a/src/api/client/client.ts b/src/api/client/client.ts index 375275d..163facd 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -21,6 +21,11 @@ type RequestOptions = { const API_PREFIX = "/api"; +// Deadline for a JSON request. Generous enough for the slowest real call +// (login's Argon2 hash under load), short enough that a hung socket surfaces +// as an error instead of a permanently disabled button. +const REQUEST_TIMEOUT_MS = 20_000; + const API_ERROR_MESSAGES: Record> = { // Settings lists reject two entries that fold to the same word — İZİN/izin, // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed. @@ -100,6 +105,47 @@ const API_ERROR_MESSAGES: Record> = { en: "The repeated slots overlap each other.", tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", }, + // Booking/decision conflicts from domain/appointment.rs — byte-exact. + "the slot is already booked": { + en: "Someone else booked this time first.", + tr: "Bu saati senden önce başkası aldı.", + }, + "the slot has already started": { + en: "This time has already started, so it can no longer be booked.", + tr: "Bu saat başladığı için artık randevu alınamaz.", + }, + "you already have an appointment at that time": { + en: "You already have an appointment at that time.", + tr: "O saatte zaten bir randevun var.", + }, + "the appointment is already settled": { + en: "This appointment is already settled.", + tr: "Bu randevu zaten sonuçlanmış.", + }, + "the appointment has already started": { + en: "This appointment has already started.", + tr: "Bu randevu çoktan başladı.", + }, + "that time has already started": { + en: "That time has already started. Pick a later one.", + tr: "O saat çoktan başladı. Daha ileri bir saat seç.", + }, + "no time has been proposed": { + en: "No time has been proposed for this appointment yet.", + tr: "Bu randevu için henüz bir saat önerilmedi.", + }, + "the appointment is no longer pending": { + en: "This appointment is no longer waiting for an answer.", + tr: "Bu randevu artık yanıt bekliyor değil.", + }, + "question: this question did not come from a bank template": { + en: "This question was not copied from a bank template, so there is nothing to refresh it from.", + tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.", + }, + "request timed out": { + en: "The server did not respond in time. Check your connection and try again.", + tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.", + }, "only the template's owner or an admin can change it": { en: "Only the teacher who created this template (or an admin) can change it.", tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", @@ -294,20 +340,42 @@ export async function client(path: string, options: RequestOptions = {}): Pro body = JSON.stringify(options.body); } - const res = await fetch(`${API_PREFIX}${path}`, { - method: options.method ?? "GET", - headers, - body, - credentials: "same-origin", - signal: options.signal, - cache: options.cache, - }); + // JSON calls only — uploads (formClient) and downloads (blobClient) stay + // untimed. Without this a dead connection leaves callers (exam-room REST + // autosave) stuck on "saving…" until the browser gives up. + const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS); + // Caller-initiated aborts keep their original AbortError so cancellation + // handling upstream is untouched; only our own deadline becomes an ApiError. + const asDeadlineError = (err: unknown) => + timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err; + + let res: Response; + try { + res = await fetch(`${API_PREFIX}${path}`, { + method: options.method ?? "GET", + headers, + body, + credentials: "same-origin", + signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout, + cache: options.cache, + }); + } catch (err) { + throw asDeadlineError(err); + } if (res.status === 204) { return undefined as T; } - const text = await res.text(); + // The deadline aborts the body stream too, so headers can arrive in time and + // res.text() still blow up mid-download on a multi-MB response. + let text: string; + try { + text = await res.text(); + } catch (err) { + throw asDeadlineError(err); + } + let data: unknown = null; if (text) { try { @@ -398,12 +466,14 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()): if ((err.status === 429 || err.status === 503) && err.retryAfter != null) { return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`; } + // The specific backend message wins over the per-status generic one — + // otherwise every 401/403/404/413/5xx entry in the table is dead code. + const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale]; + if (known) return known; if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale]; if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale]; - if (err.status === 409) return formatApiErrorMessage(err.message, locale); if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale]; - if (err.status === 422) return formatApiErrorMessage(err.message, locale); if (err.status >= 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/api/client/types.ts b/src/api/client/types.ts index 3ee2564..832e533 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -107,7 +107,8 @@ export type Appointment = { requester: PersonRef; status: AppointmentStatus; reason: string; - starts_at: number | null; // effective window (proposal if accepted, else slot's) + starts_at: number | null; // effective window: the proposal whenever one is on the + // row (accepted or not), else the slot's own time ends_at: number | null; proposed_starts_at: number | null; proposed_ends_at: number | null; diff --git a/src/components/appointments/publish-slots-form.tsx b/src/components/appointments/publish-slots-form.tsx index a5c41d2..51a303b 100644 --- a/src/components/appointments/publish-slots-form.tsx +++ b/src/components/appointments/publish-slots-form.tsx @@ -36,7 +36,8 @@ export function PublishSlotsForm(props: { const validate = (starts: number | null, ends: number | null, until: number | null): string | null => { if (starts == null || ends == null) return t("form.timeOrder"); - if (ends < starts) return t("form.timeOrder"); + // `check_window` rejects `starts >= ends` (400) — a zero-length slot is not a window. + if (ends <= starts) return t("form.timeOrder"); const grace = now() - 60_000; if (starts < grace || ends < grace) return t("form.timePast"); if (repeatWeekly()) { diff --git a/src/components/appointments/reschedule-form.tsx b/src/components/appointments/reschedule-form.tsx index f32b59f..0c9ac00 100644 --- a/src/components/appointments/reschedule-form.tsx +++ b/src/components/appointments/reschedule-form.tsx @@ -26,7 +26,8 @@ export function RescheduleForm(props: { e.preventDefault(); const starts_at = dateTimeInputToMs(startsDate(), startsTime()); const ends_at = dateTimeInputToMs(endsDate(), endsTime()); - if (starts_at == null || ends_at == null || ends_at < starts_at) { + // `propose` rejects `starts_at >= ends_at` (400 "must be after proposed_starts_at"). + if (starts_at == null || ends_at == null || ends_at <= starts_at) { setError(t("form.timeOrder")); return; } diff --git a/src/components/exams/exam-room-ws.tsx b/src/components/exams/exam-room-ws.tsx index 704ba92..84b1160 100644 --- a/src/components/exams/exam-room-ws.tsx +++ b/src/components/exams/exam-room-ws.tsx @@ -147,7 +147,7 @@ export function ExamRoomWS(props: { exam: Exam }) { ws.onerror = null; ws.onmessage = null; ws.close(); - acks.failAll(new Error(t("attempt.saveDisconnected"))); + acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); } setWsState("connecting"); const socket = new WebSocket(wsUrl()); @@ -161,7 +161,7 @@ export function ExamRoomWS(props: { exam: Exam }) { setWsState("disconnected"); ws = null; // Anything still waiting for a `saved` frame will never get one. - acks.failAll(new Error(t("attempt.saveDisconnected"))); + acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); scheduleReconnect(); }; socket.onclose = dropped; @@ -215,11 +215,13 @@ export function ExamRoomWS(props: { exam: Exam }) { case "error": { const message = formatApiErrorMessage(msg.message, locale()); setError(message); - // A frame that names a question refused that one save; anything else - // is room- or connection-level (bad frame, sitting over, unenrolled), - // so everything in flight is treated as rejected — never as saved. + // A frame that names a question refused that one save; anything else is + // room-level (bad frame, sitting over, unenrolled, internal error), so + // everything in flight is treated as rejected — never as saved. The + // socket stays open on this path, so each rejected send is still owed a + // frame of its own: `error-frame` keeps that debt instead of wiping it. if (msg.question_id) acks.fail(msg.question_id, new Error(message)); - else acks.failAll(new Error(message)); + else acks.failAll(new Error(message), "error-frame"); break; } } @@ -299,10 +301,13 @@ export function ExamRoomWS(props: { exam: Exam }) { } else { await postExamAttemptAnswer(props.exam.id, { question_id: question.id, text: value }); } - const next = await getExamAttempt(props.exam.id); - setAttempt(next); - const qs = await getExamAttemptQuestions(props.exam.id); - setQuestions(qs); + // The POST above is the save. Refreshing is only about the badges, so a + // failed refresh must not report a stored answer as lost. + try { + await refreshAnswers(); + } catch { + // ignore — the countdown/updated_at catch up on the next poll + } return true; } catch (err) { setError(formatApiError(err, locale())); @@ -735,13 +740,19 @@ function QuestionAnswerCardWS(props: { // "Saved" means the server said so. A failure leaves the typed/picked answer // untouched in the card so the student can just press save again. const save = async () => { + // The card is reused across questions, and switching question resets + // `saveState` — so an outcome that lands after the switch would paint a + // badge for a question it never belonged to. Only the question that started + // this save may be told about it. + const savedId = props.question.id; setSaveState("saving"); try { const confirmed = await props.onSave(value()); - if (!confirmed) return; // a newer save owns the outcome + if (!confirmed || props.question.id !== savedId) return; // a newer save owns the outcome setSaveState("saved"); props.onSaved?.(); } catch { + if (props.question.id !== savedId) return; setSaveState("failed"); // the parent banner carries the reason } }; diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index 983bd80..a15c0b3 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -203,10 +203,12 @@ export function AppShell(props: ParentProps) { - + {/* MobileTabBar stays inside the provider — it is a shell surface, so a + useShellFeed() badge there must not throw. */} setMobileOpen(true)} /> + (() => { const list: NotificationItem[] = []; - // 1. Unread Messages — shared inbox is the full list, filter to unread here - // (was a dedicated read:false fetch before the shell feed consolidation). - const msgs = feed.messages().items.filter((m) => !m.read); + // 1. Unread messages — the dedicated `read=false` page from the shell feed. + // Never filter the shared inbox page instead: it is capped and ordered by + // id DESC, so an older unread message is simply not in it. + const msgs = feed.unreadMessages().items; for (const m of msgs) { list.push({ id: `msg_${m.id}`, @@ -143,7 +144,26 @@ export function NotificationCenter() { return allNotifications().filter((item) => !dismissed.has(item.id)); }); - const unreadCount = () => activeNotifications().length; + // The list only holds the newest 10 unread messages; `total` is the real + // server-side unread count, so the rest still counts towards the badge. + // Those extra rows have no id here, so they cannot be dismissed one by one: + // "dismiss all" snapshots the unread total instead. Everything at or below the + // snapshot counts as dismissed; anything above it arrived afterwards and still + // raises the badge (minus the new rows already listed, which the active list + // counts). Without the snapshot, 11 unread → dismiss all → badge stuck at 1 + // over an empty popover. + // ponytail: the snapshot is in-memory while dismissed ids are persisted, so a + // reload re-shows unlisted unread — upgrade path is storing it next to the ids + // in `lib/notifications`. + const [dismissedUnreadTotal, setDismissedUnreadTotal] = createSignal(0); + const activeMessageCount = () => activeNotifications().filter((item) => item.type === "message").length; + const unlistedUnread = () => { + const page = feed.unreadMessages(); + const beyondPage = page.total - page.items.length; + const sinceDismissAll = page.total - dismissedUnreadTotal() - activeMessageCount(); + return Math.max(0, Math.min(beyondPage, sinceDismissAll)); + }; + const unreadCount = () => activeNotifications().length + unlistedUnread(); const handleDismissSingle = (evt: MouseEvent, id: string) => { evt.stopPropagation(); @@ -155,6 +175,7 @@ export function NotificationCenter() { const ids = activeNotifications().map((item) => item.id); const updated = dismissAllNotificationIds(ids); setDismissedIds(new Set(updated)); + setDismissedUnreadTotal(feed.unreadMessages().total); }; const handleSelectNotification = async (item: NotificationItem) => { diff --git a/src/components/layout/right-nav.tsx b/src/components/layout/right-nav.tsx index 6b65208..36e0694 100644 --- a/src/components/layout/right-nav.tsx +++ b/src/components/layout/right-nav.tsx @@ -17,7 +17,8 @@ import { IconX, } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; -import { personLabel } from "@/lib/person"; +import { appointmentCounterpart, personLabel } from "@/lib/person"; +import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; import { useShellFeed } from "@/stores/shell-feed-context"; @@ -35,6 +36,7 @@ export function RightNav() { const location = useLocation(); const { locale } = usePreferences(); const feed = useShellFeed(); + const auth = useAuth(); const isMessagesActive = () => location().pathname === "/messages"; const isCalendarActive = () => location().pathname === "/calendar"; @@ -63,7 +65,11 @@ export function RightNav() { // on every 60s refetch and — since RightNav sits beside in AppShell — // blanks the whole page for the fetch duration. `.latest` keeps the last value. const allMessages = () => feed.messages().items; - const unreadCount = createMemo(() => allMessages().filter((m: Message) => !m.read).length); + // Same source of truth as NotificationCenter: the dedicated `read=false` page, + // whose `total` is the exact server-side unread count. The inbox page above is + // capped at 100 and ordered by id DESC, so filtering it silently drops older + // unread messages and the two shell badges disagree. + const unreadCount = createMemo(() => feed.unreadMessages().total); const filteredMessages = createMemo(() => { let list = allMessages(); @@ -599,8 +605,7 @@ export function RightNav() { const isEvent = item.type === "event"; const isAppt = item.type === "appointment"; const title = item.type === "appointment" - ? ((item.data.teacher?.display_name ?? item.data.teacher?.username) - ?? item.data.requester.display_name ?? item.data.requester.username) + ? appointmentCounterpart(item.data, auth.user()?.id) : item.data.title; return (
(cur.type === "appointment" ? cur.data : null); const title = () => { const a = appt(); - if (a) return (a.teacher?.display_name ?? a.teacher?.username) ?? a.requester.display_name ?? a.requester.username; + if (a) return appointmentCounterpart(a, auth.user()?.id); return (cur.data as Event | Exam).title; }; return ( diff --git a/src/components/layout/shell-unread-badge.test.tsx b/src/components/layout/shell-unread-badge.test.tsx new file mode 100644 index 0000000..821b306 --- /dev/null +++ b/src/components/layout/shell-unread-badge.test.tsx @@ -0,0 +1,93 @@ +import { createSignal } from "solid-js"; +import { fireEvent, render, screen } from "@solidjs/testing-library"; +import { NotificationCenter } from "@/components/layout/notification-center"; +import { RightNav } from "@/components/layout/right-nav"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +// The shell feed is the single source of truth for both badges; the test drives +// it through signals so a refetch (new message arriving) is reproducible. +const h = vi.hoisted(() => ({ feed: null as never })); + +vi.mock("@/stores/shell-feed-context", () => ({ useShellFeed: () => h.feed })); +vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user: () => ({ id: "u-1" }) }) })); +vi.mock("@tanstack/solid-router", () => ({ + useNavigate: () => () => {}, + useLocation: () => () => ({ pathname: "/" }), +})); +// Kobalte's popover keeps its content unmounted in jsdom; the badge and the +// "dismiss all" button are the surfaces under test, so render both inline. +vi.mock("@/components/ui/popover", () => ({ + Popover: (props: never) => (props as { children: unknown }).children, + PopoverTrigger: (props: never) =>
{(props as { children: unknown }).children}
, + PopoverContent: (props: never) =>
{(props as { children: unknown }).children}
, +})); + +const emptyPage = { items: [], total: 0, limit: null, offset: 0 }; +const msg = (id: string) => ({ + id, + sender: { id: "s", name: "Ada", surname: "L" }, + subject: `subject ${id}`, + body: "", + read: false, + sent_at: 1, +}); + +function mountFeed(inbox: unknown[], unread: { items: unknown[]; total: number }) { + const [messages, setMessages] = createSignal({ ...emptyPage, items: inbox, total: inbox.length }); + const [unreadMessages, setUnreadMessages] = createSignal({ ...emptyPage, ...unread }); + h.feed = { + messages, + unreadMessages, + events: () => emptyPage, + exams: () => emptyPage, + appointments: () => emptyPage, + homework: () => emptyPage, + nowMs: () => Date.now(), + refetchMessages: () => {}, + refreshAll: () => {}, + } as never; + return { setMessages, setUnreadMessages }; +} + +const badges = () => Array.from(document.querySelectorAll(".bg-rose-500")).map((n) => n.textContent); + +beforeEach(() => localStorage.clear()); +afterEach(() => vi.restoreAllMocks()); + +// DEFECT 1: RightNav used to filter the capped `limit:100` inbox page, so an +// unread message that fell off that page was counted by one badge only. +test("both shell badges report the same unread count", () => { + // 7 unread server-side, but only 2 of them are on the capped inbox page. + mountFeed([msg("m6"), msg("m7")], { items: [msg("m3"), msg("m6"), msg("m7")], total: 7 }); + + render(() => ( + + + + + )); + + expect(badges()).toEqual(["7", "7"]); +}); + +// DEFECT 2: unlisted unread ignored dismissal, so dismiss-all left the badge +// stuck at (total - listed) over an empty popover. +test("dismiss all clears the badge, a later message raises it again", () => { + const listed = Array.from({ length: 10 }, (_, i) => msg(`m${i}`)); + const { setUnreadMessages } = mountFeed([], { items: listed, total: 11 }); + + render(() => ( + + + + )); + + expect(badges()).toEqual(["9+"]); + + fireEvent.click(screen.getByTitle("Tüm Bildirimleri Temizle")); + expect(badges()).toEqual([]); + + // A genuinely new message pushes the oldest listed one off the page. + setUnreadMessages({ ...emptyPage, items: [msg("new"), ...listed.slice(0, 9)], total: 12 }); + expect(badges()).toEqual(["1"]); +}); diff --git a/src/lib/appointment-actions.test.ts b/src/lib/appointment-actions.test.ts new file mode 100644 index 0000000..22c3e44 --- /dev/null +++ b/src/lib/appointment-actions.test.ts @@ -0,0 +1,65 @@ +import type { Appointment, AppointmentStatus } from "@/api/client"; +import { appointmentActions, hasStandingProposal } from "./appointment-actions"; + +const NOW = 1_800_000_000_000; +const FUTURE = NOW + 60 * 60 * 1000; +const PAST = NOW - 60 * 60 * 1000; + +const appt = (status: AppointmentStatus, opts: { proposed?: boolean; startsAt?: number | null } = {}): Appointment => + ({ + id: "a1", + slot: "s1", + teacher: null, + requester: { id: "u1", username: "ali", display_name: null }, + status, + reason: "ödev", + starts_at: opts.startsAt === undefined ? FUTURE : opts.startsAt, + ends_at: FUTURE + 1000, + proposed_starts_at: opts.proposed ? FUTURE : null, + proposed_ends_at: opts.proposed ? FUTURE + 1000 : null, + proposed_by: null, + decided_by: null, + cancelled_by: null, + cancel_reason: null, + reject_reason: null, + created_at: PAST, + }) as Appointment; + +it("counts a proposal as standing only while the row is still pending", () => { + expect(hasStandingProposal(appt("pending", { proposed: true }))).toBe(true); + // The backend never clears proposed_* on accept — an approved row with a + // proposal is an ANSWERED one, so the teacher keeps their reschedule action. + expect(hasStandingProposal(appt("approved", { proposed: true }))).toBe(false); + expect(hasStandingProposal(appt("cancelled", { proposed: true }))).toBe(false); +}); + +it("offers staff exactly what the backend accepts", () => { + expect(appointmentActions(appt("pending"), "staff", NOW)).toEqual(["approve", "reject", "reschedule"]); + // Standing proposal: no self-approval of one's own counter-proposal, but the + // teacher can still withdraw it (reject) or propose again. + expect(appointmentActions(appt("pending", { proposed: true }), "staff", NOW)).toEqual(["reject", "reschedule"]); + // Answered proposal: reschedule must come back (the old `proposed_* != null` + // gate lost it forever after one accepted reschedule). + expect(appointmentActions(appt("approved", { proposed: true }), "staff", NOW)).toEqual(["reschedule"]); + expect(appointmentActions(appt("approved"), "staff", NOW)).toEqual(["reschedule"]); + // Window opened: approve 409s ("that time has already started"), reject does not. + expect(appointmentActions(appt("pending", { startsAt: PAST }), "staff", NOW)).toEqual(["reject", "reschedule"]); + expect(appointmentActions(appt("rejected"), "staff", NOW)).toEqual([]); + expect(appointmentActions(appt("cancelled"), "staff", NOW)).toEqual([]); +}); + +it("offers the requester exactly what the backend accepts", () => { + expect(appointmentActions(appt("pending"), "requester", NOW)).toEqual(["cancel"]); + expect(appointmentActions(appt("approved"), "requester", NOW)).toEqual(["cancel"]); + expect(appointmentActions(appt("pending", { proposed: true }), "requester", NOW)).toEqual([ + "acceptReschedule", + "declineReschedule", + ]); + // Started windows: cancel/accept/decline all 409. + expect(appointmentActions(appt("approved", { startsAt: PAST }), "requester", NOW)).toEqual([]); + expect(appointmentActions(appt("pending", { proposed: true, startsAt: PAST }), "requester", NOW)).toEqual([]); + // Slot vanished -> every call 404s. + expect(appointmentActions(appt("pending", { startsAt: null }), "requester", NOW)).toEqual([]); + expect(appointmentActions(appt("cancelled"), "requester", NOW)).toEqual([]); + expect(appointmentActions(appt("rejected"), "requester", NOW)).toEqual([]); +}); diff --git a/src/lib/appointment-actions.ts b/src/lib/appointment-actions.ts new file mode 100644 index 0000000..41ecb41 --- /dev/null +++ b/src/lib/appointment-actions.ts @@ -0,0 +1,71 @@ +/** + * Which appointment actions the backend will actually accept, per viewer. + * + * Mirrors the guards in `hezarfen_backend/src/web/appointments.rs` and + * `src/domain/appointment.rs`. This app serves children: an action must never + * be offered when the server is going to answer 403/409. + */ +import type { Appointment } from "@/api/client"; + +export type AppointmentAction = + // staff = the slot's teacher, or any manager+ (`can_manage`) + | "approve" + | "reject" + | "reschedule" + // requester = the person who asked for the meeting (`ensure_requester`) + | "cancel" + | "acceptReschedule" + | "declineReschedule"; + +export type AppointmentViewer = "staff" | "requester"; + +/** + * A counter-proposal still waiting for the requester's answer. + * + * The backend NEVER clears `proposed_*` — `accept_proposal` delegates to + * `approve`, which writes `status`/`decided_by` only. So `proposed_* != null` + * on a settled or approved row is an *answered* proposal, not a standing one, + * and gating on it would strand the teacher without a reschedule action forever. + */ +export function hasStandingProposal(a: Appointment): boolean { + return a.status === "pending" && a.proposed_starts_at != null && a.proposed_ends_at != null; +} + +const isLive = (a: Appointment) => a.status === "pending" || a.status === "approved"; + +/** + * Has the *effective* window opened? `starts_at` is already the effective one + * (`Appointment::window` prefers a proposal whenever the row carries one), which + * is exactly the value every `<= now` 409 guard compares. `null` means the slot + * is gone, so every action would 404 — treat it as closed. + */ +const hasStarted = (a: Appointment, now: number) => a.starts_at == null || a.starts_at <= now; + +export function appointmentActions(a: Appointment, viewer: AppointmentViewer, now: number): AppointmentAction[] { + const standing = hasStandingProposal(a); + const actions: AppointmentAction[] = []; + if (viewer === "staff") { + // `approve` needs pending + a window that has not opened. While the + // teacher's own counter-proposal stands the backend would still take it, + // but accepting it is the requester's call — we do not offer a way to move + // someone else's meeting without their answer. + if (a.status === "pending" && !standing && !hasStarted(a, now)) actions.push("approve"); + // `reject` is guarded by `read_pending` alone — no time check — so a passed + // pending request (or a standing proposal the teacher wants back) can + // always be turned down. + if (a.status === "pending") actions.push("reject"); + // `propose` needs a live row only; the *new* time must be in the future, + // which the reschedule form validates. Re-proposing over an answered or a + // standing proposal is legal. + if (isLive(a)) actions.push("reschedule"); + return actions; + } + // Requester side. Accepting is `approve` at the proposed time and declining + // is `cancel`, so both close once that window opens. + if (standing) { + if (!hasStarted(a, now)) actions.push("acceptReschedule", "declineReschedule"); + return actions; + } + if (isLive(a) && !hasStarted(a, now)) actions.push("cancel"); + return actions; +} diff --git a/src/lib/create-ack-waiter.test.ts b/src/lib/create-ack-waiter.test.ts index b2bc1f7..e1c59b1 100644 --- a/src/lib/create-ack-waiter.test.ts +++ b/src/lib/create-ack-waiter.test.ts @@ -27,12 +27,51 @@ describe("createAckWaiter", () => { const w = createAckWaiter(1000); const a = w.wait("q1"); const b = w.wait("q2"); - w.failAll(new Error("disconnected")); + w.failAll(new Error("disconnected"), "socket-closed"); await expect(a).rejects.toThrow("disconnected"); await expect(b).rejects.toThrow("disconnected"); expect(w.size).toBe(0); }); + // Regression (defect 1): an unattributed error frame does NOT close the socket + // (`exam_ws.rs:496` keeps serving), so the frames owed to the sends it rejected + // are still on their way. One of them must not confirm the student's retry. + it("does not let an in-flight ack confirm the retry after an unattributed error frame", async () => { + const w = createAckWaiter(1000); + const first = w.wait("q1"); + const firstAssertion = expect(first).rejects.toThrow("state unavailable"); + w.failAll(new Error("state unavailable"), "error-frame"); // socket stays open + await firstAssertion; + + const retry = w.wait("q1"); + let outcome: string | undefined; + void retry.then( + (r) => { outcome = `resolved:${r}`; }, + (e: Error) => { outcome = `rejected:${e.message}`; }, + ); + w.ack("q1"); // the FIRST send's `saved` frame, still in flight + await Promise.resolve(); + expect(outcome).toBeUndefined(); // must NOT claim the retry was saved + + w.ack("q1"); // now the retry's own frame + await expect(retry).resolves.toBe("ok"); + }); + + // A genuine socket close means nothing is coming: the debt must not survive + // into the reconnect, or the next save on that question would eat its own ack. + it("clears owed frames when the socket actually closes", async () => { + const w = createAckWaiter(1000); + const first = w.wait("q1"); + const firstAssertion = expect(first).rejects.toThrow("state unavailable"); + w.failAll(new Error("state unavailable"), "error-frame"); + await firstAssertion; + + w.failAll(new Error("disconnected"), "socket-closed"); // socket drops, reconnect + const afterReconnect = w.wait("q1"); + w.ack("q1"); + await expect(afterReconnect).resolves.toBe("ok"); + }); + it("fails only the named save when the error frame blames one question", async () => { const w = createAckWaiter(1000); const a = w.wait("q1"); @@ -49,16 +88,78 @@ describe("createAckWaiter", () => { void w.wait("q1").catch(() => {}); w.fail("q2", new Error("boom")); // late/unknown blame must not touch q1 expect(w.size).toBe(1); - w.failAll(new Error("cleanup")); + w.failAll(new Error("cleanup"), "socket-closed"); }); - it("marks an overtaken save superseded instead of failing it", async () => { + it("marks an overtaken save superseded and lets its own ack settle nobody", async () => { const w = createAckWaiter(1000); const first = w.wait("q1"); const second = w.wait("q1"); await expect(first).resolves.toBe("superseded"); - w.ack("q1"); + expect(w.size).toBe(1); + w.ack("q1"); // the first send's ack — the second is still unconfirmed + expect(w.size).toBe(1); + w.ack("q1"); // now the second send's own ack await expect(second).resolves.toBe("ok"); + expect(w.size).toBe(0); + }); + + // Regression: a `saved` frame for a send that already timed out must never + // confirm the retry that replaced it — that told students "Saved" for an + // answer the server had refused. + it("does not let a timed-out send's late ack confirm the retry", async () => { + vi.useFakeTimers(); + const w = createAckWaiter(8000); + const first = w.wait("q1"); // student saves "A" + const firstAssertion = expect(first).rejects.toThrow("ack timeout"); + await vi.advanceTimersByTimeAsync(8000); + await firstAssertion; + + const retry = w.wait("q1"); // student presses save again with "B" + let outcome: string | undefined; + void retry.then( + (r) => { outcome = `resolved:${r}`; }, + (e: Error) => { outcome = `rejected:${e.message}`; }, + ); + + w.ack("q1"); // the FIRST send's late `saved` frame finally lands + await vi.advanceTimersByTimeAsync(0); + expect(outcome).toBeUndefined(); // must NOT claim the retry was saved + + w.fail("q1", new Error("a choice question takes selected")); // the retry's own error frame + await vi.advanceTimersByTimeAsync(0); + expect(outcome).toBe("rejected:a choice question takes selected"); + vi.useRealTimers(); + }); + + // Regression (defect 2): the old tombstone was dropped by a timer after one + // more timeout window, so a frame arriving after that settled the NEXT live + // send "ok". Debt has no expiry — it is only ever paid off by a frame. + it("does not let a very late ack confirm a newer send once the tombstone window would have lapsed", async () => { + vi.useFakeTimers(); + const w = createAckWaiter(8000); + const first = w.wait("q1"); // t=0, send #1 + const firstAssertion = expect(first).rejects.toThrow("ack timeout"); + await vi.advanceTimersByTimeAsync(8000); // t=8s, send #1 times out + await firstAssertion; + + await vi.advanceTimersByTimeAsync(1000); // t=9s + const second = w.wait("q1"); // send #2, live + let outcome: string | undefined; + void second.then( + (r) => { outcome = `resolved:${r}`; }, + (e: Error) => { outcome = `rejected:${e.message}`; }, + ); + + await vi.advanceTimersByTimeAsync(7000); // t=16s, old tombstone expiry moment + w.ack("q1"); // send #1's frame lands at last + await vi.advanceTimersByTimeAsync(0); + expect(outcome).toBeUndefined(); // must NOT confirm send #2 + + w.ack("q1"); // send #2's own frame + await vi.advanceTimersByTimeAsync(0); + expect(outcome).toBe("resolved:ok"); + vi.useRealTimers(); }); it("does not confirm after a timeout has already fired", async () => { diff --git a/src/lib/create-ack-waiter.ts b/src/lib/create-ack-waiter.ts index bfb4a72..ff2d2b1 100644 --- a/src/lib/create-ack-waiter.ts +++ b/src/lib/create-ack-waiter.ts @@ -5,9 +5,28 @@ * exam room waits for the server's `{"type":"saved", question_id}` frame before * it may tell a student their answer is stored. `wait(key)` hands back a promise * that settles on `ack(key)`, rejects on `fail(key)` (an error frame that names - * the question it refused), rejects on `failAll()` (an unattributed error frame, - * or a socket drop — which invalidates every pending save) and rejects on its - * own timeout when nothing ever comes back. + * the question it refused), rejects on `failAll()` (a socket drop, or an + * unattributed error frame) and rejects on its own timeout when nothing ever + * comes back. + * + * **Acks are matched per send, not per question.** The server answers every + * `answer` frame with exactly one `saved`/`error` frame, in order + * (`exam_ws.rs:396,410`), so each key keeps a FIFO queue of the sends that still + * own a promise, plus `owed`: a count of frames the server still has to send for + * sends that no longer own anybody's promise (they timed out, a newer save + * overtook them, or an unattributed error frame rejected them while the socket + * stayed open). Those dead sends are always older than any live one, so an + * incoming frame pays off `owed` first and is discarded; only once the debt is + * clear does a frame settle the oldest live send. That is exact and timer-free — + * nothing can expire into the wrong match, and send #1's late `saved` can never + * confirm send #2. + * + * Trade-off: if the server truly never answers a send, its debt sits there and + * swallows one later legitimate frame, so that question's next save reads "not + * saved" and the student presses save again. Wrong in the safe direction — the + * badge never claims "Saved" for a payload the server did not accept. The debt + * is not permanent: a socket close clears it (`failAll(..., "socket-closed")`), + * so a reconnect always starts from zero. * * A second `wait()` for the same key means the student saved again: the older * promise resolves `"superseded"` so its caller stays quiet and the newer save @@ -18,44 +37,102 @@ export type AckResult = "ok" | "superseded"; /** Rejection reason when nothing came back at all — callers localize it. */ export const ACK_TIMEOUT = "ack timeout"; +type Entry = { + settle: (result: AckResult) => void; + fail: (reason: Error) => void; + timer: ReturnType; +}; + +/** + * Why every pending save is being rejected at once: + * - `socket-closed` — the socket dropped or we replaced it. Nothing is coming, + * ever, so both the queue and the debt are wiped. + * - `error-frame` — the server refused something it could not attribute to one + * question and **kept the socket open** (`exam_ws.rs:496` sends + * `error_frame_for(err, None)` and keeps serving). Each in-flight send is + * still owed its own frame, so rejecting them turns them into debt. + */ +export type FailAllCause = "socket-closed" | "error-frame"; + export function createAckWaiter(timeoutMs = 8000) { - const pending = new Map< - string, - { settle: (result: AckResult) => void; fail: (reason: Error) => void; timer: ReturnType } - >(); + const queues = new Map(); + /** key → frames the server still owes for sends nobody is waiting on anymore. */ + const owed = new Map(); + + /** This send lost its owner but the server will still answer it: bank the debt. */ + const disown = (key: string, entry: Entry) => { + clearTimeout(entry.timer); + const queue = queues.get(key); + const at = queue?.indexOf(entry) ?? -1; + if (queue && at >= 0) queue.splice(at, 1); + if (queue && queue.length === 0) queues.delete(key); + owed.set(key, (owed.get(key) ?? 0) + 1); + }; - const take = (key: string) => { - const entry = pending.get(key); - if (entry) { - clearTimeout(entry.timer); - pending.delete(key); + /** + * Pop the send an incoming frame belongs to, or `undefined` when the frame + * pays off an older dead send instead (debt is always older than live sends). + */ + const takeOldest = (key: string) => { + const debt = owed.get(key) ?? 0; + if (debt > 0) { + if (debt === 1) owed.delete(key); + else owed.set(key, debt - 1); + return undefined; } + const queue = queues.get(key); + if (!queue || queue.length === 0) return undefined; + const entry = queue.shift()!; + if (queue.length === 0) queues.delete(key); + clearTimeout(entry.timer); return entry; }; return { wait(key: string): Promise { - take(key)?.settle("superseded"); + // Disowning the last live entry drops the queue, so re-seat it afterwards. + for (const entry of [...(queues.get(key) ?? [])]) { + entry.settle("superseded"); + disown(key, entry); + } + const queue = queues.get(key) ?? []; + queues.set(key, queue); return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - pending.delete(key); - reject(new Error(ACK_TIMEOUT)); - }, timeoutMs); - pending.set(key, { settle: resolve, fail: reject, timer }); + const entry: Entry = { + settle: resolve, + fail: reject, + timer: setTimeout(() => { + entry.fail(new Error(ACK_TIMEOUT)); + disown(key, entry); + }, timeoutMs), + }; + queue.push(entry); }); }, ack(key: string) { - take(key)?.settle("ok"); + takeOldest(key)?.settle("ok"); }, /** Reject one save — the server blamed this question and no other. */ fail(key: string, reason: Error) { - take(key)?.fail(reason); + takeOldest(key)?.fail(reason); }, - failAll(reason: Error) { - for (const key of [...pending.keys()]) take(key)?.fail(reason); + failAll(reason: Error, cause: FailAllCause) { + for (const [key, queue] of [...queues]) { + for (const entry of [...queue]) { + entry.fail(reason); + if (cause === "error-frame") disown(key, entry); + else clearTimeout(entry.timer); + } + if (cause === "socket-closed") queues.delete(key); + } + // A dead socket answers nothing: the reconnect must not inherit old debt. + if (cause === "socket-closed") owed.clear(); }, + /** Sends still waiting for an outcome — banked debt doesn't count. */ get size() { - return pending.size; + let n = 0; + for (const queue of queues.values()) n += queue.length; + return n; }, }; } diff --git a/src/lib/person.ts b/src/lib/person.ts index 5c4a73d..751b58a 100644 --- a/src/lib/person.ts +++ b/src/lib/person.ts @@ -1,4 +1,4 @@ -import type { PersonRef } from "@/api/client"; +import type { Appointment, PersonRef } from "@/api/client"; export type PersonLike = PersonRef | string | null | undefined; @@ -13,6 +13,13 @@ export function personLabel(person: PersonLike): string { return person.display_name || person.username || person.id; } +// Every appointment listing is scoped to the viewer (`list_for_requester` / +// `list_for_teacher`), so one of the two sides is always the viewer themselves. +// Show the OTHER person, or the row reads "Ali" to Ali. +export function appointmentCounterpart(a: Appointment, viewerId: string | undefined): string { + return personLabel(a.requester.id === viewerId ? a.teacher ?? a.requester : a.requester); +} + export function personLabelWithId(person: PersonLike): string { if (!person) return "—"; if (typeof person === "string") return person; diff --git a/src/pages/appointments-page.tsx b/src/pages/appointments-page.tsx index 724f97c..c6ab73c 100644 --- a/src/pages/appointments-page.tsx +++ b/src/pages/appointments-page.tsx @@ -31,6 +31,7 @@ import { Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle } from "@/ import { IconCalendarX, IconCheck, IconEye, IconPlus, IconRefresh, IconTrash, IconX } from "@/components/ui/icons"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; +import { appointmentActions, hasStandingProposal } from "@/lib/appointment-actions"; import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; import { cn } from "@/lib/cn"; import { createFlash } from "@/lib/flash"; @@ -42,6 +43,7 @@ import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; const PAGE_SIZE = 10; +const PAGE_LIMIT = 100; const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved"; export default function AppointmentsPage() { @@ -69,8 +71,21 @@ function AppointmentsContent() { const isStaff = () => hasMinRole(me()?.role, "teacher"); const isManager = () => hasMinRole(me()?.role, "manager"); - const [slots, { refetch: refetchSlots }] = createResource(async () => (await getSlots({ limit: 100 })).items); - const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: 100 })).items); + // Staff get EVERY slot they ever published (`list_for_teacher`, `starts_at ASC`, + // no past filter), so past ~100 lifetime slots page one is nothing but expired + // rows and the upcoming ones are unreachable. Take the last page instead — they + // always sit at the tail. Requesters get `list_upcoming` (future-only, ASC), so + // their first page is the near one and must stay first. + // ponytail: shows the newest PAGE_LIMIT slots; >100 upcoming slots would need + // real paging, and the endpoint takes only limit/offset today. + const fetchSlots = async () => { + const first = await getSlots({ limit: PAGE_LIMIT }); + if (!isStaff() || first.total <= PAGE_LIMIT) return first.items; + return (await getSlots({ limit: PAGE_LIMIT, offset: first.total - PAGE_LIMIT })).items; + }; + const [slots, { refetch: refetchSlots }] = createResource(fetchSlots); + // Appointments come back newest-first (`ORDER BY id DESC`), so page one is right. + const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: PAGE_LIMIT })).items); const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]); const loaded = () => slots.latest !== undefined && appts.latest !== undefined; @@ -78,8 +93,10 @@ function AppointmentsContent() { // Poll so statuses stay in sync when the other party acts (approve, book, // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so // a cross-actor status change isn't stale on a parked tab. Reads use `.latest`, - // so a refetch never re-suspends/blanks the tables. - createLivePoll(refetchAll, 10_000); + // so a refetch never re-suspends/blanks the tables. 30s (the primitive's + // default): this page fans out to 2 GETs a tick, and tab-back freshness comes + // from the visibility/focus wake, not from a short period. + createLivePoll(refetchAll); const act = async (fn: () => Promise, successKey?: MessageKey) => { setError(""); try { @@ -138,7 +155,6 @@ function AppointmentsContent() { {t(appointmentStatusLabelKey(status))} ); - const hasProposal = (a: Appointment) => a.proposed_starts_at != null; // Cancelled/rejected appointments carry a record (who + optional reason) shown in the details dialog. const hasRecord = (a: Appointment) => a.status === "cancelled" || a.status === "rejected"; const detailAction = (a: Appointment) => @@ -241,7 +257,7 @@ function AppointmentsContent() { cell: (cell) => (
{timeCell(cell.row.original.starts_at, cell.row.original.ends_at)} - +
{t("appointments.rescheduleProposed")}
@@ -260,12 +276,10 @@ function AppointmentsContent() { cell: (cell) => { const a = cell.row.original; const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[]; - if (a.status === "pending" && !hasProposal(a)) { - actions.push({ label: t("appointments.approve"), icon: , onSelect: () => void act(() => patchApproveAppointment(a.id), "appointments.status.approved") }); - actions.push({ label: t("appointments.reject"), icon: , destructive: true, onSelect: () => askReject(a.id) }); - } - if (isLive(a.status) && !hasProposal(a)) { - actions.push({ label: t("appointments.reschedule"), icon: , onSelect: () => setReschedAppt(a) }); + for (const action of appointmentActions(a, "staff", now())) { + if (action === "approve") actions.push({ label: t("appointments.approve"), icon: , onSelect: () => void act(() => patchApproveAppointment(a.id), "appointments.status.approved") }); + if (action === "reject") actions.push({ label: t("appointments.reject"), icon: , destructive: true, onSelect: () => askReject(a.id) }); + if (action === "reschedule") actions.push({ label: t("appointments.reschedule"), icon: , onSelect: () => setReschedAppt(a) }); } // Staff never cancel — a booking is declined via reject (pending) or reschedule; only the requester cancels (their own bookings table). actions.push(...detailAction(a)); @@ -278,7 +292,10 @@ function AppointmentsContent() { const myLiveSlotIds = () => new Set((appts.latest ?? []).filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot)); const availableSlots = () => { const taken = myLiveSlotIds(); - return (slots.latest ?? []).filter((s) => s.ends_at > now() && !taken.has(s.id)); + // `book` refuses a slot whose window has OPENED ("the slot has already + // started", no skew grace), not one that has ended — an in-progress slot + // listed here would show a Book button that always 409s. + return (slots.latest ?? []).filter((s) => s.starts_at > now() && !taken.has(s.id)); }; const availableColumns = createMemo[]>(() => [ @@ -326,11 +343,13 @@ function AppointmentsContent() { meta: { headerClass: "w-44", cellClass: "align-top pr-4" }, cell: (cell) => (
- {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)} - + {/* The effective window IS the proposal while one stands (backend + `Appointment::window`), so the row's own time already shows the + proposed one — label it instead of printing it twice. */} +
{t("appointments.proposedTime")}:
- {timeCell(cell.row.original.proposed_starts_at, cell.row.original.proposed_ends_at)}
+ {timeCell(cell.row.original.starts_at, cell.row.original.ends_at)}
), }, @@ -347,11 +366,10 @@ function AppointmentsContent() { cell: (cell) => { const a = cell.row.original; const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[]; - if (a.status === "pending" && hasProposal(a)) { - actions.push({ label: t("appointments.acceptReschedule"), icon: , onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") }); - actions.push({ label: t("appointments.declineReschedule"), icon: , destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) }); - } else if (isLive(a.status)) { - actions.push({ label: t("appointments.cancel"), icon: , destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) }); + for (const action of appointmentActions(a, "requester", now())) { + if (action === "acceptReschedule") actions.push({ label: t("appointments.acceptReschedule"), icon: , onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") }); + if (action === "declineReschedule") actions.push({ label: t("appointments.declineReschedule"), icon: , destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) }); + if (action === "cancel") actions.push({ label: t("appointments.cancel"), icon: , destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) }); } actions.push(...detailAction(a)); return 0} fallback={—}>; diff --git a/src/pages/calendar-page.tsx b/src/pages/calendar-page.tsx index 9f64369..da5ad85 100644 --- a/src/pages/calendar-page.tsx +++ b/src/pages/calendar-page.tsx @@ -11,6 +11,8 @@ import { PageSpinner } from "@/components/ui/page-spinner"; import { IconCalendarDays, IconChevronLeft, IconChevronRight } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { createNow } from "@/lib/create-now"; +import { appointmentCounterpart } from "@/lib/person"; +import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; const DAY_NAMES_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; @@ -31,6 +33,7 @@ export default function CalendarPage() { } function CalendarContent() { + const auth = useAuth(); const t = useT(); const { locale } = usePreferences(); const now = createNow(); @@ -43,6 +46,8 @@ function CalendarContent() { const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] }); const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] }); + const counterpart = (a: Appointment) => appointmentCounterpart(a, auth.user()?.id); + const monthLabel = () => { const names = locale() === "tr" ? MONTH_NAMES_TR : MONTH_NAMES; return `${names[viewMonth()]} ${viewYear()}`; @@ -197,7 +202,7 @@ function CalendarContent() { {(appt) => ( - {appt().requester.display_name ?? appt().requester.username} + {counterpart(appt())} 1}> +{dayItems().appointments.length - 1} @@ -281,7 +286,7 @@ function CalendarContent() { class="group flex items-start justify-between gap-2 rounded-lg border border-violet-500/40 bg-card p-2.5 shadow-xs transition-all hover:border-violet-500/70 hover:shadow-md dark:border-violet-500/30 dark:hover:border-violet-500/70" >
-

{appt.requester.display_name ?? appt.requester.username}

+

{counterpart(appt)}

{appt.starts_at ? new Date(appt.starts_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" }) : ""} {appt.ends_at ? ` — ${new Date(appt.ends_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" })}` : ""} diff --git a/src/pages/question-bank-page.test.tsx b/src/pages/question-bank-page.test.tsx new file mode 100644 index 0000000..f2b6ab0 --- /dev/null +++ b/src/pages/question-bank-page.test.tsx @@ -0,0 +1,81 @@ +import { fireEvent, render, screen } from "@solidjs/testing-library"; +import { Show } from "solid-js"; +import QuestionBankPage from "@/pages/question-bank-page"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +// 13 templates, page size 12: the last page holds exactly one row. +let templates = Array.from({ length: 13 }, (_, index) => ({ + id: `bq-${index}`, + text: `Template ${index}`, + kind: "text", + points: 1, + subject: "s-1", + subject_name: "Algebra", + visibility: "private", + owner: "u-1", + owner_name: "Teacher", + used_count: 0, + created_at: 0, +})); + +vi.mock("@/api/bank-questions", () => ({ + getBankQuestions: async (params: { limit: number; offset: number }) => ({ + items: templates.slice(params.offset, params.offset + params.limit), + total: templates.length, + }), + deleteBankQuestionById: async (id: string) => { + templates = templates.filter((item) => item.id !== id); + }, +})); +vi.mock("@/api/courses", () => ({ getCourses: async () => ({ items: [] }) })); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ + user: () => ({ id: "u-1", role: "teacher" }), + loading: () => false, + error: () => undefined, + refresh: async () => {}, + }), +})); +// Kobalte's dropdown/dialog chrome is not what this test is about — flatten both +// to plain buttons so the delete path can be driven in jsdom. +vi.mock("@/components/ui/table-row-actions", () => ({ + TableRowActions: (props: { actions: { label: string; onSelect: () => void }[] }) => ( + + ), +})); +vi.mock("@/components/ui/confirm-dialog", () => ({ + ConfirmDialog: (props: { open: boolean; onConfirm: () => void | Promise }) => ( + + + + ), +})); + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +afterEach(() => vi.restoreAllMocks()); + +test("deleting the last row of the last page clamps back instead of stranding the user", async () => { + render(() => ( + + + + )); + + fireEvent.click(await screen.findByRole("button", { name: "Next" })); + expect(await screen.findByText("Template 12")).toBeTruthy(); + expect(screen.getByText("2 / 2")).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "delete-row" })); + fireEvent.click(screen.getByRole("button", { name: "confirm-delete" })); + await tick(); + await tick(); + + // 12 left → one page: the user must be on it, not on the vanished page 2. + expect(screen.queryByText("Template 12")).toBeNull(); + expect(await screen.findByText("Template 0")).toBeTruthy(); +}); diff --git a/src/pages/question-bank-page.tsx b/src/pages/question-bank-page.tsx index 3a0ce95..951cd4a 100644 --- a/src/pages/question-bank-page.tsx +++ b/src/pages/question-bank-page.tsx @@ -1,4 +1,4 @@ -import { Show, Suspense, createMemo, createResource, createSignal } from "solid-js"; +import { Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js"; import type { ColumnDef } from "@tanstack/solid-table"; import { deleteBankQuestionById, getBankQuestions } from "@/api/bank-questions"; import { getCourses } from "@/api/courses"; @@ -76,6 +76,13 @@ function QuestionBankContent() { }, ); const total = () => list.latest?.total ?? 0; + // Deleting the last row of the last page shrinks the page count under the + // current page; the table then hides its pagination bar entirely and the user + // is stranded with no control to get back. Same clamp as exam-questions-panel. + const pageCount = () => Math.max(1, Math.ceil(total() / BANK_PAGE_SIZE)); + createEffect(() => { + if (page() >= pageCount()) setPage(pageCount() - 1); + }); // Only courses the teacher can author in supply subjects for a new template. const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items); diff --git a/src/stores/shell-feed-context.test.tsx b/src/stores/shell-feed-context.test.tsx new file mode 100644 index 0000000..6ecf5d3 --- /dev/null +++ b/src/stores/shell-feed-context.test.tsx @@ -0,0 +1,61 @@ +import { render, waitFor } from "@solidjs/testing-library"; +import { createSignal } from "solid-js"; +import type { User } from "@/api/client"; +import { ShellFeedProvider, useShellFeed } from "@/stores/shell-feed-context"; + +// The provider only reads `auth.user()`; drive it from a signal the test owns. +const [user, setUser] = createSignal(null); +vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user }) })); + +const page = (items: T[]) => ({ items, total: items.length, limit: null, offset: 0 }); + +// Message previews are the account-scoped payload under test; the rest stay empty. +vi.mock("@/api/messages", () => ({ + getMessages: async () => page([{ id: `${user()?.id}-msg`, read: false }]), +})); +vi.mock("@/api/events", () => ({ getEvents: async () => page([]) })); +vi.mock("@/api/exams", () => ({ getExams: async () => page([]) })); +vi.mock("@/api/appointments", () => ({ getAppointments: async () => page([]) })); +vi.mock("@/api/homework", () => ({ getHomework: async () => page([]) })); + +const as = (id: string) => ({ id }) as User; + +function Probe() { + const feed = useShellFeed(); + return {feed.messages().items.map((m) => m.id).join(",")}; +} + +test("logout clears the feed and login as another user never shows the previous one's rows", async () => { + setUser(as("alice")); + const { getByTestId } = render(() => ( + + + + )); + await waitFor(() => expect(getByTestId("ids").textContent).toBe("alice-msg")); + + setUser(null); + expect(getByTestId("ids").textContent).toBe(""); // no leftover value after logout + + setUser(as("bob")); + expect(getByTestId("ids").textContent).toBe(""); // and none while bob's fetch is in flight + await waitFor(() => expect(getByTestId("ids").textContent).toBe("bob-msg")); +}); + +test("no fetch fires while logged out", async () => { + const messages = await import("@/api/messages"); + const spy = vi.spyOn(messages, "getMessages"); + setUser(null); + render(() => ( + + + + )); + await Promise.resolve(); + expect(spy).not.toHaveBeenCalled(); +}); + +afterEach(() => { + setUser(null); + vi.restoreAllMocks(); +}); diff --git a/src/stores/shell-feed-context.tsx b/src/stores/shell-feed-context.tsx index 8ca8963..7235006 100644 --- a/src/stores/shell-feed-context.tsx +++ b/src/stores/shell-feed-context.tsx @@ -2,6 +2,7 @@ import { type Accessor, type ParentProps, createContext, + createMemo, createResource, createSignal, useContext, @@ -27,6 +28,8 @@ import { useAuth } from "@/stores/auth-context"; type ShellFeedContextValue = { messages: Accessor>; + /** Newest unread inbox rows; `.total` is the *exact* server-side unread count. */ + unreadMessages: Accessor>; events: Accessor>; exams: Accessor>; appointments: Accessor>; @@ -44,13 +47,20 @@ const ShellFeedContext = createContext(); const emptyPage = (): Page => ({ items: [], total: 0, limit: null, offset: 0 }); -export function ShellFeedProvider(props: ParentProps) { - const auth = useAuth(); - // Only fetch for a logged-in user: source is falsy while logged out, so the +type UserFeed = Omit; + +// Everything user-scoped lives here so it can be created per account id and +// disposed with it (see ShellFeedProvider): a logged-out or switched account +// gets brand-new resources seeded with empty pages, so no previous user's rows +// can survive into the next session. Solid keeps a resource's last value when +// its source goes falsy, so gating alone would leak user A's inbox into user +// B's shell until the refetch resolved. +function createUserFeed(loggedIn: boolean): UserFeed { + // Only fetch for a logged-in user: source is false while logged out, so the // resource keeps its seeded empty value and never hits the network. - const source = () => !!auth.user(); + const source = () => loggedIn; - const [messagesRes, { refetch: refetchMessages }] = createResource( + const [messagesRes, { refetch: refetchInbox }] = createResource( source, async () => { try { @@ -62,11 +72,34 @@ export function ShellFeedProvider(props: ParentProps) { { initialValue: emptyPage() } ); + // The badge cannot be derived from the inbox page above: that page is + // ORDER BY id DESC capped at 100, so an old unread message falls off it. + // `read=false` makes `total` the exact server-side unread count, and the 10 + // items are the newest unread ones the popover lists. + const [unreadRes, { refetch: refetchUnread }] = createResource( + source, + async () => { + try { + return await getMessages("inbox", { read: false, limit: 10 }); + } catch { + return emptyPage(); + } + }, + { initialValue: emptyPage() } + ); + + // No limit on events/exams: the backend has no schedule filter or ordering + // param (`GET /events`, `GET /exams` take limit/offset only and serve + // ORDER BY id DESC = creation order), so any cap drops an event scheduled + // for tomorrow that was created before the newest N rows. The server loads + // the full list either way and only slices it afterwards. + // ponytail: payload grows with school history — upgrade path is a backend + // `starts_after`/`ends_after` query param, then cap again. const [eventsRes, { refetch: refetchEvents }] = createResource( source, async () => { try { - return await getEvents({ limit: 100 }); + return await getEvents(); } catch { return emptyPage(); } @@ -78,7 +111,7 @@ export function ShellFeedProvider(props: ParentProps) { source, async () => { try { - return await getExams({ limit: 100 }); + return await getExams(); } catch { return emptyPage(); } @@ -110,38 +143,71 @@ export function ShellFeedProvider(props: ParentProps) { { initialValue: emptyPage() } ); + // One call refreshes both message views — marking a message read changes the + // preview list and the unread count together. + const refetchMessages = () => { + void refetchInbox(); + void refetchUnread(); + }; + const refreshAll = () => { - void refetchMessages(); + refetchMessages(); void refetchEvents(); void refetchExams(); void refetchAppointments(); void refetchHomework(); }; - // Reactive clock so passed items drop off without a remount. Visibility-aware: - // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is - // stale on a parked tab. This is the single shell poller. - const [nowMs, setNowMs] = createSignal(Date.now()); - createLivePoll(() => { - if (!auth.user()) return; - setNowMs(Date.now()); - refreshAll(); - }, 60_000); - - const value: ShellFeedContextValue = { + return { messages: () => messagesRes.latest, + unreadMessages: () => unreadRes.latest, events: () => eventsRes.latest, exams: () => examsRes.latest, appointments: () => appointmentsRes.latest, homework: () => homeworkRes.latest, - nowMs, - refetchMessages: () => void refetchMessages(), + refetchMessages, refetchEvents: () => void refetchEvents(), refetchExams: () => void refetchExams(), refetchAppointments: () => void refetchAppointments(), refetchHomework: () => void refetchHomework(), refreshAll, }; +} + +export function ShellFeedProvider(props: ParentProps) { + const auth = useAuth(); + // Keyed on the account id: logging out (null) or switching account disposes + // the whole feed and builds a fresh one. Children never remount, so the + // router tree below is untouched. + const userId = createMemo(() => auth.user()?.id ?? null); + const feed = createMemo(() => createUserFeed(userId() !== null)); + + // Reactive clock so passed items drop off without a remount. Visibility-aware: + // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is + // stale on a parked tab. This is the single shell poller — it outlives the + // per-user feeds and always drives the current one. + const [nowMs, setNowMs] = createSignal(Date.now()); + createLivePoll(() => { + if (!auth.user()) return; + setNowMs(Date.now()); + feed().refreshAll(); + }, 60_000); + + const value: ShellFeedContextValue = { + messages: () => feed().messages(), + unreadMessages: () => feed().unreadMessages(), + events: () => feed().events(), + exams: () => feed().exams(), + appointments: () => feed().appointments(), + homework: () => feed().homework(), + nowMs, + refetchMessages: () => feed().refetchMessages(), + refetchEvents: () => feed().refetchEvents(), + refetchExams: () => feed().refetchExams(), + refetchAppointments: () => feed().refetchAppointments(), + refetchHomework: () => feed().refetchHomework(), + refreshAll: () => feed().refreshAll(), + }; return {props.children}; }