diff --git a/src/lib/__tests__/map-concurrent.test.ts b/src/lib/__tests__/map-concurrent.test.ts new file mode 100644 index 0000000..0cd07eb --- /dev/null +++ b/src/lib/__tests__/map-concurrent.test.ts @@ -0,0 +1,34 @@ +import { mapConcurrent } from "@/lib/map-concurrent"; + +describe("mapConcurrent", () => { + it("keeps input order", async () => { + const out = await mapConcurrent([30, 10, 20], 2, async (ms, index) => { + await new Promise((resolve) => setTimeout(resolve, ms)); + return index; + }); + expect(out).toEqual([0, 1, 2]); + }); + + it("never runs more than `limit` calls at once", async () => { + let active = 0; + let peak = 0; + await mapConcurrent(Array.from({ length: 20 }, (_, i) => i), 3, async () => { + active += 1; + peak = Math.max(peak, active); + await new Promise((resolve) => setTimeout(resolve, 1)); + active -= 1; + }); + expect(peak).toBe(3); + }); + + it("returns an empty array for no items", async () => { + expect(await mapConcurrent([], 4, async () => 1)).toEqual([]); + }); + + it("rejects when a call rejects", async () => { + await expect(mapConcurrent([1, 2], 2, async (n) => { + if (n === 2) throw new Error("boom"); + return n; + })).rejects.toThrow("boom"); + }); +}); diff --git a/src/lib/map-concurrent.ts b/src/lib/map-concurrent.ts new file mode 100644 index 0000000..4e2a2f1 --- /dev/null +++ b/src/lib/map-concurrent.ts @@ -0,0 +1,28 @@ +/** + * `Promise.all(items.map(fn))` with at most `limit` calls in flight. For the + * per-row fan-outs the backend has no bulk read for (marks, balances, member + * counts): an unbounded burst of a few hundred GETs trips the backend's rate + * limit and stalls every other request the page makes behind it. + * + * Results keep the input order. A rejection rejects the whole call, like + * `Promise.all` — callers that tolerate a failed row catch inside `fn`. + */ +export async function mapConcurrent( + items: readonly T[], + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + const results = new Array(items.length); + let next = 0; + const worker = async () => { + while (next < items.length) { + const index = next++; + results[index] = await fn(items[index], index); + } + }; + await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker)); + return results; +} + +/** In-flight cap shared by the page-level fan-outs. */ +export const FAN_OUT_LIMIT = 6; diff --git a/src/pages/calendar-page.tsx b/src/pages/calendar-page.tsx index bdcc975..714a823 100644 --- a/src/pages/calendar-page.tsx +++ b/src/pages/calendar-page.tsx @@ -1,5 +1,6 @@ import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; import { createBoardResources } from "@/lib/board-resources"; +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { getEvents } from "@/api/events"; import { getExams } from "@/api/exams"; import { getHomework } from "@/api/homework"; @@ -31,6 +32,7 @@ const MONTH_NAMES_TR = ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", const SESSION_COURSE_CAP = 25; /** Chips a single day cell shows before collapsing the rest into "+N". */ const CHIPS_PER_CELL = 3; +const DAY_MS = 24 * 60 * 60 * 1000; type CalendarKind = "lesson" | "study" | "exam" | "homework" | "event" | "appointment"; @@ -152,10 +154,19 @@ function CalendarContent() { // Each feed stands alone: a failed one reads as empty and is named in the // notice above the grid, instead of blanking the whole calendar. const board = createBoardResources(); - const [events] = board.createResource(async () => (await getEvents({ limit: 100 })).items); - const [exams] = board.createResource(async () => (await getExams({ limit: 100 })).items); - const [appointments] = board.createResource(async () => (await getAppointments({ limit: 100 })).items); - const [homework] = board.createResource(async () => (await getHomework({ limit: 100 })).items); + // Events and exams take a schedule window, so they are read from the first + // day the grid can show (the month's leading week included) onward, with no + // row cap — a fixed `limit` silently emptied later months once a school had + // more rows than the cap. The window only ever widens backwards: paging + // forward stays inside what is loaded, paging to an earlier month refetches. + const viewStart = () => new Date(viewYear(), viewMonth(), 1).getTime() - 7 * DAY_MS; + const loadedFrom = createMemo((prev) => Math.min(prev, viewStart()), viewStart()); + const [events] = board.createResource(loadedFrom, async (from) => (await getEvents({ ends_after: from })).items); + const [exams] = board.createResource(loadedFrom, async (from) => (await getExams({ ends_after: from })).items); + // Appointments and homework have no date filter and list newest-created + // first, so a cap would drop rows by creation order, not by date: read all. + const [appointments] = board.createResource(async () => (await getAppointments()).items); + const [homework] = board.createResource(async () => (await getHomework()).items); // Lessons and study/club meetings both come from course sessions; the course's // own `kind` is what separates them. @@ -169,18 +180,20 @@ function CalendarContent() { role === "student" ? getMyCourses() : getCourses(), ]); const byId = new Map(courses.items.map((course) => [course.id, course])); - const pages = await Promise.all( - instances.items.slice(0, SESSION_COURSE_CAP).map(async (instance) => { + const pages = await mapConcurrent( + instances.items.slice(0, SESSION_COURSE_CAP), FAN_OUT_LIMIT, async (instance) => { const course = byId.get(instance.course); if (!course) return []; try { - const page = await getInstanceSessions(instance.id, { limit: 100 }); + // No cap: a weekly lesson alone passes 100 sessions in a school + // year, and the rows past a cap were the later months. + const page = await getInstanceSessions(instance.id); return page.items.map((session) => ({ session, course })); } catch { // One unreadable section must not empty the whole calendar. return []; } - }), + }, ); return pages.flat(); }, diff --git a/src/pages/classes-page.tsx b/src/pages/classes-page.tsx index 95adedd..5309c67 100644 --- a/src/pages/classes-page.tsx +++ b/src/pages/classes-page.tsx @@ -11,6 +11,7 @@ import { RouteGuard } from "@/components/layout/route-guard"; import { DataToolbar } from "@/components/ui/data-toolbar"; import { DropdownSelect, Select } from "@/components/ui/select"; import { Alert } from "@/components/ui/alert"; +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { DataTableSkeleton } from "@/components/ui/data-table"; @@ -101,17 +102,16 @@ function ClassesContent() { return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null; }); const [memberCounts] = createResource(memberCountIds, async (ids) => { - const entries = await Promise.all( - ids.map(async (id) => { - try { - return [id, (await getClassMembers(id, { limit: 1 })).total] as const; - } catch { - return [id, null] as const; - } - }), - ); + const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => { + try { + return [id, (await getClassMembers(id, { limit: 1 })).total] as const; + } catch { + return [id, null] as const; + } + }); return new Map(entries); }); + const memberCountsCapped = () => listData().length > MEMBER_COUNT_FETCH_CAP; const createClass = async (event: SubmitEvent) => { event.preventDefault(); @@ -254,6 +254,10 @@ function ClassesContent() { /> + + {t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })} + + }> 0} fallback={}>
diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 800afea..1bc9e6d 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -181,6 +181,7 @@ function DashboardContent() { // Unfiltered: `/homework` has no due-date window, so this one read serves both // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking // heatmap. + // `limit: 100` matches the shell's feed read, so the two coalesce. const [homework] = createResource( () => role() === "parent" || !on("homework") ? null : role(), () => quiet(getHomework({ limit: 100 })), @@ -189,9 +190,11 @@ function DashboardContent() { () => role() === "parent" ? true : null, () => quiet(getMyStudents({ limit: 12 })), ); + // Same page as the shell's notification poll (`limit: 100`), so the two + // concurrent first-paint reads coalesce into one request in `client`. const [appointments] = createResource( () => (on("appointments") ? true : null), - () => quiet(getAppointments({ limit: 20 })), + () => quiet(getAppointments({ limit: 100 })), ); const [menus] = createResource( () => (on("meals") ? clock()?.now : null), diff --git a/src/pages/payments-page.tsx b/src/pages/payments-page.tsx index 1e3504f..7fde63d 100644 --- a/src/pages/payments-page.tsx +++ b/src/pages/payments-page.tsx @@ -20,7 +20,7 @@ import { type PaymentLine, type StatementEntry, } from "@/api/payments"; -import { getUserSearch } from "@/api/users"; +import { getUserProfile, getUserSearch } from "@/api/users"; import { formatApiError, type PersonRef } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; import { Alert } from "@/components/ui/alert"; @@ -47,6 +47,7 @@ import { formatDate, formatDateTime } from "@/lib/format"; import { formatTry } from "@/lib/meals"; import { PAYMENT_METHOD_KEYS, sortStatementEntries, statementStatus } from "@/lib/payments"; import { matchesSearch } from "@/lib/search-text"; +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { personLabel } from "@/lib/person"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -149,6 +150,15 @@ function PaymentsContent() { const pagedStudents = () => studentsPage()?.items ?? []; const studentsTotal = () => studentsPage()?.total ?? 0; + const [routeProfile] = createResource( + () => { + const routeId = routeStudentId(); + if (!routeId || studentsPage.loading) return null; + return pagedStudents().some((user) => user.id === routeId) ? null : routeId; + }, + (userId) => getUserProfile(userId).catch(() => null), + ); + createEffect(() => { const routeId = routeStudentId(); if (!routeId) { @@ -161,9 +171,14 @@ function PaymentsContent() { return; } // A direct visit/refresh on /management/payments/$userId whose student - // isn't on the currently loaded page — there's no non-admin "read one - // user" endpoint to resolve a name from, so fall back to the id itself. - // The statement/balance/ledger reads below only need the id to work. + // isn't on the currently loaded page. The statement/balance/ledger reads + // below only need the id; the header name comes from the public profile + // (readable by any staff account) once it resolves. + const named = routeProfile.latest; + if (named && named.id === routeId) { + setSelectedStudent({ id: named.id, username: named.username, display_name: named.display_name }); + return; + } setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null })); }); @@ -175,15 +190,13 @@ function PaymentsContent() { return users.length > 0 ? users : null; }, async (users): Promise => - Promise.all( - users.map(async (user) => { - try { - return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor }; - } catch { - return { ...user, balance_minor: null }; - } - }), - ), + mapConcurrent(users, FAN_OUT_LIMIT, async (user) => { + try { + return { ...user, balance_minor: (await getPaymentBalanceByUserId(user.id)).balance_minor }; + } catch { + return { ...user, balance_minor: null }; + } + }), ); const studentColumns = createMemo[]>(() => [ diff --git a/src/pages/student-marks-page.tsx b/src/pages/student-marks-page.tsx index 221d0e5..648c29d 100644 --- a/src/pages/student-marks-page.tsx +++ b/src/pages/student-marks-page.tsx @@ -8,6 +8,7 @@ import { cn } from "@/lib/cn"; import { MarksReportView } from "@/components/marks/marks-report-view"; import { RouteGuard } from "@/components/layout/route-guard"; import { Alert } from "@/components/ui/alert"; +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { ErrorAlert } from "@/components/ui/error-alert"; import { IconEye } from "@/components/ui/icons"; @@ -31,6 +32,8 @@ export default function StudentMarksPage() { ); } +const MARKS_FETCH_CAP = 200; + function StudentMarksContent() { const t = useT(); const [viewUser, setViewUser] = createSignal(null); @@ -47,28 +50,26 @@ function StudentMarksContent() { }, { initialValue: [] as StudentDirectoryRow[] }); // Per-student overall marks for the inline "average" column. No bulk endpoint - // exists, so this is one getUserMarks call per listed student, bounded by cap. - // ponytail: N+1 marks fetch, capped at 200; add a bulk /reports/marks endpoint - // if whole-school listing is needed. Mirrors the payments roster balance fetch. - const MARKS_FETCH_CAP = 200; + // exists, so this is one getUserMarks call per listed student — at most + // FAN_OUT_LIMIT in flight, and skipped past the cap with a visible notice + // instead of a column that silently reads "—" for everyone. const [marksMapRes] = createResource( () => { const ids = list().map((row) => row.person.id); return ids.length > 0 && ids.length <= MARKS_FETCH_CAP ? ids : null; }, async (ids) => { - const pairs = await Promise.all( - ids.map(async (id) => { - try { - return [id, await getUserMarks(id)] as const; - } catch { - return [id, null] as const; - } - }), - ); + const pairs = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => { + try { + return [id, await getUserMarks(id)] as const; + } catch { + return [id, null] as const; + } + }); return Object.fromEntries(pairs) as Record; }, ); + const marksCapped = () => list().length > MARKS_FETCH_CAP; const marksOf = (id: string) => marksMapRes()?.[id]; const [report, { refetch: refetchReport }] = createResource( @@ -163,6 +164,10 @@ function StudentMarksContent() { {error()} + + {t("marks.averageCapped", { cap: MARKS_FETCH_CAP })} + + }> (); +const HOMEWORK_FEED_LIMIT = 100; + const emptyPage = (): Page => ({ items: [], total: 0, limit: null, offset: 0 }); type UserFeed = Omit; @@ -151,7 +153,11 @@ function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnab async () => { try { if (!isEnabled("homework")) return emptyPage(); - return await getHomework(); + // `/homework` has no due-date filter and lists newest-created first, + // so a page of the most recent rows holds everything still upcoming + // in practice. Unbounded, this poll pulled the school's whole + // homework history every minute on every page. + return await getHomework({ limit: HOMEWORK_FEED_LIMIT }); } catch { return emptyPage(); }