diff --git a/src/api/__tests__/appointments/appointments.test.ts b/src/api/__tests__/appointments/appointments.test.ts index 81f0db7..2b5dd7a 100644 --- a/src/api/__tests__/appointments/appointments.test.ts +++ b/src/api/__tests__/appointments/appointments.test.ts @@ -44,6 +44,12 @@ describe("appointments API", () => { expect(init?.method).toBe("GET"); }); + it("getSlots sends teacher and start window when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getSlots({ teacher: "me", starts_after: 1700000000000, limit: 10 }); + expect(lastFetchCall()[0]).toBe("/api/appointments/slots?limit=10&starts_after=1700000000000&teacher=me"); + }); + it("deleteSlotById calls /appointments/slots/:id", async () => { mockFetch204(); @@ -90,6 +96,18 @@ describe("appointments API", () => { expect(init?.method).toBe("GET"); }); + it("getAppointments sends status, teacher and start window when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getAppointments({ status: "pending", teacher: "me", starts_after: 1700000000000, starts_before: 1800000000000, limit: 10, offset: 20 }); + expect(lastFetchCall()[0]).toBe("/api/appointments?limit=10&offset=20&starts_after=1700000000000&starts_before=1800000000000&status=pending&teacher=me"); + }); + + it("getAppointments omits unset filters — no bare keys", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getAppointments(); + expect(lastFetchCall()[0]).toBe("/api/appointments"); + }); + it("patchApproveAppointment calls /appointments/:id/approve", async () => { const mockAppt = { id: "a1", status: "approved" }; mockFetchSuccess(mockAppt); diff --git a/src/api/__tests__/boards/boards.test.ts b/src/api/__tests__/boards/boards.test.ts index 9f6f570..6b0586f 100644 --- a/src/api/__tests__/boards/boards.test.ts +++ b/src/api/__tests__/boards/boards.test.ts @@ -41,6 +41,22 @@ describe("boards API", () => { expect(init?.method).toBe("GET"); }); + it("getBoards sends q with pagination when given", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoards({ limit: 10, offset: 20, q: "math, physics" }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/boards?q=math%2C+physics&limit=10&offset=20"); + }); + + it("getBoards omits a blank q", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getBoards({ q: " " }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/boards"); + }); + it("getBoardById calls GET /boards/:id", async () => { mockFetchSuccess({ id: "b1" }); await getBoardById("b1"); diff --git a/src/api/__tests__/classes/classes.test.ts b/src/api/__tests__/classes/classes.test.ts index 513f58b..a427525 100644 --- a/src/api/__tests__/classes/classes.test.ts +++ b/src/api/__tests__/classes/classes.test.ts @@ -51,6 +51,15 @@ describe("classes API", () => { expect(init?.method ?? "GET").toBe("GET"); }); + it("getClasses sends grade_level only when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getClasses({ grade_level: 9, limit: 5 }); + expect(lastFetchCall()[0]).toBe("/api/classes?limit=5&grade_level=9"); + + await getClasses({ grade_level: undefined, limit: 5 }); + expect(lastFetchCall()[0]).toBe("/api/classes?limit=5"); + }); + it("getClassById GETs /classes/:id", async () => { mockFetchSuccess({ id: "c1" }); await getClassById("c1"); diff --git a/src/api/__tests__/courses/courses.test.ts b/src/api/__tests__/courses/courses.test.ts index ef0df3d..389eac8 100644 --- a/src/api/__tests__/courses/courses.test.ts +++ b/src/api/__tests__/courses/courses.test.ts @@ -28,12 +28,31 @@ describe("courses API", () => { expect(init?.method).toBe("GET"); }); - it("getCourses sends pagination only — the endpoint has no kind/term/search filter", async () => { + it("getCourses keeps pagination when no filter is set", async () => { mockFetchSuccess({ items: [], total: 0 }); await getCourses({ limit: 12, offset: 24 }); expect(lastFetchCall()[0]).toBe("/api/courses?limit=12&offset=24"); }); + it("getCourses sends kind and a trimmed q only when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getCourses({ limit: 10, offset: 20, kind: "study", q: " algebra " }); + expect(lastFetchCall()[0]).toBe("/api/courses?limit=10&offset=20&kind=study&q=algebra"); + }); + + it("getCourses serializes taught as true/false and omits blank q", async () => { + mockFetchSuccess({ items: [], total: 0 }); + // Blank q drops the key entirely — the API 400s on `?q=`. + await getCourses({ q: " " }); + expect(lastFetchCall()[0]).toBe("/api/courses"); + + await getCourses({ taught: true, limit: 10 }); + expect(lastFetchCall()[0]).toBe("/api/courses?limit=10&taught=true"); + + await getCourses({ taught: false, offset: 5 }); + expect(lastFetchCall()[0]).toBe("/api/courses?offset=5&taught=false"); + }); + it("getCourseById calls /courses/:id", async () => { const mockCourse = { id: "c1", title: "Course" }; mockFetchSuccess(mockCourse); diff --git a/src/api/__tests__/events/events.test.ts b/src/api/__tests__/events/events.test.ts index 24e5d2c..3c17480 100644 --- a/src/api/__tests__/events/events.test.ts +++ b/src/api/__tests__/events/events.test.ts @@ -46,6 +46,17 @@ describe("events API", () => { expect(lastFetchCall()[0]).toBe("/api/events?limit=10"); expect(lastFetchCall()[0]).not.toContain("ends_after"); expect(lastFetchCall()[0]).not.toContain("starts_after"); + + // Upper bounds serialize after the earlier keys, in declaration order. + mockFetchSuccess({ items: [], total: 0 }); + await getEvents({ starts_after: 1, ends_after: 2, starts_before: 3, ends_before: 4 }); + expect(lastFetchCall()[0]).toBe("/api/events?starts_after=1&ends_after=2&starts_before=3&ends_before=4"); + + mockFetchSuccess({ items: [], total: 0 }); + await getEvents({ limit: 10, starts_before: undefined, ends_before: undefined }); + expect(lastFetchCall()[0]).toBe("/api/events?limit=10"); + expect(lastFetchCall()[0]).not.toContain("starts_before"); + expect(lastFetchCall()[0]).not.toContain("ends_before"); }); it("getEventById calls /events/:id", async () => { diff --git a/src/api/__tests__/exams/exams.test.ts b/src/api/__tests__/exams/exams.test.ts index 2414de5..8eba318 100644 --- a/src/api/__tests__/exams/exams.test.ts +++ b/src/api/__tests__/exams/exams.test.ts @@ -47,6 +47,17 @@ describe("exams API - core", () => { expect(lastFetchCall()[0]).toBe("/api/exams?limit=10"); expect(lastFetchCall()[0]).not.toContain("ends_after"); expect(lastFetchCall()[0]).not.toContain("starts_after"); + + // Upper bounds serialize after the earlier keys, in declaration order. + mockFetchSuccess({ items: [], total: 0 }); + await getExams({ starts_after: 1, ends_after: 2, starts_before: 3, ends_before: 4 }); + expect(lastFetchCall()[0]).toBe("/api/exams?starts_after=1&ends_after=2&starts_before=3&ends_before=4"); + + mockFetchSuccess({ items: [], total: 0 }); + await getExams({ limit: 10, starts_before: undefined, ends_before: undefined }); + expect(lastFetchCall()[0]).toBe("/api/exams?limit=10"); + expect(lastFetchCall()[0]).not.toContain("starts_before"); + expect(lastFetchCall()[0]).not.toContain("ends_before"); }); it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => { diff --git a/src/api/__tests__/homework/homework.test.ts b/src/api/__tests__/homework/homework.test.ts index 7b6dfc4..6a2339a 100644 --- a/src/api/__tests__/homework/homework.test.ts +++ b/src/api/__tests__/homework/homework.test.ts @@ -36,10 +36,18 @@ describe("homework API", () => { expect(init?.method).toBe("GET"); }); - it("getHomework sends pagination only — the endpoint has no due-date window", async () => { + it("getHomework sends the due window and class_course when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getHomework({ due_after: 1700000000000, due_before: 1800000000000, class_course: "i1", limit: 50 }); + expect(lastFetchCall()[0]).toBe("/api/homework?limit=50&due_after=1700000000000&due_before=1800000000000&class_course=i1"); + }); + + it("getHomework omits unset filters — no bare keys", async () => { mockFetchSuccess({ items: [], total: 0 }); await getHomework({ limit: 1 }); expect(lastFetchCall()[0]).toBe("/api/homework?limit=1"); + await getHomework({ class_course: " " }); + expect(lastFetchCall()[0]).toBe("/api/homework"); }); it("getHomeworkById calls /homework/:id", async () => { diff --git a/src/api/__tests__/instances/instances.test.ts b/src/api/__tests__/instances/instances.test.ts index d44968c..cbb3ade 100644 --- a/src/api/__tests__/instances/instances.test.ts +++ b/src/api/__tests__/instances/instances.test.ts @@ -150,6 +150,15 @@ describe("instances API", () => { expect(url).toBe("/api/instances/i1/sessions"); }); + it("getInstanceSessions sends the half-open start window when set", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getInstanceSessions("i1", { starts_after: 1700000000000, starts_before: 1800000000000, limit: 100 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/instances/i1/sessions?limit=100&starts_after=1700000000000&starts_before=1800000000000"); + }); + it("postInstanceSession POSTs /instances/:id/sessions with the body", async () => { mockFetchSuccess({ id: "se1" }); const body = { starts_at: 1900000000000, topic: "Limits" }; diff --git a/src/api/__tests__/meals/meals.test.ts b/src/api/__tests__/meals/meals.test.ts index 8b12996..574fca5 100644 --- a/src/api/__tests__/meals/meals.test.ts +++ b/src/api/__tests__/meals/meals.test.ts @@ -30,9 +30,17 @@ describe("meals API", () => { const json = () => mockFetchSuccess({}); const page = () => mockFetchSuccess({ items: [], total: 0 }); - it("lists menus with dates and pagination", async () => { - page(); await getMealMenus({ from: "2026-07-28", to: "2026-08-01", limit: 12, offset: 12 }); - expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=12&offset=12&from=2026-07-28&to=2026-08-01"); + it("lists menus with dates, slot, and pagination", async () => { + page(); await getMealMenus({ from: "2026-07-28", to: "2026-08-01", slot: "lunch", limit: 12, offset: 12 }); + expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=12&offset=12&from=2026-07-28&to=2026-08-01&slot=lunch"); + }); + it("omits the slot key for the all pseudo-option, blank, and unset", async () => { + page(); await getMealMenus({ slot: "all", limit: 5 }); + expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=5"); + page(); await getMealMenus({ slot: " " }); + expect(lastFetchCall()[0]).toBe("/api/meals/menus"); + page(); await getMealMenus(); + expect(lastFetchCall()[0]).toBe("/api/meals/menus"); }); it("gets a menu", async () => { json(); await getMealMenuById("m/1"); expect(lastFetchCall()[0]).toBe("/api/meals/menus/m%2F1"); }); it("publishes a menu", async () => { diff --git a/src/api/__tests__/messages/messages.test.ts b/src/api/__tests__/messages/messages.test.ts index 0502479..3d9f210 100644 --- a/src/api/__tests__/messages/messages.test.ts +++ b/src/api/__tests__/messages/messages.test.ts @@ -22,6 +22,22 @@ describe("messages API", () => { expect(init?.method).toBe("GET"); }); + it("getMessages sends q with folder, read and pagination", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getMessages("inbox", { limit: 10, offset: 20, read: false, q: "math, physics" }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/messages?folder=inbox&read=false&q=math%2C+physics&limit=10&offset=20"); + }); + + it("getMessages omits a blank q", async () => { + mockFetchSuccess({ items: [], total: 0 }); + await getMessages("sent", { q: " " }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/messages?folder=sent"); + }); + it("postMessage calls /messages with data", async () => { const mockMessage = { id: "m1" }; mockFetchSuccess(mockMessage); diff --git a/src/api/__tests__/pomodoro/pomodoro.test.ts b/src/api/__tests__/pomodoro/pomodoro.test.ts index 5505ead..dfefc5f 100644 --- a/src/api/__tests__/pomodoro/pomodoro.test.ts +++ b/src/api/__tests__/pomodoro/pomodoro.test.ts @@ -22,6 +22,36 @@ describe("pomodoro API", () => { expect(init?.method).toBe("GET"); }); + it("getPomodoroMe serializes the from/to window next to pagination", async () => { + mockFetchSuccess({ items: [], total: 0, limit: 400, offset: 0, total_focus_ms: 0 }); + + await getPomodoroMe({ limit: 400, offset: 0, from: 1000, to: 2000 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/pomodoro/me?limit=400&offset=0&from=1000&to=2000"); + expect(init?.method).toBe("GET"); + }); + + it("getPomodoroMe sends only the bounds that are set", async () => { + mockFetchSuccess({ items: [], total: 0, limit: null, offset: 0, total_focus_ms: 0 }); + + await getPomodoroMe({ from: 1000 }); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/pomodoro/me?from=1000"); + expect(init?.method).toBe("GET"); + }); + + it("getPomodoroMe sends a bare URL without any params", async () => { + mockFetchSuccess({ items: [], total: 0, limit: null, offset: 0, total_focus_ms: 0 }); + + await getPomodoroMe(); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/pomodoro/me"); + expect(init?.method).toBe("GET"); + }); + it("getPomodoroByUser calls /pomodoro/users/:id with pagination", async () => { const mockLog = { items: [{ id: "p1" }], total: 1, limit: 10, offset: 0, total_focus_ms: 1000 }; mockFetchSuccess(mockLog); diff --git a/src/api/__tests__/users/users.test.ts b/src/api/__tests__/users/users.test.ts index fb5b720..1246f53 100644 --- a/src/api/__tests__/users/users.test.ts +++ b/src/api/__tests__/users/users.test.ts @@ -60,6 +60,33 @@ describe("users API", () => { expect(init?.method).toBe("GET"); }); + it("getUsers comma-joins multiple roles (manager tab = manager+admin)", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getUsers({ roles: ["manager", "admin"], limit: 200 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/users?limit=200&roles=manager%2Cadmin"); + }); + + it("getUsers sends a single role unchanged", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getUsers({ roles: ["teacher"] }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/users?roles=teacher"); + }); + + it("getUsers omits roles when the array is empty", async () => { + mockFetchSuccess({ items: [], total: 0 }); + + await getUsers({ roles: [], limit: 5 }); + + const [url] = lastFetchCall(); + expect(url).toBe("/api/users?limit=5"); + }); + it("getUserSearch calls /users/search with query, role, and pagination", async () => { const mockPage = { items: [{ id: "u1" }], total: 1 }; mockFetchSuccess(mockPage); diff --git a/src/api/appointments/getAppointments.ts b/src/api/appointments/getAppointments.ts index 493fc88..20b20cd 100644 --- a/src/api/appointments/getAppointments.ts +++ b/src/api/appointments/getAppointments.ts @@ -1,8 +1,33 @@ import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; -import type { Appointment } from "../client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; +import type { Appointment, AppointmentStatus } from "../client"; -export async function getAppointments(params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/appointments${pageQuery(params)}`, { signal }); +/** + * `GET /appointments` filters. All optional and AND-ed; the list stays + * newest-created first. `starts_after` is unix ms and half-open on the + * appointment start (`starts_at >= v`). + */ +export type AppointmentListParams = PageParams & { + /** Only appointments in this state. */ + status?: AppointmentStatus; + /** Only appointments of the calling staff member; the value is the literal "me". */ + teacher?: "me"; + /** Keeps appointments that have started or start later: `starts_at >= v` (unix ms). */ + starts_after?: number; + /** Keeps appointments starting before this instant: `starts_at < v` (unix ms). */ + starts_before?: number; +}; + +export async function getAppointments(params?: AppointmentListParams, signal?: AbortSignal): Promise> { + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an + // unset param must drop the key, never emit `key=`. + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); + if (params?.starts_before != null) query.set("starts_before", String(params.starts_before)); + const status = params?.status?.trim(); + if (status) query.set("status", status); + if (params?.teacher) query.set("teacher", params.teacher); + const data = await client(`/appointments${query.size ? `?${query}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/appointments/getSlots.ts b/src/api/appointments/getSlots.ts index 1b2878b..ff1909b 100644 --- a/src/api/appointments/getSlots.ts +++ b/src/api/appointments/getSlots.ts @@ -1,8 +1,26 @@ import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; import type { AppointmentSlot } from "../client"; -export async function getSlots(params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/appointments/slots${pageQuery(params)}`, { signal }); +/** + * `GET /appointments/slots` filters. All optional and AND-ed; the list stays + * `starts_at ASC`. `starts_after` is unix ms and half-open on the slot start + * (`starts_at >= v`). + */ +export type SlotListParams = PageParams & { + /** Only slots of the calling staff member; the value is the literal "me". */ + teacher?: "me"; + /** Keeps slots that have started or start later: `starts_at >= v` (unix ms). */ + starts_after?: number; +}; + +export async function getSlots(params?: SlotListParams, signal?: AbortSignal): Promise> { + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an + // unset param must drop the key, never emit `key=`. + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); + if (params?.teacher) query.set("teacher", params.teacher); + const data = await client(`/appointments/slots${query.size ? `?${query}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/boards/getBoards.ts b/src/api/boards/getBoards.ts index e64d0f6..4e52886 100644 --- a/src/api/boards/getBoards.ts +++ b/src/api/boards/getBoards.ts @@ -1,8 +1,17 @@ -import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import { appendPageParams, client, normalizePage, type Page, type PageParams } from "../client"; import type { Board } from "./types"; -// Boards the caller created or was invited to, newest first. -export async function getBoards(params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/boards${pageQuery(params)}`, { signal }); +// Boards the caller created or was invited to, newest first. `q` filters by +// title server-side; blank after trim means no filter. +export async function getBoards( + params?: PageParams & { q?: string }, + signal?: AbortSignal, +): Promise> { + const query = new URLSearchParams(); + const q = params?.q?.trim(); + if (q) query.set("q", q); + appendPageParams(query, params); + const search = query.toString(); + const data = await client(`/boards${search ? `?${search}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/classes/getClasses.ts b/src/api/classes/getClasses.ts index 9095553..5007fd8 100644 --- a/src/api/classes/getClasses.ts +++ b/src/api/classes/getClasses.ts @@ -1,8 +1,21 @@ import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; -import type { ClassGroup } from "../client"; +import { appendPageParams, normalizePage, type ClassGroup, type Page, type PageParams } from "../client"; -export async function getClasses(params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/classes${pageQuery(params)}`, { signal }); +/** + * `GET /classes` list filters. `grade_level` keeps classes on one rung of the + * grade ladder; an omitted key filters nothing. + */ +export type ClassListParams = PageParams & { + grade_level?: number; +}; + +export async function getClasses(params?: ClassListParams, signal?: AbortSignal): Promise> { + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so + // an unset grade must drop the key, never emit `grade_level=`. + if (params?.grade_level != null) query.set("grade_level", String(params.grade_level)); + const value = query.toString(); + const data = await client(`/classes${value ? `?${value}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/client/page.ts b/src/api/client/page.ts index f531335..29dde85 100644 --- a/src/api/client/page.ts +++ b/src/api/client/page.ts @@ -24,8 +24,8 @@ export class PageShapeError extends Error { /** * Schedule-window filters, UTC unix ms. Only `/events` and `/exams` honour - * them; both are optional and AND-ed when both sent, and a row with no - * schedule at all is excluded by either. Sending either flips the server + * them; all are optional and AND-ed when several are sent, and a row with no + * schedule at all is excluded by any of them. Sending any flips the server * order to ASCENDING by schedule (soonest first) instead of newest-created. */ export type ScheduleWindowParams = { @@ -33,6 +33,10 @@ export type ScheduleWindowParams = { starts_after?: number; /** Keeps rows whose window has not finished: `ends_at > T`, else `starts_at > T`. */ ends_after?: number; + /** Keeps rows that have already begun or begin earlier: `starts_at < T`. */ + starts_before?: number; + /** Keeps rows whose window has already finished: `ends_at < T`. */ + ends_before?: number; }; export function pageQuery(params?: PageParams & ScheduleWindowParams): string { @@ -44,6 +48,8 @@ export function pageQuery(params?: PageParams & ScheduleWindowParams): string { if (params.offset != null) query.set("offset", String(params.offset)); if (params.starts_after != null) query.set("starts_after", String(params.starts_after)); if (params.ends_after != null) query.set("ends_after", String(params.ends_after)); + if (params.starts_before != null) query.set("starts_before", String(params.starts_before)); + if (params.ends_before != null) query.set("ends_before", String(params.ends_before)); const value = query.toString(); return value ? `?${value}` : ""; } diff --git a/src/api/courses/getCourses.ts b/src/api/courses/getCourses.ts index 0d04635..3f7df8f 100644 --- a/src/api/courses/getCourses.ts +++ b/src/api/courses/getCourses.ts @@ -1,19 +1,30 @@ import { client } from "../client"; -import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; -import type { Course } from "../client"; +import { appendPageParams, normalizePage, type Course, type Page, type PageParams } from "../client"; +import type { CourseKind } from "../client"; /** - * `GET /courses` and `GET /courses/me` take `limit`/`offset` and nothing else — - * the backend has no kind/term/search filter, and serde drops unknown query - * keys silently, so any extra param would look applied while doing nothing. - * Narrow the list in the caller instead (see `courses-page.tsx`). + * `GET /courses` list filters. `kind` keeps one course kind, `q` is the + * server-side catalog search, `taught` keeps courses with (`true`) or without + * (`false`) an attached şube. All optional, AND-ed with each other and with + * `limit`/`offset`; an omitted key filters nothing. */ -export type CourseListParams = PageParams; +export type CourseListParams = PageParams & { + kind?: CourseKind; + q?: string; + taught?: boolean; +}; export function courseListQuery(params?: CourseListParams): string { if (!params) return ""; const query = new URLSearchParams(); appendPageParams(query, params); + if (params.kind != null) query.set("kind", params.kind); + // Trimmed here so every caller sends the same thing; blank drops the key — + // the API 400s on a present-but-empty value (`?q=`). + const q = params.q?.trim(); + if (q) query.set("q", q); + // Serializes as `taught=true` / `taught=false`; unset drops the key (both). + if (params.taught != null) query.set("taught", String(params.taught)); const value = query.toString(); return value ? `?${value}` : ""; } diff --git a/src/api/homework/getHomework.ts b/src/api/homework/getHomework.ts index be1f600..cffe286 100644 --- a/src/api/homework/getHomework.ts +++ b/src/api/homework/getHomework.ts @@ -3,14 +3,28 @@ import { appendPageParams, normalizePage, type Page, type PageParams } from "../ import type { Homework } from "../client"; /** - * `GET /homework` takes `limit`/`offset` only — unlike events and exams it has - * no schedule window, so a due-date filter has to happen in the caller. + * `GET /homework` filters. All optional and AND-ed; a well-formed + * `class_course` uuid that names no row answers an empty page. The due bounds + * are unix ms and half-open on `due_at`. */ -export type HomeworkListParams = PageParams; +export type HomeworkListParams = PageParams & { + /** Keeps rows not yet due: `due_at >= v`. */ + due_after?: number; + /** Keeps rows already due: `due_at < v`. */ + due_before?: number; + /** Only homework filed against this instance (şube × ders). */ + class_course?: string; +}; export async function getHomework(params?: HomeworkListParams, signal?: AbortSignal): Promise> { const query = new URLSearchParams(); appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an + // unset param must drop the key, never emit `key=`. + if (params?.due_after != null) query.set("due_after", String(params.due_after)); + if (params?.due_before != null) query.set("due_before", String(params.due_before)); + const course = params?.class_course?.trim(); + if (course) query.set("class_course", course); const suffix = query.size ? `?${query}` : ""; const data = await client(`/homework${suffix}`, { signal }); return normalizePage(data); diff --git a/src/api/instances/getInstanceSessions.ts b/src/api/instances/getInstanceSessions.ts index 4178391..bf9735c 100644 --- a/src/api/instances/getInstanceSessions.ts +++ b/src/api/instances/getInstanceSessions.ts @@ -1,12 +1,30 @@ import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; import type { CourseSession } from "../client"; +/** + * `GET /instances/:id/sessions` filters. Both optional and AND-ed, unix ms, + * and half-open `[from, to)` on the session start: `starts_at >= starts_after` + * and `starts_at < starts_before`. + */ +export type InstanceSessionListParams = PageParams & { + /** Keeps sessions starting at or after this instant. */ + starts_after?: number; + /** Keeps sessions starting before this instant. */ + starts_before?: number; +}; + export async function getInstanceSessions( instanceId: string, - params?: PageParams, + params?: InstanceSessionListParams, signal?: AbortSignal, ): Promise> { - const data = await client(`/instances/${instanceId}/sessions${pageQuery(params)}`, { signal }); + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an + // unset param must drop the key, never emit `key=`. + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); + if (params?.starts_before != null) query.set("starts_before", String(params.starts_before)); + const data = await client(`/instances/${instanceId}/sessions${query.size ? `?${query}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/meals/getMealMenus.ts b/src/api/meals/getMealMenus.ts index e8fda8f..ed32da6 100644 --- a/src/api/meals/getMealMenus.ts +++ b/src/api/meals/getMealMenus.ts @@ -2,13 +2,18 @@ import { client } from "../client"; import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; import type { MealMenu } from "../client"; -export type MealMenuParams = PageParams & { from?: string; to?: string }; +export type MealMenuParams = PageParams & { from?: string; to?: string; slot?: string }; export async function getMealMenus(params?: MealMenuParams, signal?: AbortSignal): Promise> { const query = new URLSearchParams(); appendPageParams(query, params); if (params?.from) query.set("from", params.from); if (params?.to) query.set("to", params.to); + // "all" is the page's pseudo-option for "no slot filter", never a real slot + // name, and blank would serialize as a present-but-empty value the API + // rejects — both must be dropped instead of sent. + const slotFilter = params?.slot?.trim(); + if (slotFilter && slotFilter !== "all") query.set("slot", slotFilter); const data = await client(`/meals/menus${query.size ? `?${query}` : ""}`, { signal }); return normalizePage(data); } diff --git a/src/api/messages/getMessages.ts b/src/api/messages/getMessages.ts index ef32449..becb3f6 100644 --- a/src/api/messages/getMessages.ts +++ b/src/api/messages/getMessages.ts @@ -1,18 +1,20 @@ -import { client } from "../client"; +import { appendPageParams, client } from "../client"; import type { Page, PageParams } from "../client"; import type { Message, MessageFolder } from "../client"; export function getMessages( folder: MessageFolder = "inbox", - options?: PageParams & { read?: boolean } + options?: PageParams & { read?: boolean; q?: string } ): Promise> { const params = new URLSearchParams(); params.set("folder", folder); if (options?.read !== undefined) params.set("read", String(options.read)); - if (options?.limit !== undefined) params.set("limit", String(options.limit)); - if (options?.offset !== undefined) params.set("offset", String(options.offset)); - - const q = params.toString(); - const url = q ? `/messages?${q}` : `/messages`; + // Free-text search is server-side; blank after trim means no filter. + const q = options?.q?.trim(); + if (q) params.set("q", q); + appendPageParams(params, options); + + const query = params.toString(); + const url = query ? `/messages?${query}` : `/messages`; return client>(url); } diff --git a/src/api/pomodoro/getPomodoroMe.ts b/src/api/pomodoro/getPomodoroMe.ts index da55153..c0a755f 100644 --- a/src/api/pomodoro/getPomodoroMe.ts +++ b/src/api/pomodoro/getPomodoroMe.ts @@ -1,7 +1,22 @@ import { client } from "../client"; -import { pageQuery, type PageParams } from "../client"; +import { appendPageParams, type PageParams } from "../client"; import type { PomodoroLog } from "../client"; -export function getPomodoroMe(params?: PageParams, signal?: AbortSignal): Promise { - return client(`/pomodoro/me${pageQuery(params)}`, { signal }); +/** `/pomodoro/me` window on `started_at`, UTC unix ms. Both optional, AND-ed. */ +export type PomodoroMeParams = PageParams & { + /** Keeps sessions started at or after T: `started_at >= T`. */ + from?: number; + /** Keeps sessions started before T: `started_at < T`. */ + to?: number; +}; + +export function getPomodoroMe(params?: PomodoroMeParams, signal?: AbortSignal): Promise { + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so + // an unset bound must drop the key, never emit `from=`. + if (params?.from != null) query.set("from", String(params.from)); + if (params?.to != null) query.set("to", String(params.to)); + const value = query.toString(); + return client(`/pomodoro/me${value ? `?${value}` : ""}`, { signal }); } diff --git a/src/api/users/getUsers.ts b/src/api/users/getUsers.ts index 666487c..199b08a 100644 --- a/src/api/users/getUsers.ts +++ b/src/api/users/getUsers.ts @@ -1,8 +1,20 @@ import { client } from "../client"; -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; -import type { User } from "../client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; +import type { Role, User } from "../client"; -export async function getUsers(params?: PageParams, signal?: AbortSignal): Promise> { - const data = await client(`/users${pageQuery(params)}`, { signal }); +export type UserListParams = PageParams & { + /** Keep only these roles; comma-joined on the wire, omitted when empty. */ + roles?: Role[]; +}; + +export async function getUsers(params?: UserListParams, signal?: AbortSignal): Promise> { + const query = new URLSearchParams(); + appendPageParams(query, params); + // `!= null`/blank guards are load-bearing: the API 400s on a + // present-but-empty value (`?roles=`), so an empty list drops the key. + const roles = (params?.roles ?? []).map((role) => role.trim()).filter((role) => role !== ""); + if (roles.length) query.set("roles", roles.join(",")); + const suffix = query.size ? `?${query}` : ""; + const data = await client(`/users${suffix}`, { signal }); return normalizePage(data); } diff --git a/src/components/dashboard/today-lessons-panel.tsx b/src/components/dashboard/today-lessons-panel.tsx index 12e36dd..192c631 100644 --- a/src/components/dashboard/today-lessons-panel.tsx +++ b/src/components/dashboard/today-lessons-panel.tsx @@ -7,7 +7,8 @@ import { getSessionAttendance } from "@/api/sessions"; import { EmptyInline } from "@/components/ui/empty-inline"; import { IconChevronRight } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; -import { lessonNow, rollCallState, sessionsToday, type RollCallState, type TodayLesson } from "@/lib/today-lessons"; +import { lessonNow, rollCallState, sessionsToday, dayBounds, type RollCallState, type TodayLesson } from "@/lib/today-lessons"; +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; import { usePreferences, useT } from "@/stores/preferences-context"; import type { MessageKey } from "@/i18n/messages"; @@ -49,9 +50,15 @@ export function TodayLessonsPanel(props: { const instances = (await getMyInstances()).items.slice(0, INSTANCE_CAP); const perInstance = await Promise.all( instances.map(async (instance) => { - // No date filter on the route and newest first, so a year of - // pre-made future sessions would push today past any page size. - const sessions = await getInstanceSessions(instance.id).then((page) => page.items).catch(() => []); + // The route filters on the same half-open local-day bounds + // `sessionsToday` keeps, so the visible set is unchanged — but + // the read is now paged (offsets followed only while the + // envelope total exceeds the page) instead of every session ever. + const [dayStart, dayEnd] = dayBounds(now); + const sessions = await loadWindowedList( + (params) => getInstanceSessions(instance.id, { ...params, starts_after: dayStart, starts_before: dayEnd }), + LIST_CAP, + ).then((list) => list.items).catch(() => []); return sessionsToday(sessions, now).map((session) => ({ session, instance })); }), ); diff --git a/src/components/sessions/course-sessions-panel.tsx b/src/components/sessions/course-sessions-panel.tsx index 9184749..b90b36a 100644 --- a/src/components/sessions/course-sessions-panel.tsx +++ b/src/components/sessions/course-sessions-panel.tsx @@ -23,6 +23,7 @@ import { Select } from "@/components/ui/select"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { createFlash } from "@/lib/flash"; +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; import { formatDateTime } from "@/lib/format"; import { personLabel } from "@/lib/person"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -73,7 +74,14 @@ export function CourseSessionsPanel(props: { const { locale } = usePreferences(); const [sessions, { refetch }] = createResource( () => (props.active ? props.instanceId : null), - async (instanceId) => (instanceId ? (await getInstanceSessions(instanceId)).items : []), + async (instanceId) => { + if (!instanceId) return []; + // The table lists the section's whole lesson history, so the window is + // unfiltered — but the read is still paged: offsets are followed until + // the envelope total instead of one unpaged GET of every session ever. + const list = await loadWindowedList((params) => getInstanceSessions(instanceId, params), LIST_CAP); + return list.items; + }, ); const [selectedSession, setSelectedSession] = createSignal(null); let linkedRollCallOpened = false; diff --git a/src/lib/capped-list.test.ts b/src/lib/capped-list.test.ts index f4510ce..926c238 100644 --- a/src/lib/capped-list.test.ts +++ b/src/lib/capped-list.test.ts @@ -1,5 +1,5 @@ import type { Page, PageParams } from "@/api/client"; -import { isTruncated, loadAllPages, loadCappedList } from "./capped-list"; +import { isTruncated, loadAllPages, loadCappedList, loadWindowedList } from "./capped-list"; const page = (items: number[], total: number): Page => ({ items, total, limit: null, offset: 0 }); @@ -40,3 +40,25 @@ it("stops after one request when the first page holds everything", async () => { expect(await loadAllPages(fetch, 100)).toEqual([1, 2]); expect(fetch).toHaveBeenCalledTimes(1); }); + +it("follows offsets until the windowed total", async () => { + const fetch = vi.fn(async (params?: PageParams) => { + if (!params?.offset) return page([1, 2], 5); + if (params.offset === 2) return page([3, 4], 5); + return page([5], 5); + }); + const list = await loadWindowedList(fetch, 2); + expect(fetch).toHaveBeenNthCalledWith(1, { limit: 2, offset: 0 }); + expect(fetch).toHaveBeenNthCalledWith(2, { limit: 2, offset: 2 }); + expect(fetch).toHaveBeenNthCalledWith(3, { limit: 2, offset: 4 }); + expect(list).toEqual({ items: [1, 2, 3, 4, 5], total: 5 }); + expect(isTruncated(list)).toBe(false); +}); + +it("stops on an empty page instead of looping a shrinking window", async () => { + const fetch = vi.fn(async (params?: PageParams) => (params?.offset ? page([], 5) : page([1, 2], 5))); + const list = await loadWindowedList(fetch, 2); + expect(fetch).toHaveBeenCalledTimes(2); + expect(list.items).toEqual([1, 2]); + expect(list.total).toBe(5); +}); diff --git a/src/lib/capped-list.ts b/src/lib/capped-list.ts index 1d48caf..b5a936a 100644 --- a/src/lib/capped-list.ts +++ b/src/lib/capped-list.ts @@ -56,3 +56,27 @@ export async function loadAllPages( } return items.concat(...pages); } + + +/** + * Fetch every row of an already-windowed list, following offsets until the + * envelope total. The window (a date range or filter set) is the caller's + * job — this only pages through what the server answers, so no blind cap + * decides which rows exist. Stops on an empty page so rows deleted mid-read + * cannot loop it forever. + */ +export async function loadWindowedList( + fetch: (params?: PageParams) => Promise>, + pageSize: number, +): Promise> { + const first = await fetch({ limit: pageSize, offset: 0 }); + const items = Array.isArray(first.items) ? [...first.items] : []; + let total = typeof first.total === "number" ? Math.max(first.total, items.length) : items.length; + for (let offset = items.length; offset < total; offset = items.length) { + const page = await fetch({ limit: pageSize, offset }); + if (!Array.isArray(page.items) || page.items.length === 0) break; + items.push(...page.items); + total = typeof page.total === "number" ? Math.max(page.total, items.length) : items.length; + } + return { items, total }; +} diff --git a/src/lib/student-directory.test.ts b/src/lib/student-directory.test.ts index 3c12d61..d17853e 100644 --- a/src/lib/student-directory.test.ts +++ b/src/lib/student-directory.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, test } from "vitest"; -import type { ClassGroup, PersonRef } from "@/api/client"; -import { sortByClass } from "@/lib/student-directory"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import type { ClassGroup, ClassMember, PersonRef } from "@/api/client"; +import { getStudentDirectory, sortByClass } from "@/lib/student-directory"; const cls = (name: string, gradeLevel: number): ClassGroup => ({ id: name, creator: null, name, grade_level: gradeLevel, year: null, teacher: null, @@ -33,3 +33,79 @@ describe("sortByClass", () => { expect(sorted[0].classes.map((c) => c.name)).toEqual(["9-A", "10-B"]); }); }); + +const member = (classId: string, user: PersonRef): ClassMember => ({ + id: `m-${user.id}`, class: classId, user, added_by: user, joined_at: 0, left_at: null, source_class_group: null, +}); +const jsonResponse = (data: unknown) => + new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }); + +describe("getStudentDirectory", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + test("with no class, reads every student and every class's members as before", async () => { + const calls: string[] = []; + const respond = (url: string): Response => { + calls.push(url); + if (url === "/api/users/search?q=&role=student") + return jsonResponse({ items: [person("Zeynep"), person("Ali")], total: 2, limit: null, offset: 0 }); + if (url === "/api/classes?limit=200") + return jsonResponse({ items: [cls("9-A", 9), cls("10-B", 10)], total: 2, limit: 200, offset: 0 }); + if (url === "/api/classes/9-A/members?limit=500") + return jsonResponse({ items: [member("9-A", person("Ali"))], total: 1, limit: 500, offset: 0 }); + if (url === "/api/classes/10-B/members?limit=500") return jsonResponse({ items: [], total: 0, limit: 500, offset: 0 }); + throw new Error(`unexpected fetch: ${url}`); + }; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); + + const rows = await getStudentDirectory(); + + expect(calls).toEqual([ + "/api/users/search?q=&role=student", + "/api/classes?limit=200", + "/api/classes/9-A/members?limit=500", + "/api/classes/10-B/members?limit=500", + ]); + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Zeynep"]); + expect(rows[0].classes.map((c) => c.name)).toEqual(["9-A"]); + expect(rows[1].classes).toEqual([]); + }); + + test("with a class picked, reads only that roster, following offsets to total", async () => { + const calls: string[] = []; + const respond = (url: string): Response => { + calls.push(url); + if (url === "/api/classes/c1/members?limit=500&offset=0") + return jsonResponse({ items: [member("c1", person("Ali")), member("c1", person("Burak"))], total: 3, limit: 500, offset: 0 }); + if (url === "/api/classes/c1/members?limit=500&offset=2") + return jsonResponse({ items: [member("c1", person("Can"))], total: 3, limit: 500, offset: 2 }); + throw new Error(`unexpected fetch: ${url}`); + }; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); + const nineA = { ...cls("9-A", 9), id: "c1" }; + + const rows = await getStudentDirectory(nineA); + + expect(calls).toEqual(["/api/classes/c1/members?limit=500&offset=0", "/api/classes/c1/members?limit=500&offset=2"]); + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Burak", "Can"]); + expect(rows.every((row) => row.classes.length === 1 && row.classes[0] === nineA)).toBe(true); + }); + + test("with a class picked and a roster within one page, fetches it once", async () => { + const calls: string[] = []; + const respond = (url: string): Response => { + calls.push(url); + if (url === "/api/classes/c2/members?limit=500&offset=0") + return jsonResponse({ items: [member("c2", person("Ali"))], total: 1, limit: 500, offset: 0 }); + throw new Error(`unexpected fetch: ${url}`); + }; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); + + const rows = await getStudentDirectory({ ...cls("9-A", 9), id: "c2" }); + + expect(calls).toEqual(["/api/classes/c2/members?limit=500&offset=0"]); + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali"]); + }); +}); diff --git a/src/lib/student-directory.ts b/src/lib/student-directory.ts index 136a9b3..7feba07 100644 --- a/src/lib/student-directory.ts +++ b/src/lib/student-directory.ts @@ -1,14 +1,35 @@ import { getClassMembers, getClasses } from "@/api/classes"; import { getUserSearch } from "@/api/users"; -import type { ClassGroup, PersonRef } from "@/api/client"; +import type { ClassGroup, ClassMember, PersonRef } from "@/api/client"; export type StudentDirectoryRow = { person: PersonRef; classes: ClassGroup[]; }; -/** Shared student list for teacher-facing reports: one name column and the classes it belongs to. */ -export async function getStudentDirectory(): Promise { +/** Page size for the class-roster reads; the same one the full sweep asks for. */ +const MEMBERS_PAGE = 500; + +/** Every live member of one class: the route is paged, so follow offsets to `total`. */ +async function readClassMembers(classId: string): Promise { + const members: ClassMember[] = []; + let offset = 0; + for (;;) { + const page = await getClassMembers(classId, { limit: MEMBERS_PAGE, offset }); + members.push(...page.items); + offset += page.items.length; + if (page.items.length === 0 || offset >= page.total) return members; + } +} + +/** + * Shared student list for teacher-facing reports: one name column and the classes it belongs to. + * With `cls` the read is scoped to that class: only its roster is fetched, and + * each row's `classes` is just that class. Without it every student and every + * class's members are read, as before. + */ +export async function getStudentDirectory(cls?: ClassGroup): Promise { + if (cls) return sortByClass((await readClassMembers(cls.id)).map((member) => ({ person: member.user, classes: [cls] }))); const [students, classes] = await Promise.all([ getUserSearch("", undefined, "student"), getClasses({ limit: 200 }), diff --git a/src/pages/admin-users-page.tsx b/src/pages/admin-users-page.tsx index ecd3ad5..12cb266 100644 --- a/src/pages/admin-users-page.tsx +++ b/src/pages/admin-users-page.tsx @@ -1,5 +1,5 @@ import { useNavigate } from "@tanstack/solid-router"; -import { Show, Suspense, createMemo, createSignal } from "solid-js"; +import { Show, Suspense, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { getUsers } from "@/api/users"; import { patchUserRole } from "@/api/users"; @@ -44,15 +44,22 @@ function AdminUsersContent() { const [editTarget, setEditTarget] = createSignal(null); const [list, { refetch }] = createResource( - async () => ({ items: await loadAllPages(getUsers, USER_PAGE_SIZE) }), + // The source keys on the tab so switching tabs refetches from the server. + // Manager tab is the merged staff roster; every other tab is that one + // role. "all" omits the key entirely. Every page of the filtered set is + // read — no cap hides rows. + () => roleTab(), + async (tab) => ({ + items: await loadAllPages( + (params) => + getUsers({ + ...params, + roles: tab === "all" ? undefined : tab === "manager" ? ["manager", "admin"] : [tab], + }), + USER_PAGE_SIZE, + ), + }), ); - const allUsers = () => list()?.items ?? []; - const visibleUsers = createMemo(() => { - const tab = roleTab(); - if (tab === "all") return allUsers(); - if (tab === "manager") return allUsers().filter((user) => user.role === "manager" || user.role === "admin"); - return allUsers().filter((user) => user.role === tab); - }); const [flash, setFlash] = createFlash(); @@ -96,7 +103,7 @@ function AdminUsersContent() { {t("admin.createUser")} } - users={visibleUsers() as User[]} + users={list()?.items as User[]} currentUserId={auth.user()!.id} onRoleChange={onRoleChange} onUserClick={(user) => navigate({ to: "/admin/users/$id", params: { id: user.id } })} diff --git a/src/pages/appointments-page.test.tsx b/src/pages/appointments-page.test.tsx index 071fe76..4617daa 100644 --- a/src/pages/appointments-page.test.tsx +++ b/src/pages/appointments-page.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library"; +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; import AppointmentsPage from "@/pages/appointments-page"; import { PreferencesProvider } from "@/stores/preferences-context"; @@ -53,4 +53,11 @@ test("separates bookings and available times into tabs", async () => { expect(availableTab.getAttribute("aria-selected")).toBe("true"); expect(screen.getByRole("tab", { name: /Teachers’ open times/ })).toBeTruthy(); + + // A requester reads upcoming slots for every teacher (starts_after, no + // teacher=me) and their own bookings without a start window: neither read + // downloads history. + await waitFor(() => expect(getSlots).toHaveBeenCalled()); + expect(getSlots).toHaveBeenCalledWith({ starts_after: expect.any(Number), limit: 100 }); + expect(getAppointments).toHaveBeenCalledWith({ limit: 100 }); }); diff --git a/src/pages/appointments-page.tsx b/src/pages/appointments-page.tsx index 9016fe5..ee0927e 100644 --- a/src/pages/appointments-page.tsx +++ b/src/pages/appointments-page.tsx @@ -16,6 +16,7 @@ import { postSlots, } from "@/api/appointments"; import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; +import type { AppointmentListParams, SlotListParams } from "@/api/appointments"; import { createLivePoll } from "@/lib/create-live-poll"; import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; import type { MessageKey } from "@/i18n/messages"; @@ -75,21 +76,25 @@ function AppointmentsContent() { const isStaff = () => hasMinRole(me()?.role, "teacher"); const isManager = () => hasMinRole(me()?.role, "manager"); - // 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. + // Both slot reads only need what has not started (`starts_after`), which is + // also what keeps the read off the whole history — the old last-page trick + // existed because the endpoint had neither a window nor a teacher filter. + // Non-manager staff get their own published slots (`teacher=me`); managers + // supervise every teacher's, requesters everyone's open ones. 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 params: SlotListParams = { starts_after: Date.now(), limit: PAGE_LIMIT }; + if (isStaff() && !isManager()) params.teacher = "me"; + return (await getSlots(params)).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); + // Appointments come back newest-first (`ORDER BY id DESC`), so page one is + // right. The requests table shows decided rows too, so no status window; + // non-manager staff narrow to their own rows server-side (`teacher=me`). + const [appts, { refetch: refetchAppts }] = createResource(async () => { + const params: AppointmentListParams = { limit: PAGE_LIMIT }; + if (isStaff() && !isManager()) params.teacher = "me"; + return (await getAppointments(params)).items; + }); const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]); const loaded = () => slots.latest !== undefined && appts.latest !== undefined; @@ -192,13 +197,9 @@ function AppointmentsContent() { const recordReason = (a: Appointment) => (a.status === "rejected" ? a.reject_reason : a.cancel_reason); const recordReasonLabel = (a: Appointment) => (a.status === "rejected" ? t("appointments.rejectReason") : t("appointments.cancelReason")); - // --- staff: my published slots --- - const mySlots = () => { - const list = slots.latest ?? []; - if (isManager()) return list; - const uid = me()?.id; - return list.filter((s) => s.teacher.id === uid); - }; + // --- staff: my published slots (the server already narrows to `teacher=me` + // for non-manager staff; managers see every teacher's) --- + const mySlots = () => slots.latest ?? []; const slotBooking = (slotId: string) => (appts.latest ?? []).find((a) => a.slot === slotId && isLive(a.status)); const slotColumns = createMemo[]>(() => [ @@ -244,13 +245,9 @@ function AppointmentsContent() { }, ]); - // --- staff: booking requests for my slots --- - const requests = () => { - const list = appts.latest ?? []; - if (isManager()) return list; - const uid = me()?.id; - return list.filter((a) => a.teacher?.id === uid); - }; + // --- staff: booking requests for my slots (server-narrowed via `teacher=me` + // for non-manager staff, as with the slots above) --- + const requests = () => appts.latest ?? []; const requestColumns = createMemo[]>(() => [ { diff --git a/src/pages/calendar-page.test.tsx b/src/pages/calendar-page.test.tsx index ec2dbcb..c454aaa 100644 --- a/src/pages/calendar-page.test.tsx +++ b/src/pages/calendar-page.test.tsx @@ -3,7 +3,13 @@ import type { JSX } from "solid-js"; import CalendarPage from "@/pages/calendar-page"; import { PreferencesProvider } from "@/stores/preferences-context"; -const { failExams, getExams } = vi.hoisted(() => ({ failExams: { times: 0 }, getExams: vi.fn() })); +const { failExams, getExams, getEvents, getHomework, getAppointments } = vi.hoisted(() => ({ + failExams: { times: 0 }, + getExams: vi.fn(), + getEvents: vi.fn(), + getHomework: vi.fn(), + getAppointments: vi.fn(), +})); vi.mock("@tanstack/solid-router", () => ({ Link: (props: { to: string; children: JSX.Element; class?: string }) => {props.children}, @@ -18,19 +24,34 @@ vi.mock("@/stores/auth-context", () => ({ error: () => undefined, }), })); -const page = (items: T[]) => ({ items, total: items.length, limit: 100, offset: 0 }); +const page = (items: T[], total = items.length) => ({ items, total, limit: 100, offset: 0 }); vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) })); -vi.mock("@/api/events", () => ({ getEvents: vi.fn(async () => page([])) })); +vi.mock("@/api/events", () => ({ getEvents })); vi.mock("@/api/exams", () => ({ getExams })); -vi.mock("@/api/homework", () => ({ getHomework: vi.fn(async () => page([])) })); -vi.mock("@/api/appointments", () => ({ getAppointments: vi.fn(async () => page([])) })); +vi.mock("@/api/homework", () => ({ getHomework })); +vi.mock("@/api/appointments", () => ({ getAppointments })); vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) })); vi.mock("@/api/instances", () => ({ getMyInstances: vi.fn(async () => page([])), getInstanceSessions: vi.fn(async () => page([])), })); +// The page bounds its month feeds by the visible month; the test recomputes +// the same bounds the page derives from today at mount. +const monthBounds = () => { + const now = new Date(); + return { + start: new Date(now.getFullYear(), now.getMonth(), 1).getTime(), + end: new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime(), + }; +}; +const homeworkRows = (count: number, offset = 0) => + Array.from({ length: count }, (_, i) => ({ id: `hw${offset + i}`, title: `H${offset + i}`, due_at: Date.now() + i, class_course: "c1" })); + beforeEach(() => { + getEvents.mockImplementation(async () => page([])); + getHomework.mockImplementation(async () => page([])); + getAppointments.mockImplementation(async () => page([])); getExams.mockImplementation(async () => { if (failExams.times > 0) { failExams.times -= 1; @@ -60,3 +81,39 @@ test("a failed feed is named above the grid instead of reading as an empty calen await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); expect(getExams).toHaveBeenCalledTimes(2); }); + +test("homework and appointments feeds read the visible month window, one bounded page at a time", async () => { + render(() => ( + + + + )); + + const { start, end } = monthBounds(); + await waitFor(() => expect(getHomework).toHaveBeenCalled()); + expect(getHomework).toHaveBeenCalledWith({ due_after: start, due_before: end, limit: 100, offset: 0 }); + await waitFor(() => expect(getAppointments).toHaveBeenCalled()); + expect(getAppointments).toHaveBeenCalledWith({ starts_after: start, starts_before: end, limit: 100, offset: 0 }); + // Events and exams keep their open-ended window from the grid's first day, + // now with an explicit page size instead of an unpaged read. + expect(getEvents).toHaveBeenCalledWith({ ends_after: expect.any(Number), limit: 100, offset: 0 }); + expect(getExams).toHaveBeenCalledWith({ ends_after: expect.any(Number), limit: 100, offset: 0 }); +}); + +test("a month window bigger than one page follows offsets until the server total", async () => { + getHomework.mockImplementation(async (params: { offset?: number }) => + params.offset ? page(homeworkRows(50, 100), 150) : page(homeworkRows(100), 150)); + render(() => ( + + + + )); + + await waitFor(() => expect(getHomework).toHaveBeenCalledTimes(2)); + expect(getHomework).toHaveBeenLastCalledWith({ + due_after: monthBounds().start, + due_before: monthBounds().end, + limit: 100, + offset: 100, + }); +}); diff --git a/src/pages/calendar-page.tsx b/src/pages/calendar-page.tsx index 00cdbd5..5172c88 100644 --- a/src/pages/calendar-page.tsx +++ b/src/pages/calendar-page.tsx @@ -8,7 +8,7 @@ import { getHomework } from "@/api/homework"; import { getAppointments } from "@/api/appointments"; import { getCourses } from "@/api/courses"; import { getInstanceSessions, getMyInstances } from "@/api/instances"; -import type { Appointment, AppointmentStatus, Course } from "@/api/client"; +import type { Appointment, AppointmentStatus, Course, Page } from "@/api/client"; import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; import { RouteGuard } from "@/components/layout/route-guard"; import { Badge } from "@/components/ui/badge"; @@ -125,6 +125,26 @@ const KIND_ORDER = Object.keys(KIND_STYLES) as CalendarKind[]; * offer. The month grid alone is unreadable at 45px per cell. */ type CalendarView = "day" | "week" | "month"; +/** Page size for the windowed reads below; a busy month outgrows one page. */ +const FEED_PAGE = 100; + +/** + * Read every row the server window matches: follow `offset` until the + * envelope's `total` is drained. The loop is bounded by the server total — a + * stale total can cost one extra page, never spin, and nothing is dropped + * behind a silent cap. + */ +async function fetchWindow(fetchPage: (params: { limit: number; offset: number }) => Promise>): Promise { + const first = await fetchPage({ limit: FEED_PAGE, offset: 0 }); + const items = [...first.items]; + while (items.length < first.total) { + const next = await fetchPage({ limit: FEED_PAGE, offset: items.length }); + if (next.items.length === 0) break; + items.push(...next.items); + } + return items; +} + const VIEWS: { id: CalendarView; labelKey: MessageKey }[] = [ { id: "day", labelKey: "calendar.viewDay" }, { id: "week", labelKey: "calendar.viewWeek" }, @@ -196,24 +216,43 @@ function CalendarContent() { // notice above the grid, instead of blanking the whole calendar. const board = createBoardResources(); // Events and exams take a schedule window, so they are read from the first - // day the grid can show (the month's leading week included) onward, with no - // row cap — a fixed `limit` silently emptied later months once a school had - // more rows than the cap. The window only ever widens backwards: paging - // forward stays inside what is loaded, paging to an earlier month refetches. + // day the grid can show (the month's leading week included) onward. The + // window only ever widens backwards: paging forward stays inside what is + // loaded, paging to an earlier month refetches. Offsets follow the envelope + // total, so a window busier than one page still arrives whole. const viewStart = () => new Date(viewYear(), viewMonth(), 1).getTime() - 7 * DAY_MS; const loadedFrom = createMemo((prev) => Math.min(prev, viewStart()), viewStart()); - const [events] = board.createResource(loadedFrom, async (from) => (await getEvents({ ends_after: from })).items); - const [exams] = board.createResource(loadedFrom, async (from) => (await getExams({ ends_after: from })).items); - // Appointments and homework have no date filter and list newest-created - // first, so a cap would drop rows by creation order, not by date: read all. - const [appointments] = board.createResource(async () => (await getAppointments()).items); - const [homework] = board.createResource(async () => (await getHomework()).items); + const [events] = board.createResource(loadedFrom, async (from) => fetchWindow((page) => getEvents({ ...page, ends_after: from }))); + const [exams] = board.createResource(loadedFrom, async (from) => fetchWindow((page) => getExams({ ...page, ends_after: from }))); + // Homework and appointments are bound to the visible month itself: a + // two-sided window cannot widen incrementally, so the source key is the + // month and paging months refetches. Homework filters on its due date, + // appointments on their start. + const monthWindow = () => ({ + start: new Date(viewYear(), viewMonth(), 1).getTime(), + end: new Date(viewYear(), viewMonth() + 1, 1).getTime(), + }); + const [appointments] = board.createResource( + monthWindow, + async (bounds) => fetchWindow((page) => getAppointments({ ...page, starts_after: bounds.start, starts_before: bounds.end })), + ); + const [homework] = board.createResource( + monthWindow, + async (bounds) => fetchWindow((page) => getHomework({ ...page, due_after: bounds.start, due_before: bounds.end })), + ); // Lessons and study/club meetings both come from course sessions; the course's // own `kind` is what separates them. const [sessions] = board.createResource( - () => auth.user()?.role ?? null, - async () => { + () => { + const role = auth.user()?.role ?? null; + return role ? `${role}|${loadedFrom()}` : null; + }, + async (key) => { + // Sessions read from the earliest viewed month onward — like events and + // exams, the window only widens backwards, so future months ride the + // already-loaded rows and paging to an earlier month refetches. + const from = Number(key.split("|")[1]); // Sessions hang off the instance (şube × ders) now; the catalog course is // still what says whether a meeting is a ders, an etüt or a kulüp. const [instances, courses] = await Promise.all([ @@ -226,10 +265,8 @@ function CalendarContent() { const course = byId.get(instance.course); if (!course) return []; try { - // No cap: a weekly lesson alone passes 100 sessions in a school - // year, and the rows past a cap were the later months. - const page = await getInstanceSessions(instance.id); - return page.items.map((session) => ({ session, course })); + const items = await fetchWindow((page) => getInstanceSessions(instance.id, { ...page, starts_after: from })); + return items.map((session) => ({ session, course })); } catch { // One unreadable section must not empty the whole calendar. return []; diff --git a/src/pages/classes-page.test.tsx b/src/pages/classes-page.test.tsx index 3897b22..e1d17ef 100644 --- a/src/pages/classes-page.test.tsx +++ b/src/pages/classes-page.test.tsx @@ -103,3 +103,41 @@ test("a blank class name is flagged under the field, not sent", async () => { expect(field.getAttribute("aria-describedby")).toBe("class-name-error"); expect(postClass).not.toHaveBeenCalled(); }); + +// The grade dropdown's options come from their own unfiltered read: if they +// came from the table rows, picking a grade would collapse the option list to +// that one grade and there would be no way back. +test("the grade filter narrows on the server and keeps every option listed", async () => { + const grade9 = { id: "c9", creator: null, name: "9-A", grade_level: 9, year: null, teacher: null }; + const grade10 = { id: "c10", creator: null, name: "10-A", grade_level: 10, year: null, teacher: null }; + // The table fetch narrows by grade_level; the dropdown's own read never does. + getClasses.mockImplementation((params?: { grade_level?: number }) => { + if (params?.grade_level != null) { + const items = [grade9, grade10].filter((cls) => cls.grade_level === params.grade_level); + return Promise.resolve({ items, total: items.length, limit: 200, offset: 0 }); + } + return Promise.resolve({ items: [grade9, grade10], total: 2, limit: 200, offset: 0 }); + }); + getClassMembers.mockResolvedValue({ items: [], total: 0 }); + + render(() => ); + + expect(await screen.findByRole("button", { name: /^9-A/ })).toBeTruthy(); + expect(screen.getByRole("button", { name: /Grade:/ })).toBeTruthy(); + + fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" }); + const grade9Item = await screen.findByRole("menuitem", { name: "Grade 9" }); + fireEvent.pointerDown(grade9Item, { button: 0, pointerType: "mouse" }); + fireEvent.pointerUp(grade9Item, { button: 0, pointerType: "mouse" }); + fireEvent.click(grade9Item); + + // The refetch carries `grade_level`; the unfiltered options read does not. + await waitFor(() => expect(getClasses.mock.calls.at(-1)[0]).toEqual({ grade_level: 9 })); + expect(getClasses.mock.calls.some((call) => call[0]?.grade_level === undefined && call[0]?.limit === 200)).toBe(true); + expect(await screen.findByRole("button", { name: /^9-A/ })).toBeTruthy(); + await waitFor(() => expect(screen.queryByRole("button", { name: /^10-A/ })).toBeNull()); + + // Picking a grade must not erase the other options. + fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" }); + expect(await screen.findByRole("menuitem", { name: "Grade 10" })).toBeTruthy(); +}); diff --git a/src/pages/classes-page.tsx b/src/pages/classes-page.tsx index 2d89f84..2b559de 100644 --- a/src/pages/classes-page.tsx +++ b/src/pages/classes-page.tsx @@ -73,13 +73,28 @@ function ClassesContent() { const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); const [limits] = createResource(() => canManage() ? getLimits() : null); - const [list, { refetch }] = createResource(async () => (await getClasses()).items); + // The grade filter narrows on the server now: the table fetch carries + // `grade_level` and re-runs when the filter changes. An unreadable `?grade=` + // (only possible by hand) falls back to unfiltered, like every URL param. + const [list, { refetch }] = createResource( + () => gradeFilter(), + async (grade) => { + const level = Number(grade); + return (await getClasses(grade === "all" || !Number.isInteger(level) ? undefined : { grade_level: level })).items; + }, + ); + // The dropdown's options must not collapse to the selected grade, so they + // come from their own unfiltered read, not from the filtered table rows. + const [gradeList, { refetch: refetchGrades }] = createResource( + async () => (await getClasses({ limit: 200 })).items, + ); const courseTitle = (id: string) => skippedCourseTitles()[id] ?? "—"; const listData = () => list.latest ?? list() ?? []; + const gradeData = () => gradeList.latest ?? gradeList() ?? []; const yearName = (id: string | null) => (id ? years.latest?.find((year) => year.id === id)?.name ?? "—" : t("academicYears.unassigned")); // The grade filter offers only the rungs this school's classes sit on. - const grades = createMemo(() => [...new Set(listData().map((cls) => cls.grade_level))].sort((a, b) => a - b)); + const grades = createMemo(() => [...new Set(gradeData().map((cls) => cls.grade_level))].sort((a, b) => a - b)); const memberCountIds = createMemo(() => { const ids = listData().map((cls) => cls.id); @@ -98,11 +113,9 @@ function ClassesContent() { // A memo: the columns read it, and must not rebuild on every list refetch. const memberCountsCapped = createMemo(() => listData().length > MEMBER_COUNT_FETCH_CAP); - // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it. - const gradeFiltered = createMemo(() => { - const g = gradeFilter(); - return (g === "all" ? listData() : listData().filter((cls) => String(cls.grade_level) === g)).slice().sort(compareClasses); - }); + // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it. The + // grade narrowing itself happens on the server. + const gradeFiltered = createMemo(() => listData().slice().sort(compareClasses)); // A fresh array once the member counts land: the table redraws a row only // when its data changes, so the counts would otherwise stay "—". const rows = createMemo(() => { @@ -117,7 +130,9 @@ function ClassesContent() { const [deleteTarget, setDeleteTarget] = createSignal(null); const [rowError, setRowError] = createSignal(""); const refreshList = async () => { - try { await refetch(); } catch { /* stale rows until the next load */ } + // The grade dropdown reads its own unfiltered page, so a create, edit or + // delete that changes which rungs have classes must refresh it too. + try { await Promise.all([refetch(), refetchGrades()]); } catch { /* stale rows until the next load */ } }; // Applying is best-effort: the request succeeds and reports the pairs it // could not attach, so a shortfall opens the same report the create uses. @@ -257,7 +272,7 @@ function ClassesContent() { // failure here used to be reported as if the class had not been created, // and it swallowed the navigation to the class that plainly existed. try { - await refetch(); + await Promise.all([refetch(), refetchGrades()]); } catch { // The list reloads on the next visit; the class was created. } diff --git a/src/pages/courses-page.test.tsx b/src/pages/courses-page.test.tsx index 0450f81..838b4be 100644 --- a/src/pages/courses-page.test.tsx +++ b/src/pages/courses-page.test.tsx @@ -33,78 +33,93 @@ afterEach(() => { vi.clearAllMocks(); }); -// GET /courses is scoped server-side: a student reads only what they take. -test("student class directory uses only enrolled-course data", async () => { - getCourses.mockResolvedValue({ - items: [ - { - id: "course-1", - title: "Algebra", - description: "Core mathematics", - kind: "course", - class_course_count: 2, - course_membership_count: 0, - creator: { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }, - }, - { - id: "study-1", - title: "Study Lab", - description: "Weekly review", - kind: "study", - class_course_count: 0, - course_membership_count: 5, - creator: { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }, - }, - { - id: "club-1", - title: "Robotics", - description: "Build robots", - kind: "club", - class_course_count: 1, - course_membership_count: 9, - creator: { id: "teacher-2", username: "mentor", display_name: "Club Mentor" }, - }, - ], - total: 3, - limit: 3, - offset: 0, +const creator = { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }; +const catalog = [ + { id: "course-1", title: "Algebra", description: "Core mathematics", kind: "course", class_course_count: 2, course_membership_count: 0, creator }, + { id: "study-1", title: "Study Lab", description: "Weekly review", kind: "study", class_course_count: 0, course_membership_count: 5, creator }, + { + id: "club-1", + title: "Robotics", + description: "Build robots", + kind: "club", + class_course_count: 1, + course_membership_count: 9, + creator: { id: "teacher-2", username: "mentor", display_name: "Club Mentor" }, + }, +]; + +// The mock plays server: `kind`, `q` and `taught` narrow the page, `total` +// counts what matched. +function serveCatalog() { + getCourses.mockImplementation((params?: { kind?: string; q?: string; taught?: boolean; offset?: number }) => { + const needle = params?.q?.toLowerCase(); + const items = catalog.filter( + (course) => + (!params?.kind || course.kind === params.kind) && + (!needle || `${course.title} ${course.description}`.toLowerCase().includes(needle)) && + (params?.taught === undefined || (params.taught ? course.class_course_count > 0 : course.class_course_count === 0)), + ); + return Promise.resolve({ items, total: items.length, limit: 10, offset: params?.offset ?? 0 }); }); +} +// GET /courses is scoped server-side: a student reads only what they take, and +// the kind tab / search box / sections dropdown narrow on the server — the +// table never filters. +test("student course list filters on the server via kind, q and taught", async () => { + serveCatalog(); render(() => ); expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); expect(screen.getAllByText("Enrolled")).toHaveLength(3); - expect(getCourses).toHaveBeenCalledWith(); + // Unset filters stay off the wire — no `kind`, no `q`, no `taught`, not even empty. + const first = getCourses.mock.calls[0][0]; + expect(first).not.toHaveProperty("kind"); + expect(first).not.toHaveProperty("q"); + expect(first).not.toHaveProperty("taught"); + expect(first.offset).toBe(0); + // The kind tab refetches with `kind` and resets the offset. fireEvent.click(screen.getByRole("tab", { name: "Study" })); - expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy(); - expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull(); - expect(getCourses).toHaveBeenCalledTimes(1); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].kind).toBe("study")); + expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"); + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record) => Record }; expect(tabNavigation.to).toBe("/courses"); expect(tabNavigation.replace).toBe(true); - // The kind tab keeps the search text and restarts paging. - expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, sort: undefined, action: undefined, kind: "study", page: undefined }); + // The kind tab keeps the search text and the sections choice, and restarts paging. + expect(tabNavigation.search({ q: "alg", taught: "taught", page: 3, action: "new" })).toEqual({ q: "alg", taught: "taught", sort: undefined, action: undefined, kind: "study", page: undefined }); fireEvent.click(screen.getByRole("tab", { name: "Club" })); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].kind).toBe("club")); expect(await screen.findByRole("button", { name: /^Robotics/ })).toBeTruthy(); - expect(screen.queryByRole("button", { name: /^Study Lab/ })).toBeNull(); - fireEvent.click(screen.getByRole("tab", { name: "Classes" })); + fireEvent.click(screen.getByRole("tab", { name: "All" })); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("kind")); expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); - expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull(); - fireEvent.click(screen.getByRole("tab", { name: "All" })); - fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "robot" } }); - await waitFor(() => expect(screen.getByRole("button", { name: /^Robotics/ })).toBeTruthy()); - expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull(); + // The search box is the `q` param: trimmed, blank omitted, offset reset. + fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: " robots " } }); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].q).toBe("robots"), { timeout: 2000 }); + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); + + fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: " " } }); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"), { timeout: 2000 }); + expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); - fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } }); + // The sections dropdown is the `taught` param: untaught sends taught=false + // and resets the offset; the server then returns only courses with no şube. + expect(screen.getByRole("button", { name: /Section:/ })).toBeTruthy(); fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" }); const untaught = await screen.findByRole("menuitem", { name: "No sections" }); fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" }); fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" }); fireEvent.click(untaught); - expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy(); + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].taught).toBe(false)); + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); + expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"); + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull(); }); diff --git a/src/pages/courses-page.tsx b/src/pages/courses-page.tsx index 1f8c049..b502594 100644 --- a/src/pages/courses-page.tsx +++ b/src/pages/courses-page.tsx @@ -1,4 +1,5 @@ -import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; +import { Show, Suspense, createEffect, createMemo, createSignal, on } from "solid-js"; +import { createResponsivePageSize } from "@/lib/create-page-size"; import { createResource } from "@/lib/create-resource"; import { useNavigate, useSearch } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; @@ -22,11 +23,11 @@ import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; import { createFlash } from "@/lib/flash"; -import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; -import { createUrlEnum } from "@/lib/url-state"; +import { createUrlEnum, readPageIndex, readString } from "@/lib/url-state"; import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -52,11 +53,17 @@ function CoursesContent() { const [showForm, setShowForm] = createSignal(routeSearch().action === "new"); const [title, setTitle] = createSignal(""); const [description, setDescription] = createSignal(""); - // Catalog rows carry no term, capacity or staff any more — a şube decides - // all three when it attaches the course. `taughtFilter` narrows by whether - // any şube has. It rides in the URL beside the table's own search, sort and - // page, so Back from a course and a reload land where the list was left. + // Filters and paging are server-side now: the kind tab is the `kind` param, + // the search box the `q` param, the sections dropdown the `taught` param, + // and the envelope's total is already the filtered one. `?kind=` tracks the + // tab; `?q=`, `?page=` and `?taught=` restore the list on a reload (Back + // from a course lands where the list was left). const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all"); + const taughtParam = () => (taughtFilter() === "taught" ? true : taughtFilter() === "untaught" ? false : undefined); + const pageSize = createResponsivePageSize(PAGE_SIZE); + const [page, setPage] = createSignal(readPageIndex(routeSearch().page)); + createEffect(on(pageSize, () => setPage(0), { defer: true })); + const [search, setSearch, debouncedSearch] = createDebouncedSignal(readString(routeSearch().q)); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [flash, setFlash] = createFlash(); @@ -69,21 +76,34 @@ function CoursesContent() { }); const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); + // Scoped server-side: a student reads only the courses they take. The + // source carries every input the fetch reads, so each change refetches. const [list, { refetch }] = createResource( - () => auth.user()?.role ?? null, - // Scoped server-side: a student reads only the courses they take. - () => getCourses(), - ); - const listData = () => list.latest ?? list(); - // A memo: the table must see one array per change, not a fresh one per read. - const filteredCourses = createMemo(() => - (listData()?.items ?? []).filter((course) => { - if (pageKind() && course.kind !== pageKind()) return false; - if (taughtFilter() === "untaught" && course.class_course_count > 0) return false; - if (taughtFilter() === "taught" && course.class_course_count === 0) return false; - return true; + () => ({ + role: auth.user()?.role ?? null, + kind: pageKind(), + q: debouncedSearch().trim(), + taught: taughtParam(), + page: page(), + size: pageSize(), }), + (filters) => + getCourses({ + limit: filters.size, + offset: filters.page * filters.size, + ...(filters.kind ? { kind: filters.kind } : {}), + ...(filters.q ? { q: filters.q } : {}), + ...(filters.taught != null ? { taught: filters.taught } : {}), + }), ); + const listData = () => list.latest ?? list(); + const total = () => listData()?.total ?? 0; + // Deleting the last row of the last page shrinks the page count under the + // current page; clamp instead of stranding the user off the end. + const pageCount = () => Math.max(1, Math.ceil(total() / pageSize())); + createEffect(() => { + if (page() >= pageCount()) setPage(pageCount() - 1); + }); const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } }); // Catalog rights, as on the detail page: the creator or a manager+. const canManageCatalog = (course: Course) => { @@ -258,6 +278,7 @@ function CoursesContent() { onChange={(value) => { const kind = value === "course" || value === "study" || value === "club" ? value : undefined; setPageKind(kind); + setPage(0); void navigate({ to: "/courses", search: (prev) => ({ q: prev.q, taught: prev.taught, sort: prev.sort, action: undefined, kind, page: undefined }), @@ -278,26 +299,34 @@ function CoursesContent() { void refetch()} /> matchesSearch(query, course.title, course.description, personLabel(course.creator))} filterPlaceholder={t("common.searchPlaceholder")} filterHint={t("search.hint.courses")} + searchValue={search()} + onSearchInput={(value) => { + setSearch(value); + setPage(0); + }} enablePagination - pageSize={PAGE_SIZE} - storageKey="courses" - pageResetKey={`${pageKind() ?? "all"}|${taughtFilter()}`} + manualPagination={{ pageIndex: page(), pageSize: pageSize(), total: total(), onPageChange: setPage }} filtersActive={taughtFilter() !== "all"} - onClearFilters={() => setTaughtFilter("all")} + onClearFilters={() => { + setTaughtFilter("all"); + setPage(0); + }} empty={t("courses.empty", { item: kindInSentence() })} onRowClick={openCourse} + storageKey="courses" filters={ setTaughtFilter(value === "taught" || value === "untaught" ? value : "all")} + onChange={(value) => { + setTaughtFilter(value === "taught" || value === "untaught" ? value : "all"); + setPage(0); + }} options={[ { value: "all", label: t("common.all") }, { value: "taught", label: t("courses.withSections") }, diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 1c005ab..9208a02 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -62,6 +62,7 @@ import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { getModulesCatalog } from "@/api/modules"; import { useModules } from "@/stores/modules-context"; import { useAuth } from "@/stores/auth-context"; +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; import { usePreferences, useT } from "@/stores/preferences-context"; const DAY_MS = 24 * 60 * 60 * 1000; @@ -78,6 +79,8 @@ const TREND_EXAM_CAP = 20; const TREND_MARK_CAP = 20; /** Classes whose roster size the admin "Şubeler" quick links read. */ const CLASS_LINK_CAP = 12; +/** Page size for the paged heatmap window read of `/pomodoro/me`. */ +const POMODORO_PAGE = 400; /** * Chronological key for an exam: its schedule when it has one, else when it @@ -175,6 +178,9 @@ function DashboardContent() { throw err; }); const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); + // Server-anchored time (local fallback). Declared before the resources that + // read it in their fetchers. + const now = () => clock()?.now ?? Date.now(); // Unpaged: the backend has no `kind` filter, so a "courses" count that // excludes studies and clubs has to be counted here over the whole list. const [courses] = createResource( @@ -194,23 +200,34 @@ function DashboardContent() { () => role() === "parent" || !on("exams") ? null : role(), () => quiet(getExams({ limit: 100 })), ); - // Unfiltered: `/homework` has no due-date window, so this one read serves both - // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking - // heatmap. - // `limit: 100` matches the shell's feed read, so the two coalesce. + // One windowed read serves all three homework consumers: the deadlines + // table keeps the upcoming rows via its scheduleStatus filter, the teacher + // queue grades homework due around now, and the activity heatmap looks + // back exactly this far. Pages are followed until the envelope total — + // no blind cap decides which rows exist. const [homework] = createResource( () => role() === "parent" || !on("homework") ? null : role(), - () => quiet(getHomework({ limit: 100 })), + () => + quiet(loadWindowedList( + (params) => getHomework({ ...params, due_after: now() - HEATMAP_WEEKS * WEEK_MS }), + LIST_CAP, + )), ); const [children] = createResource( () => role() === "parent" ? true : null, () => quiet(getMyStudents({ limit: 12 })), ); - // Same page as the shell's notification poll (`limit: 100`), so the two - // concurrent first-paint reads coalesce into one request in `client`. + // Windowed like homework: the pending-approvals rail, the deadlines table + // and the activity heatmap all read this. 26 weeks back keeps a stale but + // still-pending request visible while the heatmap gets its history; pages + // are followed until the envelope total instead of a blind cap. const [appointments] = createResource( () => (on("appointments") ? true : null), - () => quiet(getAppointments({ limit: 100 })), + () => + quiet(loadWindowedList( + (params) => getAppointments({ ...params, starts_after: now() - HEATMAP_WEEKS * WEEK_MS }), + LIST_CAP, + )), ); const [menus] = createResource( () => (on("meals") ? clock()?.now : null), @@ -230,9 +247,16 @@ function DashboardContent() { ); // Focus heatmap source. Only a student owns pomodoro sessions — reading // another user's log is the teacher+ /management/pomodoros page's job. + // The 26-week grid window rides in the query (`from` inclusive, `to` + // exclusive, unix ms) and every page is followed until the envelope total, + // so neither a blind cap nor a JS cutoff decides what the grid shows. const [pomodoro] = createResource( () => role() === "student" && on("pomodoro") ? true : null, - () => quiet(getPomodoroMe({ limit: 400 })), + () => + quiet(loadWindowedList( + (params) => getPomodoroMe({ ...params, from: now() - HEATMAP_WEEKS * WEEK_MS, to: now() }), + POMODORO_PAGE, + )), ); // `/events` is the one list here that really is filtered server-side, by the // `ends_after` window the deadlines table needs. The heatmap looks backwards @@ -431,7 +455,6 @@ function DashboardContent() { }); const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username; - const now = () => clock()?.now ?? Date.now(); // STU-01 "Bu Hafta" rail — this week's pomodoro focus minutes, Monday // through Sunday. Distinct granularity from the 26-week heatmap below; diff --git a/src/pages/events-page.test.tsx b/src/pages/events-page.test.tsx index 3814891..129e909 100644 --- a/src/pages/events-page.test.tsx +++ b/src/pages/events-page.test.tsx @@ -3,13 +3,16 @@ import type { JSX } from "solid-js"; import EventsPage from "@/pages/events-page"; import { PreferencesProvider } from "@/stores/preferences-context"; -const { getEvents } = vi.hoisted(() => ({ getEvents: vi.fn() })); +const { getEvents, locationSearch } = vi.hoisted(() => ({ + getEvents: vi.fn(), + locationSearch: { value: {} as Record }, +})); vi.mock("@tanstack/solid-router", () => ({ Link: (props: { to: string; children: JSX.Element; class?: string }) => {props.children}, Navigate: () => null, useNavigate: () => vi.fn(), - useLocation: () => () => ({ pathname: "/events", searchStr: "" }), + useLocation: () => () => ({ pathname: "/events", searchStr: "", search: locationSearch.value }), })); vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ @@ -35,6 +38,7 @@ const event = (n: number) => ({ afterEach(() => { cleanup(); vi.clearAllMocks(); + locationSearch.value = {}; }); test("the event list reads every page instead of stopping at the first 100", async () => { @@ -55,3 +59,34 @@ test("the event list reads every page instead of stopping at the first 100", asy expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0 }); expect(screen.queryByRole("button", { name: /Tümünü yükle|Load all/ })).toBeNull(); }); + +test("the upcoming tab asks the server for rows whose window has not finished", async () => { + locationSearch.value = { when: "upcoming" }; + getEvents.mockResolvedValue({ items: [event(1)], total: 1, limit: 100, offset: 0 }); + + render(() => ( + + + + )); + + await waitFor(() => expect(getEvents).toHaveBeenCalled()); + // Exact key set: exactly one bound, no other window key, no `?key=` blank. + expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0, ends_after: expect.any(Number) }); +}); + +test("the past tab asks the server for rows that finished before now", async () => { + locationSearch.value = { when: "past" }; + getEvents.mockResolvedValue({ items: [event(1)], total: 1, limit: 100, offset: 0 }); + + render(() => ( + + + + )); + + await waitFor(() => expect(getEvents).toHaveBeenCalled()); + expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0, ends_before: expect.any(Number) }); +}); + + diff --git a/src/pages/events-page.tsx b/src/pages/events-page.tsx index 946ebb7..6dc40b5 100644 --- a/src/pages/events-page.tsx +++ b/src/pages/events-page.tsx @@ -59,13 +59,12 @@ function EventsContent() { const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); const filterEvents = (items: Event[]) => { - const scope = timeFilter(); const nowMs = now(); const isPast = (event: Event) => event.ends_at != null && event.ends_at < nowMs; const at = (event: Event) => event.starts_at ?? event.ends_at ?? null; // Default order, before any header sort: what is still ahead comes first, - // soonest first; what is over follows, most recent first. The API lists - // newest first, which put a far-off event above next week's. + // soonest first; what is over follows, most recent first. Applied here + // whatever order the server chose — it differs per tab window. const byDefault = (a: Event, b: Event) => { const pastA = isPast(a); const pastB = isPast(b); @@ -75,17 +74,24 @@ function EventsContent() { if (atA == null || atB == null) return atA == null ? (atB == null ? 0 : 1) : -1; return pastA ? atB - atA : atA - atB; }; - return items - .filter((event) => { - if (scope === "upcoming" && isPast(event)) return false; - if (scope === "past" && !isPast(event)) return false; - return true; - }) - .sort(byDefault); + // Tab membership is the server's job now (see the fetch bounds below); + // the client only orders what came back. Copy first: sorting in place + // would mutate the resource's array. + return [...items].sort(byDefault); }; + // Tab windows are enforced server-side, at the moment of the request: + // upcoming keeps rows whose window has not finished (`ends_after`), past + // keeps rows that finished before now (`ends_before`); `all` sends nothing + // and stays unfiltered. The window rides in the source key so switching + // tabs refetches with that tab's bounds; every page of the filtered set is + // read (no cap, no truncation notice). const [list, { refetch }] = createResource( - async () => ({ items: await loadAllPages(getEvents) }), + () => timeFilter(), + async (scope) => { + const bounds = scope === "upcoming" ? { ends_after: now() } : scope === "past" ? { ends_before: now() } : undefined; + return { items: await loadAllPages((params) => getEvents(bounds ? { ...params, ...bounds } : params)) }; + }, ); const rows = createMemo(() => filterEvents(list()?.items ?? [])); diff --git a/src/pages/exams-page.tsx b/src/pages/exams-page.tsx index c7b41b4..21a7f0e 100644 --- a/src/pages/exams-page.tsx +++ b/src/pages/exams-page.tsx @@ -59,11 +59,6 @@ function ExamsContent() { const { locale } = usePreferences(); const now = createNow(); type ExamTab = "all" | "upcoming" | "completed" | "draft"; - const examTabGroup = (status: ExamDisplayStatus): ExamTab => { - if (status === "draft") return "draft"; - if (status === "upcoming" || status === "active" || status === "unscheduled") return "upcoming"; - return "completed"; - }; // Tab and filters live in the URL beside the table's own search/page/sort, // so Back from an exam lands on the same slice of the list. const [tab, setTab] = createUrlEnum("tab", ["all", "upcoming", "completed", "draft"], "all"); @@ -134,7 +129,12 @@ function ExamsContent() { const allowed = isStudent() ? new Set(visibleCourses().map((row) => row.id)) : null; return items.filter((exam) => { if (allowed && !allowed.has(exam.class_course)) return false; - if (tab() !== "all" && examTabGroup(examStatus(exam)) !== tab()) return false; + // Upcoming/completed membership is the server's job now (see the fetch + // bounds); the client keeps only the draft split, which no schedule + // window can express. + const status = examStatus(exam); + if (tab() === "draft" && status !== "draft") return false; + if (tab() !== "all" && tab() !== "draft" && status === "draft") return false; if (courseFilter() !== "all" && exam.class_course !== courseFilter()) return false; if (kindFilter() !== "all" && String(exam.kind) !== kindFilter()) return false; return true; @@ -150,13 +150,23 @@ function ExamsContent() { statusLabel(exam.displayStatus), ); + // Tab windows are enforced server-side, at the moment of the request: + // completed keeps rows that finished before now (`ends_before`), upcoming + // keeps rows whose window has not finished (`ends_after`); `all` and + // `draft` send nothing — drafts carry no schedule, so no bound can select + // them and the client splits them instead. The window rides in the source + // key so switching tabs refetches with that tab's bounds; every page of + // the filtered set is read (no cap, no truncation notice). const [list, { refetch: refetchExams }] = createResource( () => { if (sections() === undefined) return null; - return `${visibleCourses().map((row) => row.id).join(",")}`; + const windowScope = tab() === "completed" ? "completed" : tab() === "upcoming" ? "upcoming" : "unbounded"; + return `${windowScope}|${visibleCourses().map((row) => row.id).join(",")}`; }, - async () => { - const items = await loadAllPages(getExams); + async (key) => { + const scope = key.split("|")[0]; + const bounds = scope === "completed" ? { ends_before: now() } : scope === "upcoming" ? { ends_after: now() } : undefined; + const items = await loadAllPages((params) => getExams(bounds ? { ...params, ...bounds } : params)); const page = { items }; const known = new Map(visibleCourses().map((row) => [row.id, row.label])); const missing = [...new Set(items.map((exam) => exam.class_course))].filter((instanceId) => !known.has(instanceId)); diff --git a/src/pages/homework-page.tsx b/src/pages/homework-page.tsx index 1761465..01dcd7e 100644 --- a/src/pages/homework-page.tsx +++ b/src/pages/homework-page.tsx @@ -5,10 +5,11 @@ import type { ColumnDef } from "@tanstack/solid-table"; import { getInstanceSubjects, postInstanceHomework } from "@/api/instances"; import { loadInstanceOptions } from "@/lib/instance-options"; import { loadInstanceLabels } from "@/lib/instance-labels"; -import { getHomework } from "@/api/homework"; +import { getHomework, type HomeworkListParams } from "@/api/homework"; import { getTime } from "@/api/time"; import { formatApiError } from "@/api/client"; import type { Homework } from "@/api/client"; +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; import { RouteGuard } from "@/components/layout/route-guard"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; @@ -21,6 +22,7 @@ import { SearchableSelect } from "@/components/ui/searchable-select"; import { DropdownSelect } from "@/components/ui/select"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; + import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import { formatDateTime } from "@/lib/format"; @@ -77,12 +79,6 @@ function HomeworkContent() { // in two şubeler yields rows with the same title, so a row's label names // both — " — <şube>", as the exams list does. const [courseNames, setCourseNames] = createSignal>({}); - const [list, { refetch }] = createResource(async () => { - const items = (await getHomework({ limit: 100 })).items; - const labels = await loadInstanceLabels(items.map((item) => item.class_course), auth.user()?.role); - setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label]))); - return items; - }); // The caller's sections, labelled " — <şube>" and ordered class by // class: the şube filter lists them all, the create form only for teachers. const [instances] = createResource( @@ -98,7 +94,7 @@ function HomeworkContent() { const knownIds = new Set(known.map((row) => row.id)); // Homework in a şube the picker does not list (e.g. one the caller only // sees through an assignment) still gets its own entry, after the rest. - const extra = [...new Set((list() ?? []).map((item) => item.class_course))] + const extra = [...new Set((list()?.items ?? []).map((item) => item.class_course))] .filter((id) => !knownIds.has(id) && courseNames()[id]) .map((id) => ({ value: id, label: courseNames()[id] })); return [{ value: "all", label: t("common.all") }, ...known.map((row) => ({ value: row.id, label: row.label })), ...extra]; @@ -114,13 +110,26 @@ function HomeworkContent() { const pageTitle = () => auth.user()?.role === "student" ? t("homework.mineTitle") : t("homework.title"); type DueTab = "all" | "open" | "past"; const [dueTab, setDueTab] = createSignal("all"); - const dueFilteredList = createMemo(() => { - const now = serverTime()?.now ?? Date.now(); - const items = (list() ?? []).filter((item) => courseFilter() === "all" || item.class_course === courseFilter()); - if (dueTab() === "open") return items.filter((item) => item.due_at >= now); - if (dueTab() === "past") return items.filter((item) => item.due_at < now); - return items; - }); + // Tab and section filters are enforced server-side, at the moment of the + // request: Open keeps rows still due (`due_after`), Past keeps rows already + // due (`due_before`), a picked section narrows to it (`class_course`); `all` + // sends no bound. The window rides in the source key so switching tabs + // refetches with that tab's bound, and every page of the filtered set is + // read (no cap, no truncation notice). + const [list, { refetch }] = createResource( + () => `${dueTab()}|${courseFilter()}`, + async (key) => { + const [tab, course] = key.split("|"); + const params: HomeworkListParams = {}; + if (tab === "open") params.due_after = Date.now(); + if (tab === "past") params.due_before = Date.now(); + if (course !== "all") params.class_course = course; + const page = await loadWindowedList((paging) => getHomework({ ...params, ...paging }), LIST_CAP); + const labels = await loadInstanceLabels(page.items.map((item) => item.class_course), auth.user()?.role); + setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label]))); + return page; + }, + ); createEffect(() => { if (!createOpen()) return; @@ -269,10 +278,11 @@ function HomeworkContent() { {formatApiError(list.error)} + getSettings()); const [limits, { refetch: refetchLimits }] = createResource(() => (canManage() ? getLimits() : null)); - const [menus, { refetch }] = createResource(weekStart, (start) => + const [menus, { refetch }] = createResource( + () => [weekStart(), slot()] as const, // `to` is a day past Sunday so the week is whole whether the API reads it - // inclusively or not; the filter below trims anything past Sunday. - getMealMenus({ from: start, to: addDaysIso(start, 7), limit: WEEK_LIMIT, offset: 0 }), + // inclusively or not; the filter below trims anything past Sunday. A real + // slot is filtered server-side; "all" is a pseudo-option the api helper + // drops, so the request stays unfiltered then. + ([start, chosenSlot]) => + getMealMenus({ from: start, to: addDaysIso(start, 7), slot: chosenSlot, limit: WEEK_LIMIT, offset: 0 }), ); const slots = () => settings()?.meal_slots ?? []; diff --git a/src/pages/messages-page.test.tsx b/src/pages/messages-page.test.tsx index 2ce5afe..f9b16c9 100644 --- a/src/pages/messages-page.test.tsx +++ b/src/pages/messages-page.test.tsx @@ -69,3 +69,20 @@ test("emptying trash waits for confirmation and names what it deletes", async () fireEvent.click(within(dialog).getByRole("button", { name: /Empty trash|Çöp kutusunu boşalt/ })); await waitFor(() => expect(deleteMessageById).toHaveBeenCalledTimes(2)); }); + +test("searching hits the server with a trimmed q at first-page offset", async () => { + getMessages.mockResolvedValue({ items: [message(1)], total: 1, limit: 30, offset: 0 }); + + render(() => ( + + + + )); + + const search = await screen.findByPlaceholderText(/Search messages|Mesajlarda ara/); + fireEvent.input(search, { target: { value: " Subject 7 " } }); + + await waitFor(() => + expect(getMessages).toHaveBeenCalledWith("inbox", { limit: 30, offset: 0, q: "Subject 7" }), + ); +}); diff --git a/src/pages/messages-page.tsx b/src/pages/messages-page.tsx index d31973a..a664d64 100644 --- a/src/pages/messages-page.tsx +++ b/src/pages/messages-page.tsx @@ -34,8 +34,7 @@ import type { MessageKey } from "@/i18n/messages"; import { formatApiError } from "@/api/client"; import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; -import { matchesSearch } from "@/lib/search-text"; -import { personLabel } from "@/lib/person"; +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; import { createFlash } from "@/lib/flash"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; @@ -53,15 +52,20 @@ export default function MessagesPage() { const [page, setPage] = createSignal(1); const limit = 30; const [selectedId, setSelectedId] = createSignal(""); - const [query, setQuery] = createSignal(""); + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); const [composeOpen, setComposeOpen] = createSignal(false); const [isRefreshing, setIsRefreshing] = createSignal(false); const [isPending, startTransition] = useTransition(); const [, setFlash] = createFlash(); const [messagePage, { refetch }] = createResource( - () => ({ f: folder(), p: page() }), - async (args) => await getMessages(args.f, { limit, offset: (args.p - 1) * limit }) + () => ({ f: folder(), p: page(), q: debouncedQuery().trim() }), + async (args) => + await getMessages(args.f, { + limit, + offset: (args.p - 1) * limit, + ...(args.q ? { q: args.q } : {}), + }) ); const [unreadCount, { refetch: refetchUnread }] = createResource( @@ -75,17 +79,6 @@ export default function MessagesPage() { rawMessages().slice().sort((a, b) => b.sent_at - a.sent_at) ); - const filtered = createMemo(() => { - const q = query().trim(); - if (!q) return messages(); - return messages().filter((m) => { - const isSent = folder() === "sent" || m.sender.id === auth.user()?.id; - const peer = isSent ? m.recipient : m.sender; - const other = personLabel(peer); - return matchesSearch(q, other, m.subject, m.body, m.label); - }); - }); - const selected = createMemo(() => messages().find((m) => m.id === selectedId()) ?? null); const isOwnSentMessage = (msg: Message) => msg.sender.id === auth.user()?.id; @@ -278,7 +271,11 @@ export default function MessagesPage() { class="h-8 rounded-lg bg-surface-tint pl-9 pr-4 text-[13px] border-none focus-visible:ring-1" placeholder={t("messages.search")} value={query()} - onInput={(event) => setQuery(event.currentTarget.value)} + onInput={(event) => { + setQuery(event.currentTarget.value); + // The server filters from the first row; offset restarts with each search. + setPage(1); + }} /> @@ -327,14 +324,14 @@ export default function MessagesPage() { } > 0} + when={messages().length > 0} fallback={
{t("messages.noMessages")}
} > - + {(message) => ( (null); const [error, setError] = createSignal(""); - const [list] = createResource(async () => { - try { - setError(""); - return await getStudentDirectory(); - } catch (err) { - setError(formatApiError(err)); - return []; - } - }, { initialValue: [] as StudentDirectoryRow[] }); + // No endpoint reports attendance or focus time for a list of students — + // only one student at a time — so the list stays a roster (a column per + // student would be one report read per row). Picking a class scopes the + // directory read to that class's roster; with no class every student is read. + const [classFilter, setClassFilter] = createSignal(""); + // Classes seen on the last full read: the scoped read returns only the + // picked class's roster, so the dropdown keeps listing every class and the + // scoped fetch resolves the picked class without another request. + const [allClasses, setAllClasses] = createSignal([]); + const [list] = createResource( + () => classFilter(), + async (classId) => { + try { + setError(""); + if (!classId) { + const rows = await getStudentDirectory(); + const seen = new Map(); + for (const row of rows) for (const cls of row.classes) seen.set(cls.id, cls); + setAllClasses([...seen.values()]); + return rows; + } + const picked = allClasses().find((cls) => cls.id === classId); + return await getStudentDirectory(picked); + } catch (err) { + setError(formatApiError(err)); + return []; + } + }, + { initialValue: [] as StudentDirectoryRow[] }, + ); const [report, { refetch: refetchReport }] = createResource( () => viewUser()?.id ?? null, @@ -61,18 +82,11 @@ function StudentAttendanceContent() { }, ); - // No endpoint reports attendance or focus time for a list of students — - // only one student at a time — so the list stays a roster (a column per - // student would be one report read per row). The class filter narrows it - // with the memberships the directory already read. - const [classFilter, setClassFilter] = createSignal(""); - const classOptions = createMemo(() => { - const seen = new Map(); - for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); - return [...seen] - .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) - .map(([value, label]) => ({ value, label })); - }); + const classOptions = createMemo(() => + [...allClasses()] + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) + .map((cls) => ({ value: cls.id, label: cls.name })), + ); const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); const listLoading = () => list.loading; const searchPerson = (row: StudentDirectoryRow, query: string) => diff --git a/src/pages/student-pomodoro-page.tsx b/src/pages/student-pomodoro-page.tsx index 8837f72..7f7cdb8 100644 --- a/src/pages/student-pomodoro-page.tsx +++ b/src/pages/student-pomodoro-page.tsx @@ -2,7 +2,7 @@ import { Show, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import type { ColumnDef } from "@tanstack/solid-table"; import { getPomodoroByUser } from "@/api/pomodoro"; -import type { PersonRef } from "@/api/client"; +import type { ClassGroup, PersonRef } from "@/api/client"; import { ApiError, formatApiError } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; @@ -34,15 +34,36 @@ function StudentPomodoroContent() { const [viewUser, setViewUser] = createSignal(null); const [error, setError] = createSignal(""); - const [list] = createResource(async () => { - try { - setError(""); - return await getStudentDirectory(); - } catch (err) { - setError(formatApiError(err)); - return []; - } - }, { initialValue: [] as StudentDirectoryRow[] }); + // No endpoint reports attendance or focus time for a list of students — + // only one student at a time — so the list stays a roster (a column per + // student would be one report read per row). Picking a class scopes the + // directory read to that class's roster; with no class every student is read. + const [classFilter, setClassFilter] = createSignal(""); + // Classes seen on the last full read: the scoped read returns only the + // picked class's roster, so the dropdown keeps listing every class and the + // scoped fetch resolves the picked class without another request. + const [allClasses, setAllClasses] = createSignal([]); + const [list] = createResource( + () => classFilter(), + async (classId) => { + try { + setError(""); + if (!classId) { + const rows = await getStudentDirectory(); + const seen = new Map(); + for (const row of rows) for (const cls of row.classes) seen.set(cls.id, cls); + setAllClasses([...seen.values()]); + return rows; + } + const picked = allClasses().find((cls) => cls.id === classId); + return await getStudentDirectory(picked); + } catch (err) { + setError(formatApiError(err)); + return []; + } + }, + { initialValue: [] as StudentDirectoryRow[] }, + ); const [log, { refetch: refetchLog }] = createResource( () => viewUser()?.id ?? null, @@ -61,18 +82,11 @@ function StudentPomodoroContent() { }, ); - // No endpoint reports attendance or focus time for a list of students — - // only one student at a time — so the list stays a roster (a column per - // student would be one report read per row). The class filter narrows it - // with the memberships the directory already read. - const [classFilter, setClassFilter] = createSignal(""); - const classOptions = createMemo(() => { - const seen = new Map(); - for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); - return [...seen] - .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) - .map(([value, label]) => ({ value, label })); - }); + const classOptions = createMemo(() => + [...allClasses()] + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) + .map((cls) => ({ value: cls.id, label: cls.name })), + ); const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); const listLoading = () => list.loading; const searchPerson = (row: StudentDirectoryRow, query: string) => diff --git a/src/pages/students-roster-page.tsx b/src/pages/students-roster-page.tsx index f652bdb..b0ccbd4 100644 --- a/src/pages/students-roster-page.tsx +++ b/src/pages/students-roster-page.tsx @@ -4,9 +4,8 @@ import { Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { matchesSearch } from "@/lib/search-text"; import { createUrlString } from "@/lib/url-state"; -import { getClassMembers, getClasses } from "@/api/classes"; +import { getClasses } from "@/api/classes"; import { getAcademicYears } from "@/api/academic-years"; -import { getUserSearch } from "@/api/users"; import { formatApiError, type ClassGroup, type PersonRef } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; import { CreateUserPanel } from "@/components/users/create-user-panel"; @@ -20,7 +19,7 @@ import { DropdownSelect } from "@/components/ui/select"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { useT } from "@/stores/preferences-context"; import { useAuth } from "@/stores/auth-context"; -import { sortByClass } from "@/lib/student-directory"; +import { getStudentDirectory } from "@/lib/student-directory"; import { studentInfoSource } from "@/lib/student-info-access"; const ROSTER_PAGE_SIZE = 10; @@ -51,24 +50,22 @@ function StudentsRosterContent() { const [infoTarget, setInfoTarget] = createSignal(null); const infoSource = (person: PersonRef) => studentInfoSource(auth.user(), { id: person.id, role: "student" }); - const [data, { refetch }] = createResource(async () => { - const [students, classes, years] = await Promise.all([ - getUserSearch("", undefined, "student"), - getClasses(), - getAcademicYears().catch(() => ({ items: [] })), - ]); - // No endpoint maps students to classes in bulk; one members read per class - // is bounded by the class count, not the student count. - const memberships = await Promise.all( - classes.items.map(async (cls) => ({ cls, members: (await getClassMembers(cls.id)).items })), - ); - const byStudent = new Map(); - for (const { cls, members } of memberships) { - for (const member of members) byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]); - } - const rows: StudentRow[] = sortByClass(students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] }))); - return { rows, classes: classes.items, years: years.items }; - }); + const [data, { refetch }] = createResource( + () => classFilter(), + async (classId) => { + const [classes, years] = await Promise.all([ + getClasses(), + getAcademicYears().catch(() => ({ items: [] })), + ]); + // A picked class (?class=) scopes the roster read to that class's + // members; with no class every student and every class's members are + // read. The class and year lists always come along: the filter + // dropdowns need them either way. + const picked = classId ? classes.items.find((cls) => cls.id === classId) : undefined; + const rows = await getStudentDirectory(picked); + return { rows, classes: classes.items, years: years.items }; + }, + ); const rows = createMemo(() => (data()?.rows ?? []).filter((row) => { diff --git a/src/pages/whiteboards-page.tsx b/src/pages/whiteboards-page.tsx index 7041885..cce1fa5 100644 --- a/src/pages/whiteboards-page.tsx +++ b/src/pages/whiteboards-page.tsx @@ -1,6 +1,7 @@ import { useNavigate } from "@tanstack/solid-router"; import { For, Show, Suspense, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"; import { createResponsivePageSize } from "@/lib/create-page-size"; +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; import { createResource } from "@/lib/create-resource"; import { getBoards, postBoard, type Board } from "@/api/boards"; import { getUserSearch } from "@/api/users"; @@ -19,7 +20,6 @@ import { SidePanel } from "@/components/ui/side-panel"; import { TablePagination } from "@/components/ui/table-pagination"; import { cn } from "@/lib/cn"; import { formatDate } from "@/lib/format"; -import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; @@ -42,21 +42,21 @@ function WhiteboardsContent() { const pageSize = createResponsivePageSize(12); const [page, setPage] = createSignal(0); createEffect(on(pageSize, () => setPage(0), { defer: true })); + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); const [boards, { refetch }] = createResource( - () => ({ page: page(), size: pageSize() }), - (source) => getBoards({ limit: source.size, offset: source.page * source.size }), + () => ({ page: page(), size: pageSize(), q: debouncedQuery().trim() }), + (source) => + getBoards({ + limit: source.size, + offset: source.page * source.size, + ...(source.q ? { q: source.q } : {}), + }), ); const [createOpen, setCreateOpen] = createSignal(false); const pageCount = createMemo(() => Math.max(1, Math.ceil((boards.latest?.total ?? 0) / pageSize()))); - const [query, setQuery] = createSignal(""); - // The board list endpoint has no server-side text filter, so this narrows - // only the current page's real titles — a client-side search over real - // data, not a promise of searching every board the caller has ever opened. - const visibleBoards = createMemo(() => { - const q = query().trim(); - const items = boards()?.items ?? []; - return q ? items.filter((b) => matchesSearch(q, b.title)) : items; - }); + // The server narrows by title via `q`; the page holds whatever the current + // query matched, so totals and pagination already reflect the search. + const visibleBoards = createMemo(() => boards()?.items ?? []); const meId = () => auth.user()?.id ?? ""; @@ -68,7 +68,11 @@ function WhiteboardsContent() { searchValue={query()} searchPlaceholder={t("whiteboard.searchPlaceholder")} searchHint={t("search.hint.whiteboards")} - onSearchInput={setQuery} + onSearchInput={(value) => { + setQuery(value); + // The server filters from the first row; offset restarts with each search. + setPage(0); + }} actions={