forge
Explore
Log in

Don't you dare go Hollow

🚀 paginate the payments student roster server-side

Browse files at this commit

d77e9758b097d77eee2c0443b22ee572154fbb78Burak BoduroğluParent: 78a4738
  • perf
    • 🚀 paginate the payments student roster server-side
Show full message
perf: 🚀 paginate the payments student roster server-side
- replaced the 500-row bulk fetch + in-memory filter/sort/page with
  debounced server-side search (/users/search, role=student), so the
  page no longer caps out or slows down once a school passes a few
  hundred students
- a plan filter has no matching search+membership endpoint on the
  backend, so that path reads the plan's (already name-resolved,
  inherently small) assignee list and filters/pages it client-side
  instead
- the route-deep-linked student (/management/payments/$userId) is
  resolved from whatever page is loaded; when it isn't on that page
  (a cold visit/refresh) it falls back to showing the id in place of
  a name, since there is still no non-admin "read one user" endpoint
  to resolve it from — the statement/balance/ledger reads underneath
  only need the id anyway
src/pages/payments-page.tsxmodified+62 -51
@@ -1,5 +1,5 @@
1 import { useLocation, useNavigate } from "@tanstack/solid-router";1 import { useLocation, useNavigate } from "@tanstack/solid-router";
2-import { For, Index, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";2+import { For, Index, Show, Suspense, createEffect, createMemo, createResource, createSignal, onCleanup } from "solid-js";
3 import type { ColumnDef } from "@tanstack/solid-table";3 import type { ColumnDef } from "@tanstack/solid-table";
4 import {4 import {
5 deletePaymentPlanById,5 deletePaymentPlanById,
@@ -98,60 +98,71 @@ function PaymentsContent() {
98 const prefix = "/management/payments/";98 const prefix = "/management/payments/";
99 return location().pathname.startsWith(prefix) ? decodeURIComponent(location().pathname.slice(prefix.length)) : null;99 return location().pathname.startsWith(prefix) ? decodeURIComponent(location().pathname.slice(prefix.length)) : null;
100 });100 });
101- // `GET /users` and `GET /users/{id}` are admin-only on the backend, so a
102- // manager (the page's actual minimum role) 403'd the moment either fired —
103- // `/users/search` is teacher+, and a blank query with `role` set lists the
104- // whole role, which is exactly the roster this table needs. The route's
105- // student (deep link from `/management/payments/$userId`) is resolved from
106- // that same roster instead of a second per-id fetch, since there is no
107- // non-admin "read one user" endpoint to fall back on.
108- const [students, { refetch: refetchStudents }] = createResource(async () =>
109- (await getUserSearch("", undefined, "student", { limit: 500 })).items,
110- );
111- const studentList = () => students() ?? [];
112- createEffect(() => {
113- const routeId = routeStudentId();
114- if (!routeId) {
115- setSelectedStudent(null);
116- return;
117- }
118- const match = studentList().find((user) => user.id === routeId);
119- if (match) setSelectedStudent(match);
120- });
121 const student = () => selectedStudent()?.id ?? "";101 const student = () => selectedStudent()?.id ?? "";
122 102
123- // Filter the student list by fee plan (via that plan's assignment roster).
124 const [planFilter, setPlanFilter] = createSignal("");103 const [planFilter, setPlanFilter] = createSignal("");
125- const [filterAssignments] = createResource(
126- () => planFilter() || null,
127- (planId) => getPlanAssignments(planId, { limit: 500 }),
128- );
129- const filteredStudents = createMemo(() => {
130- const all = studentList();
131- if (!planFilter()) return all;
132- const ids = new Set((filterAssignments()?.items ?? []).map((row) => row.student.id));
133- return all.filter((user) => ids.has(user.id));
134- });
135 const [studentQuery, setStudentQuery] = createSignal("");104 const [studentQuery, setStudentQuery] = createSignal("");
105+ // Debounced so typing doesn't fire a search request per keystroke.
106+ const [debouncedQuery, setDebouncedQuery] = createSignal("");
107+ let queryTimer: ReturnType<typeof setTimeout> | undefined;
108+ createEffect(() => {
109+ const q = studentQuery();
110+ clearTimeout(queryTimer);
111+ queryTimer = setTimeout(() => setDebouncedQuery(q.trim()), 300);
112+ });
113+ onCleanup(() => clearTimeout(queryTimer));
114+
136 const [studentPage, setStudentPage] = createSignal(0);115 const [studentPage, setStudentPage] = createSignal(0);
137 const [studentPageSize, setStudentPageSize] = createSignal(STUDENT_PAGE_SIZE);116 const [studentPageSize, setStudentPageSize] = createSignal(STUDENT_PAGE_SIZE);
138- const searchedStudents = createMemo(() => {117+ // Reset to page 1 whenever the query or plan filter changes underneath it.
139- const query = studentQuery().trim().toLocaleLowerCase(locale());118+ createEffect(() => {
140- if (!query) return filteredStudents();119+ debouncedQuery();
141- return filteredStudents().filter((user) =>120+ planFilter();
142- [personLabel(user), user.username, user.id]121+ setStudentPage(0);
143- .join(" ")
144- .toLocaleLowerCase(locale())
145- .includes(query),
146- );
147- });
148- const pagedStudents = createMemo(() => {
149- const start = studentPage() * studentPageSize();
150- return searchedStudents().slice(start, start + studentPageSize());
151 });122 });
123+
124+ // `GET /users` is admin-only on the backend (this page is manager+), and a
125+ // full-roster fetch doesn't scale past a few hundred students anyway — so
126+ // this is server-side paged search (`/users/search`, teacher+; a blank
127+ // query with `role` set lists the whole role) rather than one big fetch
128+ // filtered/paged in memory. A plan filter is the one case with no matching
129+ // search+membership endpoint on the backend, so that path instead reads the
130+ // (already name-resolved) plan roster and filters/pages it client-side —
131+ // a plan's assignees are a small, bounded list on their own.
132+ const [studentsPage, { refetch: refetchStudents }] = createResource(
133+ () => ({ plan: planFilter(), q: debouncedQuery(), page: studentPage(), size: studentPageSize(), loc: locale() }),
134+ async ({ plan, q, page, size, loc }): Promise<{ items: PersonRef[]; total: number }> => {
135+ if (plan) {
136+ const assignments = await getPlanAssignments(plan, { limit: 500 });
137+ const needle = q.toLocaleLowerCase(loc);
138+ const all = assignments.items
139+ .map((row) => row.student)
140+ .filter((user) => !needle || [personLabel(user), user.username, user.id].join(" ").toLocaleLowerCase(loc).includes(needle));
141+ const start = page * size;
142+ return { items: all.slice(start, start + size), total: all.length };
143+ }
144+ return getUserSearch(q, undefined, "student", { limit: size, offset: page * size });
145+ },
146+ );
147+ const pagedStudents = () => studentsPage()?.items ?? [];
148+ const studentsTotal = () => studentsPage()?.total ?? 0;
149+
152 createEffect(() => {150 createEffect(() => {
153- const lastPage = Math.max(0, Math.ceil(searchedStudents().length / studentPageSize()) - 1);151+ const routeId = routeStudentId();
154- if (studentPage() > lastPage) setStudentPage(lastPage);152+ if (!routeId) {
153+ setSelectedStudent(null);
154+ return;
155+ }
156+ const match = pagedStudents().find((user) => user.id === routeId);
157+ if (match) {
158+ setSelectedStudent(match);
159+ return;
160+ }
161+ // A direct visit/refresh on /management/payments/$userId whose student
162+ // isn't on the currently loaded page — there's no non-admin "read one
163+ // user" endpoint to resolve a name from, so fall back to the id itself.
164+ // The statement/balance/ledger reads below only need the id to work.
165+ setSelectedStudent((prev) => (prev?.id === routeId ? prev : { id: routeId, username: routeId, display_name: null }));
155 });166 });
156 167
157 // The backend has no bulk balance endpoint. Fetch only the visible page so168 // The backend has no bulk balance endpoint. Fetch only the visible page so
@@ -521,10 +532,10 @@ function PaymentsContent() {
521 fallback={532 fallback={
522 <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">533 <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">
523 <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}>534 <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}>
524- <Show when={students.error}>535+ <Show when={studentsPage.error}>
525- <ErrorAlert message={formatApiError(students.error)} onRetry={() => void refetchStudents()} />536+ <ErrorAlert message={formatApiError(studentsPage.error)} onRetry={() => void refetchStudents()} />
526 </Show>537 </Show>
527- <Show when={studentList().length > 0} fallback={<EmptyState title={t("payments.selectStudent")} />}>538+ <Show when={pagedStudents().length > 0} fallback={<EmptyState title={t("payments.selectStudent")} />}>
528 <DataTable539 <DataTable
529 columns={studentColumns()}540 columns={studentColumns()}
530 data={paymentStudentRows() ?? []}541 data={paymentStudentRows() ?? []}
@@ -549,7 +560,7 @@ function PaymentsContent() {
549 manualPagination={{560 manualPagination={{
550 pageIndex: studentPage(),561 pageIndex: studentPage(),
551 pageSize: studentPageSize(),562 pageSize: studentPageSize(),
552- total: searchedStudents().length,563+ total: studentsTotal(),
553 onPageChange: setStudentPage,564 onPageChange: setStudentPage,
554 onPageSizeChange: (size) => {565 onPageSizeChange: (size) => {
555 setStudentPageSize(size);566 setStudentPageSize(size);