🔎 send the new server filters from the list pages
Browse files at this commit76f3534d888b4185fb85618aa57e956c648b4479Parent: 4bea99d- feat
- 🔎 send the new server filters from the list pages
52 changed files +1192 -376
- src/api/__tests__/appointments/appointments.test.ts +18 -0
- src/api/__tests__/boards/boards.test.ts +16 -0
- src/api/__tests__/classes/classes.test.ts +9 -0
- src/api/__tests__/courses/courses.test.ts +20 -1
- src/api/__tests__/events/events.test.ts +11 -0
- src/api/__tests__/exams/exams.test.ts +11 -0
- src/api/__tests__/homework/homework.test.ts +9 -1
- src/api/__tests__/instances/instances.test.ts +9 -0
- src/api/__tests__/meals/meals.test.ts +11 -3
- src/api/__tests__/messages/messages.test.ts +16 -0
- src/api/__tests__/pomodoro/pomodoro.test.ts +30 -0
- src/api/__tests__/users/users.test.ts +27 -0
- src/api/appointments/getAppointments.ts +29 -4
- src/api/appointments/getSlots.ts +21 -3
- src/api/boards/getBoards.ts +13 -4
- src/api/classes/getClasses.ts +17 -4
- src/api/client/page.ts +8 -2
- src/api/courses/getCourses.ts +18 -7
- src/api/homework/getHomework.ts +17 -3
- src/api/instances/getInstanceSessions.ts +21 -3
- src/api/meals/getMealMenus.ts +6 -1
- src/api/messages/getMessages.ts +9 -7
- src/api/pomodoro/getPomodoroMe.ts +18 -3
- src/api/users/getUsers.ts +16 -4
- src/components/dashboard/today-lessons-panel.tsx +11 -4
- src/components/sessions/course-sessions-panel.tsx +9 -1
- src/lib/capped-list.test.ts +23 -1
- src/lib/capped-list.ts +24 -0
- src/lib/student-directory.test.ts +79 -3
- src/lib/student-directory.ts +24 -3
- src/pages/admin-users-page.tsx +17 -10
- src/pages/appointments-page.test.tsx +8 -1
- src/pages/appointments-page.tsx +23 -26
- src/pages/calendar-page.test.tsx +62 -5
- src/pages/calendar-page.tsx +54 -17
- src/pages/classes-page.test.tsx +38 -0
- src/pages/classes-page.tsx +24 -9
- src/pages/courses-page.test.tsx +65 -50
- src/pages/courses-page.tsx +56 -27
- src/pages/dashboard-page.tsx +33 -10
- src/pages/events-page.test.tsx +37 -2
- src/pages/events-page.tsx +17 -11
- src/pages/exams-page.tsx +19 -9
- src/pages/homework-page.tsx +26 -16
- src/pages/meals-page.tsx +7 -3
- src/pages/messages-page.test.tsx +17 -0
- src/pages/messages-page.tsx +16 -19
- src/pages/student-attendance-page.tsx +36 -22
- src/pages/student-pomodoro-page.tsx +36 -22
- src/pages/students-roster-page.tsx +18 -21
- src/pages/whiteboards-page.tsx +18 -14
- src/stores/shell-feed-context.tsx +15 -20
src/api/__tests__/appointments/appointments.test.tsmodified+18 -0
| @@ -44,6 +44,12 @@ describe("appointments API", () => { | |||
| 44 | expect(init?.method).toBe("GET"); | 44 | expect(init?.method).toBe("GET"); |
| 45 | }); | 45 | }); |
| 46 | 46 | ||
| 47 | + it("getSlots sends teacher and start window when set", async () => { | ||
| 48 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 49 | + await getSlots({ teacher: "me", starts_after: 1700000000000, limit: 10 }); | ||
| 50 | + expect(lastFetchCall()[0]).toBe("/api/appointments/slots?limit=10&starts_after=1700000000000&teacher=me"); | ||
| 51 | + }); | ||
| 52 | + | ||
| 47 | it("deleteSlotById calls /appointments/slots/:id", async () => { | 53 | it("deleteSlotById calls /appointments/slots/:id", async () => { |
| 48 | mockFetch204(); | 54 | mockFetch204(); |
| 49 | 55 | ||
| @@ -90,6 +96,18 @@ describe("appointments API", () => { | |||
| 90 | expect(init?.method).toBe("GET"); | 96 | expect(init?.method).toBe("GET"); |
| 91 | }); | 97 | }); |
| 92 | 98 | ||
| 99 | + it("getAppointments sends status, teacher and start window when set", async () => { | ||
| 100 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 101 | + await getAppointments({ status: "pending", teacher: "me", starts_after: 1700000000000, starts_before: 1800000000000, limit: 10, offset: 20 }); | ||
| 102 | + expect(lastFetchCall()[0]).toBe("/api/appointments?limit=10&offset=20&starts_after=1700000000000&starts_before=1800000000000&status=pending&teacher=me"); | ||
| 103 | + }); | ||
| 104 | + | ||
| 105 | + it("getAppointments omits unset filters — no bare keys", async () => { | ||
| 106 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 107 | + await getAppointments(); | ||
| 108 | + expect(lastFetchCall()[0]).toBe("/api/appointments"); | ||
| 109 | + }); | ||
| 110 | + | ||
| 93 | it("patchApproveAppointment calls /appointments/:id/approve", async () => { | 111 | it("patchApproveAppointment calls /appointments/:id/approve", async () => { |
| 94 | const mockAppt = { id: "a1", status: "approved" }; | 112 | const mockAppt = { id: "a1", status: "approved" }; |
| 95 | mockFetchSuccess(mockAppt); | 113 | mockFetchSuccess(mockAppt); |
src/api/__tests__/boards/boards.test.tsmodified+16 -0
| @@ -41,6 +41,22 @@ describe("boards API", () => { | |||
| 41 | expect(init?.method).toBe("GET"); | 41 | expect(init?.method).toBe("GET"); |
| 42 | }); | 42 | }); |
| 43 | 43 | ||
| 44 | + it("getBoards sends q with pagination when given", async () => { | ||
| 45 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 46 | + await getBoards({ limit: 10, offset: 20, q: "math, physics" }); | ||
| 47 | + | ||
| 48 | + const [url] = lastFetchCall(); | ||
| 49 | + expect(url).toBe("/api/boards?q=math%2C+physics&limit=10&offset=20"); | ||
| 50 | + }); | ||
| 51 | + | ||
| 52 | + it("getBoards omits a blank q", async () => { | ||
| 53 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 54 | + await getBoards({ q: " " }); | ||
| 55 | + | ||
| 56 | + const [url] = lastFetchCall(); | ||
| 57 | + expect(url).toBe("/api/boards"); | ||
| 58 | + }); | ||
| 59 | + | ||
| 44 | it("getBoardById calls GET /boards/:id", async () => { | 60 | it("getBoardById calls GET /boards/:id", async () => { |
| 45 | mockFetchSuccess({ id: "b1" }); | 61 | mockFetchSuccess({ id: "b1" }); |
| 46 | await getBoardById("b1"); | 62 | await getBoardById("b1"); |
src/api/__tests__/classes/classes.test.tsmodified+9 -0
| @@ -51,6 +51,15 @@ describe("classes API", () => { | |||
| 51 | expect(init?.method ?? "GET").toBe("GET"); | 51 | expect(init?.method ?? "GET").toBe("GET"); |
| 52 | }); | 52 | }); |
| 53 | 53 | ||
| 54 | + it("getClasses sends grade_level only when set", async () => { | ||
| 55 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 56 | + await getClasses({ grade_level: 9, limit: 5 }); | ||
| 57 | + expect(lastFetchCall()[0]).toBe("/api/classes?limit=5&grade_level=9"); | ||
| 58 | + | ||
| 59 | + await getClasses({ grade_level: undefined, limit: 5 }); | ||
| 60 | + expect(lastFetchCall()[0]).toBe("/api/classes?limit=5"); | ||
| 61 | + }); | ||
| 62 | + | ||
| 54 | it("getClassById GETs /classes/:id", async () => { | 63 | it("getClassById GETs /classes/:id", async () => { |
| 55 | mockFetchSuccess({ id: "c1" }); | 64 | mockFetchSuccess({ id: "c1" }); |
| 56 | await getClassById("c1"); | 65 | await getClassById("c1"); |
src/api/__tests__/courses/courses.test.tsmodified+20 -1
| @@ -28,12 +28,31 @@ describe("courses API", () => { | |||
| 28 | expect(init?.method).toBe("GET"); | 28 | expect(init?.method).toBe("GET"); |
| 29 | }); | 29 | }); |
| 30 | 30 | ||
| 31 | - it("getCourses sends pagination only — the endpoint has no kind/term/search filter", async () => { | 31 | + it("getCourses keeps pagination when no filter is set", async () => { |
| 32 | mockFetchSuccess({ items: [], total: 0 }); | 32 | mockFetchSuccess({ items: [], total: 0 }); |
| 33 | await getCourses({ limit: 12, offset: 24 }); | 33 | await getCourses({ limit: 12, offset: 24 }); |
| 34 | expect(lastFetchCall()[0]).toBe("/api/courses?limit=12&offset=24"); | 34 | expect(lastFetchCall()[0]).toBe("/api/courses?limit=12&offset=24"); |
| 35 | }); | 35 | }); |
| 36 | 36 | ||
| 37 | + it("getCourses sends kind and a trimmed q only when set", async () => { | ||
| 38 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 39 | + await getCourses({ limit: 10, offset: 20, kind: "study", q: " algebra " }); | ||
| 40 | + expect(lastFetchCall()[0]).toBe("/api/courses?limit=10&offset=20&kind=study&q=algebra"); | ||
| 41 | + }); | ||
| 42 | + | ||
| 43 | + it("getCourses serializes taught as true/false and omits blank q", async () => { | ||
| 44 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 45 | + // Blank q drops the key entirely — the API 400s on `?q=`. | ||
| 46 | + await getCourses({ q: " " }); | ||
| 47 | + expect(lastFetchCall()[0]).toBe("/api/courses"); | ||
| 48 | + | ||
| 49 | + await getCourses({ taught: true, limit: 10 }); | ||
| 50 | + expect(lastFetchCall()[0]).toBe("/api/courses?limit=10&taught=true"); | ||
| 51 | + | ||
| 52 | + await getCourses({ taught: false, offset: 5 }); | ||
| 53 | + expect(lastFetchCall()[0]).toBe("/api/courses?offset=5&taught=false"); | ||
| 54 | + }); | ||
| 55 | + | ||
| 37 | it("getCourseById calls /courses/:id", async () => { | 56 | it("getCourseById calls /courses/:id", async () => { |
| 38 | const mockCourse = { id: "c1", title: "Course" }; | 57 | const mockCourse = { id: "c1", title: "Course" }; |
| 39 | mockFetchSuccess(mockCourse); | 58 | mockFetchSuccess(mockCourse); |
src/api/__tests__/events/events.test.tsmodified+11 -0
| @@ -46,6 +46,17 @@ describe("events API", () => { | |||
| 46 | expect(lastFetchCall()[0]).toBe("/api/events?limit=10"); | 46 | expect(lastFetchCall()[0]).toBe("/api/events?limit=10"); |
| 47 | expect(lastFetchCall()[0]).not.toContain("ends_after"); | 47 | expect(lastFetchCall()[0]).not.toContain("ends_after"); |
| 48 | expect(lastFetchCall()[0]).not.toContain("starts_after"); | 48 | expect(lastFetchCall()[0]).not.toContain("starts_after"); |
| 49 | + | ||
| 50 | + // Upper bounds serialize after the earlier keys, in declaration order. | ||
| 51 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 52 | + await getEvents({ starts_after: 1, ends_after: 2, starts_before: 3, ends_before: 4 }); | ||
| 53 | + expect(lastFetchCall()[0]).toBe("/api/events?starts_after=1&ends_after=2&starts_before=3&ends_before=4"); | ||
| 54 | + | ||
| 55 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 56 | + await getEvents({ limit: 10, starts_before: undefined, ends_before: undefined }); | ||
| 57 | + expect(lastFetchCall()[0]).toBe("/api/events?limit=10"); | ||
| 58 | + expect(lastFetchCall()[0]).not.toContain("starts_before"); | ||
| 59 | + expect(lastFetchCall()[0]).not.toContain("ends_before"); | ||
| 49 | }); | 60 | }); |
| 50 | 61 | ||
| 51 | it("getEventById calls /events/:id", async () => { | 62 | it("getEventById calls /events/:id", async () => { |
src/api/__tests__/exams/exams.test.tsmodified+11 -0
| @@ -47,6 +47,17 @@ describe("exams API - core", () => { | |||
| 47 | expect(lastFetchCall()[0]).toBe("/api/exams?limit=10"); | 47 | expect(lastFetchCall()[0]).toBe("/api/exams?limit=10"); |
| 48 | expect(lastFetchCall()[0]).not.toContain("ends_after"); | 48 | expect(lastFetchCall()[0]).not.toContain("ends_after"); |
| 49 | expect(lastFetchCall()[0]).not.toContain("starts_after"); | 49 | expect(lastFetchCall()[0]).not.toContain("starts_after"); |
| 50 | + | ||
| 51 | + // Upper bounds serialize after the earlier keys, in declaration order. | ||
| 52 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 53 | + await getExams({ starts_after: 1, ends_after: 2, starts_before: 3, ends_before: 4 }); | ||
| 54 | + expect(lastFetchCall()[0]).toBe("/api/exams?starts_after=1&ends_after=2&starts_before=3&ends_before=4"); | ||
| 55 | + | ||
| 56 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 57 | + await getExams({ limit: 10, starts_before: undefined, ends_before: undefined }); | ||
| 58 | + expect(lastFetchCall()[0]).toBe("/api/exams?limit=10"); | ||
| 59 | + expect(lastFetchCall()[0]).not.toContain("starts_before"); | ||
| 60 | + expect(lastFetchCall()[0]).not.toContain("ends_before"); | ||
| 50 | }); | 61 | }); |
| 51 | 62 | ||
| 52 | it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => { | 63 | it("getExamChoiceImageBlob calls /exams/:id/questions/:qid/choices/:choiceId/image", async () => { |
src/api/__tests__/homework/homework.test.tsmodified+9 -1
| @@ -36,10 +36,18 @@ describe("homework API", () => { | |||
| 36 | expect(init?.method).toBe("GET"); | 36 | expect(init?.method).toBe("GET"); |
| 37 | }); | 37 | }); |
| 38 | 38 | ||
| 39 | - it("getHomework sends pagination only — the endpoint has no due-date window", async () => { | 39 | + it("getHomework sends the due window and class_course when set", async () => { |
| 40 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 41 | + await getHomework({ due_after: 1700000000000, due_before: 1800000000000, class_course: "i1", limit: 50 }); | ||
| 42 | + expect(lastFetchCall()[0]).toBe("/api/homework?limit=50&due_after=1700000000000&due_before=1800000000000&class_course=i1"); | ||
| 43 | + }); | ||
| 44 | + | ||
| 45 | + it("getHomework omits unset filters — no bare keys", async () => { | ||
| 40 | mockFetchSuccess({ items: [], total: 0 }); | 46 | mockFetchSuccess({ items: [], total: 0 }); |
| 41 | await getHomework({ limit: 1 }); | 47 | await getHomework({ limit: 1 }); |
| 42 | expect(lastFetchCall()[0]).toBe("/api/homework?limit=1"); | 48 | expect(lastFetchCall()[0]).toBe("/api/homework?limit=1"); |
| 49 | + await getHomework({ class_course: " " }); | ||
| 50 | + expect(lastFetchCall()[0]).toBe("/api/homework"); | ||
| 43 | }); | 51 | }); |
| 44 | 52 | ||
| 45 | it("getHomeworkById calls /homework/:id", async () => { | 53 | it("getHomeworkById calls /homework/:id", async () => { |
src/api/__tests__/instances/instances.test.tsmodified+9 -0
| @@ -150,6 +150,15 @@ describe("instances API", () => { | |||
| 150 | expect(url).toBe("/api/instances/i1/sessions"); | 150 | expect(url).toBe("/api/instances/i1/sessions"); |
| 151 | }); | 151 | }); |
| 152 | 152 | ||
| 153 | + it("getInstanceSessions sends the half-open start window when set", async () => { | ||
| 154 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 155 | + | ||
| 156 | + await getInstanceSessions("i1", { starts_after: 1700000000000, starts_before: 1800000000000, limit: 100 }); | ||
| 157 | + | ||
| 158 | + const [url] = lastFetchCall(); | ||
| 159 | + expect(url).toBe("/api/instances/i1/sessions?limit=100&starts_after=1700000000000&starts_before=1800000000000"); | ||
| 160 | + }); | ||
| 161 | + | ||
| 153 | it("postInstanceSession POSTs /instances/:id/sessions with the body", async () => { | 162 | it("postInstanceSession POSTs /instances/:id/sessions with the body", async () => { |
| 154 | mockFetchSuccess({ id: "se1" }); | 163 | mockFetchSuccess({ id: "se1" }); |
| 155 | const body = { starts_at: 1900000000000, topic: "Limits" }; | 164 | const body = { starts_at: 1900000000000, topic: "Limits" }; |
src/api/__tests__/meals/meals.test.tsmodified+11 -3
| @@ -30,9 +30,17 @@ describe("meals API", () => { | |||
| 30 | const json = () => mockFetchSuccess({}); | 30 | const json = () => mockFetchSuccess({}); |
| 31 | const page = () => mockFetchSuccess({ items: [], total: 0 }); | 31 | const page = () => mockFetchSuccess({ items: [], total: 0 }); |
| 32 | 32 | ||
| 33 | - it("lists menus with dates and pagination", async () => { | 33 | + it("lists menus with dates, slot, and pagination", async () => { |
| 34 | - page(); await getMealMenus({ from: "2026-07-28", to: "2026-08-01", limit: 12, offset: 12 }); | 34 | + page(); await getMealMenus({ from: "2026-07-28", to: "2026-08-01", slot: "lunch", limit: 12, offset: 12 }); |
| 35 | - expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=12&offset=12&from=2026-07-28&to=2026-08-01"); | 35 | + expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=12&offset=12&from=2026-07-28&to=2026-08-01&slot=lunch"); |
| 36 | + }); | ||
| 37 | + it("omits the slot key for the all pseudo-option, blank, and unset", async () => { | ||
| 38 | + page(); await getMealMenus({ slot: "all", limit: 5 }); | ||
| 39 | + expect(lastFetchCall()[0]).toBe("/api/meals/menus?limit=5"); | ||
| 40 | + page(); await getMealMenus({ slot: " " }); | ||
| 41 | + expect(lastFetchCall()[0]).toBe("/api/meals/menus"); | ||
| 42 | + page(); await getMealMenus(); | ||
| 43 | + expect(lastFetchCall()[0]).toBe("/api/meals/menus"); | ||
| 36 | }); | 44 | }); |
| 37 | it("gets a menu", async () => { json(); await getMealMenuById("m/1"); expect(lastFetchCall()[0]).toBe("/api/meals/menus/m%2F1"); }); | 45 | it("gets a menu", async () => { json(); await getMealMenuById("m/1"); expect(lastFetchCall()[0]).toBe("/api/meals/menus/m%2F1"); }); |
| 38 | it("publishes a menu", async () => { | 46 | it("publishes a menu", async () => { |
src/api/__tests__/messages/messages.test.tsmodified+16 -0
| @@ -22,6 +22,22 @@ describe("messages API", () => { | |||
| 22 | expect(init?.method).toBe("GET"); | 22 | expect(init?.method).toBe("GET"); |
| 23 | }); | 23 | }); |
| 24 | 24 | ||
| 25 | + it("getMessages sends q with folder, read and pagination", async () => { | ||
| 26 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 27 | + await getMessages("inbox", { limit: 10, offset: 20, read: false, q: "math, physics" }); | ||
| 28 | + | ||
| 29 | + const [url] = lastFetchCall(); | ||
| 30 | + expect(url).toBe("/api/messages?folder=inbox&read=false&q=math%2C+physics&limit=10&offset=20"); | ||
| 31 | + }); | ||
| 32 | + | ||
| 33 | + it("getMessages omits a blank q", async () => { | ||
| 34 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 35 | + await getMessages("sent", { q: " " }); | ||
| 36 | + | ||
| 37 | + const [url] = lastFetchCall(); | ||
| 38 | + expect(url).toBe("/api/messages?folder=sent"); | ||
| 39 | + }); | ||
| 40 | + | ||
| 25 | it("postMessage calls /messages with data", async () => { | 41 | it("postMessage calls /messages with data", async () => { |
| 26 | const mockMessage = { id: "m1" }; | 42 | const mockMessage = { id: "m1" }; |
| 27 | mockFetchSuccess(mockMessage); | 43 | mockFetchSuccess(mockMessage); |
src/api/__tests__/pomodoro/pomodoro.test.tsmodified+30 -0
| @@ -22,6 +22,36 @@ describe("pomodoro API", () => { | |||
| 22 | expect(init?.method).toBe("GET"); | 22 | expect(init?.method).toBe("GET"); |
| 23 | }); | 23 | }); |
| 24 | 24 | ||
| 25 | + it("getPomodoroMe serializes the from/to window next to pagination", async () => { | ||
| 26 | + mockFetchSuccess({ items: [], total: 0, limit: 400, offset: 0, total_focus_ms: 0 }); | ||
| 27 | + | ||
| 28 | + await getPomodoroMe({ limit: 400, offset: 0, from: 1000, to: 2000 }); | ||
| 29 | + | ||
| 30 | + const [url, init] = lastFetchCall(); | ||
| 31 | + expect(url).toBe("/api/pomodoro/me?limit=400&offset=0&from=1000&to=2000"); | ||
| 32 | + expect(init?.method).toBe("GET"); | ||
| 33 | + }); | ||
| 34 | + | ||
| 35 | + it("getPomodoroMe sends only the bounds that are set", async () => { | ||
| 36 | + mockFetchSuccess({ items: [], total: 0, limit: null, offset: 0, total_focus_ms: 0 }); | ||
| 37 | + | ||
| 38 | + await getPomodoroMe({ from: 1000 }); | ||
| 39 | + | ||
| 40 | + const [url, init] = lastFetchCall(); | ||
| 41 | + expect(url).toBe("/api/pomodoro/me?from=1000"); | ||
| 42 | + expect(init?.method).toBe("GET"); | ||
| 43 | + }); | ||
| 44 | + | ||
| 45 | + it("getPomodoroMe sends a bare URL without any params", async () => { | ||
| 46 | + mockFetchSuccess({ items: [], total: 0, limit: null, offset: 0, total_focus_ms: 0 }); | ||
| 47 | + | ||
| 48 | + await getPomodoroMe(); | ||
| 49 | + | ||
| 50 | + const [url, init] = lastFetchCall(); | ||
| 51 | + expect(url).toBe("/api/pomodoro/me"); | ||
| 52 | + expect(init?.method).toBe("GET"); | ||
| 53 | + }); | ||
| 54 | + | ||
| 25 | it("getPomodoroByUser calls /pomodoro/users/:id with pagination", async () => { | 55 | it("getPomodoroByUser calls /pomodoro/users/:id with pagination", async () => { |
| 26 | const mockLog = { items: [{ id: "p1" }], total: 1, limit: 10, offset: 0, total_focus_ms: 1000 }; | 56 | const mockLog = { items: [{ id: "p1" }], total: 1, limit: 10, offset: 0, total_focus_ms: 1000 }; |
| 27 | mockFetchSuccess(mockLog); | 57 | mockFetchSuccess(mockLog); |
src/api/__tests__/users/users.test.tsmodified+27 -0
| @@ -60,6 +60,33 @@ describe("users API", () => { | |||
| 60 | expect(init?.method).toBe("GET"); | 60 | expect(init?.method).toBe("GET"); |
| 61 | }); | 61 | }); |
| 62 | 62 | ||
| 63 | + it("getUsers comma-joins multiple roles (manager tab = manager+admin)", async () => { | ||
| 64 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 65 | + | ||
| 66 | + await getUsers({ roles: ["manager", "admin"], limit: 200 }); | ||
| 67 | + | ||
| 68 | + const [url] = lastFetchCall(); | ||
| 69 | + expect(url).toBe("/api/users?limit=200&roles=manager%2Cadmin"); | ||
| 70 | + }); | ||
| 71 | + | ||
| 72 | + it("getUsers sends a single role unchanged", async () => { | ||
| 73 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 74 | + | ||
| 75 | + await getUsers({ roles: ["teacher"] }); | ||
| 76 | + | ||
| 77 | + const [url] = lastFetchCall(); | ||
| 78 | + expect(url).toBe("/api/users?roles=teacher"); | ||
| 79 | + }); | ||
| 80 | + | ||
| 81 | + it("getUsers omits roles when the array is empty", async () => { | ||
| 82 | + mockFetchSuccess({ items: [], total: 0 }); | ||
| 83 | + | ||
| 84 | + await getUsers({ roles: [], limit: 5 }); | ||
| 85 | + | ||
| 86 | + const [url] = lastFetchCall(); | ||
| 87 | + expect(url).toBe("/api/users?limit=5"); | ||
| 88 | + }); | ||
| 89 | + | ||
| 63 | it("getUserSearch calls /users/search with query, role, and pagination", async () => { | 90 | it("getUserSearch calls /users/search with query, role, and pagination", async () => { |
| 64 | const mockPage = { items: [{ id: "u1" }], total: 1 }; | 91 | const mockPage = { items: [{ id: "u1" }], total: 1 }; |
| 65 | mockFetchSuccess(mockPage); | 92 | mockFetchSuccess(mockPage); |
src/api/appointments/getAppointments.tsmodified+29 -4
| @@ -1,8 +1,33 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; |
| 3 | -import type { Appointment } from "../client"; | 3 | +import type { Appointment, AppointmentStatus } from "../client"; |
| 4 | 4 | ||
| 5 | -export async function getAppointments(params?: PageParams, signal?: AbortSignal): Promise<Page<Appointment>> { | 5 | +/** |
| 6 | - const data = await client<unknown>(`/appointments${pageQuery(params)}`, { signal }); | 6 | + * `GET /appointments` filters. All optional and AND-ed; the list stays |
| 7 | + * newest-created first. `starts_after` is unix ms and half-open on the | ||
| 8 | + * appointment start (`starts_at >= v`). | ||
| 9 | + */ | ||
| 10 | +export type AppointmentListParams = PageParams & { | ||
| 11 | + /** Only appointments in this state. */ | ||
| 12 | + status?: AppointmentStatus; | ||
| 13 | + /** Only appointments of the calling staff member; the value is the literal "me". */ | ||
| 14 | + teacher?: "me"; | ||
| 15 | + /** Keeps appointments that have started or start later: `starts_at >= v` (unix ms). */ | ||
| 16 | + starts_after?: number; | ||
| 17 | + /** Keeps appointments starting before this instant: `starts_at < v` (unix ms). */ | ||
| 18 | + starts_before?: number; | ||
| 19 | +}; | ||
| 20 | + | ||
| 21 | +export async function getAppointments(params?: AppointmentListParams, signal?: AbortSignal): Promise<Page<Appointment>> { | ||
| 22 | + const query = new URLSearchParams(); | ||
| 23 | + appendPageParams(query, params); | ||
| 24 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an | ||
| 25 | + // unset param must drop the key, never emit `key=`. | ||
| 26 | + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); | ||
| 27 | + if (params?.starts_before != null) query.set("starts_before", String(params.starts_before)); | ||
| 28 | + const status = params?.status?.trim(); | ||
| 29 | + if (status) query.set("status", status); | ||
| 30 | + if (params?.teacher) query.set("teacher", params.teacher); | ||
| 31 | + const data = await client<unknown>(`/appointments${query.size ? `?${query}` : ""}`, { signal }); | ||
| 7 | return normalizePage<Appointment>(data); | 32 | return normalizePage<Appointment>(data); |
| 8 | } | 33 | } |
src/api/appointments/getSlots.tsmodified+21 -3
| @@ -1,8 +1,26 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; |
| 3 | import type { AppointmentSlot } from "../client"; | 3 | import type { AppointmentSlot } from "../client"; |
| 4 | 4 | ||
| 5 | -export async function getSlots(params?: PageParams, signal?: AbortSignal): Promise<Page<AppointmentSlot>> { | 5 | +/** |
| 6 | - const data = await client<unknown>(`/appointments/slots${pageQuery(params)}`, { signal }); | 6 | + * `GET /appointments/slots` filters. All optional and AND-ed; the list stays |
| 7 | + * `starts_at ASC`. `starts_after` is unix ms and half-open on the slot start | ||
| 8 | + * (`starts_at >= v`). | ||
| 9 | + */ | ||
| 10 | +export type SlotListParams = PageParams & { | ||
| 11 | + /** Only slots of the calling staff member; the value is the literal "me". */ | ||
| 12 | + teacher?: "me"; | ||
| 13 | + /** Keeps slots that have started or start later: `starts_at >= v` (unix ms). */ | ||
| 14 | + starts_after?: number; | ||
| 15 | +}; | ||
| 16 | + | ||
| 17 | +export async function getSlots(params?: SlotListParams, signal?: AbortSignal): Promise<Page<AppointmentSlot>> { | ||
| 18 | + const query = new URLSearchParams(); | ||
| 19 | + appendPageParams(query, params); | ||
| 20 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an | ||
| 21 | + // unset param must drop the key, never emit `key=`. | ||
| 22 | + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); | ||
| 23 | + if (params?.teacher) query.set("teacher", params.teacher); | ||
| 24 | + const data = await client<unknown>(`/appointments/slots${query.size ? `?${query}` : ""}`, { signal }); | ||
| 7 | return normalizePage<AppointmentSlot>(data); | 25 | return normalizePage<AppointmentSlot>(data); |
| 8 | } | 26 | } |
src/api/boards/getBoards.tsmodified+13 -4
| @@ -1,8 +1,17 @@ | |||
| 1 | -import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 1 | +import { appendPageParams, client, normalizePage, type Page, type PageParams } from "../client"; |
| 2 | import type { Board } from "./types"; | 2 | import type { Board } from "./types"; |
| 3 | 3 | ||
| 4 | -// Boards the caller created or was invited to, newest first. | 4 | +// Boards the caller created or was invited to, newest first. `q` filters by |
| 5 | -export async function getBoards(params?: PageParams, signal?: AbortSignal): Promise<Page<Board>> { | 5 | +// title server-side; blank after trim means no filter. |
| 6 | - const data = await client<unknown>(`/boards${pageQuery(params)}`, { signal }); | 6 | +export async function getBoards( |
| 7 | + params?: PageParams & { q?: string }, | ||
| 8 | + signal?: AbortSignal, | ||
| 9 | +): Promise<Page<Board>> { | ||
| 10 | + const query = new URLSearchParams(); | ||
| 11 | + const q = params?.q?.trim(); | ||
| 12 | + if (q) query.set("q", q); | ||
| 13 | + appendPageParams(query, params); | ||
| 14 | + const search = query.toString(); | ||
| 15 | + const data = await client<unknown>(`/boards${search ? `?${search}` : ""}`, { signal }); | ||
| 7 | return normalizePage<Board>(data); | 16 | return normalizePage<Board>(data); |
| 8 | } | 17 | } |
src/api/classes/getClasses.tsmodified+17 -4
| @@ -1,8 +1,21 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type ClassGroup, type Page, type PageParams } from "../client"; |
| 3 | -import type { ClassGroup } from "../client"; | ||
| 4 | 3 | ||
| 5 | -export async function getClasses(params?: PageParams, signal?: AbortSignal): Promise<Page<ClassGroup>> { | 4 | +/** |
| 6 | - const data = await client<unknown>(`/classes${pageQuery(params)}`, { signal }); | 5 | + * `GET /classes` list filters. `grade_level` keeps classes on one rung of the |
| 6 | + * grade ladder; an omitted key filters nothing. | ||
| 7 | + */ | ||
| 8 | +export type ClassListParams = PageParams & { | ||
| 9 | + grade_level?: number; | ||
| 10 | +}; | ||
| 11 | + | ||
| 12 | +export async function getClasses(params?: ClassListParams, signal?: AbortSignal): Promise<Page<ClassGroup>> { | ||
| 13 | + const query = new URLSearchParams(); | ||
| 14 | + appendPageParams(query, params); | ||
| 15 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so | ||
| 16 | + // an unset grade must drop the key, never emit `grade_level=`. | ||
| 17 | + if (params?.grade_level != null) query.set("grade_level", String(params.grade_level)); | ||
| 18 | + const value = query.toString(); | ||
| 19 | + const data = await client<unknown>(`/classes${value ? `?${value}` : ""}`, { signal }); | ||
| 7 | return normalizePage<ClassGroup>(data); | 20 | return normalizePage<ClassGroup>(data); |
| 8 | } | 21 | } |
src/api/client/page.tsmodified+8 -2
| @@ -24,8 +24,8 @@ export class PageShapeError extends Error { | |||
| 24 | 24 | ||
| 25 | /** | 25 | /** |
| 26 | * Schedule-window filters, UTC unix ms. Only `/events` and `/exams` honour | 26 | * Schedule-window filters, UTC unix ms. Only `/events` and `/exams` honour |
| 27 | - * them; both are optional and AND-ed when both sent, and a row with no | 27 | + * them; all are optional and AND-ed when several are sent, and a row with no |
| 28 | - * schedule at all is excluded by either. Sending either flips the server | 28 | + * schedule at all is excluded by any of them. Sending any flips the server |
| 29 | * order to ASCENDING by schedule (soonest first) instead of newest-created. | 29 | * order to ASCENDING by schedule (soonest first) instead of newest-created. |
| 30 | */ | 30 | */ |
| 31 | export type ScheduleWindowParams = { | 31 | export type ScheduleWindowParams = { |
| @@ -33,6 +33,10 @@ export type ScheduleWindowParams = { | |||
| 33 | starts_after?: number; | 33 | starts_after?: number; |
| 34 | /** Keeps rows whose window has not finished: `ends_at > T`, else `starts_at > T`. */ | 34 | /** Keeps rows whose window has not finished: `ends_at > T`, else `starts_at > T`. */ |
| 35 | ends_after?: number; | 35 | ends_after?: number; |
| 36 | + /** Keeps rows that have already begun or begin earlier: `starts_at < T`. */ | ||
| 37 | + starts_before?: number; | ||
| 38 | + /** Keeps rows whose window has already finished: `ends_at < T`. */ | ||
| 39 | + ends_before?: number; | ||
| 36 | }; | 40 | }; |
| 37 | 41 | ||
| 38 | export function pageQuery(params?: PageParams & ScheduleWindowParams): string { | 42 | export function pageQuery(params?: PageParams & ScheduleWindowParams): string { |
| @@ -44,6 +48,8 @@ export function pageQuery(params?: PageParams & ScheduleWindowParams): string { | |||
| 44 | if (params.offset != null) query.set("offset", String(params.offset)); | 48 | if (params.offset != null) query.set("offset", String(params.offset)); |
| 45 | if (params.starts_after != null) query.set("starts_after", String(params.starts_after)); | 49 | if (params.starts_after != null) query.set("starts_after", String(params.starts_after)); |
| 46 | if (params.ends_after != null) query.set("ends_after", String(params.ends_after)); | 50 | if (params.ends_after != null) query.set("ends_after", String(params.ends_after)); |
| 51 | + if (params.starts_before != null) query.set("starts_before", String(params.starts_before)); | ||
| 52 | + if (params.ends_before != null) query.set("ends_before", String(params.ends_before)); | ||
| 47 | const value = query.toString(); | 53 | const value = query.toString(); |
| 48 | return value ? `?${value}` : ""; | 54 | return value ? `?${value}` : ""; |
| 49 | } | 55 | } |
src/api/courses/getCourses.tsmodified+18 -7
| @@ -1,19 +1,30 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type Course, type Page, type PageParams } from "../client"; |
| 3 | -import type { Course } from "../client"; | 3 | +import type { CourseKind } from "../client"; |
| 4 | 4 | ||
| 5 | /** | 5 | /** |
| 6 | - * `GET /courses` and `GET /courses/me` take `limit`/`offset` and nothing else — | 6 | + * `GET /courses` list filters. `kind` keeps one course kind, `q` is the |
| 7 | - * the backend has no kind/term/search filter, and serde drops unknown query | 7 | + * server-side catalog search, `taught` keeps courses with (`true`) or without |
| 8 | - * keys silently, so any extra param would look applied while doing nothing. | 8 | + * (`false`) an attached şube. All optional, AND-ed with each other and with |
| 9 | - * Narrow the list in the caller instead (see `courses-page.tsx`). | 9 | + * `limit`/`offset`; an omitted key filters nothing. |
| 10 | */ | 10 | */ |
| 11 | -export type CourseListParams = PageParams; | 11 | +export type CourseListParams = PageParams & { |
| 12 | + kind?: CourseKind; | ||
| 13 | + q?: string; | ||
| 14 | + taught?: boolean; | ||
| 15 | +}; | ||
| 12 | 16 | ||
| 13 | export function courseListQuery(params?: CourseListParams): string { | 17 | export function courseListQuery(params?: CourseListParams): string { |
| 14 | if (!params) return ""; | 18 | if (!params) return ""; |
| 15 | const query = new URLSearchParams(); | 19 | const query = new URLSearchParams(); |
| 16 | appendPageParams(query, params); | 20 | appendPageParams(query, params); |
| 21 | + if (params.kind != null) query.set("kind", params.kind); | ||
| 22 | + // Trimmed here so every caller sends the same thing; blank drops the key — | ||
| 23 | + // the API 400s on a present-but-empty value (`?q=`). | ||
| 24 | + const q = params.q?.trim(); | ||
| 25 | + if (q) query.set("q", q); | ||
| 26 | + // Serializes as `taught=true` / `taught=false`; unset drops the key (both). | ||
| 27 | + if (params.taught != null) query.set("taught", String(params.taught)); | ||
| 17 | const value = query.toString(); | 28 | const value = query.toString(); |
| 18 | return value ? `?${value}` : ""; | 29 | return value ? `?${value}` : ""; |
| 19 | } | 30 | } |
src/api/homework/getHomework.tsmodified+17 -3
| @@ -3,14 +3,28 @@ import { appendPageParams, normalizePage, type Page, type PageParams } from "../ | |||
| 3 | import type { Homework } from "../client"; | 3 | import type { Homework } from "../client"; |
| 4 | 4 | ||
| 5 | /** | 5 | /** |
| 6 | - * `GET /homework` takes `limit`/`offset` only — unlike events and exams it has | 6 | + * `GET /homework` filters. All optional and AND-ed; a well-formed |
| 7 | - * no schedule window, so a due-date filter has to happen in the caller. | 7 | + * `class_course` uuid that names no row answers an empty page. The due bounds |
| 8 | + * are unix ms and half-open on `due_at`. | ||
| 8 | */ | 9 | */ |
| 9 | -export type HomeworkListParams = PageParams; | 10 | +export type HomeworkListParams = PageParams & { |
| 11 | + /** Keeps rows not yet due: `due_at >= v`. */ | ||
| 12 | + due_after?: number; | ||
| 13 | + /** Keeps rows already due: `due_at < v`. */ | ||
| 14 | + due_before?: number; | ||
| 15 | + /** Only homework filed against this instance (şube × ders). */ | ||
| 16 | + class_course?: string; | ||
| 17 | +}; | ||
| 10 | 18 | ||
| 11 | export async function getHomework(params?: HomeworkListParams, signal?: AbortSignal): Promise<Page<Homework>> { | 19 | export async function getHomework(params?: HomeworkListParams, signal?: AbortSignal): Promise<Page<Homework>> { |
| 12 | const query = new URLSearchParams(); | 20 | const query = new URLSearchParams(); |
| 13 | appendPageParams(query, params); | 21 | appendPageParams(query, params); |
| 22 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an | ||
| 23 | + // unset param must drop the key, never emit `key=`. | ||
| 24 | + if (params?.due_after != null) query.set("due_after", String(params.due_after)); | ||
| 25 | + if (params?.due_before != null) query.set("due_before", String(params.due_before)); | ||
| 26 | + const course = params?.class_course?.trim(); | ||
| 27 | + if (course) query.set("class_course", course); | ||
| 14 | const suffix = query.size ? `?${query}` : ""; | 28 | const suffix = query.size ? `?${query}` : ""; |
| 15 | const data = await client<unknown>(`/homework${suffix}`, { signal }); | 29 | const data = await client<unknown>(`/homework${suffix}`, { signal }); |
| 16 | return normalizePage<Homework>(data); | 30 | return normalizePage<Homework>(data); |
src/api/instances/getInstanceSessions.tsmodified+21 -3
| @@ -1,12 +1,30 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; |
| 3 | import type { CourseSession } from "../client"; | 3 | import type { CourseSession } from "../client"; |
| 4 | 4 | ||
| 5 | +/** | ||
| 6 | + * `GET /instances/:id/sessions` filters. Both optional and AND-ed, unix ms, | ||
| 7 | + * and half-open `[from, to)` on the session start: `starts_at >= starts_after` | ||
| 8 | + * and `starts_at < starts_before`. | ||
| 9 | + */ | ||
| 10 | +export type InstanceSessionListParams = PageParams & { | ||
| 11 | + /** Keeps sessions starting at or after this instant. */ | ||
| 12 | + starts_after?: number; | ||
| 13 | + /** Keeps sessions starting before this instant. */ | ||
| 14 | + starts_before?: number; | ||
| 15 | +}; | ||
| 16 | + | ||
| 5 | export async function getInstanceSessions( | 17 | export async function getInstanceSessions( |
| 6 | instanceId: string, | 18 | instanceId: string, |
| 7 | - params?: PageParams, | 19 | + params?: InstanceSessionListParams, |
| 8 | signal?: AbortSignal, | 20 | signal?: AbortSignal, |
| 9 | ): Promise<Page<CourseSession>> { | 21 | ): Promise<Page<CourseSession>> { |
| 10 | - const data = await client<unknown>(`/instances/${instanceId}/sessions${pageQuery(params)}`, { signal }); | 22 | + const query = new URLSearchParams(); |
| 23 | + appendPageParams(query, params); | ||
| 24 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so an | ||
| 25 | + // unset param must drop the key, never emit `key=`. | ||
| 26 | + if (params?.starts_after != null) query.set("starts_after", String(params.starts_after)); | ||
| 27 | + if (params?.starts_before != null) query.set("starts_before", String(params.starts_before)); | ||
| 28 | + const data = await client<unknown>(`/instances/${instanceId}/sessions${query.size ? `?${query}` : ""}`, { signal }); | ||
| 11 | return normalizePage<CourseSession>(data); | 29 | return normalizePage<CourseSession>(data); |
| 12 | } | 30 | } |
src/api/meals/getMealMenus.tsmodified+6 -1
| @@ -2,13 +2,18 @@ import { client } from "../client"; | |||
| 2 | import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; | 2 | import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; |
| 3 | import type { MealMenu } from "../client"; | 3 | import type { MealMenu } from "../client"; |
| 4 | 4 | ||
| 5 | -export type MealMenuParams = PageParams & { from?: string; to?: string }; | 5 | +export type MealMenuParams = PageParams & { from?: string; to?: string; slot?: string }; |
| 6 | 6 | ||
| 7 | export async function getMealMenus(params?: MealMenuParams, signal?: AbortSignal): Promise<Page<MealMenu>> { | 7 | export async function getMealMenus(params?: MealMenuParams, signal?: AbortSignal): Promise<Page<MealMenu>> { |
| 8 | const query = new URLSearchParams(); | 8 | const query = new URLSearchParams(); |
| 9 | appendPageParams(query, params); | 9 | appendPageParams(query, params); |
| 10 | if (params?.from) query.set("from", params.from); | 10 | if (params?.from) query.set("from", params.from); |
| 11 | if (params?.to) query.set("to", params.to); | 11 | if (params?.to) query.set("to", params.to); |
| 12 | + // "all" is the page's pseudo-option for "no slot filter", never a real slot | ||
| 13 | + // name, and blank would serialize as a present-but-empty value the API | ||
| 14 | + // rejects — both must be dropped instead of sent. | ||
| 15 | + const slotFilter = params?.slot?.trim(); | ||
| 16 | + if (slotFilter && slotFilter !== "all") query.set("slot", slotFilter); | ||
| 12 | const data = await client<unknown>(`/meals/menus${query.size ? `?${query}` : ""}`, { signal }); | 17 | const data = await client<unknown>(`/meals/menus${query.size ? `?${query}` : ""}`, { signal }); |
| 13 | return normalizePage<MealMenu>(data); | 18 | return normalizePage<MealMenu>(data); |
| 14 | } | 19 | } |
src/api/messages/getMessages.tsmodified+9 -7
| @@ -1,18 +1,20 @@ | |||
| 1 | -import { client } from "../client"; | 1 | +import { appendPageParams, client } from "../client"; |
| 2 | import type { Page, PageParams } from "../client"; | 2 | import type { Page, PageParams } from "../client"; |
| 3 | import type { Message, MessageFolder } from "../client"; | 3 | import type { Message, MessageFolder } from "../client"; |
| 4 | 4 | ||
| 5 | export function getMessages( | 5 | export function getMessages( |
| 6 | folder: MessageFolder = "inbox", | 6 | folder: MessageFolder = "inbox", |
| 7 | - options?: PageParams & { read?: boolean } | 7 | + options?: PageParams & { read?: boolean; q?: string } |
| 8 | ): Promise<Page<Message>> { | 8 | ): Promise<Page<Message>> { |
| 9 | const params = new URLSearchParams(); | 9 | const params = new URLSearchParams(); |
| 10 | params.set("folder", folder); | 10 | params.set("folder", folder); |
| 11 | if (options?.read !== undefined) params.set("read", String(options.read)); | 11 | if (options?.read !== undefined) params.set("read", String(options.read)); |
| 12 | - if (options?.limit !== undefined) params.set("limit", String(options.limit)); | 12 | + // Free-text search is server-side; blank after trim means no filter. |
| 13 | - if (options?.offset !== undefined) params.set("offset", String(options.offset)); | 13 | + const q = options?.q?.trim(); |
| 14 | - | 14 | + if (q) params.set("q", q); |
| 15 | - const q = params.toString(); | 15 | + appendPageParams(params, options); |
| 16 | - const url = q ? `/messages?${q}` : `/messages`; | 16 | + |
| 17 | + const query = params.toString(); | ||
| 18 | + const url = query ? `/messages?${query}` : `/messages`; | ||
| 17 | return client<Page<Message>>(url); | 19 | return client<Page<Message>>(url); |
| 18 | } | 20 | } |
src/api/pomodoro/getPomodoroMe.tsmodified+18 -3
| @@ -1,7 +1,22 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { pageQuery, type PageParams } from "../client"; | 2 | +import { appendPageParams, type PageParams } from "../client"; |
| 3 | import type { PomodoroLog } from "../client"; | 3 | import type { PomodoroLog } from "../client"; |
| 4 | 4 | ||
| 5 | -export function getPomodoroMe(params?: PageParams, signal?: AbortSignal): Promise<PomodoroLog> { | 5 | +/** `/pomodoro/me` window on `started_at`, UTC unix ms. Both optional, AND-ed. */ |
| 6 | - return client<PomodoroLog>(`/pomodoro/me${pageQuery(params)}`, { signal }); | 6 | +export type PomodoroMeParams = PageParams & { |
| 7 | + /** Keeps sessions started at or after T: `started_at >= T`. */ | ||
| 8 | + from?: number; | ||
| 9 | + /** Keeps sessions started before T: `started_at < T`. */ | ||
| 10 | + to?: number; | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +export function getPomodoroMe(params?: PomodoroMeParams, signal?: AbortSignal): Promise<PomodoroLog> { | ||
| 14 | + const query = new URLSearchParams(); | ||
| 15 | + appendPageParams(query, params); | ||
| 16 | + // `!= null` is load-bearing: the API 400s on a present-but-empty value, so | ||
| 17 | + // an unset bound must drop the key, never emit `from=`. | ||
| 18 | + if (params?.from != null) query.set("from", String(params.from)); | ||
| 19 | + if (params?.to != null) query.set("to", String(params.to)); | ||
| 20 | + const value = query.toString(); | ||
| 21 | + return client<PomodoroLog>(`/pomodoro/me${value ? `?${value}` : ""}`, { signal }); | ||
| 7 | } | 22 | } |
src/api/users/getUsers.tsmodified+16 -4
| @@ -1,8 +1,20 @@ | |||
| 1 | import { client } from "../client"; | 1 | import { client } from "../client"; |
| 2 | -import { normalizePage, pageQuery, type Page, type PageParams } from "../client"; | 2 | +import { appendPageParams, normalizePage, type Page, type PageParams } from "../client"; |
| 3 | -import type { User } from "../client"; | 3 | +import type { Role, User } from "../client"; |
| 4 | 4 | ||
| 5 | -export async function getUsers(params?: PageParams, signal?: AbortSignal): Promise<Page<User>> { | 5 | +export type UserListParams = PageParams & { |
| 6 | - const data = await client<unknown>(`/users${pageQuery(params)}`, { signal }); | 6 | + /** Keep only these roles; comma-joined on the wire, omitted when empty. */ |
| 7 | + roles?: Role[]; | ||
| 8 | +}; | ||
| 9 | + | ||
| 10 | +export async function getUsers(params?: UserListParams, signal?: AbortSignal): Promise<Page<User>> { | ||
| 11 | + const query = new URLSearchParams(); | ||
| 12 | + appendPageParams(query, params); | ||
| 13 | + // `!= null`/blank guards are load-bearing: the API 400s on a | ||
| 14 | + // present-but-empty value (`?roles=`), so an empty list drops the key. | ||
| 15 | + const roles = (params?.roles ?? []).map((role) => role.trim()).filter((role) => role !== ""); | ||
| 16 | + if (roles.length) query.set("roles", roles.join(",")); | ||
| 17 | + const suffix = query.size ? `?${query}` : ""; | ||
| 18 | + const data = await client<unknown>(`/users${suffix}`, { signal }); | ||
| 7 | return normalizePage<User>(data); | 19 | return normalizePage<User>(data); |
| 8 | } | 20 | } |
src/components/dashboard/today-lessons-panel.tsxmodified+11 -4
| @@ -7,7 +7,8 @@ import { getSessionAttendance } from "@/api/sessions"; | |||
| 7 | import { EmptyInline } from "@/components/ui/empty-inline"; | 7 | import { EmptyInline } from "@/components/ui/empty-inline"; |
| 8 | import { IconChevronRight } from "@/components/ui/icons"; | 8 | import { IconChevronRight } from "@/components/ui/icons"; |
| 9 | import { cn } from "@/lib/cn"; | 9 | import { cn } from "@/lib/cn"; |
| 10 | -import { lessonNow, rollCallState, sessionsToday, type RollCallState, type TodayLesson } from "@/lib/today-lessons"; | 10 | +import { lessonNow, rollCallState, sessionsToday, dayBounds, type RollCallState, type TodayLesson } from "@/lib/today-lessons"; |
| 11 | +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; | ||
| 11 | import { usePreferences, useT } from "@/stores/preferences-context"; | 12 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 12 | import type { MessageKey } from "@/i18n/messages"; | 13 | import type { MessageKey } from "@/i18n/messages"; |
| 13 | 14 | ||
| @@ -49,9 +50,15 @@ export function TodayLessonsPanel(props: { | |||
| 49 | const instances = (await getMyInstances()).items.slice(0, INSTANCE_CAP); | 50 | const instances = (await getMyInstances()).items.slice(0, INSTANCE_CAP); |
| 50 | const perInstance = await Promise.all( | 51 | const perInstance = await Promise.all( |
| 51 | instances.map(async (instance) => { | 52 | instances.map(async (instance) => { |
| 52 | - // No date filter on the route and newest first, so a year of | 53 | + // The route filters on the same half-open local-day bounds |
| 53 | - // pre-made future sessions would push today past any page size. | 54 | + // `sessionsToday` keeps, so the visible set is unchanged — but |
| 54 | - const sessions = await getInstanceSessions(instance.id).then((page) => page.items).catch(() => []); | 55 | + // the read is now paged (offsets followed only while the |
| 56 | + // envelope total exceeds the page) instead of every session ever. | ||
| 57 | + const [dayStart, dayEnd] = dayBounds(now); | ||
| 58 | + const sessions = await loadWindowedList( | ||
| 59 | + (params) => getInstanceSessions(instance.id, { ...params, starts_after: dayStart, starts_before: dayEnd }), | ||
| 60 | + LIST_CAP, | ||
| 61 | + ).then((list) => list.items).catch(() => []); | ||
| 55 | return sessionsToday(sessions, now).map((session) => ({ session, instance })); | 62 | return sessionsToday(sessions, now).map((session) => ({ session, instance })); |
| 56 | }), | 63 | }), |
| 57 | ); | 64 | ); |
src/components/sessions/course-sessions-panel.tsxmodified+9 -1
| @@ -23,6 +23,7 @@ import { Select } from "@/components/ui/select"; | |||
| 23 | import { SidePanel } from "@/components/ui/side-panel"; | 23 | import { SidePanel } from "@/components/ui/side-panel"; |
| 24 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 24 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 25 | import { createFlash } from "@/lib/flash"; | 25 | import { createFlash } from "@/lib/flash"; |
| 26 | +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; | ||
| 26 | import { formatDateTime } from "@/lib/format"; | 27 | import { formatDateTime } from "@/lib/format"; |
| 27 | import { personLabel } from "@/lib/person"; | 28 | import { personLabel } from "@/lib/person"; |
| 28 | import { usePreferences, useT } from "@/stores/preferences-context"; | 29 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| @@ -73,7 +74,14 @@ export function CourseSessionsPanel(props: { | |||
| 73 | const { locale } = usePreferences(); | 74 | const { locale } = usePreferences(); |
| 74 | const [sessions, { refetch }] = createResource( | 75 | const [sessions, { refetch }] = createResource( |
| 75 | () => (props.active ? props.instanceId : null), | 76 | () => (props.active ? props.instanceId : null), |
| 76 | - async (instanceId) => (instanceId ? (await getInstanceSessions(instanceId)).items : []), | 77 | + async (instanceId) => { |
| 78 | + if (!instanceId) return []; | ||
| 79 | + // The table lists the section's whole lesson history, so the window is | ||
| 80 | + // unfiltered — but the read is still paged: offsets are followed until | ||
| 81 | + // the envelope total instead of one unpaged GET of every session ever. | ||
| 82 | + const list = await loadWindowedList((params) => getInstanceSessions(instanceId, params), LIST_CAP); | ||
| 83 | + return list.items; | ||
| 84 | + }, | ||
| 77 | ); | 85 | ); |
| 78 | const [selectedSession, setSelectedSession] = createSignal<CourseSession | null>(null); | 86 | const [selectedSession, setSelectedSession] = createSignal<CourseSession | null>(null); |
| 79 | let linkedRollCallOpened = false; | 87 | let linkedRollCallOpened = false; |
src/lib/capped-list.test.tsmodified+23 -1
| @@ -1,5 +1,5 @@ | |||
| 1 | import type { Page, PageParams } from "@/api/client"; | 1 | import type { Page, PageParams } from "@/api/client"; |
| 2 | -import { isTruncated, loadAllPages, loadCappedList } from "./capped-list"; | 2 | +import { isTruncated, loadAllPages, loadCappedList, loadWindowedList } from "./capped-list"; |
| 3 | 3 | ||
| 4 | const page = (items: number[], total: number): Page<number> => ({ items, total, limit: null, offset: 0 }); | 4 | const page = (items: number[], total: number): Page<number> => ({ items, total, limit: null, offset: 0 }); |
| 5 | 5 | ||
| @@ -40,3 +40,25 @@ it("stops after one request when the first page holds everything", async () => { | |||
| 40 | expect(await loadAllPages(fetch, 100)).toEqual([1, 2]); | 40 | expect(await loadAllPages(fetch, 100)).toEqual([1, 2]); |
| 41 | expect(fetch).toHaveBeenCalledTimes(1); | 41 | expect(fetch).toHaveBeenCalledTimes(1); |
| 42 | }); | 42 | }); |
| 43 | + | ||
| 44 | +it("follows offsets until the windowed total", async () => { | ||
| 45 | + const fetch = vi.fn(async (params?: PageParams) => { | ||
| 46 | + if (!params?.offset) return page([1, 2], 5); | ||
| 47 | + if (params.offset === 2) return page([3, 4], 5); | ||
| 48 | + return page([5], 5); | ||
| 49 | + }); | ||
| 50 | + const list = await loadWindowedList(fetch, 2); | ||
| 51 | + expect(fetch).toHaveBeenNthCalledWith(1, { limit: 2, offset: 0 }); | ||
| 52 | + expect(fetch).toHaveBeenNthCalledWith(2, { limit: 2, offset: 2 }); | ||
| 53 | + expect(fetch).toHaveBeenNthCalledWith(3, { limit: 2, offset: 4 }); | ||
| 54 | + expect(list).toEqual({ items: [1, 2, 3, 4, 5], total: 5 }); | ||
| 55 | + expect(isTruncated(list)).toBe(false); | ||
| 56 | +}); | ||
| 57 | + | ||
| 58 | +it("stops on an empty page instead of looping a shrinking window", async () => { | ||
| 59 | + const fetch = vi.fn(async (params?: PageParams) => (params?.offset ? page([], 5) : page([1, 2], 5))); | ||
| 60 | + const list = await loadWindowedList(fetch, 2); | ||
| 61 | + expect(fetch).toHaveBeenCalledTimes(2); | ||
| 62 | + expect(list.items).toEqual([1, 2]); | ||
| 63 | + expect(list.total).toBe(5); | ||
| 64 | +}); | ||
src/lib/capped-list.tsmodified+24 -0
| @@ -56,3 +56,27 @@ export async function loadAllPages<T>( | |||
| 56 | } | 56 | } |
| 57 | return items.concat(...pages); | 57 | return items.concat(...pages); |
| 58 | } | 58 | } |
| 59 | + | ||
| 60 | + | ||
| 61 | +/** | ||
| 62 | + * Fetch every row of an already-windowed list, following offsets until the | ||
| 63 | + * envelope total. The window (a date range or filter set) is the caller's | ||
| 64 | + * job — this only pages through what the server answers, so no blind cap | ||
| 65 | + * decides which rows exist. Stops on an empty page so rows deleted mid-read | ||
| 66 | + * cannot loop it forever. | ||
| 67 | + */ | ||
| 68 | +export async function loadWindowedList<T>( | ||
| 69 | + fetch: (params?: PageParams) => Promise<Page<T>>, | ||
| 70 | + pageSize: number, | ||
| 71 | +): Promise<CappedList<T>> { | ||
| 72 | + const first = await fetch({ limit: pageSize, offset: 0 }); | ||
| 73 | + const items = Array.isArray(first.items) ? [...first.items] : []; | ||
| 74 | + let total = typeof first.total === "number" ? Math.max(first.total, items.length) : items.length; | ||
| 75 | + for (let offset = items.length; offset < total; offset = items.length) { | ||
| 76 | + const page = await fetch({ limit: pageSize, offset }); | ||
| 77 | + if (!Array.isArray(page.items) || page.items.length === 0) break; | ||
| 78 | + items.push(...page.items); | ||
| 79 | + total = typeof page.total === "number" ? Math.max(page.total, items.length) : items.length; | ||
| 80 | + } | ||
| 81 | + return { items, total }; | ||
| 82 | +} | ||
src/lib/student-directory.test.tsmodified+79 -3
| @@ -1,6 +1,6 @@ | |||
| 1 | -import { describe, expect, test } from "vitest"; | 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; |
| 2 | -import type { ClassGroup, PersonRef } from "@/api/client"; | 2 | +import type { ClassGroup, ClassMember, PersonRef } from "@/api/client"; |
| 3 | -import { sortByClass } from "@/lib/student-directory"; | 3 | +import { getStudentDirectory, sortByClass } from "@/lib/student-directory"; |
| 4 | 4 | ||
| 5 | const cls = (name: string, gradeLevel: number): ClassGroup => ({ | 5 | const cls = (name: string, gradeLevel: number): ClassGroup => ({ |
| 6 | id: name, creator: null, name, grade_level: gradeLevel, year: null, teacher: null, | 6 | id: name, creator: null, name, grade_level: gradeLevel, year: null, teacher: null, |
| @@ -33,3 +33,79 @@ describe("sortByClass", () => { | |||
| 33 | expect(sorted[0].classes.map((c) => c.name)).toEqual(["9-A", "10-B"]); | 33 | expect(sorted[0].classes.map((c) => c.name)).toEqual(["9-A", "10-B"]); |
| 34 | }); | 34 | }); |
| 35 | }); | 35 | }); |
| 36 | + | ||
| 37 | +const member = (classId: string, user: PersonRef): ClassMember => ({ | ||
| 38 | + id: `m-${user.id}`, class: classId, user, added_by: user, joined_at: 0, left_at: null, source_class_group: null, | ||
| 39 | +}); | ||
| 40 | +const jsonResponse = (data: unknown) => | ||
| 41 | + new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" } }); | ||
| 42 | + | ||
| 43 | +describe("getStudentDirectory", () => { | ||
| 44 | + afterEach(() => { | ||
| 45 | + vi.restoreAllMocks(); | ||
| 46 | + }); | ||
| 47 | + | ||
| 48 | + test("with no class, reads every student and every class's members as before", async () => { | ||
| 49 | + const calls: string[] = []; | ||
| 50 | + const respond = (url: string): Response => { | ||
| 51 | + calls.push(url); | ||
| 52 | + if (url === "/api/users/search?q=&role=student") | ||
| 53 | + return jsonResponse({ items: [person("Zeynep"), person("Ali")], total: 2, limit: null, offset: 0 }); | ||
| 54 | + if (url === "/api/classes?limit=200") | ||
| 55 | + return jsonResponse({ items: [cls("9-A", 9), cls("10-B", 10)], total: 2, limit: 200, offset: 0 }); | ||
| 56 | + if (url === "/api/classes/9-A/members?limit=500") | ||
| 57 | + return jsonResponse({ items: [member("9-A", person("Ali"))], total: 1, limit: 500, offset: 0 }); | ||
| 58 | + if (url === "/api/classes/10-B/members?limit=500") return jsonResponse({ items: [], total: 0, limit: 500, offset: 0 }); | ||
| 59 | + throw new Error(`unexpected fetch: ${url}`); | ||
| 60 | + }; | ||
| 61 | + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); | ||
| 62 | + | ||
| 63 | + const rows = await getStudentDirectory(); | ||
| 64 | + | ||
| 65 | + expect(calls).toEqual([ | ||
| 66 | + "/api/users/search?q=&role=student", | ||
| 67 | + "/api/classes?limit=200", | ||
| 68 | + "/api/classes/9-A/members?limit=500", | ||
| 69 | + "/api/classes/10-B/members?limit=500", | ||
| 70 | + ]); | ||
| 71 | + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Zeynep"]); | ||
| 72 | + expect(rows[0].classes.map((c) => c.name)).toEqual(["9-A"]); | ||
| 73 | + expect(rows[1].classes).toEqual([]); | ||
| 74 | + }); | ||
| 75 | + | ||
| 76 | + test("with a class picked, reads only that roster, following offsets to total", async () => { | ||
| 77 | + const calls: string[] = []; | ||
| 78 | + const respond = (url: string): Response => { | ||
| 79 | + calls.push(url); | ||
| 80 | + if (url === "/api/classes/c1/members?limit=500&offset=0") | ||
| 81 | + return jsonResponse({ items: [member("c1", person("Ali")), member("c1", person("Burak"))], total: 3, limit: 500, offset: 0 }); | ||
| 82 | + if (url === "/api/classes/c1/members?limit=500&offset=2") | ||
| 83 | + return jsonResponse({ items: [member("c1", person("Can"))], total: 3, limit: 500, offset: 2 }); | ||
| 84 | + throw new Error(`unexpected fetch: ${url}`); | ||
| 85 | + }; | ||
| 86 | + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); | ||
| 87 | + const nineA = { ...cls("9-A", 9), id: "c1" }; | ||
| 88 | + | ||
| 89 | + const rows = await getStudentDirectory(nineA); | ||
| 90 | + | ||
| 91 | + expect(calls).toEqual(["/api/classes/c1/members?limit=500&offset=0", "/api/classes/c1/members?limit=500&offset=2"]); | ||
| 92 | + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali", "Burak", "Can"]); | ||
| 93 | + expect(rows.every((row) => row.classes.length === 1 && row.classes[0] === nineA)).toBe(true); | ||
| 94 | + }); | ||
| 95 | + | ||
| 96 | + test("with a class picked and a roster within one page, fetches it once", async () => { | ||
| 97 | + const calls: string[] = []; | ||
| 98 | + const respond = (url: string): Response => { | ||
| 99 | + calls.push(url); | ||
| 100 | + if (url === "/api/classes/c2/members?limit=500&offset=0") | ||
| 101 | + return jsonResponse({ items: [member("c2", person("Ali"))], total: 1, limit: 500, offset: 0 }); | ||
| 102 | + throw new Error(`unexpected fetch: ${url}`); | ||
| 103 | + }; | ||
| 104 | + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => respond(String(input)))); | ||
| 105 | + | ||
| 106 | + const rows = await getStudentDirectory({ ...cls("9-A", 9), id: "c2" }); | ||
| 107 | + | ||
| 108 | + expect(calls).toEqual(["/api/classes/c2/members?limit=500&offset=0"]); | ||
| 109 | + expect(rows.map((row) => row.person.display_name)).toEqual(["Ali"]); | ||
| 110 | + }); | ||
| 111 | +}); | ||
src/lib/student-directory.tsmodified+24 -3
| @@ -1,14 +1,35 @@ | |||
| 1 | import { getClassMembers, getClasses } from "@/api/classes"; | 1 | import { getClassMembers, getClasses } from "@/api/classes"; |
| 2 | import { getUserSearch } from "@/api/users"; | 2 | import { getUserSearch } from "@/api/users"; |
| 3 | -import type { ClassGroup, PersonRef } from "@/api/client"; | 3 | +import type { ClassGroup, ClassMember, PersonRef } from "@/api/client"; |
| 4 | 4 | ||
| 5 | export type StudentDirectoryRow = { | 5 | export type StudentDirectoryRow = { |
| 6 | person: PersonRef; | 6 | person: PersonRef; |
| 7 | classes: ClassGroup[]; | 7 | classes: ClassGroup[]; |
| 8 | }; | 8 | }; |
| 9 | 9 | ||
| 10 | -/** Shared student list for teacher-facing reports: one name column and the classes it belongs to. */ | 10 | +/** Page size for the class-roster reads; the same one the full sweep asks for. */ |
| 11 | -export async function getStudentDirectory(): Promise<StudentDirectoryRow[]> { | 11 | +const MEMBERS_PAGE = 500; |
| 12 | + | ||
| 13 | +/** Every live member of one class: the route is paged, so follow offsets to `total`. */ | ||
| 14 | +async function readClassMembers(classId: string): Promise<ClassMember[]> { | ||
| 15 | + const members: ClassMember[] = []; | ||
| 16 | + let offset = 0; | ||
| 17 | + for (;;) { | ||
| 18 | + const page = await getClassMembers(classId, { limit: MEMBERS_PAGE, offset }); | ||
| 19 | + members.push(...page.items); | ||
| 20 | + offset += page.items.length; | ||
| 21 | + if (page.items.length === 0 || offset >= page.total) return members; | ||
| 22 | + } | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/** | ||
| 26 | + * Shared student list for teacher-facing reports: one name column and the classes it belongs to. | ||
| 27 | + * With `cls` the read is scoped to that class: only its roster is fetched, and | ||
| 28 | + * each row's `classes` is just that class. Without it every student and every | ||
| 29 | + * class's members are read, as before. | ||
| 30 | + */ | ||
| 31 | +export async function getStudentDirectory(cls?: ClassGroup): Promise<StudentDirectoryRow[]> { | ||
| 32 | + if (cls) return sortByClass((await readClassMembers(cls.id)).map((member) => ({ person: member.user, classes: [cls] }))); | ||
| 12 | const [students, classes] = await Promise.all([ | 33 | const [students, classes] = await Promise.all([ |
| 13 | getUserSearch("", undefined, "student"), | 34 | getUserSearch("", undefined, "student"), |
| 14 | getClasses({ limit: 200 }), | 35 | getClasses({ limit: 200 }), |
src/pages/admin-users-page.tsxmodified+17 -10
| @@ -1,5 +1,5 @@ | |||
| 1 | import { useNavigate } from "@tanstack/solid-router"; | 1 | import { useNavigate } from "@tanstack/solid-router"; |
| 2 | -import { Show, Suspense, createMemo, createSignal } from "solid-js"; | 2 | +import { Show, Suspense, createSignal } from "solid-js"; |
| 3 | import { createResource } from "@/lib/create-resource"; | 3 | import { createResource } from "@/lib/create-resource"; |
| 4 | import { getUsers } from "@/api/users"; | 4 | import { getUsers } from "@/api/users"; |
| 5 | import { patchUserRole } from "@/api/users"; | 5 | import { patchUserRole } from "@/api/users"; |
| @@ -44,15 +44,22 @@ function AdminUsersContent() { | |||
| 44 | const [editTarget, setEditTarget] = createSignal<User | null>(null); | 44 | const [editTarget, setEditTarget] = createSignal<User | null>(null); |
| 45 | 45 | ||
| 46 | const [list, { refetch }] = createResource( | 46 | const [list, { refetch }] = createResource( |
| 47 | - async () => ({ items: await loadAllPages(getUsers, USER_PAGE_SIZE) }), | 47 | + // The source keys on the tab so switching tabs refetches from the server. |
| 48 | + // Manager tab is the merged staff roster; every other tab is that one | ||
| 49 | + // role. "all" omits the key entirely. Every page of the filtered set is | ||
| 50 | + // read — no cap hides rows. | ||
| 51 | + () => roleTab(), | ||
| 52 | + async (tab) => ({ | ||
| 53 | + items: await loadAllPages( | ||
| 54 | + (params) => | ||
| 55 | + getUsers({ | ||
| 56 | + ...params, | ||
| 57 | + roles: tab === "all" ? undefined : tab === "manager" ? ["manager", "admin"] : [tab], | ||
| 58 | + }), | ||
| 59 | + USER_PAGE_SIZE, | ||
| 60 | + ), | ||
| 61 | + }), | ||
| 48 | ); | 62 | ); |
| 49 | - const allUsers = () => list()?.items ?? []; | ||
| 50 | - const visibleUsers = createMemo(() => { | ||
| 51 | - const tab = roleTab(); | ||
| 52 | - if (tab === "all") return allUsers(); | ||
| 53 | - if (tab === "manager") return allUsers().filter((user) => user.role === "manager" || user.role === "admin"); | ||
| 54 | - return allUsers().filter((user) => user.role === tab); | ||
| 55 | - }); | ||
| 56 | 63 | ||
| 57 | const [flash, setFlash] = createFlash(); | 64 | const [flash, setFlash] = createFlash(); |
| 58 | 65 | ||
| @@ -96,7 +103,7 @@ function AdminUsersContent() { | |||
| 96 | {t("admin.createUser")} | 103 | {t("admin.createUser")} |
| 97 | </Button> | 104 | </Button> |
| 98 | } | 105 | } |
| 99 | - users={visibleUsers() as User[]} | 106 | + users={list()?.items as User[]} |
| 100 | currentUserId={auth.user()!.id} | 107 | currentUserId={auth.user()!.id} |
| 101 | onRoleChange={onRoleChange} | 108 | onRoleChange={onRoleChange} |
| 102 | onUserClick={(user) => navigate({ to: "/admin/users/$id", params: { id: user.id } })} | 109 | onUserClick={(user) => navigate({ to: "/admin/users/$id", params: { id: user.id } })} |
src/pages/appointments-page.test.tsxmodified+8 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library"; | 1 | +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; |
| 2 | import AppointmentsPage from "@/pages/appointments-page"; | 2 | import AppointmentsPage from "@/pages/appointments-page"; |
| 3 | import { PreferencesProvider } from "@/stores/preferences-context"; | 3 | import { PreferencesProvider } from "@/stores/preferences-context"; |
| 4 | 4 | ||
| @@ -53,4 +53,11 @@ test("separates bookings and available times into tabs", async () => { | |||
| 53 | 53 | ||
| 54 | expect(availableTab.getAttribute("aria-selected")).toBe("true"); | 54 | expect(availableTab.getAttribute("aria-selected")).toBe("true"); |
| 55 | expect(screen.getByRole("tab", { name: /Teachers’ open times/ })).toBeTruthy(); | 55 | expect(screen.getByRole("tab", { name: /Teachers’ open times/ })).toBeTruthy(); |
| 56 | + | ||
| 57 | + // A requester reads upcoming slots for every teacher (starts_after, no | ||
| 58 | + // teacher=me) and their own bookings without a start window: neither read | ||
| 59 | + // downloads history. | ||
| 60 | + await waitFor(() => expect(getSlots).toHaveBeenCalled()); | ||
| 61 | + expect(getSlots).toHaveBeenCalledWith({ starts_after: expect.any(Number), limit: 100 }); | ||
| 62 | + expect(getAppointments).toHaveBeenCalledWith({ limit: 100 }); | ||
| 56 | }); | 63 | }); |
src/pages/appointments-page.tsxmodified+23 -26
| @@ -16,6 +16,7 @@ import { | |||
| 16 | postSlots, | 16 | postSlots, |
| 17 | } from "@/api/appointments"; | 17 | } from "@/api/appointments"; |
| 18 | import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; | 18 | import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client"; |
| 19 | +import type { AppointmentListParams, SlotListParams } from "@/api/appointments"; | ||
| 19 | import { createLivePoll } from "@/lib/create-live-poll"; | 20 | import { createLivePoll } from "@/lib/create-live-poll"; |
| 20 | import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; | 21 | import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client"; |
| 21 | import type { MessageKey } from "@/i18n/messages"; | 22 | import type { MessageKey } from "@/i18n/messages"; |
| @@ -75,21 +76,25 @@ function AppointmentsContent() { | |||
| 75 | const isStaff = () => hasMinRole(me()?.role, "teacher"); | 76 | const isStaff = () => hasMinRole(me()?.role, "teacher"); |
| 76 | const isManager = () => hasMinRole(me()?.role, "manager"); | 77 | const isManager = () => hasMinRole(me()?.role, "manager"); |
| 77 | 78 | ||
| 78 | - // Staff get EVERY slot they ever published (`list_for_teacher`, `starts_at ASC`, | 79 | + // Both slot reads only need what has not started (`starts_after`), which is |
| 79 | - // no past filter), so past ~100 lifetime slots page one is nothing but expired | 80 | + // also what keeps the read off the whole history — the old last-page trick |
| 80 | - // rows and the upcoming ones are unreachable. Take the last page instead — they | 81 | + // existed because the endpoint had neither a window nor a teacher filter. |
| 81 | - // always sit at the tail. Requesters get `list_upcoming` (future-only, ASC), so | 82 | + // Non-manager staff get their own published slots (`teacher=me`); managers |
| 82 | - // their first page is the near one and must stay first. | 83 | + // supervise every teacher's, requesters everyone's open ones. |
| 83 | - // ponytail: shows the newest PAGE_LIMIT slots; >100 upcoming slots would need | ||
| 84 | - // real paging, and the endpoint takes only limit/offset today. | ||
| 85 | const fetchSlots = async () => { | 84 | const fetchSlots = async () => { |
| 86 | - const first = await getSlots({ limit: PAGE_LIMIT }); | 85 | + const params: SlotListParams = { starts_after: Date.now(), limit: PAGE_LIMIT }; |
| 87 | - if (!isStaff() || first.total <= PAGE_LIMIT) return first.items; | 86 | + if (isStaff() && !isManager()) params.teacher = "me"; |
| 88 | - return (await getSlots({ limit: PAGE_LIMIT, offset: first.total - PAGE_LIMIT })).items; | 87 | + return (await getSlots(params)).items; |
| 89 | }; | 88 | }; |
| 90 | const [slots, { refetch: refetchSlots }] = createResource(fetchSlots); | 89 | const [slots, { refetch: refetchSlots }] = createResource(fetchSlots); |
| 91 | - // Appointments come back newest-first (`ORDER BY id DESC`), so page one is right. | 90 | + // Appointments come back newest-first (`ORDER BY id DESC`), so page one is |
| 92 | - const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: PAGE_LIMIT })).items); | 91 | + // right. The requests table shows decided rows too, so no status window; |
| 92 | + // non-manager staff narrow to their own rows server-side (`teacher=me`). | ||
| 93 | + const [appts, { refetch: refetchAppts }] = createResource(async () => { | ||
| 94 | + const params: AppointmentListParams = { limit: PAGE_LIMIT }; | ||
| 95 | + if (isStaff() && !isManager()) params.teacher = "me"; | ||
| 96 | + return (await getAppointments(params)).items; | ||
| 97 | + }); | ||
| 93 | 98 | ||
| 94 | const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]); | 99 | const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]); |
| 95 | const loaded = () => slots.latest !== undefined && appts.latest !== undefined; | 100 | const loaded = () => slots.latest !== undefined && appts.latest !== undefined; |
| @@ -192,13 +197,9 @@ function AppointmentsContent() { | |||
| 192 | const recordReason = (a: Appointment) => (a.status === "rejected" ? a.reject_reason : a.cancel_reason); | 197 | const recordReason = (a: Appointment) => (a.status === "rejected" ? a.reject_reason : a.cancel_reason); |
| 193 | const recordReasonLabel = (a: Appointment) => (a.status === "rejected" ? t("appointments.rejectReason") : t("appointments.cancelReason")); | 198 | const recordReasonLabel = (a: Appointment) => (a.status === "rejected" ? t("appointments.rejectReason") : t("appointments.cancelReason")); |
| 194 | 199 | ||
| 195 | - // --- staff: my published slots --- | 200 | + // --- staff: my published slots (the server already narrows to `teacher=me` |
| 196 | - const mySlots = () => { | 201 | + // for non-manager staff; managers see every teacher's) --- |
| 197 | - const list = slots.latest ?? []; | 202 | + const mySlots = () => slots.latest ?? []; |
| 198 | - if (isManager()) return list; | ||
| 199 | - const uid = me()?.id; | ||
| 200 | - return list.filter((s) => s.teacher.id === uid); | ||
| 201 | - }; | ||
| 202 | const slotBooking = (slotId: string) => (appts.latest ?? []).find((a) => a.slot === slotId && isLive(a.status)); | 203 | const slotBooking = (slotId: string) => (appts.latest ?? []).find((a) => a.slot === slotId && isLive(a.status)); |
| 203 | 204 | ||
| 204 | const slotColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [ | 205 | const slotColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [ |
| @@ -244,13 +245,9 @@ function AppointmentsContent() { | |||
| 244 | }, | 245 | }, |
| 245 | ]); | 246 | ]); |
| 246 | 247 | ||
| 247 | - // --- staff: booking requests for my slots --- | 248 | + // --- staff: booking requests for my slots (server-narrowed via `teacher=me` |
| 248 | - const requests = () => { | 249 | + // for non-manager staff, as with the slots above) --- |
| 249 | - const list = appts.latest ?? []; | 250 | + const requests = () => appts.latest ?? []; |
| 250 | - if (isManager()) return list; | ||
| 251 | - const uid = me()?.id; | ||
| 252 | - return list.filter((a) => a.teacher?.id === uid); | ||
| 253 | - }; | ||
| 254 | 251 | ||
| 255 | const requestColumns = createMemo<ColumnDef<Appointment>[]>(() => [ | 252 | const requestColumns = createMemo<ColumnDef<Appointment>[]>(() => [ |
| 256 | { | 253 | { |
src/pages/calendar-page.test.tsxmodified+62 -5
| @@ -3,7 +3,13 @@ import type { JSX } from "solid-js"; | |||
| 3 | import CalendarPage from "@/pages/calendar-page"; | 3 | import CalendarPage from "@/pages/calendar-page"; |
| 4 | import { PreferencesProvider } from "@/stores/preferences-context"; | 4 | import { PreferencesProvider } from "@/stores/preferences-context"; |
| 5 | 5 | ||
| 6 | -const { failExams, getExams } = vi.hoisted(() => ({ failExams: { times: 0 }, getExams: vi.fn() })); | 6 | +const { failExams, getExams, getEvents, getHomework, getAppointments } = vi.hoisted(() => ({ |
| 7 | + failExams: { times: 0 }, | ||
| 8 | + getExams: vi.fn(), | ||
| 9 | + getEvents: vi.fn(), | ||
| 10 | + getHomework: vi.fn(), | ||
| 11 | + getAppointments: vi.fn(), | ||
| 12 | +})); | ||
| 7 | 13 | ||
| 8 | vi.mock("@tanstack/solid-router", () => ({ | 14 | vi.mock("@tanstack/solid-router", () => ({ |
| 9 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, | 15 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, |
| @@ -18,19 +24,34 @@ vi.mock("@/stores/auth-context", () => ({ | |||
| 18 | error: () => undefined, | 24 | error: () => undefined, |
| 19 | }), | 25 | }), |
| 20 | })); | 26 | })); |
| 21 | -const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 100, offset: 0 }); | 27 | +const page = <T,>(items: T[], total = items.length) => ({ items, total, limit: 100, offset: 0 }); |
| 22 | vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) })); | 28 | vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) })); |
| 23 | -vi.mock("@/api/events", () => ({ getEvents: vi.fn(async () => page([])) })); | 29 | +vi.mock("@/api/events", () => ({ getEvents })); |
| 24 | vi.mock("@/api/exams", () => ({ getExams })); | 30 | vi.mock("@/api/exams", () => ({ getExams })); |
| 25 | -vi.mock("@/api/homework", () => ({ getHomework: vi.fn(async () => page([])) })); | 31 | +vi.mock("@/api/homework", () => ({ getHomework })); |
| 26 | -vi.mock("@/api/appointments", () => ({ getAppointments: vi.fn(async () => page([])) })); | 32 | +vi.mock("@/api/appointments", () => ({ getAppointments })); |
| 27 | vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) })); | 33 | vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) })); |
| 28 | vi.mock("@/api/instances", () => ({ | 34 | vi.mock("@/api/instances", () => ({ |
| 29 | getMyInstances: vi.fn(async () => page([])), | 35 | getMyInstances: vi.fn(async () => page([])), |
| 30 | getInstanceSessions: vi.fn(async () => page([])), | 36 | getInstanceSessions: vi.fn(async () => page([])), |
| 31 | })); | 37 | })); |
| 32 | 38 | ||
| 39 | +// The page bounds its month feeds by the visible month; the test recomputes | ||
| 40 | +// the same bounds the page derives from today at mount. | ||
| 41 | +const monthBounds = () => { | ||
| 42 | + const now = new Date(); | ||
| 43 | + return { | ||
| 44 | + start: new Date(now.getFullYear(), now.getMonth(), 1).getTime(), | ||
| 45 | + end: new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime(), | ||
| 46 | + }; | ||
| 47 | +}; | ||
| 48 | +const homeworkRows = (count: number, offset = 0) => | ||
| 49 | + Array.from({ length: count }, (_, i) => ({ id: `hw${offset + i}`, title: `H${offset + i}`, due_at: Date.now() + i, class_course: "c1" })); | ||
| 50 | + | ||
| 33 | beforeEach(() => { | 51 | beforeEach(() => { |
| 52 | + getEvents.mockImplementation(async () => page([])); | ||
| 53 | + getHomework.mockImplementation(async () => page([])); | ||
| 54 | + getAppointments.mockImplementation(async () => page([])); | ||
| 34 | getExams.mockImplementation(async () => { | 55 | getExams.mockImplementation(async () => { |
| 35 | if (failExams.times > 0) { | 56 | if (failExams.times > 0) { |
| 36 | failExams.times -= 1; | 57 | failExams.times -= 1; |
| @@ -60,3 +81,39 @@ test("a failed feed is named above the grid instead of reading as an empty calen | |||
| 60 | await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); | 81 | await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); |
| 61 | expect(getExams).toHaveBeenCalledTimes(2); | 82 | expect(getExams).toHaveBeenCalledTimes(2); |
| 62 | }); | 83 | }); |
| 84 | + | ||
| 85 | +test("homework and appointments feeds read the visible month window, one bounded page at a time", async () => { | ||
| 86 | + render(() => ( | ||
| 87 | + <PreferencesProvider> | ||
| 88 | + <CalendarPage /> | ||
| 89 | + </PreferencesProvider> | ||
| 90 | + )); | ||
| 91 | + | ||
| 92 | + const { start, end } = monthBounds(); | ||
| 93 | + await waitFor(() => expect(getHomework).toHaveBeenCalled()); | ||
| 94 | + expect(getHomework).toHaveBeenCalledWith({ due_after: start, due_before: end, limit: 100, offset: 0 }); | ||
| 95 | + await waitFor(() => expect(getAppointments).toHaveBeenCalled()); | ||
| 96 | + expect(getAppointments).toHaveBeenCalledWith({ starts_after: start, starts_before: end, limit: 100, offset: 0 }); | ||
| 97 | + // Events and exams keep their open-ended window from the grid's first day, | ||
| 98 | + // now with an explicit page size instead of an unpaged read. | ||
| 99 | + expect(getEvents).toHaveBeenCalledWith({ ends_after: expect.any(Number), limit: 100, offset: 0 }); | ||
| 100 | + expect(getExams).toHaveBeenCalledWith({ ends_after: expect.any(Number), limit: 100, offset: 0 }); | ||
| 101 | +}); | ||
| 102 | + | ||
| 103 | +test("a month window bigger than one page follows offsets until the server total", async () => { | ||
| 104 | + getHomework.mockImplementation(async (params: { offset?: number }) => | ||
| 105 | + params.offset ? page(homeworkRows(50, 100), 150) : page(homeworkRows(100), 150)); | ||
| 106 | + render(() => ( | ||
| 107 | + <PreferencesProvider> | ||
| 108 | + <CalendarPage /> | ||
| 109 | + </PreferencesProvider> | ||
| 110 | + )); | ||
| 111 | + | ||
| 112 | + await waitFor(() => expect(getHomework).toHaveBeenCalledTimes(2)); | ||
| 113 | + expect(getHomework).toHaveBeenLastCalledWith({ | ||
| 114 | + due_after: monthBounds().start, | ||
| 115 | + due_before: monthBounds().end, | ||
| 116 | + limit: 100, | ||
| 117 | + offset: 100, | ||
| 118 | + }); | ||
| 119 | +}); | ||
src/pages/calendar-page.tsxmodified+54 -17
| @@ -8,7 +8,7 @@ import { getHomework } from "@/api/homework"; | |||
| 8 | import { getAppointments } from "@/api/appointments"; | 8 | import { getAppointments } from "@/api/appointments"; |
| 9 | import { getCourses } from "@/api/courses"; | 9 | import { getCourses } from "@/api/courses"; |
| 10 | import { getInstanceSessions, getMyInstances } from "@/api/instances"; | 10 | import { getInstanceSessions, getMyInstances } from "@/api/instances"; |
| 11 | -import type { Appointment, AppointmentStatus, Course } from "@/api/client"; | 11 | +import type { Appointment, AppointmentStatus, Course, Page } from "@/api/client"; |
| 12 | import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; | 12 | import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status"; |
| 13 | import { RouteGuard } from "@/components/layout/route-guard"; | 13 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 14 | import { Badge } from "@/components/ui/badge"; | 14 | import { Badge } from "@/components/ui/badge"; |
| @@ -125,6 +125,26 @@ const KIND_ORDER = Object.keys(KIND_STYLES) as CalendarKind[]; | |||
| 125 | * offer. The month grid alone is unreadable at 45px per cell. */ | 125 | * offer. The month grid alone is unreadable at 45px per cell. */ |
| 126 | type CalendarView = "day" | "week" | "month"; | 126 | type CalendarView = "day" | "week" | "month"; |
| 127 | 127 | ||
| 128 | +/** Page size for the windowed reads below; a busy month outgrows one page. */ | ||
| 129 | +const FEED_PAGE = 100; | ||
| 130 | + | ||
| 131 | +/** | ||
| 132 | + * Read every row the server window matches: follow `offset` until the | ||
| 133 | + * envelope's `total` is drained. The loop is bounded by the server total — a | ||
| 134 | + * stale total can cost one extra page, never spin, and nothing is dropped | ||
| 135 | + * behind a silent cap. | ||
| 136 | + */ | ||
| 137 | +async function fetchWindow<T>(fetchPage: (params: { limit: number; offset: number }) => Promise<Page<T>>): Promise<T[]> { | ||
| 138 | + const first = await fetchPage({ limit: FEED_PAGE, offset: 0 }); | ||
| 139 | + const items = [...first.items]; | ||
| 140 | + while (items.length < first.total) { | ||
| 141 | + const next = await fetchPage({ limit: FEED_PAGE, offset: items.length }); | ||
| 142 | + if (next.items.length === 0) break; | ||
| 143 | + items.push(...next.items); | ||
| 144 | + } | ||
| 145 | + return items; | ||
| 146 | +} | ||
| 147 | + | ||
| 128 | const VIEWS: { id: CalendarView; labelKey: MessageKey }[] = [ | 148 | const VIEWS: { id: CalendarView; labelKey: MessageKey }[] = [ |
| 129 | { id: "day", labelKey: "calendar.viewDay" }, | 149 | { id: "day", labelKey: "calendar.viewDay" }, |
| 130 | { id: "week", labelKey: "calendar.viewWeek" }, | 150 | { id: "week", labelKey: "calendar.viewWeek" }, |
| @@ -196,24 +216,43 @@ function CalendarContent() { | |||
| 196 | // notice above the grid, instead of blanking the whole calendar. | 216 | // notice above the grid, instead of blanking the whole calendar. |
| 197 | const board = createBoardResources(); | 217 | const board = createBoardResources(); |
| 198 | // Events and exams take a schedule window, so they are read from the first | 218 | // Events and exams take a schedule window, so they are read from the first |
| 199 | - // day the grid can show (the month's leading week included) onward, with no | 219 | + // day the grid can show (the month's leading week included) onward. The |
| 200 | - // row cap — a fixed `limit` silently emptied later months once a school had | 220 | + // window only ever widens backwards: paging forward stays inside what is |
| 201 | - // more rows than the cap. The window only ever widens backwards: paging | 221 | + // loaded, paging to an earlier month refetches. Offsets follow the envelope |
| 202 | - // forward stays inside what is loaded, paging to an earlier month refetches. | 222 | + // total, so a window busier than one page still arrives whole. |
| 203 | const viewStart = () => new Date(viewYear(), viewMonth(), 1).getTime() - 7 * DAY_MS; | 223 | const viewStart = () => new Date(viewYear(), viewMonth(), 1).getTime() - 7 * DAY_MS; |
| 204 | const loadedFrom = createMemo<number>((prev) => Math.min(prev, viewStart()), viewStart()); | 224 | const loadedFrom = createMemo<number>((prev) => Math.min(prev, viewStart()), viewStart()); |
| 205 | - const [events] = board.createResource(loadedFrom, async (from) => (await getEvents({ ends_after: from })).items); | 225 | + const [events] = board.createResource(loadedFrom, async (from) => fetchWindow((page) => getEvents({ ...page, ends_after: from }))); |
| 206 | - const [exams] = board.createResource(loadedFrom, async (from) => (await getExams({ ends_after: from })).items); | 226 | + const [exams] = board.createResource(loadedFrom, async (from) => fetchWindow((page) => getExams({ ...page, ends_after: from }))); |
| 207 | - // Appointments and homework have no date filter and list newest-created | 227 | + // Homework and appointments are bound to the visible month itself: a |
| 208 | - // first, so a cap would drop rows by creation order, not by date: read all. | 228 | + // two-sided window cannot widen incrementally, so the source key is the |
| 209 | - const [appointments] = board.createResource(async () => (await getAppointments()).items); | 229 | + // month and paging months refetches. Homework filters on its due date, |
| 210 | - const [homework] = board.createResource(async () => (await getHomework()).items); | 230 | + // appointments on their start. |
| 231 | + const monthWindow = () => ({ | ||
| 232 | + start: new Date(viewYear(), viewMonth(), 1).getTime(), | ||
| 233 | + end: new Date(viewYear(), viewMonth() + 1, 1).getTime(), | ||
| 234 | + }); | ||
| 235 | + const [appointments] = board.createResource( | ||
| 236 | + monthWindow, | ||
| 237 | + async (bounds) => fetchWindow((page) => getAppointments({ ...page, starts_after: bounds.start, starts_before: bounds.end })), | ||
| 238 | + ); | ||
| 239 | + const [homework] = board.createResource( | ||
| 240 | + monthWindow, | ||
| 241 | + async (bounds) => fetchWindow((page) => getHomework({ ...page, due_after: bounds.start, due_before: bounds.end })), | ||
| 242 | + ); | ||
| 211 | 243 | ||
| 212 | // Lessons and study/club meetings both come from course sessions; the course's | 244 | // Lessons and study/club meetings both come from course sessions; the course's |
| 213 | // own `kind` is what separates them. | 245 | // own `kind` is what separates them. |
| 214 | const [sessions] = board.createResource( | 246 | const [sessions] = board.createResource( |
| 215 | - () => auth.user()?.role ?? null, | 247 | + () => { |
| 216 | - async () => { | 248 | + const role = auth.user()?.role ?? null; |
| 249 | + return role ? `${role}|${loadedFrom()}` : null; | ||
| 250 | + }, | ||
| 251 | + async (key) => { | ||
| 252 | + // Sessions read from the earliest viewed month onward — like events and | ||
| 253 | + // exams, the window only widens backwards, so future months ride the | ||
| 254 | + // already-loaded rows and paging to an earlier month refetches. | ||
| 255 | + const from = Number(key.split("|")[1]); | ||
| 217 | // Sessions hang off the instance (şube × ders) now; the catalog course is | 256 | // Sessions hang off the instance (şube × ders) now; the catalog course is |
| 218 | // still what says whether a meeting is a ders, an etüt or a kulüp. | 257 | // still what says whether a meeting is a ders, an etüt or a kulüp. |
| 219 | const [instances, courses] = await Promise.all([ | 258 | const [instances, courses] = await Promise.all([ |
| @@ -226,10 +265,8 @@ function CalendarContent() { | |||
| 226 | const course = byId.get(instance.course); | 265 | const course = byId.get(instance.course); |
| 227 | if (!course) return []; | 266 | if (!course) return []; |
| 228 | try { | 267 | try { |
| 229 | - // No cap: a weekly lesson alone passes 100 sessions in a school | 268 | + const items = await fetchWindow((page) => getInstanceSessions(instance.id, { ...page, starts_after: from })); |
| 230 | - // year, and the rows past a cap were the later months. | 269 | + return items.map((session) => ({ session, course })); |
| 231 | - const page = await getInstanceSessions(instance.id); | ||
| 232 | - return page.items.map((session) => ({ session, course })); | ||
| 233 | } catch { | 270 | } catch { |
| 234 | // One unreadable section must not empty the whole calendar. | 271 | // One unreadable section must not empty the whole calendar. |
| 235 | return []; | 272 | return []; |
src/pages/classes-page.test.tsxmodified+38 -0
| @@ -103,3 +103,41 @@ test("a blank class name is flagged under the field, not sent", async () => { | |||
| 103 | expect(field.getAttribute("aria-describedby")).toBe("class-name-error"); | 103 | expect(field.getAttribute("aria-describedby")).toBe("class-name-error"); |
| 104 | expect(postClass).not.toHaveBeenCalled(); | 104 | expect(postClass).not.toHaveBeenCalled(); |
| 105 | }); | 105 | }); |
| 106 | + | ||
| 107 | +// The grade dropdown's options come from their own unfiltered read: if they | ||
| 108 | +// came from the table rows, picking a grade would collapse the option list to | ||
| 109 | +// that one grade and there would be no way back. | ||
| 110 | +test("the grade filter narrows on the server and keeps every option listed", async () => { | ||
| 111 | + const grade9 = { id: "c9", creator: null, name: "9-A", grade_level: 9, year: null, teacher: null }; | ||
| 112 | + const grade10 = { id: "c10", creator: null, name: "10-A", grade_level: 10, year: null, teacher: null }; | ||
| 113 | + // The table fetch narrows by grade_level; the dropdown's own read never does. | ||
| 114 | + getClasses.mockImplementation((params?: { grade_level?: number }) => { | ||
| 115 | + if (params?.grade_level != null) { | ||
| 116 | + const items = [grade9, grade10].filter((cls) => cls.grade_level === params.grade_level); | ||
| 117 | + return Promise.resolve({ items, total: items.length, limit: 200, offset: 0 }); | ||
| 118 | + } | ||
| 119 | + return Promise.resolve({ items: [grade9, grade10], total: 2, limit: 200, offset: 0 }); | ||
| 120 | + }); | ||
| 121 | + getClassMembers.mockResolvedValue({ items: [], total: 0 }); | ||
| 122 | + | ||
| 123 | + render(() => <PreferencesProvider><ClassesPage /></PreferencesProvider>); | ||
| 124 | + | ||
| 125 | + expect(await screen.findByRole("button", { name: /^9-A/ })).toBeTruthy(); | ||
| 126 | + expect(screen.getByRole("button", { name: /Grade:/ })).toBeTruthy(); | ||
| 127 | + | ||
| 128 | + fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" }); | ||
| 129 | + const grade9Item = await screen.findByRole("menuitem", { name: "Grade 9" }); | ||
| 130 | + fireEvent.pointerDown(grade9Item, { button: 0, pointerType: "mouse" }); | ||
| 131 | + fireEvent.pointerUp(grade9Item, { button: 0, pointerType: "mouse" }); | ||
| 132 | + fireEvent.click(grade9Item); | ||
| 133 | + | ||
| 134 | + // The refetch carries `grade_level`; the unfiltered options read does not. | ||
| 135 | + await waitFor(() => expect(getClasses.mock.calls.at(-1)[0]).toEqual({ grade_level: 9 })); | ||
| 136 | + expect(getClasses.mock.calls.some((call) => call[0]?.grade_level === undefined && call[0]?.limit === 200)).toBe(true); | ||
| 137 | + expect(await screen.findByRole("button", { name: /^9-A/ })).toBeTruthy(); | ||
| 138 | + await waitFor(() => expect(screen.queryByRole("button", { name: /^10-A/ })).toBeNull()); | ||
| 139 | + | ||
| 140 | + // Picking a grade must not erase the other options. | ||
| 141 | + fireEvent.pointerDown(screen.getByRole("button", { name: /Grade:/ }), { button: 0, pointerType: "mouse" }); | ||
| 142 | + expect(await screen.findByRole("menuitem", { name: "Grade 10" })).toBeTruthy(); | ||
| 143 | +}); | ||
src/pages/classes-page.tsxmodified+24 -9
| @@ -73,13 +73,28 @@ function ClassesContent() { | |||
| 73 | 73 | ||
| 74 | const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); | 74 | const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); |
| 75 | const [limits] = createResource(() => canManage() ? getLimits() : null); | 75 | const [limits] = createResource(() => canManage() ? getLimits() : null); |
| 76 | - const [list, { refetch }] = createResource(async () => (await getClasses()).items); | 76 | + // The grade filter narrows on the server now: the table fetch carries |
| 77 | + // `grade_level` and re-runs when the filter changes. An unreadable `?grade=` | ||
| 78 | + // (only possible by hand) falls back to unfiltered, like every URL param. | ||
| 79 | + const [list, { refetch }] = createResource( | ||
| 80 | + () => gradeFilter(), | ||
| 81 | + async (grade) => { | ||
| 82 | + const level = Number(grade); | ||
| 83 | + return (await getClasses(grade === "all" || !Number.isInteger(level) ? undefined : { grade_level: level })).items; | ||
| 84 | + }, | ||
| 85 | + ); | ||
| 86 | + // The dropdown's options must not collapse to the selected grade, so they | ||
| 87 | + // come from their own unfiltered read, not from the filtered table rows. | ||
| 88 | + const [gradeList, { refetch: refetchGrades }] = createResource( | ||
| 89 | + async () => (await getClasses({ limit: 200 })).items, | ||
| 90 | + ); | ||
| 77 | const courseTitle = (id: string) => skippedCourseTitles()[id] ?? "—"; | 91 | const courseTitle = (id: string) => skippedCourseTitles()[id] ?? "—"; |
| 78 | const listData = () => list.latest ?? list() ?? []; | 92 | const listData = () => list.latest ?? list() ?? []; |
| 93 | + const gradeData = () => gradeList.latest ?? gradeList() ?? []; | ||
| 79 | const yearName = (id: string | null) => (id ? years.latest?.find((year) => year.id === id)?.name ?? "—" : t("academicYears.unassigned")); | 94 | const yearName = (id: string | null) => (id ? years.latest?.find((year) => year.id === id)?.name ?? "—" : t("academicYears.unassigned")); |
| 80 | 95 | ||
| 81 | // The grade filter offers only the rungs this school's classes sit on. | 96 | // The grade filter offers only the rungs this school's classes sit on. |
| 82 | - const grades = createMemo(() => [...new Set(listData().map((cls) => cls.grade_level))].sort((a, b) => a - b)); | 97 | + const grades = createMemo(() => [...new Set(gradeData().map((cls) => cls.grade_level))].sort((a, b) => a - b)); |
| 83 | 98 | ||
| 84 | const memberCountIds = createMemo(() => { | 99 | const memberCountIds = createMemo(() => { |
| 85 | const ids = listData().map((cls) => cls.id); | 100 | const ids = listData().map((cls) => cls.id); |
| @@ -98,11 +113,9 @@ function ClassesContent() { | |||
| 98 | // A memo: the columns read it, and must not rebuild on every list refetch. | 113 | // A memo: the columns read it, and must not rebuild on every list refetch. |
| 99 | const memberCountsCapped = createMemo(() => listData().length > MEMBER_COUNT_FETCH_CAP); | 114 | const memberCountsCapped = createMemo(() => listData().length > MEMBER_COUNT_FETCH_CAP); |
| 100 | 115 | ||
| 101 | - // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it. | 116 | + // Class by class (9-A, 9-B, 10-A…) until a column header re-sorts it. The |
| 102 | - const gradeFiltered = createMemo(() => { | 117 | + // grade narrowing itself happens on the server. |
| 103 | - const g = gradeFilter(); | 118 | + const gradeFiltered = createMemo(() => listData().slice().sort(compareClasses)); |
| 104 | - return (g === "all" ? listData() : listData().filter((cls) => String(cls.grade_level) === g)).slice().sort(compareClasses); | ||
| 105 | - }); | ||
| 106 | // A fresh array once the member counts land: the table redraws a row only | 119 | // A fresh array once the member counts land: the table redraws a row only |
| 107 | // when its data changes, so the counts would otherwise stay "—". | 120 | // when its data changes, so the counts would otherwise stay "—". |
| 108 | const rows = createMemo(() => { | 121 | const rows = createMemo(() => { |
| @@ -117,7 +130,9 @@ function ClassesContent() { | |||
| 117 | const [deleteTarget, setDeleteTarget] = createSignal<ClassGroup | null>(null); | 130 | const [deleteTarget, setDeleteTarget] = createSignal<ClassGroup | null>(null); |
| 118 | const [rowError, setRowError] = createSignal(""); | 131 | const [rowError, setRowError] = createSignal(""); |
| 119 | const refreshList = async () => { | 132 | const refreshList = async () => { |
| 120 | - try { await refetch(); } catch { /* stale rows until the next load */ } | 133 | + // The grade dropdown reads its own unfiltered page, so a create, edit or |
| 134 | + // delete that changes which rungs have classes must refresh it too. | ||
| 135 | + try { await Promise.all([refetch(), refetchGrades()]); } catch { /* stale rows until the next load */ } | ||
| 121 | }; | 136 | }; |
| 122 | // Applying is best-effort: the request succeeds and reports the pairs it | 137 | // Applying is best-effort: the request succeeds and reports the pairs it |
| 123 | // could not attach, so a shortfall opens the same report the create uses. | 138 | // could not attach, so a shortfall opens the same report the create uses. |
| @@ -257,7 +272,7 @@ function ClassesContent() { | |||
| 257 | // failure here used to be reported as if the class had not been created, | 272 | // failure here used to be reported as if the class had not been created, |
| 258 | // and it swallowed the navigation to the class that plainly existed. | 273 | // and it swallowed the navigation to the class that plainly existed. |
| 259 | try { | 274 | try { |
| 260 | - await refetch(); | 275 | + await Promise.all([refetch(), refetchGrades()]); |
| 261 | } catch { | 276 | } catch { |
| 262 | // The list reloads on the next visit; the class was created. | 277 | // The list reloads on the next visit; the class was created. |
| 263 | } | 278 | } |
src/pages/courses-page.test.tsxmodified+65 -50
| @@ -33,78 +33,93 @@ afterEach(() => { | |||
| 33 | vi.clearAllMocks(); | 33 | vi.clearAllMocks(); |
| 34 | }); | 34 | }); |
| 35 | 35 | ||
| 36 | -// GET /courses is scoped server-side: a student reads only what they take. | 36 | +const creator = { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }; |
| 37 | -test("student class directory uses only enrolled-course data", async () => { | 37 | +const catalog = [ |
| 38 | - getCourses.mockResolvedValue({ | 38 | + { id: "course-1", title: "Algebra", description: "Core mathematics", kind: "course", class_course_count: 2, course_membership_count: 0, creator }, |
| 39 | - items: [ | 39 | + { id: "study-1", title: "Study Lab", description: "Weekly review", kind: "study", class_course_count: 0, course_membership_count: 5, creator }, |
| 40 | - { | 40 | + { |
| 41 | - id: "course-1", | 41 | + id: "club-1", |
| 42 | - title: "Algebra", | 42 | + title: "Robotics", |
| 43 | - description: "Core mathematics", | 43 | + description: "Build robots", |
| 44 | - kind: "course", | 44 | + kind: "club", |
| 45 | - class_course_count: 2, | 45 | + class_course_count: 1, |
| 46 | - course_membership_count: 0, | 46 | + course_membership_count: 9, |
| 47 | - creator: { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }, | 47 | + creator: { id: "teacher-2", username: "mentor", display_name: "Club Mentor" }, |
| 48 | - }, | 48 | + }, |
| 49 | - { | 49 | +]; |
| 50 | - id: "study-1", | 50 | + |
| 51 | - title: "Study Lab", | 51 | +// The mock plays server: `kind`, `q` and `taught` narrow the page, `total` |
| 52 | - description: "Weekly review", | 52 | +// counts what matched. |
| 53 | - kind: "study", | 53 | +function serveCatalog() { |
| 54 | - class_course_count: 0, | 54 | + getCourses.mockImplementation((params?: { kind?: string; q?: string; taught?: boolean; offset?: number }) => { |
| 55 | - course_membership_count: 5, | 55 | + const needle = params?.q?.toLowerCase(); |
| 56 | - creator: { id: "teacher-1", username: "teacher", display_name: "Ada Teacher" }, | 56 | + const items = catalog.filter( |
| 57 | - }, | 57 | + (course) => |
| 58 | - { | 58 | + (!params?.kind || course.kind === params.kind) && |
| 59 | - id: "club-1", | 59 | + (!needle || `${course.title} ${course.description}`.toLowerCase().includes(needle)) && |
| 60 | - title: "Robotics", | 60 | + (params?.taught === undefined || (params.taught ? course.class_course_count > 0 : course.class_course_count === 0)), |
| 61 | - description: "Build robots", | 61 | + ); |
| 62 | - kind: "club", | 62 | + return Promise.resolve({ items, total: items.length, limit: 10, offset: params?.offset ?? 0 }); |
| 63 | - class_course_count: 1, | ||
| 64 | - course_membership_count: 9, | ||
| 65 | - creator: { id: "teacher-2", username: "mentor", display_name: "Club Mentor" }, | ||
| 66 | - }, | ||
| 67 | - ], | ||
| 68 | - total: 3, | ||
| 69 | - limit: 3, | ||
| 70 | - offset: 0, | ||
| 71 | }); | 63 | }); |
| 64 | +} | ||
| 72 | 65 | ||
| 66 | +// GET /courses is scoped server-side: a student reads only what they take, and | ||
| 67 | +// the kind tab / search box / sections dropdown narrow on the server — the | ||
| 68 | +// table never filters. | ||
| 69 | +test("student course list filters on the server via kind, q and taught", async () => { | ||
| 70 | + serveCatalog(); | ||
| 73 | render(() => <PreferencesProvider><CoursesPage /></PreferencesProvider>); | 71 | render(() => <PreferencesProvider><CoursesPage /></PreferencesProvider>); |
| 74 | 72 | ||
| 75 | expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); | 73 | expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); |
| 76 | expect(screen.getAllByText("Enrolled")).toHaveLength(3); | 74 | expect(screen.getAllByText("Enrolled")).toHaveLength(3); |
| 77 | - expect(getCourses).toHaveBeenCalledWith(); | 75 | + // Unset filters stay off the wire — no `kind`, no `q`, no `taught`, not even empty. |
| 76 | + const first = getCourses.mock.calls[0][0]; | ||
| 77 | + expect(first).not.toHaveProperty("kind"); | ||
| 78 | + expect(first).not.toHaveProperty("q"); | ||
| 79 | + expect(first).not.toHaveProperty("taught"); | ||
| 80 | + expect(first.offset).toBe(0); | ||
| 78 | 81 | ||
| 82 | + // The kind tab refetches with `kind` and resets the offset. | ||
| 79 | fireEvent.click(screen.getByRole("tab", { name: "Study" })); | 83 | fireEvent.click(screen.getByRole("tab", { name: "Study" })); |
| 80 | - expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy(); | 84 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].kind).toBe("study")); |
| 81 | - expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull(); | 85 | + expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"); |
| 82 | - expect(getCourses).toHaveBeenCalledTimes(1); | 86 | + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); |
| 87 | + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); | ||
| 83 | const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record<string, unknown>) => Record<string, unknown> }; | 88 | const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record<string, unknown>) => Record<string, unknown> }; |
| 84 | expect(tabNavigation.to).toBe("/courses"); | 89 | expect(tabNavigation.to).toBe("/courses"); |
| 85 | expect(tabNavigation.replace).toBe(true); | 90 | expect(tabNavigation.replace).toBe(true); |
| 86 | - // The kind tab keeps the search text and restarts paging. | 91 | + // The kind tab keeps the search text and the sections choice, and restarts paging. |
| 87 | - expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, sort: undefined, action: undefined, kind: "study", page: undefined }); | 92 | + expect(tabNavigation.search({ q: "alg", taught: "taught", page: 3, action: "new" })).toEqual({ q: "alg", taught: "taught", sort: undefined, action: undefined, kind: "study", page: undefined }); |
| 88 | 93 | ||
| 89 | fireEvent.click(screen.getByRole("tab", { name: "Club" })); | 94 | fireEvent.click(screen.getByRole("tab", { name: "Club" })); |
| 95 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].kind).toBe("club")); | ||
| 90 | expect(await screen.findByRole("button", { name: /^Robotics/ })).toBeTruthy(); | 96 | expect(await screen.findByRole("button", { name: /^Robotics/ })).toBeTruthy(); |
| 91 | - expect(screen.queryByRole("button", { name: /^Study Lab/ })).toBeNull(); | ||
| 92 | 97 | ||
| 93 | - fireEvent.click(screen.getByRole("tab", { name: "Classes" })); | 98 | + fireEvent.click(screen.getByRole("tab", { name: "All" })); |
| 99 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("kind")); | ||
| 94 | expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); | 100 | expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); |
| 95 | - expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull(); | ||
| 96 | 101 | ||
| 97 | - fireEvent.click(screen.getByRole("tab", { name: "All" })); | 102 | + // The search box is the `q` param: trimmed, blank omitted, offset reset. |
| 98 | - fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "robot" } }); | 103 | + fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: " robots " } }); |
| 99 | - await waitFor(() => expect(screen.getByRole("button", { name: /^Robotics/ })).toBeTruthy()); | 104 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].q).toBe("robots"), { timeout: 2000 }); |
| 100 | - expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull(); | 105 | + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); |
| 106 | + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); | ||
| 107 | + | ||
| 108 | + fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: " " } }); | ||
| 109 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"), { timeout: 2000 }); | ||
| 110 | + expect(await screen.findByRole("button", { name: /^Algebra/ })).toBeTruthy(); | ||
| 101 | 111 | ||
| 102 | - fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } }); | 112 | + // The sections dropdown is the `taught` param: untaught sends taught=false |
| 113 | + // and resets the offset; the server then returns only courses with no şube. | ||
| 114 | + expect(screen.getByRole("button", { name: /Section:/ })).toBeTruthy(); | ||
| 103 | fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" }); | 115 | fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" }); |
| 104 | const untaught = await screen.findByRole("menuitem", { name: "No sections" }); | 116 | const untaught = await screen.findByRole("menuitem", { name: "No sections" }); |
| 105 | fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" }); | 117 | fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" }); |
| 106 | fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" }); | 118 | fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" }); |
| 107 | fireEvent.click(untaught); | 119 | fireEvent.click(untaught); |
| 108 | - expect(await screen.findByRole("button", { name: /^Study Lab/ })).toBeTruthy(); | 120 | + await waitFor(() => expect(getCourses.mock.calls.at(-1)[0].taught).toBe(false)); |
| 121 | + expect(getCourses.mock.calls.at(-1)[0].offset).toBe(0); | ||
| 122 | + expect(getCourses.mock.calls.at(-1)[0]).not.toHaveProperty("q"); | ||
| 123 | + await waitFor(() => expect(screen.queryByRole("button", { name: /^Algebra/ })).toBeNull()); | ||
| 109 | expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull(); | 124 | expect(screen.queryByRole("button", { name: /^Robotics/ })).toBeNull(); |
| 110 | }); | 125 | }); |
src/pages/courses-page.tsxmodified+56 -27
| @@ -1,4 +1,5 @@ | |||
| 1 | -import { Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; | 1 | +import { Show, Suspense, createEffect, createMemo, createSignal, on } from "solid-js"; |
| 2 | +import { createResponsivePageSize } from "@/lib/create-page-size"; | ||
| 2 | import { createResource } from "@/lib/create-resource"; | 3 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { useNavigate, useSearch } from "@tanstack/solid-router"; | 4 | import { useNavigate, useSearch } from "@tanstack/solid-router"; |
| 4 | import type { ColumnDef } from "@tanstack/solid-table"; | 5 | import type { ColumnDef } from "@tanstack/solid-table"; |
| @@ -22,11 +23,11 @@ import { SidePanel } from "@/components/ui/side-panel"; | |||
| 22 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 23 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 23 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | 24 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| 24 | import { Textarea } from "@/components/ui/textarea"; | 25 | import { Textarea } from "@/components/ui/textarea"; |
| 26 | +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; | ||
| 25 | import { createFlash } from "@/lib/flash"; | 27 | import { createFlash } from "@/lib/flash"; |
| 26 | -import { matchesSearch } from "@/lib/search-text"; | ||
| 27 | import { personLabel } from "@/lib/person"; | 28 | import { personLabel } from "@/lib/person"; |
| 28 | import { hasMinRole } from "@/lib/roles"; | 29 | import { hasMinRole } from "@/lib/roles"; |
| 29 | -import { createUrlEnum } from "@/lib/url-state"; | 30 | +import { createUrlEnum, readPageIndex, readString } from "@/lib/url-state"; |
| 30 | import { useAuth } from "@/stores/auth-context"; | 31 | import { useAuth } from "@/stores/auth-context"; |
| 31 | import { usePreferences, useT } from "@/stores/preferences-context"; | 32 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 32 | 33 | ||
| @@ -52,11 +53,17 @@ function CoursesContent() { | |||
| 52 | const [showForm, setShowForm] = createSignal(routeSearch().action === "new"); | 53 | const [showForm, setShowForm] = createSignal(routeSearch().action === "new"); |
| 53 | const [title, setTitle] = createSignal(""); | 54 | const [title, setTitle] = createSignal(""); |
| 54 | const [description, setDescription] = createSignal(""); | 55 | const [description, setDescription] = createSignal(""); |
| 55 | - // Catalog rows carry no term, capacity or staff any more — a şube decides | 56 | + // Filters and paging are server-side now: the kind tab is the `kind` param, |
| 56 | - // all three when it attaches the course. `taughtFilter` narrows by whether | 57 | + // the search box the `q` param, the sections dropdown the `taught` param, |
| 57 | - // any şube has. It rides in the URL beside the table's own search, sort and | 58 | + // and the envelope's total is already the filtered one. `?kind=` tracks the |
| 58 | - // page, so Back from a course and a reload land where the list was left. | 59 | + // tab; `?q=`, `?page=` and `?taught=` restore the list on a reload (Back |
| 60 | + // from a course lands where the list was left). | ||
| 59 | const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all"); | 61 | const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all"); |
| 62 | + const taughtParam = () => (taughtFilter() === "taught" ? true : taughtFilter() === "untaught" ? false : undefined); | ||
| 63 | + const pageSize = createResponsivePageSize(PAGE_SIZE); | ||
| 64 | + const [page, setPage] = createSignal(readPageIndex(routeSearch().page)); | ||
| 65 | + createEffect(on(pageSize, () => setPage(0), { defer: true })); | ||
| 66 | + const [search, setSearch, debouncedSearch] = createDebouncedSignal(readString(routeSearch().q)); | ||
| 60 | const [error, setError] = createSignal(""); | 67 | const [error, setError] = createSignal(""); |
| 61 | const [pending, setPending] = createSignal(false); | 68 | const [pending, setPending] = createSignal(false); |
| 62 | const [flash, setFlash] = createFlash(); | 69 | const [flash, setFlash] = createFlash(); |
| @@ -69,21 +76,34 @@ function CoursesContent() { | |||
| 69 | }); | 76 | }); |
| 70 | 77 | ||
| 71 | const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); | 78 | const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); |
| 79 | + // Scoped server-side: a student reads only the courses they take. The | ||
| 80 | + // source carries every input the fetch reads, so each change refetches. | ||
| 72 | const [list, { refetch }] = createResource( | 81 | const [list, { refetch }] = createResource( |
| 73 | - () => auth.user()?.role ?? null, | 82 | + () => ({ |
| 74 | - // Scoped server-side: a student reads only the courses they take. | 83 | + role: auth.user()?.role ?? null, |
| 75 | - () => getCourses(), | 84 | + kind: pageKind(), |
| 76 | - ); | 85 | + q: debouncedSearch().trim(), |
| 77 | - const listData = () => list.latest ?? list(); | 86 | + taught: taughtParam(), |
| 78 | - // A memo: the table must see one array per change, not a fresh one per read. | 87 | + page: page(), |
| 79 | - const filteredCourses = createMemo(() => | 88 | + size: pageSize(), |
| 80 | - (listData()?.items ?? []).filter((course) => { | ||
| 81 | - if (pageKind() && course.kind !== pageKind()) return false; | ||
| 82 | - if (taughtFilter() === "untaught" && course.class_course_count > 0) return false; | ||
| 83 | - if (taughtFilter() === "taught" && course.class_course_count === 0) return false; | ||
| 84 | - return true; | ||
| 85 | }), | 89 | }), |
| 90 | + (filters) => | ||
| 91 | + getCourses({ | ||
| 92 | + limit: filters.size, | ||
| 93 | + offset: filters.page * filters.size, | ||
| 94 | + ...(filters.kind ? { kind: filters.kind } : {}), | ||
| 95 | + ...(filters.q ? { q: filters.q } : {}), | ||
| 96 | + ...(filters.taught != null ? { taught: filters.taught } : {}), | ||
| 97 | + }), | ||
| 86 | ); | 98 | ); |
| 99 | + const listData = () => list.latest ?? list(); | ||
| 100 | + const total = () => listData()?.total ?? 0; | ||
| 101 | + // Deleting the last row of the last page shrinks the page count under the | ||
| 102 | + // current page; clamp instead of stranding the user off the end. | ||
| 103 | + const pageCount = () => Math.max(1, Math.ceil(total() / pageSize())); | ||
| 104 | + createEffect(() => { | ||
| 105 | + if (page() >= pageCount()) setPage(pageCount() - 1); | ||
| 106 | + }); | ||
| 87 | const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } }); | 107 | const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } }); |
| 88 | // Catalog rights, as on the detail page: the creator or a manager+. | 108 | // Catalog rights, as on the detail page: the creator or a manager+. |
| 89 | const canManageCatalog = (course: Course) => { | 109 | const canManageCatalog = (course: Course) => { |
| @@ -258,6 +278,7 @@ function CoursesContent() { | |||
| 258 | onChange={(value) => { | 278 | onChange={(value) => { |
| 259 | const kind = value === "course" || value === "study" || value === "club" ? value : undefined; | 279 | const kind = value === "course" || value === "study" || value === "club" ? value : undefined; |
| 260 | setPageKind(kind); | 280 | setPageKind(kind); |
| 281 | + setPage(0); | ||
| 261 | void navigate({ | 282 | void navigate({ |
| 262 | to: "/courses", | 283 | to: "/courses", |
| 263 | search: (prev) => ({ q: prev.q, taught: prev.taught, sort: prev.sort, action: undefined, kind, page: undefined }), | 284 | search: (prev) => ({ q: prev.q, taught: prev.taught, sort: prev.sort, action: undefined, kind, page: undefined }), |
| @@ -278,26 +299,34 @@ function CoursesContent() { | |||
| 278 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> | 299 | <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} /> |
| 279 | </Show> | 300 | </Show> |
| 280 | <DataTable | 301 | <DataTable |
| 281 | - urlState | ||
| 282 | columns={columns()} | 302 | columns={columns()} |
| 283 | - data={filteredCourses()} | 303 | + data={listData()?.items ?? []} |
| 284 | tableClass="table-fixed min-w-[44rem]" | 304 | tableClass="table-fixed min-w-[44rem]" |
| 285 | - searchPredicate={(course, query) => matchesSearch(query, course.title, course.description, personLabel(course.creator))} | ||
| 286 | filterPlaceholder={t("common.searchPlaceholder")} | 305 | filterPlaceholder={t("common.searchPlaceholder")} |
| 287 | filterHint={t("search.hint.courses")} | 306 | filterHint={t("search.hint.courses")} |
| 307 | + searchValue={search()} | ||
| 308 | + onSearchInput={(value) => { | ||
| 309 | + setSearch(value); | ||
| 310 | + setPage(0); | ||
| 311 | + }} | ||
| 288 | enablePagination | 312 | enablePagination |
| 289 | - pageSize={PAGE_SIZE} | 313 | + manualPagination={{ pageIndex: page(), pageSize: pageSize(), total: total(), onPageChange: setPage }} |
| 290 | - storageKey="courses" | ||
| 291 | - pageResetKey={`${pageKind() ?? "all"}|${taughtFilter()}`} | ||
| 292 | filtersActive={taughtFilter() !== "all"} | 314 | filtersActive={taughtFilter() !== "all"} |
| 293 | - onClearFilters={() => setTaughtFilter("all")} | 315 | + onClearFilters={() => { |
| 316 | + setTaughtFilter("all"); | ||
| 317 | + setPage(0); | ||
| 318 | + }} | ||
| 294 | empty={t("courses.empty", { item: kindInSentence() })} | 319 | empty={t("courses.empty", { item: kindInSentence() })} |
| 295 | onRowClick={openCourse} | 320 | onRowClick={openCourse} |
| 321 | + storageKey="courses" | ||
| 296 | filters={ | 322 | filters={ |
| 297 | <DropdownSelect | 323 | <DropdownSelect |
| 298 | labelPrefix={t("courses.sectionsFilter")} | 324 | labelPrefix={t("courses.sectionsFilter")} |
| 299 | value={taughtFilter()} | 325 | value={taughtFilter()} |
| 300 | - onChange={(value) => setTaughtFilter(value === "taught" || value === "untaught" ? value : "all")} | 326 | + onChange={(value) => { |
| 327 | + setTaughtFilter(value === "taught" || value === "untaught" ? value : "all"); | ||
| 328 | + setPage(0); | ||
| 329 | + }} | ||
| 301 | options={[ | 330 | options={[ |
| 302 | { value: "all", label: t("common.all") }, | 331 | { value: "all", label: t("common.all") }, |
| 303 | { value: "taught", label: t("courses.withSections") }, | 332 | { value: "taught", label: t("courses.withSections") }, |
src/pages/dashboard-page.tsxmodified+33 -10
| @@ -62,6 +62,7 @@ import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; | |||
| 62 | import { getModulesCatalog } from "@/api/modules"; | 62 | import { getModulesCatalog } from "@/api/modules"; |
| 63 | import { useModules } from "@/stores/modules-context"; | 63 | import { useModules } from "@/stores/modules-context"; |
| 64 | import { useAuth } from "@/stores/auth-context"; | 64 | import { useAuth } from "@/stores/auth-context"; |
| 65 | +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; | ||
| 65 | import { usePreferences, useT } from "@/stores/preferences-context"; | 66 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 66 | 67 | ||
| 67 | const DAY_MS = 24 * 60 * 60 * 1000; | 68 | const DAY_MS = 24 * 60 * 60 * 1000; |
| @@ -78,6 +79,8 @@ const TREND_EXAM_CAP = 20; | |||
| 78 | const TREND_MARK_CAP = 20; | 79 | const TREND_MARK_CAP = 20; |
| 79 | /** Classes whose roster size the admin "Şubeler" quick links read. */ | 80 | /** Classes whose roster size the admin "Şubeler" quick links read. */ |
| 80 | const CLASS_LINK_CAP = 12; | 81 | const CLASS_LINK_CAP = 12; |
| 82 | +/** Page size for the paged heatmap window read of `/pomodoro/me`. */ | ||
| 83 | +const POMODORO_PAGE = 400; | ||
| 81 | 84 | ||
| 82 | /** | 85 | /** |
| 83 | * Chronological key for an exam: its schedule when it has one, else when it | 86 | * Chronological key for an exam: its schedule when it has one, else when it |
| @@ -175,6 +178,9 @@ function DashboardContent() { | |||
| 175 | throw err; | 178 | throw err; |
| 176 | }); | 179 | }); |
| 177 | const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); | 180 | const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); |
| 181 | + // Server-anchored time (local fallback). Declared before the resources that | ||
| 182 | + // read it in their fetchers. | ||
| 183 | + const now = () => clock()?.now ?? Date.now(); | ||
| 178 | // Unpaged: the backend has no `kind` filter, so a "courses" count that | 184 | // Unpaged: the backend has no `kind` filter, so a "courses" count that |
| 179 | // excludes studies and clubs has to be counted here over the whole list. | 185 | // excludes studies and clubs has to be counted here over the whole list. |
| 180 | const [courses] = createResource( | 186 | const [courses] = createResource( |
| @@ -194,23 +200,34 @@ function DashboardContent() { | |||
| 194 | () => role() === "parent" || !on("exams") ? null : role(), | 200 | () => role() === "parent" || !on("exams") ? null : role(), |
| 195 | () => quiet(getExams({ limit: 100 })), | 201 | () => quiet(getExams({ limit: 100 })), |
| 196 | ); | 202 | ); |
| 197 | - // Unfiltered: `/homework` has no due-date window, so this one read serves both | 203 | + // One windowed read serves all three homework consumers: the deadlines |
| 198 | - // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking | 204 | + // table keeps the upcoming rows via its scheduleStatus filter, the teacher |
| 199 | - // heatmap. | 205 | + // queue grades homework due around now, and the activity heatmap looks |
| 200 | - // `limit: 100` matches the shell's feed read, so the two coalesce. | 206 | + // back exactly this far. Pages are followed until the envelope total — |
| 207 | + // no blind cap decides which rows exist. | ||
| 201 | const [homework] = createResource( | 208 | const [homework] = createResource( |
| 202 | () => role() === "parent" || !on("homework") ? null : role(), | 209 | () => role() === "parent" || !on("homework") ? null : role(), |
| 203 | - () => quiet(getHomework({ limit: 100 })), | 210 | + () => |
| 211 | + quiet(loadWindowedList( | ||
| 212 | + (params) => getHomework({ ...params, due_after: now() - HEATMAP_WEEKS * WEEK_MS }), | ||
| 213 | + LIST_CAP, | ||
| 214 | + )), | ||
| 204 | ); | 215 | ); |
| 205 | const [children] = createResource( | 216 | const [children] = createResource( |
| 206 | () => role() === "parent" ? true : null, | 217 | () => role() === "parent" ? true : null, |
| 207 | () => quiet(getMyStudents({ limit: 12 })), | 218 | () => quiet(getMyStudents({ limit: 12 })), |
| 208 | ); | 219 | ); |
| 209 | - // Same page as the shell's notification poll (`limit: 100`), so the two | 220 | + // Windowed like homework: the pending-approvals rail, the deadlines table |
| 210 | - // concurrent first-paint reads coalesce into one request in `client`. | 221 | + // and the activity heatmap all read this. 26 weeks back keeps a stale but |
| 222 | + // still-pending request visible while the heatmap gets its history; pages | ||
| 223 | + // are followed until the envelope total instead of a blind cap. | ||
| 211 | const [appointments] = createResource( | 224 | const [appointments] = createResource( |
| 212 | () => (on("appointments") ? true : null), | 225 | () => (on("appointments") ? true : null), |
| 213 | - () => quiet(getAppointments({ limit: 100 })), | 226 | + () => |
| 227 | + quiet(loadWindowedList( | ||
| 228 | + (params) => getAppointments({ ...params, starts_after: now() - HEATMAP_WEEKS * WEEK_MS }), | ||
| 229 | + LIST_CAP, | ||
| 230 | + )), | ||
| 214 | ); | 231 | ); |
| 215 | const [menus] = createResource( | 232 | const [menus] = createResource( |
| 216 | () => (on("meals") ? clock()?.now : null), | 233 | () => (on("meals") ? clock()?.now : null), |
| @@ -230,9 +247,16 @@ function DashboardContent() { | |||
| 230 | ); | 247 | ); |
| 231 | // Focus heatmap source. Only a student owns pomodoro sessions — reading | 248 | // Focus heatmap source. Only a student owns pomodoro sessions — reading |
| 232 | // another user's log is the teacher+ /management/pomodoros page's job. | 249 | // another user's log is the teacher+ /management/pomodoros page's job. |
| 250 | + // The 26-week grid window rides in the query (`from` inclusive, `to` | ||
| 251 | + // exclusive, unix ms) and every page is followed until the envelope total, | ||
| 252 | + // so neither a blind cap nor a JS cutoff decides what the grid shows. | ||
| 233 | const [pomodoro] = createResource( | 253 | const [pomodoro] = createResource( |
| 234 | () => role() === "student" && on("pomodoro") ? true : null, | 254 | () => role() === "student" && on("pomodoro") ? true : null, |
| 235 | - () => quiet(getPomodoroMe({ limit: 400 })), | 255 | + () => |
| 256 | + quiet(loadWindowedList( | ||
| 257 | + (params) => getPomodoroMe({ ...params, from: now() - HEATMAP_WEEKS * WEEK_MS, to: now() }), | ||
| 258 | + POMODORO_PAGE, | ||
| 259 | + )), | ||
| 236 | ); | 260 | ); |
| 237 | // `/events` is the one list here that really is filtered server-side, by the | 261 | // `/events` is the one list here that really is filtered server-side, by the |
| 238 | // `ends_after` window the deadlines table needs. The heatmap looks backwards | 262 | // `ends_after` window the deadlines table needs. The heatmap looks backwards |
| @@ -431,7 +455,6 @@ function DashboardContent() { | |||
| 431 | }); | 455 | }); |
| 432 | 456 | ||
| 433 | const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username; | 457 | const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username; |
| 434 | - const now = () => clock()?.now ?? Date.now(); | ||
| 435 | 458 | ||
| 436 | // STU-01 "Bu Hafta" rail — this week's pomodoro focus minutes, Monday | 459 | // STU-01 "Bu Hafta" rail — this week's pomodoro focus minutes, Monday |
| 437 | // through Sunday. Distinct granularity from the 26-week heatmap below; | 460 | // through Sunday. Distinct granularity from the 26-week heatmap below; |
src/pages/events-page.test.tsxmodified+37 -2
| @@ -3,13 +3,16 @@ import type { JSX } from "solid-js"; | |||
| 3 | import EventsPage from "@/pages/events-page"; | 3 | import EventsPage from "@/pages/events-page"; |
| 4 | import { PreferencesProvider } from "@/stores/preferences-context"; | 4 | import { PreferencesProvider } from "@/stores/preferences-context"; |
| 5 | 5 | ||
| 6 | -const { getEvents } = vi.hoisted(() => ({ getEvents: vi.fn() })); | 6 | +const { getEvents, locationSearch } = vi.hoisted(() => ({ |
| 7 | + getEvents: vi.fn(), | ||
| 8 | + locationSearch: { value: {} as Record<string, unknown> }, | ||
| 9 | +})); | ||
| 7 | 10 | ||
| 8 | vi.mock("@tanstack/solid-router", () => ({ | 11 | vi.mock("@tanstack/solid-router", () => ({ |
| 9 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, | 12 | Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>, |
| 10 | Navigate: () => null, | 13 | Navigate: () => null, |
| 11 | useNavigate: () => vi.fn(), | 14 | useNavigate: () => vi.fn(), |
| 12 | - useLocation: () => () => ({ pathname: "/events", searchStr: "" }), | 15 | + useLocation: () => () => ({ pathname: "/events", searchStr: "", search: locationSearch.value }), |
| 13 | })); | 16 | })); |
| 14 | vi.mock("@/stores/auth-context", () => ({ | 17 | vi.mock("@/stores/auth-context", () => ({ |
| 15 | useAuth: () => ({ | 18 | useAuth: () => ({ |
| @@ -35,6 +38,7 @@ const event = (n: number) => ({ | |||
| 35 | afterEach(() => { | 38 | afterEach(() => { |
| 36 | cleanup(); | 39 | cleanup(); |
| 37 | vi.clearAllMocks(); | 40 | vi.clearAllMocks(); |
| 41 | + locationSearch.value = {}; | ||
| 38 | }); | 42 | }); |
| 39 | 43 | ||
| 40 | test("the event list reads every page instead of stopping at the first 100", async () => { | 44 | 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 | |||
| 55 | expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0 }); | 59 | expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0 }); |
| 56 | expect(screen.queryByRole("button", { name: /Tümünü yükle|Load all/ })).toBeNull(); | 60 | expect(screen.queryByRole("button", { name: /Tümünü yükle|Load all/ })).toBeNull(); |
| 57 | }); | 61 | }); |
| 62 | + | ||
| 63 | +test("the upcoming tab asks the server for rows whose window has not finished", async () => { | ||
| 64 | + locationSearch.value = { when: "upcoming" }; | ||
| 65 | + getEvents.mockResolvedValue({ items: [event(1)], total: 1, limit: 100, offset: 0 }); | ||
| 66 | + | ||
| 67 | + render(() => ( | ||
| 68 | + <PreferencesProvider> | ||
| 69 | + <EventsPage /> | ||
| 70 | + </PreferencesProvider> | ||
| 71 | + )); | ||
| 72 | + | ||
| 73 | + await waitFor(() => expect(getEvents).toHaveBeenCalled()); | ||
| 74 | + // Exact key set: exactly one bound, no other window key, no `?key=` blank. | ||
| 75 | + expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0, ends_after: expect.any(Number) }); | ||
| 76 | +}); | ||
| 77 | + | ||
| 78 | +test("the past tab asks the server for rows that finished before now", async () => { | ||
| 79 | + locationSearch.value = { when: "past" }; | ||
| 80 | + getEvents.mockResolvedValue({ items: [event(1)], total: 1, limit: 100, offset: 0 }); | ||
| 81 | + | ||
| 82 | + render(() => ( | ||
| 83 | + <PreferencesProvider> | ||
| 84 | + <EventsPage /> | ||
| 85 | + </PreferencesProvider> | ||
| 86 | + )); | ||
| 87 | + | ||
| 88 | + await waitFor(() => expect(getEvents).toHaveBeenCalled()); | ||
| 89 | + expect(getEvents).toHaveBeenCalledWith({ limit: 100, offset: 0, ends_before: expect.any(Number) }); | ||
| 90 | +}); | ||
| 91 | + | ||
| 92 | + | ||
src/pages/events-page.tsxmodified+17 -11
| @@ -59,13 +59,12 @@ function EventsContent() { | |||
| 59 | const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); | 59 | const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); |
| 60 | 60 | ||
| 61 | const filterEvents = (items: Event[]) => { | 61 | const filterEvents = (items: Event[]) => { |
| 62 | - const scope = timeFilter(); | ||
| 63 | const nowMs = now(); | 62 | const nowMs = now(); |
| 64 | const isPast = (event: Event) => event.ends_at != null && event.ends_at < nowMs; | 63 | const isPast = (event: Event) => event.ends_at != null && event.ends_at < nowMs; |
| 65 | const at = (event: Event) => event.starts_at ?? event.ends_at ?? null; | 64 | const at = (event: Event) => event.starts_at ?? event.ends_at ?? null; |
| 66 | // Default order, before any header sort: what is still ahead comes first, | 65 | // Default order, before any header sort: what is still ahead comes first, |
| 67 | - // soonest first; what is over follows, most recent first. The API lists | 66 | + // soonest first; what is over follows, most recent first. Applied here |
| 68 | - // newest first, which put a far-off event above next week's. | 67 | + // whatever order the server chose — it differs per tab window. |
| 69 | const byDefault = (a: Event, b: Event) => { | 68 | const byDefault = (a: Event, b: Event) => { |
| 70 | const pastA = isPast(a); | 69 | const pastA = isPast(a); |
| 71 | const pastB = isPast(b); | 70 | const pastB = isPast(b); |
| @@ -75,17 +74,24 @@ function EventsContent() { | |||
| 75 | if (atA == null || atB == null) return atA == null ? (atB == null ? 0 : 1) : -1; | 74 | if (atA == null || atB == null) return atA == null ? (atB == null ? 0 : 1) : -1; |
| 76 | return pastA ? atB - atA : atA - atB; | 75 | return pastA ? atB - atA : atA - atB; |
| 77 | }; | 76 | }; |
| 78 | - return items | 77 | + // Tab membership is the server's job now (see the fetch bounds below); |
| 79 | - .filter((event) => { | 78 | + // the client only orders what came back. Copy first: sorting in place |
| 80 | - if (scope === "upcoming" && isPast(event)) return false; | 79 | + // would mutate the resource's array. |
| 81 | - if (scope === "past" && !isPast(event)) return false; | 80 | + return [...items].sort(byDefault); |
| 82 | - return true; | ||
| 83 | - }) | ||
| 84 | - .sort(byDefault); | ||
| 85 | }; | 81 | }; |
| 86 | 82 | ||
| 83 | + // Tab windows are enforced server-side, at the moment of the request: | ||
| 84 | + // upcoming keeps rows whose window has not finished (`ends_after`), past | ||
| 85 | + // keeps rows that finished before now (`ends_before`); `all` sends nothing | ||
| 86 | + // and stays unfiltered. The window rides in the source key so switching | ||
| 87 | + // tabs refetches with that tab's bounds; every page of the filtered set is | ||
| 88 | + // read (no cap, no truncation notice). | ||
| 87 | const [list, { refetch }] = createResource( | 89 | const [list, { refetch }] = createResource( |
| 88 | - async () => ({ items: await loadAllPages(getEvents) }), | 90 | + () => timeFilter(), |
| 91 | + async (scope) => { | ||
| 92 | + const bounds = scope === "upcoming" ? { ends_after: now() } : scope === "past" ? { ends_before: now() } : undefined; | ||
| 93 | + return { items: await loadAllPages((params) => getEvents(bounds ? { ...params, ...bounds } : params)) }; | ||
| 94 | + }, | ||
| 89 | ); | 95 | ); |
| 90 | const rows = createMemo(() => filterEvents(list()?.items ?? [])); | 96 | const rows = createMemo(() => filterEvents(list()?.items ?? [])); |
| 91 | 97 | ||
src/pages/exams-page.tsxmodified+19 -9
| @@ -59,11 +59,6 @@ function ExamsContent() { | |||
| 59 | const { locale } = usePreferences(); | 59 | const { locale } = usePreferences(); |
| 60 | const now = createNow(); | 60 | const now = createNow(); |
| 61 | type ExamTab = "all" | "upcoming" | "completed" | "draft"; | 61 | type ExamTab = "all" | "upcoming" | "completed" | "draft"; |
| 62 | - const examTabGroup = (status: ExamDisplayStatus): ExamTab => { | ||
| 63 | - if (status === "draft") return "draft"; | ||
| 64 | - if (status === "upcoming" || status === "active" || status === "unscheduled") return "upcoming"; | ||
| 65 | - return "completed"; | ||
| 66 | - }; | ||
| 67 | // Tab and filters live in the URL beside the table's own search/page/sort, | 62 | // Tab and filters live in the URL beside the table's own search/page/sort, |
| 68 | // so Back from an exam lands on the same slice of the list. | 63 | // so Back from an exam lands on the same slice of the list. |
| 69 | const [tab, setTab] = createUrlEnum<ExamTab>("tab", ["all", "upcoming", "completed", "draft"], "all"); | 64 | const [tab, setTab] = createUrlEnum<ExamTab>("tab", ["all", "upcoming", "completed", "draft"], "all"); |
| @@ -134,7 +129,12 @@ function ExamsContent() { | |||
| 134 | const allowed = isStudent() ? new Set(visibleCourses().map((row) => row.id)) : null; | 129 | const allowed = isStudent() ? new Set(visibleCourses().map((row) => row.id)) : null; |
| 135 | return items.filter((exam) => { | 130 | return items.filter((exam) => { |
| 136 | if (allowed && !allowed.has(exam.class_course)) return false; | 131 | if (allowed && !allowed.has(exam.class_course)) return false; |
| 137 | - if (tab() !== "all" && examTabGroup(examStatus(exam)) !== tab()) return false; | 132 | + // Upcoming/completed membership is the server's job now (see the fetch |
| 133 | + // bounds); the client keeps only the draft split, which no schedule | ||
| 134 | + // window can express. | ||
| 135 | + const status = examStatus(exam); | ||
| 136 | + if (tab() === "draft" && status !== "draft") return false; | ||
| 137 | + if (tab() !== "all" && tab() !== "draft" && status === "draft") return false; | ||
| 138 | if (courseFilter() !== "all" && exam.class_course !== courseFilter()) return false; | 138 | if (courseFilter() !== "all" && exam.class_course !== courseFilter()) return false; |
| 139 | if (kindFilter() !== "all" && String(exam.kind) !== kindFilter()) return false; | 139 | if (kindFilter() !== "all" && String(exam.kind) !== kindFilter()) return false; |
| 140 | return true; | 140 | return true; |
| @@ -150,13 +150,23 @@ function ExamsContent() { | |||
| 150 | statusLabel(exam.displayStatus), | 150 | statusLabel(exam.displayStatus), |
| 151 | ); | 151 | ); |
| 152 | 152 | ||
| 153 | + // Tab windows are enforced server-side, at the moment of the request: | ||
| 154 | + // completed keeps rows that finished before now (`ends_before`), upcoming | ||
| 155 | + // keeps rows whose window has not finished (`ends_after`); `all` and | ||
| 156 | + // `draft` send nothing — drafts carry no schedule, so no bound can select | ||
| 157 | + // them and the client splits them instead. The window rides in the source | ||
| 158 | + // key so switching tabs refetches with that tab's bounds; every page of | ||
| 159 | + // the filtered set is read (no cap, no truncation notice). | ||
| 153 | const [list, { refetch: refetchExams }] = createResource( | 160 | const [list, { refetch: refetchExams }] = createResource( |
| 154 | () => { | 161 | () => { |
| 155 | if (sections() === undefined) return null; | 162 | if (sections() === undefined) return null; |
| 156 | - return `${visibleCourses().map((row) => row.id).join(",")}`; | 163 | + const windowScope = tab() === "completed" ? "completed" : tab() === "upcoming" ? "upcoming" : "unbounded"; |
| 164 | + return `${windowScope}|${visibleCourses().map((row) => row.id).join(",")}`; | ||
| 157 | }, | 165 | }, |
| 158 | - async () => { | 166 | + async (key) => { |
| 159 | - const items = await loadAllPages(getExams); | 167 | + const scope = key.split("|")[0]; |
| 168 | + const bounds = scope === "completed" ? { ends_before: now() } : scope === "upcoming" ? { ends_after: now() } : undefined; | ||
| 169 | + const items = await loadAllPages<Exam>((params) => getExams(bounds ? { ...params, ...bounds } : params)); | ||
| 160 | const page = { items }; | 170 | const page = { items }; |
| 161 | const known = new Map(visibleCourses().map((row) => [row.id, row.label])); | 171 | const known = new Map(visibleCourses().map((row) => [row.id, row.label])); |
| 162 | const missing = [...new Set(items.map((exam) => exam.class_course))].filter((instanceId) => !known.has(instanceId)); | 172 | const missing = [...new Set(items.map((exam) => exam.class_course))].filter((instanceId) => !known.has(instanceId)); |
src/pages/homework-page.tsxmodified+26 -16
| @@ -5,10 +5,11 @@ import type { ColumnDef } from "@tanstack/solid-table"; | |||
| 5 | import { getInstanceSubjects, postInstanceHomework } from "@/api/instances"; | 5 | import { getInstanceSubjects, postInstanceHomework } from "@/api/instances"; |
| 6 | import { loadInstanceOptions } from "@/lib/instance-options"; | 6 | import { loadInstanceOptions } from "@/lib/instance-options"; |
| 7 | import { loadInstanceLabels } from "@/lib/instance-labels"; | 7 | import { loadInstanceLabels } from "@/lib/instance-labels"; |
| 8 | -import { getHomework } from "@/api/homework"; | 8 | +import { getHomework, type HomeworkListParams } from "@/api/homework"; |
| 9 | import { getTime } from "@/api/time"; | 9 | import { getTime } from "@/api/time"; |
| 10 | import { formatApiError } from "@/api/client"; | 10 | import { formatApiError } from "@/api/client"; |
| 11 | import type { Homework } from "@/api/client"; | 11 | import type { Homework } from "@/api/client"; |
| 12 | +import { LIST_CAP, loadWindowedList } from "@/lib/capped-list"; | ||
| 12 | import { RouteGuard } from "@/components/layout/route-guard"; | 13 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 13 | import { Alert } from "@/components/ui/alert"; | 14 | import { Alert } from "@/components/ui/alert"; |
| 14 | import { Button } from "@/components/ui/button"; | 15 | import { Button } from "@/components/ui/button"; |
| @@ -21,6 +22,7 @@ import { SearchableSelect } from "@/components/ui/searchable-select"; | |||
| 21 | import { DropdownSelect } from "@/components/ui/select"; | 22 | import { DropdownSelect } from "@/components/ui/select"; |
| 22 | import { SidePanel } from "@/components/ui/side-panel"; | 23 | import { SidePanel } from "@/components/ui/side-panel"; |
| 23 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 24 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 25 | + | ||
| 24 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | 26 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| 25 | import { Textarea } from "@/components/ui/textarea"; | 27 | import { Textarea } from "@/components/ui/textarea"; |
| 26 | import { formatDateTime } from "@/lib/format"; | 28 | import { formatDateTime } from "@/lib/format"; |
| @@ -77,12 +79,6 @@ function HomeworkContent() { | |||
| 77 | // in two şubeler yields rows with the same title, so a row's label names | 79 | // in two şubeler yields rows with the same title, so a row's label names |
| 78 | // both — "<ders> — <şube>", as the exams list does. | 80 | // both — "<ders> — <şube>", as the exams list does. |
| 79 | const [courseNames, setCourseNames] = createSignal<Record<string, string>>({}); | 81 | const [courseNames, setCourseNames] = createSignal<Record<string, string>>({}); |
| 80 | - const [list, { refetch }] = createResource(async () => { | ||
| 81 | - const items = (await getHomework({ limit: 100 })).items; | ||
| 82 | - const labels = await loadInstanceLabels(items.map((item) => item.class_course), auth.user()?.role); | ||
| 83 | - setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label]))); | ||
| 84 | - return items; | ||
| 85 | - }); | ||
| 86 | // The caller's sections, labelled "<ders> — <şube>" and ordered class by | 82 | // The caller's sections, labelled "<ders> — <şube>" and ordered class by |
| 87 | // class: the şube filter lists them all, the create form only for teachers. | 83 | // class: the şube filter lists them all, the create form only for teachers. |
| 88 | const [instances] = createResource( | 84 | const [instances] = createResource( |
| @@ -98,7 +94,7 @@ function HomeworkContent() { | |||
| 98 | const knownIds = new Set(known.map((row) => row.id)); | 94 | const knownIds = new Set(known.map((row) => row.id)); |
| 99 | // Homework in a şube the picker does not list (e.g. one the caller only | 95 | // Homework in a şube the picker does not list (e.g. one the caller only |
| 100 | // sees through an assignment) still gets its own entry, after the rest. | 96 | // sees through an assignment) still gets its own entry, after the rest. |
| 101 | - const extra = [...new Set((list() ?? []).map((item) => item.class_course))] | 97 | + const extra = [...new Set((list()?.items ?? []).map((item) => item.class_course))] |
| 102 | .filter((id) => !knownIds.has(id) && courseNames()[id]) | 98 | .filter((id) => !knownIds.has(id) && courseNames()[id]) |
| 103 | .map((id) => ({ value: id, label: courseNames()[id] })); | 99 | .map((id) => ({ value: id, label: courseNames()[id] })); |
| 104 | return [{ value: "all", label: t("common.all") }, ...known.map((row) => ({ value: row.id, label: row.label })), ...extra]; | 100 | return [{ value: "all", label: t("common.all") }, ...known.map((row) => ({ value: row.id, label: row.label })), ...extra]; |
| @@ -114,13 +110,26 @@ function HomeworkContent() { | |||
| 114 | const pageTitle = () => auth.user()?.role === "student" ? t("homework.mineTitle") : t("homework.title"); | 110 | const pageTitle = () => auth.user()?.role === "student" ? t("homework.mineTitle") : t("homework.title"); |
| 115 | type DueTab = "all" | "open" | "past"; | 111 | type DueTab = "all" | "open" | "past"; |
| 116 | const [dueTab, setDueTab] = createSignal<DueTab>("all"); | 112 | const [dueTab, setDueTab] = createSignal<DueTab>("all"); |
| 117 | - const dueFilteredList = createMemo(() => { | 113 | + // Tab and section filters are enforced server-side, at the moment of the |
| 118 | - const now = serverTime()?.now ?? Date.now(); | 114 | + // request: Open keeps rows still due (`due_after`), Past keeps rows already |
| 119 | - const items = (list() ?? []).filter((item) => courseFilter() === "all" || item.class_course === courseFilter()); | 115 | + // due (`due_before`), a picked section narrows to it (`class_course`); `all` |
| 120 | - if (dueTab() === "open") return items.filter((item) => item.due_at >= now); | 116 | + // sends no bound. The window rides in the source key so switching tabs |
| 121 | - if (dueTab() === "past") return items.filter((item) => item.due_at < now); | 117 | + // refetches with that tab's bound, and every page of the filtered set is |
| 122 | - return items; | 118 | + // read (no cap, no truncation notice). |
| 123 | - }); | 119 | + const [list, { refetch }] = createResource( |
| 120 | + () => `${dueTab()}|${courseFilter()}`, | ||
| 121 | + async (key) => { | ||
| 122 | + const [tab, course] = key.split("|"); | ||
| 123 | + const params: HomeworkListParams = {}; | ||
| 124 | + if (tab === "open") params.due_after = Date.now(); | ||
| 125 | + if (tab === "past") params.due_before = Date.now(); | ||
| 126 | + if (course !== "all") params.class_course = course; | ||
| 127 | + const page = await loadWindowedList((paging) => getHomework({ ...params, ...paging }), LIST_CAP); | ||
| 128 | + const labels = await loadInstanceLabels(page.items.map((item) => item.class_course), auth.user()?.role); | ||
| 129 | + setCourseNames(Object.fromEntries([...labels].map(([id, entry]) => [id, entry.label]))); | ||
| 130 | + return page; | ||
| 131 | + }, | ||
| 132 | + ); | ||
| 124 | 133 | ||
| 125 | createEffect(() => { | 134 | createEffect(() => { |
| 126 | if (!createOpen()) return; | 135 | if (!createOpen()) return; |
| @@ -269,10 +278,11 @@ function HomeworkContent() { | |||
| 269 | <Show when={list.error}> | 278 | <Show when={list.error}> |
| 270 | <Alert variant="destructive">{formatApiError(list.error)}</Alert> | 279 | <Alert variant="destructive">{formatApiError(list.error)}</Alert> |
| 271 | </Show> | 280 | </Show> |
| 281 | + | ||
| 272 | <DataTable | 282 | <DataTable |
| 273 | urlState | 283 | urlState |
| 274 | columns={columns()} | 284 | columns={columns()} |
| 275 | - data={dueFilteredList()} | 285 | + data={list()?.items ?? []} |
| 276 | tableClass="table-fixed min-w-[44rem]" | 286 | tableClass="table-fixed min-w-[44rem]" |
| 277 | filterColumn="title" | 287 | filterColumn="title" |
| 278 | filterHint={t("search.hint.homework")} | 288 | filterHint={t("search.hint.homework")} |
src/pages/meals-page.tsxmodified+7 -3
| @@ -43,10 +43,14 @@ function MealsContent() { | |||
| 43 | const [flash, setFlash] = createFlash(); | 43 | const [flash, setFlash] = createFlash(); |
| 44 | const [settings] = createResource(() => getSettings()); | 44 | const [settings] = createResource(() => getSettings()); |
| 45 | const [limits, { refetch: refetchLimits }] = createResource(() => (canManage() ? getLimits() : null)); | 45 | const [limits, { refetch: refetchLimits }] = createResource(() => (canManage() ? getLimits() : null)); |
| 46 | - const [menus, { refetch }] = createResource(weekStart, (start) => | 46 | + const [menus, { refetch }] = createResource( |
| 47 | + () => [weekStart(), slot()] as const, | ||
| 47 | // `to` is a day past Sunday so the week is whole whether the API reads it | 48 | // `to` is a day past Sunday so the week is whole whether the API reads it |
| 48 | - // inclusively or not; the filter below trims anything past Sunday. | 49 | + // inclusively or not; the filter below trims anything past Sunday. A real |
| 49 | - getMealMenus({ from: start, to: addDaysIso(start, 7), limit: WEEK_LIMIT, offset: 0 }), | 50 | + // slot is filtered server-side; "all" is a pseudo-option the api helper |
| 51 | + // drops, so the request stays unfiltered then. | ||
| 52 | + ([start, chosenSlot]) => | ||
| 53 | + getMealMenus({ from: start, to: addDaysIso(start, 7), slot: chosenSlot, limit: WEEK_LIMIT, offset: 0 }), | ||
| 50 | ); | 54 | ); |
| 51 | 55 | ||
| 52 | const slots = () => settings()?.meal_slots ?? []; | 56 | const slots = () => settings()?.meal_slots ?? []; |
src/pages/messages-page.test.tsxmodified+17 -0
| @@ -69,3 +69,20 @@ test("emptying trash waits for confirmation and names what it deletes", async () | |||
| 69 | fireEvent.click(within(dialog).getByRole("button", { name: /Empty trash|Çöp kutusunu boşalt/ })); | 69 | fireEvent.click(within(dialog).getByRole("button", { name: /Empty trash|Çöp kutusunu boşalt/ })); |
| 70 | await waitFor(() => expect(deleteMessageById).toHaveBeenCalledTimes(2)); | 70 | await waitFor(() => expect(deleteMessageById).toHaveBeenCalledTimes(2)); |
| 71 | }); | 71 | }); |
| 72 | + | ||
| 73 | +test("searching hits the server with a trimmed q at first-page offset", async () => { | ||
| 74 | + getMessages.mockResolvedValue({ items: [message(1)], total: 1, limit: 30, offset: 0 }); | ||
| 75 | + | ||
| 76 | + render(() => ( | ||
| 77 | + <PreferencesProvider> | ||
| 78 | + <MessagesPage /> | ||
| 79 | + </PreferencesProvider> | ||
| 80 | + )); | ||
| 81 | + | ||
| 82 | + const search = await screen.findByPlaceholderText(/Search messages|Mesajlarda ara/); | ||
| 83 | + fireEvent.input(search, { target: { value: " Subject 7 " } }); | ||
| 84 | + | ||
| 85 | + await waitFor(() => | ||
| 86 | + expect(getMessages).toHaveBeenCalledWith("inbox", { limit: 30, offset: 0, q: "Subject 7" }), | ||
| 87 | + ); | ||
| 88 | +}); | ||
src/pages/messages-page.tsxmodified+16 -19
| @@ -34,8 +34,7 @@ import type { MessageKey } from "@/i18n/messages"; | |||
| 34 | import { formatApiError } from "@/api/client"; | 34 | import { formatApiError } from "@/api/client"; |
| 35 | import { useAuth } from "@/stores/auth-context"; | 35 | import { useAuth } from "@/stores/auth-context"; |
| 36 | import { useT } from "@/stores/preferences-context"; | 36 | import { useT } from "@/stores/preferences-context"; |
| 37 | -import { matchesSearch } from "@/lib/search-text"; | 37 | +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; |
| 38 | -import { personLabel } from "@/lib/person"; | ||
| 39 | import { createFlash } from "@/lib/flash"; | 38 | import { createFlash } from "@/lib/flash"; |
| 40 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 39 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 41 | 40 | ||
| @@ -53,15 +52,20 @@ export default function MessagesPage() { | |||
| 53 | const [page, setPage] = createSignal(1); | 52 | const [page, setPage] = createSignal(1); |
| 54 | const limit = 30; | 53 | const limit = 30; |
| 55 | const [selectedId, setSelectedId] = createSignal<string>(""); | 54 | const [selectedId, setSelectedId] = createSignal<string>(""); |
| 56 | - const [query, setQuery] = createSignal(""); | 55 | + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); |
| 57 | const [composeOpen, setComposeOpen] = createSignal(false); | 56 | const [composeOpen, setComposeOpen] = createSignal(false); |
| 58 | const [isRefreshing, setIsRefreshing] = createSignal(false); | 57 | const [isRefreshing, setIsRefreshing] = createSignal(false); |
| 59 | const [isPending, startTransition] = useTransition(); | 58 | const [isPending, startTransition] = useTransition(); |
| 60 | const [, setFlash] = createFlash(); | 59 | const [, setFlash] = createFlash(); |
| 61 | 60 | ||
| 62 | const [messagePage, { refetch }] = createResource( | 61 | const [messagePage, { refetch }] = createResource( |
| 63 | - () => ({ f: folder(), p: page() }), | 62 | + () => ({ f: folder(), p: page(), q: debouncedQuery().trim() }), |
| 64 | - async (args) => await getMessages(args.f, { limit, offset: (args.p - 1) * limit }) | 63 | + async (args) => |
| 64 | + await getMessages(args.f, { | ||
| 65 | + limit, | ||
| 66 | + offset: (args.p - 1) * limit, | ||
| 67 | + ...(args.q ? { q: args.q } : {}), | ||
| 68 | + }) | ||
| 65 | ); | 69 | ); |
| 66 | 70 | ||
| 67 | const [unreadCount, { refetch: refetchUnread }] = createResource( | 71 | const [unreadCount, { refetch: refetchUnread }] = createResource( |
| @@ -75,17 +79,6 @@ export default function MessagesPage() { | |||
| 75 | rawMessages().slice().sort((a, b) => b.sent_at - a.sent_at) | 79 | rawMessages().slice().sort((a, b) => b.sent_at - a.sent_at) |
| 76 | ); | 80 | ); |
| 77 | 81 | ||
| 78 | - const filtered = createMemo(() => { | ||
| 79 | - const q = query().trim(); | ||
| 80 | - if (!q) return messages(); | ||
| 81 | - return messages().filter((m) => { | ||
| 82 | - const isSent = folder() === "sent" || m.sender.id === auth.user()?.id; | ||
| 83 | - const peer = isSent ? m.recipient : m.sender; | ||
| 84 | - const other = personLabel(peer); | ||
| 85 | - return matchesSearch(q, other, m.subject, m.body, m.label); | ||
| 86 | - }); | ||
| 87 | - }); | ||
| 88 | - | ||
| 89 | const selected = createMemo(() => messages().find((m) => m.id === selectedId()) ?? null); | 82 | const selected = createMemo(() => messages().find((m) => m.id === selectedId()) ?? null); |
| 90 | const isOwnSentMessage = (msg: Message) => msg.sender.id === auth.user()?.id; | 83 | const isOwnSentMessage = (msg: Message) => msg.sender.id === auth.user()?.id; |
| 91 | 84 | ||
| @@ -278,7 +271,11 @@ export default function MessagesPage() { | |||
| 278 | class="h-8 rounded-lg bg-surface-tint pl-9 pr-4 text-[13px] border-none focus-visible:ring-1" | 271 | class="h-8 rounded-lg bg-surface-tint pl-9 pr-4 text-[13px] border-none focus-visible:ring-1" |
| 279 | placeholder={t("messages.search")} | 272 | placeholder={t("messages.search")} |
| 280 | value={query()} | 273 | value={query()} |
| 281 | - onInput={(event) => setQuery(event.currentTarget.value)} | 274 | + onInput={(event) => { |
| 275 | + setQuery(event.currentTarget.value); | ||
| 276 | + // The server filters from the first row; offset restarts with each search. | ||
| 277 | + setPage(1); | ||
| 278 | + }} | ||
| 282 | /> | 279 | /> |
| 283 | </div> | 280 | </div> |
| 284 | </div> | 281 | </div> |
| @@ -327,14 +324,14 @@ export default function MessagesPage() { | |||
| 327 | } | 324 | } |
| 328 | > | 325 | > |
| 329 | <Show | 326 | <Show |
| 330 | - when={filtered().length > 0} | 327 | + when={messages().length > 0} |
| 331 | fallback={ | 328 | fallback={ |
| 332 | <div class="p-12 text-center text-xs text-muted-foreground"> | 329 | <div class="p-12 text-center text-xs text-muted-foreground"> |
| 333 | {t("messages.noMessages")} | 330 | {t("messages.noMessages")} |
| 334 | </div> | 331 | </div> |
| 335 | } | 332 | } |
| 336 | > | 333 | > |
| 337 | - <For each={filtered()}> | 334 | + <For each={messages()}> |
| 338 | {(message) => ( | 335 | {(message) => ( |
| 339 | <GmailMailRow | 336 | <GmailMailRow |
| 340 | message={message} | 337 | message={message} |
src/pages/student-attendance-page.tsxmodified+36 -22
| @@ -3,7 +3,7 @@ import { createResource } from "@/lib/create-resource"; | |||
| 3 | import type { ColumnDef } from "@tanstack/solid-table"; | 3 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 4 | import { getUserAttendance } from "@/api/reports"; | 4 | import { getUserAttendance } from "@/api/reports"; |
| 5 | import { ApiError, formatApiError } from "@/api/client"; | 5 | import { ApiError, formatApiError } from "@/api/client"; |
| 6 | -import type { PersonRef } from "@/api/client"; | 6 | +import type { ClassGroup, PersonRef } from "@/api/client"; |
| 7 | import { AttendanceReportView } from "@/components/attendance/attendance-report-view"; | 7 | import { AttendanceReportView } from "@/components/attendance/attendance-report-view"; |
| 8 | import { RouteGuard } from "@/components/layout/route-guard"; | 8 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 9 | import { Alert } from "@/components/ui/alert"; | 9 | import { Alert } from "@/components/ui/alert"; |
| @@ -34,15 +34,36 @@ function StudentAttendanceContent() { | |||
| 34 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); | 34 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); |
| 35 | const [error, setError] = createSignal(""); | 35 | const [error, setError] = createSignal(""); |
| 36 | 36 | ||
| 37 | - const [list] = createResource(async () => { | 37 | + // No endpoint reports attendance or focus time for a list of students — |
| 38 | - try { | 38 | + // only one student at a time — so the list stays a roster (a column per |
| 39 | - setError(""); | 39 | + // student would be one report read per row). Picking a class scopes the |
| 40 | - return await getStudentDirectory(); | 40 | + // directory read to that class's roster; with no class every student is read. |
| 41 | - } catch (err) { | 41 | + const [classFilter, setClassFilter] = createSignal(""); |
| 42 | - setError(formatApiError(err)); | 42 | + // Classes seen on the last full read: the scoped read returns only the |
| 43 | - return []; | 43 | + // picked class's roster, so the dropdown keeps listing every class and the |
| 44 | - } | 44 | + // scoped fetch resolves the picked class without another request. |
| 45 | - }, { initialValue: [] as StudentDirectoryRow[] }); | 45 | + const [allClasses, setAllClasses] = createSignal<ClassGroup[]>([]); |
| 46 | + const [list] = createResource( | ||
| 47 | + () => classFilter(), | ||
| 48 | + async (classId) => { | ||
| 49 | + try { | ||
| 50 | + setError(""); | ||
| 51 | + if (!classId) { | ||
| 52 | + const rows = await getStudentDirectory(); | ||
| 53 | + const seen = new Map<string, ClassGroup>(); | ||
| 54 | + for (const row of rows) for (const cls of row.classes) seen.set(cls.id, cls); | ||
| 55 | + setAllClasses([...seen.values()]); | ||
| 56 | + return rows; | ||
| 57 | + } | ||
| 58 | + const picked = allClasses().find((cls) => cls.id === classId); | ||
| 59 | + return await getStudentDirectory(picked); | ||
| 60 | + } catch (err) { | ||
| 61 | + setError(formatApiError(err)); | ||
| 62 | + return []; | ||
| 63 | + } | ||
| 64 | + }, | ||
| 65 | + { initialValue: [] as StudentDirectoryRow[] }, | ||
| 66 | + ); | ||
| 46 | 67 | ||
| 47 | const [report, { refetch: refetchReport }] = createResource( | 68 | const [report, { refetch: refetchReport }] = createResource( |
| 48 | () => viewUser()?.id ?? null, | 69 | () => viewUser()?.id ?? null, |
| @@ -61,18 +82,11 @@ function StudentAttendanceContent() { | |||
| 61 | }, | 82 | }, |
| 62 | ); | 83 | ); |
| 63 | 84 | ||
| 64 | - // No endpoint reports attendance or focus time for a list of students — | 85 | + const classOptions = createMemo(() => |
| 65 | - // only one student at a time — so the list stays a roster (a column per | 86 | + [...allClasses()] |
| 66 | - // student would be one report read per row). The class filter narrows it | 87 | + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) |
| 67 | - // with the memberships the directory already read. | 88 | + .map((cls) => ({ value: cls.id, label: cls.name })), |
| 68 | - const [classFilter, setClassFilter] = createSignal(""); | 89 | + ); |
| 69 | - const classOptions = createMemo(() => { | ||
| 70 | - const seen = new Map<string, string>(); | ||
| 71 | - for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); | ||
| 72 | - return [...seen] | ||
| 73 | - .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) | ||
| 74 | - .map(([value, label]) => ({ value, label })); | ||
| 75 | - }); | ||
| 76 | const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); | 90 | const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); |
| 77 | const listLoading = () => list.loading; | 91 | const listLoading = () => list.loading; |
| 78 | const searchPerson = (row: StudentDirectoryRow, query: string) => | 92 | const searchPerson = (row: StudentDirectoryRow, query: string) => |
src/pages/student-pomodoro-page.tsxmodified+36 -22
| @@ -2,7 +2,7 @@ import { Show, createMemo, createSignal } from "solid-js"; | |||
| 2 | import { createResource } from "@/lib/create-resource"; | 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import type { ColumnDef } from "@tanstack/solid-table"; | 3 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 4 | import { getPomodoroByUser } from "@/api/pomodoro"; | 4 | import { getPomodoroByUser } from "@/api/pomodoro"; |
| 5 | -import type { PersonRef } from "@/api/client"; | 5 | +import type { ClassGroup, PersonRef } from "@/api/client"; |
| 6 | import { ApiError, formatApiError } from "@/api/client"; | 6 | import { ApiError, formatApiError } from "@/api/client"; |
| 7 | import { RouteGuard } from "@/components/layout/route-guard"; | 7 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 8 | import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; | 8 | import { PomodoroLogView } from "@/components/pomodoro/pomodoro-log-view"; |
| @@ -34,15 +34,36 @@ function StudentPomodoroContent() { | |||
| 34 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); | 34 | const [viewUser, setViewUser] = createSignal<PersonRef | null>(null); |
| 35 | const [error, setError] = createSignal(""); | 35 | const [error, setError] = createSignal(""); |
| 36 | 36 | ||
| 37 | - const [list] = createResource(async () => { | 37 | + // No endpoint reports attendance or focus time for a list of students — |
| 38 | - try { | 38 | + // only one student at a time — so the list stays a roster (a column per |
| 39 | - setError(""); | 39 | + // student would be one report read per row). Picking a class scopes the |
| 40 | - return await getStudentDirectory(); | 40 | + // directory read to that class's roster; with no class every student is read. |
| 41 | - } catch (err) { | 41 | + const [classFilter, setClassFilter] = createSignal(""); |
| 42 | - setError(formatApiError(err)); | 42 | + // Classes seen on the last full read: the scoped read returns only the |
| 43 | - return []; | 43 | + // picked class's roster, so the dropdown keeps listing every class and the |
| 44 | - } | 44 | + // scoped fetch resolves the picked class without another request. |
| 45 | - }, { initialValue: [] as StudentDirectoryRow[] }); | 45 | + const [allClasses, setAllClasses] = createSignal<ClassGroup[]>([]); |
| 46 | + const [list] = createResource( | ||
| 47 | + () => classFilter(), | ||
| 48 | + async (classId) => { | ||
| 49 | + try { | ||
| 50 | + setError(""); | ||
| 51 | + if (!classId) { | ||
| 52 | + const rows = await getStudentDirectory(); | ||
| 53 | + const seen = new Map<string, ClassGroup>(); | ||
| 54 | + for (const row of rows) for (const cls of row.classes) seen.set(cls.id, cls); | ||
| 55 | + setAllClasses([...seen.values()]); | ||
| 56 | + return rows; | ||
| 57 | + } | ||
| 58 | + const picked = allClasses().find((cls) => cls.id === classId); | ||
| 59 | + return await getStudentDirectory(picked); | ||
| 60 | + } catch (err) { | ||
| 61 | + setError(formatApiError(err)); | ||
| 62 | + return []; | ||
| 63 | + } | ||
| 64 | + }, | ||
| 65 | + { initialValue: [] as StudentDirectoryRow[] }, | ||
| 66 | + ); | ||
| 46 | 67 | ||
| 47 | const [log, { refetch: refetchLog }] = createResource( | 68 | const [log, { refetch: refetchLog }] = createResource( |
| 48 | () => viewUser()?.id ?? null, | 69 | () => viewUser()?.id ?? null, |
| @@ -61,18 +82,11 @@ function StudentPomodoroContent() { | |||
| 61 | }, | 82 | }, |
| 62 | ); | 83 | ); |
| 63 | 84 | ||
| 64 | - // No endpoint reports attendance or focus time for a list of students — | 85 | + const classOptions = createMemo(() => |
| 65 | - // only one student at a time — so the list stays a roster (a column per | 86 | + [...allClasses()] |
| 66 | - // student would be one report read per row). The class filter narrows it | 87 | + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) |
| 67 | - // with the memberships the directory already read. | 88 | + .map((cls) => ({ value: cls.id, label: cls.name })), |
| 68 | - const [classFilter, setClassFilter] = createSignal(""); | 89 | + ); |
| 69 | - const classOptions = createMemo(() => { | ||
| 70 | - const seen = new Map<string, string>(); | ||
| 71 | - for (const row of list()) for (const cls of row.classes) seen.set(cls.id, cls.name); | ||
| 72 | - return [...seen] | ||
| 73 | - .sort((a, b) => a[1].localeCompare(b[1], "tr", { numeric: true })) | ||
| 74 | - .map(([value, label]) => ({ value, label })); | ||
| 75 | - }); | ||
| 76 | const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); | 90 | const rows = () => (classFilter() ? list().filter((row) => row.classes.some((cls) => cls.id === classFilter())) : list()); |
| 77 | const listLoading = () => list.loading; | 91 | const listLoading = () => list.loading; |
| 78 | const searchPerson = (row: StudentDirectoryRow, query: string) => | 92 | const searchPerson = (row: StudentDirectoryRow, query: string) => |
src/pages/students-roster-page.tsxmodified+18 -21
| @@ -4,9 +4,8 @@ import { Show, Suspense, createMemo, createSignal } from "solid-js"; | |||
| 4 | import { createResource } from "@/lib/create-resource"; | 4 | import { createResource } from "@/lib/create-resource"; |
| 5 | import { matchesSearch } from "@/lib/search-text"; | 5 | import { matchesSearch } from "@/lib/search-text"; |
| 6 | import { createUrlString } from "@/lib/url-state"; | 6 | import { createUrlString } from "@/lib/url-state"; |
| 7 | -import { getClassMembers, getClasses } from "@/api/classes"; | 7 | +import { getClasses } from "@/api/classes"; |
| 8 | import { getAcademicYears } from "@/api/academic-years"; | 8 | import { getAcademicYears } from "@/api/academic-years"; |
| 9 | -import { getUserSearch } from "@/api/users"; | ||
| 10 | import { formatApiError, type ClassGroup, type PersonRef } from "@/api/client"; | 9 | import { formatApiError, type ClassGroup, type PersonRef } from "@/api/client"; |
| 11 | import { RouteGuard } from "@/components/layout/route-guard"; | 10 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 12 | import { CreateUserPanel } from "@/components/users/create-user-panel"; | 11 | import { CreateUserPanel } from "@/components/users/create-user-panel"; |
| @@ -20,7 +19,7 @@ import { DropdownSelect } from "@/components/ui/select"; | |||
| 20 | import { TableRowActions } from "@/components/ui/table-row-actions"; | 19 | import { TableRowActions } from "@/components/ui/table-row-actions"; |
| 21 | import { useT } from "@/stores/preferences-context"; | 20 | import { useT } from "@/stores/preferences-context"; |
| 22 | import { useAuth } from "@/stores/auth-context"; | 21 | import { useAuth } from "@/stores/auth-context"; |
| 23 | -import { sortByClass } from "@/lib/student-directory"; | 22 | +import { getStudentDirectory } from "@/lib/student-directory"; |
| 24 | import { studentInfoSource } from "@/lib/student-info-access"; | 23 | import { studentInfoSource } from "@/lib/student-info-access"; |
| 25 | 24 | ||
| 26 | const ROSTER_PAGE_SIZE = 10; | 25 | const ROSTER_PAGE_SIZE = 10; |
| @@ -51,24 +50,22 @@ function StudentsRosterContent() { | |||
| 51 | const [infoTarget, setInfoTarget] = createSignal<PersonRef | null>(null); | 50 | const [infoTarget, setInfoTarget] = createSignal<PersonRef | null>(null); |
| 52 | const infoSource = (person: PersonRef) => studentInfoSource(auth.user(), { id: person.id, role: "student" }); | 51 | const infoSource = (person: PersonRef) => studentInfoSource(auth.user(), { id: person.id, role: "student" }); |
| 53 | 52 | ||
| 54 | - const [data, { refetch }] = createResource(async () => { | 53 | + const [data, { refetch }] = createResource( |
| 55 | - const [students, classes, years] = await Promise.all([ | 54 | + () => classFilter(), |
| 56 | - getUserSearch("", undefined, "student"), | 55 | + async (classId) => { |
| 57 | - getClasses(), | 56 | + const [classes, years] = await Promise.all([ |
| 58 | - getAcademicYears().catch(() => ({ items: [] })), | 57 | + getClasses(), |
| 59 | - ]); | 58 | + getAcademicYears().catch(() => ({ items: [] })), |
| 60 | - // No endpoint maps students to classes in bulk; one members read per class | 59 | + ]); |
| 61 | - // is bounded by the class count, not the student count. | 60 | + // A picked class (?class=) scopes the roster read to that class's |
| 62 | - const memberships = await Promise.all( | 61 | + // members; with no class every student and every class's members are |
| 63 | - classes.items.map(async (cls) => ({ cls, members: (await getClassMembers(cls.id)).items })), | 62 | + // read. The class and year lists always come along: the filter |
| 64 | - ); | 63 | + // dropdowns need them either way. |
| 65 | - const byStudent = new Map<string, ClassGroup[]>(); | 64 | + const picked = classId ? classes.items.find((cls) => cls.id === classId) : undefined; |
| 66 | - for (const { cls, members } of memberships) { | 65 | + const rows = await getStudentDirectory(picked); |
| 67 | - for (const member of members) byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]); | 66 | + return { rows, classes: classes.items, years: years.items }; |
| 68 | - } | 67 | + }, |
| 69 | - const rows: StudentRow[] = sortByClass(students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] }))); | 68 | + ); |
| 70 | - return { rows, classes: classes.items, years: years.items }; | ||
| 71 | - }); | ||
| 72 | 69 | ||
| 73 | const rows = createMemo(() => | 70 | const rows = createMemo(() => |
| 74 | (data()?.rows ?? []).filter((row) => { | 71 | (data()?.rows ?? []).filter((row) => { |
src/pages/whiteboards-page.tsxmodified+18 -14
| @@ -1,6 +1,7 @@ | |||
| 1 | import { useNavigate } from "@tanstack/solid-router"; | 1 | import { useNavigate } from "@tanstack/solid-router"; |
| 2 | import { For, Show, Suspense, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"; | 2 | import { For, Show, Suspense, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"; |
| 3 | import { createResponsivePageSize } from "@/lib/create-page-size"; | 3 | import { createResponsivePageSize } from "@/lib/create-page-size"; |
| 4 | +import { createDebouncedSignal } from "@/lib/create-debounced-signal"; | ||
| 4 | import { createResource } from "@/lib/create-resource"; | 5 | import { createResource } from "@/lib/create-resource"; |
| 5 | import { getBoards, postBoard, type Board } from "@/api/boards"; | 6 | import { getBoards, postBoard, type Board } from "@/api/boards"; |
| 6 | import { getUserSearch } from "@/api/users"; | 7 | import { getUserSearch } from "@/api/users"; |
| @@ -19,7 +20,6 @@ import { SidePanel } from "@/components/ui/side-panel"; | |||
| 19 | import { TablePagination } from "@/components/ui/table-pagination"; | 20 | import { TablePagination } from "@/components/ui/table-pagination"; |
| 20 | import { cn } from "@/lib/cn"; | 21 | import { cn } from "@/lib/cn"; |
| 21 | import { formatDate } from "@/lib/format"; | 22 | import { formatDate } from "@/lib/format"; |
| 22 | -import { matchesSearch } from "@/lib/search-text"; | ||
| 23 | import { personLabel } from "@/lib/person"; | 23 | import { personLabel } from "@/lib/person"; |
| 24 | import { hasMinRole } from "@/lib/roles"; | 24 | import { hasMinRole } from "@/lib/roles"; |
| 25 | import { useAuth } from "@/stores/auth-context"; | 25 | import { useAuth } from "@/stores/auth-context"; |
| @@ -42,21 +42,21 @@ function WhiteboardsContent() { | |||
| 42 | const pageSize = createResponsivePageSize(12); | 42 | const pageSize = createResponsivePageSize(12); |
| 43 | const [page, setPage] = createSignal(0); | 43 | const [page, setPage] = createSignal(0); |
| 44 | createEffect(on(pageSize, () => setPage(0), { defer: true })); | 44 | createEffect(on(pageSize, () => setPage(0), { defer: true })); |
| 45 | + const [query, setQuery, debouncedQuery] = createDebouncedSignal(); | ||
| 45 | const [boards, { refetch }] = createResource( | 46 | const [boards, { refetch }] = createResource( |
| 46 | - () => ({ page: page(), size: pageSize() }), | 47 | + () => ({ page: page(), size: pageSize(), q: debouncedQuery().trim() }), |
| 47 | - (source) => getBoards({ limit: source.size, offset: source.page * source.size }), | 48 | + (source) => |
| 49 | + getBoards({ | ||
| 50 | + limit: source.size, | ||
| 51 | + offset: source.page * source.size, | ||
| 52 | + ...(source.q ? { q: source.q } : {}), | ||
| 53 | + }), | ||
| 48 | ); | 54 | ); |
| 49 | const [createOpen, setCreateOpen] = createSignal(false); | 55 | const [createOpen, setCreateOpen] = createSignal(false); |
| 50 | const pageCount = createMemo(() => Math.max(1, Math.ceil((boards.latest?.total ?? 0) / pageSize()))); | 56 | const pageCount = createMemo(() => Math.max(1, Math.ceil((boards.latest?.total ?? 0) / pageSize()))); |
| 51 | - const [query, setQuery] = createSignal(""); | 57 | + // The server narrows by title via `q`; the page holds whatever the current |
| 52 | - // The board list endpoint has no server-side text filter, so this narrows | 58 | + // query matched, so totals and pagination already reflect the search. |
| 53 | - // only the current page's real titles — a client-side search over real | 59 | + const visibleBoards = createMemo(() => boards()?.items ?? []); |
| 54 | - // data, not a promise of searching every board the caller has ever opened. | ||
| 55 | - const visibleBoards = createMemo(() => { | ||
| 56 | - const q = query().trim(); | ||
| 57 | - const items = boards()?.items ?? []; | ||
| 58 | - return q ? items.filter((b) => matchesSearch(q, b.title)) : items; | ||
| 59 | - }); | ||
| 60 | 60 | ||
| 61 | const meId = () => auth.user()?.id ?? ""; | 61 | const meId = () => auth.user()?.id ?? ""; |
| 62 | 62 | ||
| @@ -68,7 +68,11 @@ function WhiteboardsContent() { | |||
| 68 | searchValue={query()} | 68 | searchValue={query()} |
| 69 | searchPlaceholder={t("whiteboard.searchPlaceholder")} | 69 | searchPlaceholder={t("whiteboard.searchPlaceholder")} |
| 70 | searchHint={t("search.hint.whiteboards")} | 70 | searchHint={t("search.hint.whiteboards")} |
| 71 | - onSearchInput={setQuery} | 71 | + onSearchInput={(value) => { |
| 72 | + setQuery(value); | ||
| 73 | + // The server filters from the first row; offset restarts with each search. | ||
| 74 | + setPage(0); | ||
| 75 | + }} | ||
| 72 | actions={ | 76 | actions={ |
| 73 | <Button type="button" size="sm" class="rounded-lg" onClick={() => setCreateOpen(true)}> | 77 | <Button type="button" size="sm" class="rounded-lg" onClick={() => setCreateOpen(true)}> |
| 74 | <IconPlus class="h-4 w-4" /> | 78 | <IconPlus class="h-4 w-4" /> |
| @@ -82,7 +86,7 @@ function WhiteboardsContent() { | |||
| 82 | <ErrorAlert message={formatApiError(boards.error, locale())} /> | 86 | <ErrorAlert message={formatApiError(boards.error, locale())} /> |
| 83 | </Show> | 87 | </Show> |
| 84 | <Show | 88 | <Show |
| 85 | - when={(boards()?.items ?? []).length > 0} | 89 | + when={query().trim() || (boards()?.items ?? []).length > 0} |
| 86 | fallback={<EmptyState kind="whiteboard" title={t("whiteboard.empty")} description={t("whiteboard.subtitle")} />} | 90 | fallback={<EmptyState kind="whiteboard" title={t("whiteboard.empty")} description={t("whiteboard.subtitle")} />} |
| 87 | > | 91 | > |
| 88 | <div class="space-y-3"> | 92 | <div class="space-y-3"> |
src/stores/shell-feed-context.tsxmodified+15 -20
| @@ -46,7 +46,16 @@ type ShellFeedContextValue = { | |||
| 46 | 46 | ||
| 47 | const ShellFeedContext = createContext<ShellFeedContextValue>(); | 47 | const ShellFeedContext = createContext<ShellFeedContextValue>(); |
| 48 | 48 | ||
| 49 | -const HOMEWORK_FEED_LIMIT = 100; | 49 | +// 50: the feed drives "upcoming" badges and the notification rows — it needs |
| 50 | +// the next handful, not the archive, and every windowed source orders by its | ||
| 51 | +// own schedule now. 50 soonest-first rows cover a busy month per source; the | ||
| 52 | +// consumers render only not-yet-passed rows, so the dropped rows were never | ||
| 53 | +// rendered. | ||
| 54 | +// ponytail: a school with >50 simultaneously-open items per source loses the | ||
| 55 | +// tail — upgrade path is narrowing the window further, not a bigger cap. | ||
| 56 | +const FEED_LIMIT = 50; | ||
| 57 | + | ||
| 58 | +const upcoming = () => ({ ends_after: Date.now(), limit: FEED_LIMIT }); | ||
| 50 | 59 | ||
| 51 | const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 }); | 60 | const emptyPage = <T,>(): Page<T> => ({ items: [], total: 0, limit: null, offset: 0 }); |
| 52 | 61 | ||
| @@ -96,19 +105,6 @@ function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnab | |||
| 96 | { initialValue: emptyPage<Message>() } | 105 | { initialValue: emptyPage<Message>() } |
| 97 | ); | 106 | ); |
| 98 | 107 | ||
| 99 | - // `ends_after=now` keeps only rows whose window has not finished AND flips | ||
| 100 | - // the server order to soonest-first, so a cap finally truncates the archive | ||
| 101 | - // end instead of the upcoming end. Without it the whole school history rode | ||
| 102 | - // along (~3.4 MB/poll at 5k+5k rows) only to be filtered out client-side. | ||
| 103 | - // | ||
| 104 | - // 50: the feed drives "upcoming" badges and the calendar dot — it needs the | ||
| 105 | - // next handful, not the archive. 50 soonest-first rows cover a busy month | ||
| 106 | - // per source. Both consumers already show only not-yet-ended items, so the | ||
| 107 | - // dropped rows were never rendered. | ||
| 108 | - // ponytail: a school with >50 simultaneously-open events loses the tail — | ||
| 109 | - // upgrade path is narrowing the window (add an upper bound), not a bigger cap. | ||
| 110 | - const upcoming = () => ({ ends_after: Date.now(), limit: 50 }); | ||
| 111 | - | ||
| 112 | const [eventsRes, { refetch: refetchEvents }] = createResource( | 108 | const [eventsRes, { refetch: refetchEvents }] = createResource( |
| 113 | source, | 109 | source, |
| 114 | async () => { | 110 | async () => { |
| @@ -135,12 +131,15 @@ function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnab | |||
| 135 | { initialValue: emptyPage<Exam>() } | 131 | { initialValue: emptyPage<Exam>() } |
| 136 | ); | 132 | ); |
| 137 | 133 | ||
| 134 | + // Same feed semantics as events/exams: only what is still ahead. The | ||
| 135 | + // notification feed renders homework whose due date has not passed, and both | ||
| 136 | + // polls used to carry a blind newest-100 cap only because no window existed. | ||
| 138 | const [appointmentsRes, { refetch: refetchAppointments }] = createResource( | 137 | const [appointmentsRes, { refetch: refetchAppointments }] = createResource( |
| 139 | source, | 138 | source, |
| 140 | async () => { | 139 | async () => { |
| 141 | try { | 140 | try { |
| 142 | if (!isEnabled("appointments")) return emptyPage<Appointment>(); | 141 | if (!isEnabled("appointments")) return emptyPage<Appointment>(); |
| 143 | - return await getAppointments({ limit: 100 }); | 142 | + return await getAppointments({ starts_after: Date.now(), limit: FEED_LIMIT }); |
| 144 | } catch { | 143 | } catch { |
| 145 | return emptyPage<Appointment>(); | 144 | return emptyPage<Appointment>(); |
| 146 | } | 145 | } |
| @@ -153,11 +152,7 @@ function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnab | |||
| 153 | async () => { | 152 | async () => { |
| 154 | try { | 153 | try { |
| 155 | if (!isEnabled("homework")) return emptyPage<Homework>(); | 154 | if (!isEnabled("homework")) return emptyPage<Homework>(); |
| 156 | - // `/homework` has no due-date filter and lists newest-created first, | 155 | + return await getHomework({ due_after: Date.now(), limit: FEED_LIMIT }); |
| 157 | - // so a page of the most recent rows holds everything still upcoming | ||
| 158 | - // in practice. Unbounded, this poll pulled the school's whole | ||
| 159 | - // homework history every minute on every page. | ||
| 160 | - return await getHomework({ limit: HOMEWORK_FEED_LIMIT }); | ||
| 161 | } catch { | 156 | } catch { |
| 162 | return emptyPage<Homework>(); | 157 | return emptyPage<Homework>(); |
| 163 | } | 158 | } |