forge
Explore
Log in

Don't you dare go Hollow

🔄 server-pagination api pattern + role-scope-matrix doc

Browse files at this commit

7befd0c20afe9987a3e4cdf297a8931902372c62Burak BoduroğluParent: 0be6983
  • refactor
    • 🔄 server-pagination api pattern + role-scope-matrix doc
Show full message
refactor: 🔄 server-pagination api pattern + role-scope-matrix doc
- src/api/page.ts: shared Page<T>, PageParams, pageQuery, normalizePage
- src/lib/list-page.ts: loadListPage helper (server or client pagination)
- all listing API functions: accept PageParams, return Page<T>
- pages: adopt loadListPage for pagination state management
- docs/role-scope-matrix.md: full role access matrix per page/nav/dashboard
- docs/frontend-next-steps: sync pagination audit status
docs/frontend-next-steps.mdmodified+11 -18
@@ -18,7 +18,7 @@ validation, and list filtering cleanup.
18 - Settings requests are cached and refreshed after settings patches.18 - Settings requests are cached and refreshed after settings patches.
19 - Sidebar icons use local SVG wrappers to avoid large icon package module graphs.19 - Sidebar icons use local SVG wrappers to avoid large icon package module graphs.
20 - Notes use a paper-style notebook card layout, a paper-style read dialog, and dialog-based create/edit/delete flows.20 - Notes use a paper-style notebook card layout, a paper-style read dialog, and dialog-based create/edit/delete flows.
21-- Courses use client-side table search plus term/unassigned filters while backend pagination/filter params are pending.21+- List endpoints return `{ items, total, limit, offset }`. API helpers under `src/api/` accept optional `limit`/`offset` via `Page<T>`.
22 - Events keep card rendering with shared toolbar search and all/upcoming/past filters.22 - Events keep card rendering with shared toolbar search and all/upcoming/past filters.
23 - Event, exam, and lesson-session schedule forms use `GET /time` for server-clock-aware past-date warnings before submit.23 - Event, exam, and lesson-session schedule forms use `GET /time` for server-clock-aware past-date warnings before submit.
24 - Start/end date-time rows use equal-width date and time controls.24 - Start/end date-time rows use equal-width date and time controls.
@@ -40,29 +40,22 @@ validation, and list filtering cleanup.
40 40
41 ## Request And Pagination Result41 ## Request And Pagination Result
42 42
43-- `/courses`: client-paginated after `GET /courses` for teacher+ and `GET /courses/me` for students. Toolbar search and term filters are client-side until backend params exist.43+- Backend list contract: `?limit=&offset=` → `{ items, total, limit, offset }` (opt-in; omit `limit` for full `items`).
44-- `/exams`: client-paginated after `GET /exams`. Student filters use `GET /courses/me`; teacher+ filters use `GET /courses`.44+- Shared helpers: `src/api/page.ts` + `src/lib/list-page.ts` (`loadListPage`).
45-- `/events`: client-paginated after `GET /events`. Toolbar search and all/upcoming/past filters are client-side.45+- All paged list API files return `Page<T>` and accept optional page params.
46-- `/admin/users`: unpaginated `GET /users` plus client filtering/search UI. Admin-only.46+- Main lists use real server paging (`limit`/`offset` + `total`) when no client-only filter is active:
47-- `/work`: unpaginated `GET /work/me`, newest first. Personal staff log.47+ - courses, exams, events (hybrid: full fetch only while search/status/term filters need it)
48-- `/courses/:id` exams: unpaginated `GET /courses/{id}/exams`; course-scoped.48+ - notes, terms, work log, admin users (server page; admin metrics still load full list once)
49-- `/courses/:id` sessions: unpaginated `GET /courses/{id}/sessions`, deferred until sessions section or create panel is opened.49+- Nested/deferred lists unwrap full `.items` (sessions, enrollments, attendance, exam results/questions).
50-- `/courses/:id` roster: unpaginated `GET /courses/{id}/enrollments`, course-management only.50+- `/exams/:id/live`: client-paginated roster over snapshot/SSE (not the list envelope).
51-- `/events/:id` attendance: unpaginated `GET /events/{id}/attendance`, teacher+ only and deferred until the attendance disclosure opens.51+- `/attendance` and marks reports: not paged; aggregate report shapes.
52-- `/exams/:id` results: unpaginated `GET /exams/{id}/results`, deferred until results/grade/answer-sheet workflow needs it.
53-- `/exams/:id` questions: unpaginated `GET /exams/{id}/questions`, deferred until questions section is opened.
54-- `/exams/:id/live`: client-paginated/sorted live roster over backend snapshot/SSE.
55-- `/attendance` and `/management/student-attendance`: unpaginated report payloads; backend returns aggregate report shape, not a raw row list.
56 52
57 ## Backend-Dependent Follow-Up53 ## Backend-Dependent Follow-Up
58 54
59-- Backend pagination/search/filter params have been requested.55+- Server-side search/filter params are still absent; hybrid full-fetch remains for client filters until the API adds them.
60-- Do not claim true server-side pagination until those params exist in the backend README/API contract.
61-- When backend params arrive, update `src/api/*` helpers first and then move toolbar/search/filter/page state into request params.
62 56
63 ## Active Backlog57 ## Active Backlog
64 58
65-- Backend server-side pagination/search/filter params still pending (see Backend-Dependent Follow-Up).
66 - Deferred product features (not started): exam `allow_rejoin` UI, manager work-log corrections, session edit (`PATCH`).59 - Deferred product features (not started): exam `allow_rejoin` UI, manager work-log corrections, session edit (`PATCH`).
67 60
68 ## UX polish batch (completed)61 ## UX polish batch (completed)
docs/role-scope-matrix.mdadded+81 -0
@@ -0,0 +1,81 @@
1+# Rol Kapsamı Matrisi
2+
3+## Sayfa Bazında Erişim
4+
5+| Sayfa / Özellik | Öğrenci | Öğretmen | Müdür | Admin |
6+|---|---|---|---|---|
7+| Ana sayfa `/` | ✅ | ✅ | ✅ | ✅ |
8+| Profil `/profile` | ✅ | ✅ | ✅ | ✅ |
9+| Rehber `/guide` | ✅ | ✅ | ✅ | ✅ |
10+| Notlar `/notes` | ✅ | ✅ | ✅ | ✅ |
11+| Dersler `/courses` | ✅ | ✅ | ✅ | ✅ |
12+| Ders detay `/courses/:id` | ✅ | ✅ | ✅ | ✅ |
13+| Sınavlar `/exams` | ✅ | ✅ | ✅ | ✅ |
14+| Sınav detay `/exams/:id` | ✅ | ✅ | ✅ | ✅ |
15+| Sınav salonu `/exam-room/:id` | ✅ | ❌ | ❌ | ❌ |
16+| Canlı monitör `/exams/:id/live` | ❌ | ✅ | ✅ | ✅ |
17+| Etkinlikler `/events` | ✅ | ✅ | ✅ | ✅ |
18+| Etkinlik detay `/events/:id` | ✅ | ✅ | ✅ | ✅ |
19+| **Karnem `/marks`** | ✅ | ❌ | ❌ | ❌ |
20+| **Yoklamam `/attendance`** | ✅ | ❌ | ❌ | ❌ |
21+| Öğrenci not sorgula `/management/student-marks` | ❌ | ✅ | ✅ | ✅ |
22+| Öğrenci yoklama sorgula `/management/student-attendance` | ❌ | ✅ | ✅ | ✅ |
23+| Mesai `/work` | ❌ | ✅ | ✅ | ✅ |
24+| Ayarlar `/management/settings` | ❌ | ❌ | ✅ | ✅ |
25+| Dönemler `/management/terms` | ❌ | ❌ | ✅ | ✅ |
26+| Kullanıcı yönetimi `/admin/users` | ❌ | ❌ | ❌ | ✅ |
27+
28+## Sidebar’da Ne Görsün?
29+
30+| Sidebar grubu / item | Öğrenci | Öğretmen | Müdür | Admin |
31+|---|---|---|---|---|
32+| **classes** — Dersler / Sınavlar / Etkinlikler | ✅ | ✅ | ✅ | ✅ |
33+| **grades** — Karnem (`/marks`) | ✅ | ❌ | ❌ | ❌ |
34+| **grades** — Notlar | ✅ | ✅ | ✅ | ✅ |
35+| **students** — Yoklamam (`/attendance`) | ✅ | ❌ | ❌ | ❌ |
36+| **reports** — Öğrenci notları / yoklama / mesai | ❌ | ✅ | ✅ | ✅ |
37+| **settings** — Ayarlar / Dönemler | ❌ | ❌ | ✅ | ✅ |
38+| **admin** — Kullanıcılar | ❌ | ❌ | ❌ | ✅ |
39+
40+## Dashboard Portal Kartları
41+
42+| Kart | Öğrenci | Öğretmen | Müdür | Admin |
43+|---|---|---|---|---|
44+| Dersler | ✅ (kayıtlı) | ✅ | ✅ | ✅ |
45+| Sınavlar | ✅ (kayıtlı) | ✅ | ✅ | ✅ |
46+| Etkinlikler | ✅ | ✅ (teacher badge) | ✅ | ✅ |
47+| Karnem | ✅ | ❌ | ❌ | ❌ |
48+| Notlar | ✅ | ✅ | ✅ | ✅ |
49+| Öğrenci notları | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) |
50+| Öğrenci yoklaması | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) |
51+| Mesai | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) |
52+| Ayarlar | ❌ | ❌ | ✅ (manager badge) | ✅ (manager badge) |
53+| Dönemler | ❌ | ❌ | ✅ (manager badge) | ✅ (manager badge) |
54+| Kullanıcılar | ❌ | ❌ | ❌ | ✅ (admin badge) |
55+
56+## Tespit Edilen Hatalar
57+
58+| # | Hata | Dosya(lar) | Önem |
59+|---|---|---|---|
60+| 1 | `/marks` her role açık, RouteGuard yok, nav'da herkes görür | `marks-page.tsx`, `router.tsx`, `side-nav.tsx` | YÜKSEK |
61+| 2 | `/attendance` her role açık, RouteGuard yok, nav'da herkes görür | `attendance-page.tsx`, `router.tsx`, `side-nav.tsx` | YÜKSEK |
62+| 3 | `RouteGuard` student-only desteklemiyor (sadece `minRole` var) | `route-guard.tsx` | ORTA |
63+| 4 | `/work`, `/live`, `/settings`, `/terms` `beforeLoad` guard'ı yok (client-side RouteGuard var ama tutarsız) | `router.tsx` | DÜŞÜK |
64+| 5 | Sınav salonu butonu manager/admin'e görünüyor (tıklayınca hata) | `exam-detail-page.tsx` | DÜŞÜK |
65+
66+## Backend Notu
67+
68+Backend README Auth kolonunda:
69+- `GET /marks/me` = **student**
70+- `GET /attendance/me` = **student**
71+- `GET /marks/{user}` = **teacher**
72+- `GET /attendance/{user}` = **teacher**
73+
74+Ancak kodda `*/me` endpoint'leri `CurrentUser` (rol kontrolü yok) ile çalışıyor, `RequireTeacher`/`RequireStudent` değil. README'de `student` yazıp kodda herkese açık olması tutarsız. Bu endpoint'ler ya `RequireStudent` ile korunmalı ya da mevcut davranış (herkese açık) README'e yansıtılmalı.
75+
76+## Kullanılan Kısaltmalar
77+
78+- ✅ = erişim var
79+- ❌ = erişim yok
80+- FE = frontend (düzeltme sadece ön yüzde)
81+- BE = backend (düzeltme sunucu tarafında)
src/api/getCourseEnrollments.tsmodified+6 -3
@@ -1,9 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Enrollment } from "./types";3 import type { Enrollment } from "./types";
3 4
4-export function getCourseEnrollments(5+export async function getCourseEnrollments(
5 courseId: string,6 courseId: string,
7+ params?: PageParams,
6 signal?: AbortSignal,8 signal?: AbortSignal,
7-): Promise<Enrollment[]> {9+): Promise<Page<Enrollment>> {
8- return client<Enrollment[]>(`/courses/${courseId}/enrollments`, { signal });10+ const data = await client<unknown>(`/courses/${courseId}/enrollments${pageQuery(params)}`, { signal });
11+ return normalizePage<Enrollment>(data);
9 }12 }
src/api/getCourseExams.tsmodified+8 -2
@@ -1,6 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Exam } from "./types";3 import type { Exam } from "./types";
3 4
4-export function getCourseExams(courseId: string, signal?: AbortSignal): Promise<Exam[]> {5+export async function getCourseExams(
5- return client<Exam[]>(`/courses/${courseId}/exams`, { signal });6+ courseId: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<Exam>> {
10+ const data = await client<unknown>(`/courses/${courseId}/exams${pageQuery(params)}`, { signal });
11+ return normalizePage<Exam>(data);
6 }12 }
src/api/getCourseSessions.tsmodified+8 -2
@@ -1,6 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { CourseSession } from "./types";3 import type { CourseSession } from "./types";
3 4
4-export function getCourseSessions(courseId: string, signal?: AbortSignal): Promise<CourseSession[]> {5+export async function getCourseSessions(
5- return client<CourseSession[]>(`/courses/${courseId}/sessions`, { signal });6+ courseId: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<CourseSession>> {
10+ const data = await client<unknown>(`/courses/${courseId}/sessions${pageQuery(params)}`, { signal });
11+ return normalizePage<CourseSession>(data);
6 }12 }
src/api/getCourses.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Course } from "./types";3 import type { Course } from "./types";
3 4
4-export function getCourses(signal?: AbortSignal): Promise<Course[]> {5+export async function getCourses(params?: PageParams, signal?: AbortSignal): Promise<Page<Course>> {
5- return client<Course[]>("/courses", { signal });6+ const data = await client<unknown>(`/courses${pageQuery(params)}`, { signal });
7+ return normalizePage<Course>(data);
6 }8 }
src/api/getEventAttendance.tsmodified+6 -3
@@ -1,9 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Attendance } from "./types";3 import type { Attendance } from "./types";
3 4
4-export function getEventAttendance(5+export async function getEventAttendance(
5 eventId: string,6 eventId: string,
7+ params?: PageParams,
6 signal?: AbortSignal,8 signal?: AbortSignal,
7-): Promise<Attendance[]> {9+): Promise<Page<Attendance>> {
8- return client<Attendance[]>(`/events/${eventId}/attendance`, { signal });10+ const data = await client<unknown>(`/events/${eventId}/attendance${pageQuery(params)}`, { signal });
11+ return normalizePage<Attendance>(data);
9 }12 }
src/api/getEvents.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Event } from "./types";3 import type { Event } from "./types";
3 4
4-export function getEvents(signal?: AbortSignal): Promise<Event[]> {5+export async function getEvents(params?: PageParams, signal?: AbortSignal): Promise<Page<Event>> {
5- return client<Event[]>("/events", { signal });6+ const data = await client<unknown>(`/events${pageQuery(params)}`, { signal });
7+ return normalizePage<Event>(data);
6 }8 }
src/api/getExamQuestions.tsmodified+8 -2
@@ -1,6 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { ExamQuestion } from "./types";3 import type { ExamQuestion } from "./types";
3 4
4-export function getExamQuestions(examId: string, signal?: AbortSignal): Promise<ExamQuestion[]> {5+export async function getExamQuestions(
5- return client<ExamQuestion[]>(`/exams/${examId}/questions`, { signal });6+ examId: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<ExamQuestion>> {
10+ const data = await client<unknown>(`/exams/${examId}/questions${pageQuery(params)}`, { signal });
11+ return normalizePage<ExamQuestion>(data);
6 }12 }
src/api/getExamResults.tsmodified+6 -3
@@ -1,9 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { ExamResult } from "./types";3 import type { ExamResult } from "./types";
3 4
4-export function getExamResults(5+export async function getExamResults(
5 examId: string,6 examId: string,
7+ params?: PageParams,
6 signal?: AbortSignal,8 signal?: AbortSignal,
7-): Promise<ExamResult[]> {9+): Promise<Page<ExamResult>> {
8- return client<ExamResult[]>(`/exams/${examId}/results`, { signal });10+ const data = await client<unknown>(`/exams/${examId}/results${pageQuery(params)}`, { signal });
11+ return normalizePage<ExamResult>(data);
9 }12 }
src/api/getExams.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Exam } from "./types";3 import type { Exam } from "./types";
3 4
4-export function getExams(signal?: AbortSignal): Promise<Exam[]> {5+export async function getExams(params?: PageParams, signal?: AbortSignal): Promise<Page<Exam>> {
5- return client<Exam[]>("/exams", { signal });6+ const data = await client<unknown>(`/exams${pageQuery(params)}`, { signal });
7+ return normalizePage<Exam>(data);
6 }8 }
src/api/getMyCourses.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Course } from "./types";3 import type { Course } from "./types";
3 4
4-export function getMyCourses(signal?: AbortSignal): Promise<Course[]> {5+export async function getMyCourses(params?: PageParams, signal?: AbortSignal): Promise<Page<Course>> {
5- return client<Course[]>("/courses/me", { signal });6+ const data = await client<unknown>(`/courses/me${pageQuery(params)}`, { signal });
7+ return normalizePage<Course>(data);
6 }8 }
src/api/getMyWorkLog.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { WorkEntry } from "./types";3 import type { WorkEntry } from "./types";
3 4
4-export function getMyWorkLog(signal?: AbortSignal): Promise<WorkEntry[]> {5+export async function getMyWorkLog(params?: PageParams, signal?: AbortSignal): Promise<Page<WorkEntry>> {
5- return client<WorkEntry[]>("/work/me", { signal });6+ const data = await client<unknown>(`/work/me${pageQuery(params)}`, { signal });
7+ return normalizePage<WorkEntry>(data);
6 }8 }
src/api/getNotes.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Note } from "./types";3 import type { Note } from "./types";
3 4
4-export function getNotes(signal?: AbortSignal): Promise<Note[]> {5+export async function getNotes(params?: PageParams, signal?: AbortSignal): Promise<Page<Note>> {
5- return client<Note[]>("/notes", { signal });6+ const data = await client<unknown>(`/notes${pageQuery(params)}`, { signal });
7+ return normalizePage<Note>(data);
6 }8 }
src/api/getSessionAttendance.tsmodified+8 -2
@@ -1,6 +1,12 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { SessionAttendance } from "./types";3 import type { SessionAttendance } from "./types";
3 4
4-export function getSessionAttendance(id: string, signal?: AbortSignal): Promise<SessionAttendance[]> {5+export async function getSessionAttendance(
5- return client<SessionAttendance[]>(`/sessions/${id}/attendance`, { signal });6+ id: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<SessionAttendance>> {
10+ const data = await client<unknown>(`/sessions/${id}/attendance${pageQuery(params)}`, { signal });
11+ return normalizePage<SessionAttendance>(data);
6 }12 }
src/api/getTerms.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { Term } from "./types";3 import type { Term } from "./types";
3 4
4-export function getTerms(signal?: AbortSignal): Promise<Term[]> {5+export async function getTerms(params?: PageParams, signal?: AbortSignal): Promise<Page<Term>> {
5- return client<Term[]>("/terms", { signal });6+ const data = await client<unknown>(`/terms${pageQuery(params)}`, { signal });
7+ return normalizePage<Term>(data);
6 }8 }
src/api/getUserSearch.tsmodified+10 -2
@@ -1,8 +1,16 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { appendPageParams, normalizePage, type Page, type PageParams } from "./page";
2 import type { PersonRef, Role } from "./types";3 import type { PersonRef, Role } from "./types";
3 4
4-export function getUserSearch(query: string, signal?: AbortSignal, role?: Role): Promise<PersonRef[]> {5+export async function getUserSearch(
6+ query: string,
7+ signal?: AbortSignal,
8+ role?: Role,
9+ page?: PageParams,
10+): Promise<Page<PersonRef>> {
5 const params = new URLSearchParams({ q: query });11 const params = new URLSearchParams({ q: query });
6 if (role) params.set("role", role);12 if (role) params.set("role", role);
7- return client<PersonRef[]>(`/users/search?${params.toString()}`, { signal });13+ appendPageParams(params, page);
14+ const data = await client<unknown>(`/users/search?${params.toString()}`, { signal });
15+ return normalizePage<PersonRef>(data);
8 }16 }
src/api/getUsers.tsmodified+4 -2
@@ -1,6 +1,8 @@
1 import { client } from "./client";1 import { client } from "./client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "./page";
2 import type { User } from "./types";3 import type { User } from "./types";
3 4
4-export function getUsers(signal?: AbortSignal): Promise<User[]> {5+export async function getUsers(params?: PageParams, signal?: AbortSignal): Promise<Page<User>> {
5- return client<User[]>("/users", { signal });6+ const data = await client<unknown>(`/users${pageQuery(params)}`, { signal });
7+ return normalizePage<User>(data);
6 }8 }
src/api/page.tsadded+44 -0
@@ -0,0 +1,44 @@
1+export type PageParams = {
2+ limit?: number;
3+ offset?: number;
4+};
5+
6+export type Page<T> = {
7+ items: T[];
8+ total: number;
9+ limit: number | null;
10+ offset: number;
11+};
12+
13+export function pageQuery(params?: PageParams): string {
14+ if (!params) return "";
15+ const query = new URLSearchParams();
16+ if (params.limit != null) query.set("limit", String(params.limit));
17+ if (params.offset != null) query.set("offset", String(params.offset));
18+ const value = query.toString();
19+ return value ? `?${value}` : "";
20+}
21+
22+export function appendPageParams(base: URLSearchParams, params?: PageParams): void {
23+ if (!params) return;
24+ if (params.limit != null) base.set("limit", String(params.limit));
25+ if (params.offset != null) base.set("offset", String(params.offset));
26+}
27+
28+/** Accept Page envelope or legacy bare array so lists never crash on shape mismatch. */
29+export function normalizePage<T>(data: unknown): Page<T> {
30+ if (Array.isArray(data)) {
31+ return { items: data as T[], total: data.length, limit: null, offset: 0 };
32+ }
33+ if (data && typeof data === "object") {
34+ const record = data as Record<string, unknown>;
35+ if (Array.isArray(record.items)) {
36+ const items = record.items as T[];
37+ const total = typeof record.total === "number" ? record.total : items.length;
38+ const limit = typeof record.limit === "number" ? record.limit : null;
39+ const offset = typeof record.offset === "number" ? record.offset : 0;
40+ return { items, total, limit, offset };
41+ }
42+ }
43+ return { items: [], total: 0, limit: null, offset: 0 };
44+}
src/api/types.tsmodified+2 -0
@@ -1,3 +1,5 @@
1+export type { Page, PageParams } from "./page";
2+
1 export type Role = "student" | "teacher" | "manager" | "admin";3 export type Role = "student" | "teacher" | "manager" | "admin";
2 export type CoreAttendanceStatus = "present" | "absent" | "late" | "excused";4 export type CoreAttendanceStatus = "present" | "absent" | "late" | "excused";
3 export type AttendanceStatus = CoreAttendanceStatus | string;5 export type AttendanceStatus = CoreAttendanceStatus | string;
src/components/exams/exam-questions-panel.tsxmodified+1 -1
@@ -20,7 +20,7 @@ export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean;
20 const t = useT();20 const t = useT();
21 const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {21 const [questions, { refetch }] = createResource(() => props.examId, async (examId) => {
22 try {22 try {
23- return await getExamQuestions(examId);23+ return (await getExamQuestions(examId)).items;
24 } catch (err) {24 } catch (err) {
25 if (err instanceof ApiError && err.status === 404) return [];25 if (err instanceof ApiError && err.status === 404) return [];
26 throw err;26 throw err;
src/components/sessions/course-sessions-panel.tsxmodified+5 -2
@@ -53,7 +53,7 @@ export function CourseSessionsPanel(props: {
53 const { locale } = usePreferences();53 const { locale } = usePreferences();
54 const [sessions, { refetch }] = createResource(54 const [sessions, { refetch }] = createResource(
55 () => (props.active || props.createOpen ? props.courseId : null),55 () => (props.active || props.createOpen ? props.courseId : null),
56- async (courseId) => (courseId ? getCourseSessions(courseId) : []),56+ async (courseId) => (courseId ? (await getCourseSessions(courseId)).items : []),
57 );57 );
58 const [selectedSession, setSelectedSession] = createSignal<CourseSession | null>(null);58 const [selectedSession, setSelectedSession] = createSignal<CourseSession | null>(null);
59 const [deleteTarget, setDeleteTarget] = createSignal<CourseSession | null>(null);59 const [deleteTarget, setDeleteTarget] = createSignal<CourseSession | null>(null);
@@ -240,7 +240,10 @@ export function CourseSessionsPanel(props: {
240 240
241 function RollCall(props: { sessionId: string; roster: Enrollment[] }) {241 function RollCall(props: { sessionId: string; roster: Enrollment[] }) {
242 const t = useT();242 const t = useT();
243- const [attendance, { refetch }] = createResource(() => props.sessionId, (sessionId) => getSessionAttendance(sessionId));243+ const [attendance, { refetch }] = createResource(
244+ () => props.sessionId,
245+ async (sessionId) => (await getSessionAttendance(sessionId)).items,
246+ );
244 const rows = createMemo(() => new Map((attendance() ?? []).map((row) => [row.user.id, row])));247 const rows = createMemo(() => new Map((attendance() ?? []).map((row) => [row.user.id, row])));
245 const [local, setLocal] = createSignal<Record<string, AttendanceStatus>>({});248 const [local, setLocal] = createSignal<Record<string, AttendanceStatus>>({});
246 const [error, setError] = createSignal("");249 const [error, setError] = createSignal("");
src/components/users/user-search-select.tsxmodified+1 -1
@@ -57,7 +57,7 @@ export function UserSearchSelect(props: {
57 setLoading(true);57 setLoading(true);
58 try {58 try {
59 const data = await getUserSearch(q, abortController.signal, props.role);59 const data = await getUserSearch(q, abortController.signal, props.role);
60- setUsers(data);60+ setUsers(data.items);
61 } catch {61 } catch {
62 if (!abortController?.signal.aborted) setUsers([]);62 if (!abortController?.signal.aborted) setUsers([]);
63 } finally {63 } finally {
src/i18n/messages.tsmodified+3 -0
@@ -151,6 +151,7 @@ export type MessageKey =
151 | "dashboard.emptyEventsTitle"151 | "dashboard.emptyEventsTitle"
152 | "dashboard.emptyNotesCta"152 | "dashboard.emptyNotesCta"
153 | "dashboard.emptyEventsCta"153 | "dashboard.emptyEventsCta"
154+ | "dashboard.upcomingEmpty"
154 | "dashboard.viewAll"155 | "dashboard.viewAll"
155 | "dashboard.getStarted"156 | "dashboard.getStarted"
156 | "dashboard.helpTitle"157 | "dashboard.helpTitle"
@@ -635,6 +636,7 @@ const en: Dict = {
635 "dashboard.emptyEventsTitle": "No events yet",636 "dashboard.emptyEventsTitle": "No events yet",
636 "dashboard.emptyNotesCta": "Write a note",637 "dashboard.emptyNotesCta": "Write a note",
637 "dashboard.emptyEventsCta": "Browse events",638 "dashboard.emptyEventsCta": "Browse events",
639+ "dashboard.upcomingEmpty": "Nothing here.",
638 "dashboard.viewAll": "View all",640 "dashboard.viewAll": "View all",
639 "dashboard.getStarted": "Get started",641 "dashboard.getStarted": "Get started",
640 "dashboard.helpTitle": "Need a hand?",642 "dashboard.helpTitle": "Need a hand?",
@@ -1131,6 +1133,7 @@ const tr: Dict = {
1131 "dashboard.emptyEventsTitle": "Henüz etkinlik yok",1133 "dashboard.emptyEventsTitle": "Henüz etkinlik yok",
1132 "dashboard.emptyNotesCta": "Not yaz",1134 "dashboard.emptyNotesCta": "Not yaz",
1133 "dashboard.emptyEventsCta": "Etkinliklere git",1135 "dashboard.emptyEventsCta": "Etkinliklere git",
1136+ "dashboard.upcomingEmpty": "Burada bir şey yok.",
1134 "dashboard.viewAll": "Tümünü gör",1137 "dashboard.viewAll": "Tümünü gör",
1135 "dashboard.getStarted": "Başla",1138 "dashboard.getStarted": "Başla",
1136 "dashboard.helpTitle": "Yardıma mı ihtiyacın var?",1139 "dashboard.helpTitle": "Yardıma mı ihtiyacın var?",
src/lib/list-page.tsadded+38 -0
@@ -0,0 +1,38 @@
1+import type { Page, PageParams } from "@/api/page";
2+
3+export type ListPageState<T> = {
4+ items: T[];
5+ total: number;
6+};
7+
8+/** Server page when `clientMode` is false; full fetch + caller-supplied filter when true. */
9+export async function loadListPage<T>(options: {
10+ page: number;
11+ pageSize: number;
12+ clientMode: boolean;
13+ fetch: (params?: PageParams) => Promise<Page<T>>;
14+ filter?: (items: T[]) => T[];
15+}): Promise<ListPageState<T>> {
16+ if (options.clientMode) {
17+ const all = await options.fetch();
18+ const source = Array.isArray(all.items) ? all.items : [];
19+ const filtered = options.filter ? options.filter(source) : source;
20+ const start = options.page * options.pageSize;
21+ return {
22+ items: filtered.slice(start, start + options.pageSize),
23+ total: filtered.length,
24+ };
25+ }
26+
27+ const result = await options.fetch({
28+ limit: options.pageSize,
29+ offset: options.page * options.pageSize,
30+ });
31+ const items = Array.isArray(result.items) ? result.items : [];
32+ const total = typeof result.total === "number" ? result.total : items.length;
33+ return { items, total };
34+}
35+
36+export function totalPages(total: number, pageSize: number): number {
37+ return Math.max(1, Math.ceil(Math.max(0, total) / pageSize));
38+}
src/pages/admin-users-page.tsxmodified+51 -23
@@ -2,7 +2,7 @@ import { For, Show, Suspense, createMemo, createResource, createSignal } from "s
2 import { getUsers } from "@/api/getUsers";2 import { getUsers } from "@/api/getUsers";
3 import { patchUserRole } from "@/api/patchUserRole";3 import { patchUserRole } from "@/api/patchUserRole";
4 import { formatApiError } from "@/api/client";4 import { formatApiError } from "@/api/client";
5-import type { Role } from "@/api/types";5+import type { Role, User } from "@/api/types";
6 import { RouteGuard } from "@/components/layout/route-guard";6 import { RouteGuard } from "@/components/layout/route-guard";
7 import { PageHeader } from "@/components/layout/page-header";7 import { PageHeader } from "@/components/layout/page-header";
8 import { UserSearchSelect } from "@/components/users/user-search-select";8 import { UserSearchSelect } from "@/components/users/user-search-select";
@@ -10,11 +10,15 @@ import { UserTable } from "@/components/users/user-table";
10 import { Badge } from "@/components/ui/badge";10 import { Badge } from "@/components/ui/badge";
11 import { DataTableEmpty, DataTableSkeleton } from "@/components/ui/data-table";11 import { DataTableEmpty, DataTableSkeleton } from "@/components/ui/data-table";
12 import { DataToolbar } from "@/components/ui/data-toolbar";12 import { DataToolbar } from "@/components/ui/data-toolbar";
13+import { PaginationControls } from "@/components/ui/pagination-controls";
14+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
13 import { useAuth } from "@/stores/auth-context";15 import { useAuth } from "@/stores/auth-context";
14 import { useT } from "@/stores/preferences-context";16 import { useT } from "@/stores/preferences-context";
15 import type { MessageKey } from "@/i18n/messages";17 import type { MessageKey } from "@/i18n/messages";
16 import { ROLES } from "@/lib/roles";18 import { ROLES } from "@/lib/roles";
17 19
20+const USER_PAGE_SIZE = 20;
21+
18 export default function AdminUsersPage() {22 export default function AdminUsersPage() {
19 return (23 return (
20 <RouteGuard minRole="admin">24 <RouteGuard minRole="admin">
@@ -26,16 +30,37 @@ export default function AdminUsersPage() {
26 function AdminUsersContent() {30 function AdminUsersContent() {
27 const auth = useAuth();31 const auth = useAuth();
28 const t = useT();32 const t = useT();
29- const [users, { refetch }] = createResource(() => getUsers());
30 const [error, setError] = createSignal("");33 const [error, setError] = createSignal("");
31 const [selectedUserId, setSelectedUserId] = createSignal("");34 const [selectedUserId, setSelectedUserId] = createSignal("");
32- const visibleUsers = createMemo(() => {35+ const [page, setPage] = createSignal(0);
33- const list = users() ?? [];36+
34- const id = selectedUserId().trim();37+ const [stats] = createResource(async () => (await getUsers()).items);
35- if (!id) return list;38+
36- return list.filter((user) => user.id === id);39+ const [list, { refetch }] = createResource(
37- });40+ () => ({
38- const roleCount = (role: Role) => users()?.filter((user) => user.role === role).length ?? 0;41+ page: page(),
42+ selected: selectedUserId().trim(),
43+ }),
44+ async (key) => {
45+ if (key.selected) {
46+ const all = await getUsers();
47+ const match = all.items.filter((user) => user.id === key.selected);
48+ return { items: match, total: match.length };
49+ }
50+ return loadListPage({
51+ page: key.page,
52+ pageSize: USER_PAGE_SIZE,
53+ clientMode: false,
54+ fetch: getUsers,
55+ });
56+ },
57+ );
58+
59+ const total = () => list()?.total ?? 0;
60+ const visibleUsers = () => list()?.items ?? [];
61+ const totalPages = createMemo(() => pagesOf(total(), USER_PAGE_SIZE));
62+ const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
63+ const roleCount = (role: Role) => stats()?.filter((user) => user.role === role).length ?? 0;
39 64
40 const onRoleChange = async (userId: string, role: Role) => {65 const onRoleChange = async (userId: string, role: Role) => {
41 setError("");66 setError("");
@@ -61,7 +86,7 @@ function AdminUsersContent() {
61 {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}86 {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}
62 87
63 <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">88 <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
64- <Metric label={t("common.all")} value={users()?.length ?? 0} />89+ <Metric label={t("common.all")} value={stats()?.length ?? total()} />
65 <For each={ROLES}>{(role) => <Metric label={t(`role.${role}` as MessageKey)} value={roleCount(role)} />}</For>90 <For each={ROLES}>{(role) => <Metric label={t(`role.${role}` as MessageKey)} value={roleCount(role)} />}</For>
66 </section>91 </section>
67 92
@@ -69,9 +94,13 @@ function AdminUsersContent() {
69 <div class="flex flex-wrap items-center justify-between gap-3">94 <div class="flex flex-wrap items-center justify-between gap-3">
70 <div>95 <div>
71 <h2 class="font-display text-lg font-semibold">{t("nav.users")}</h2>96 <h2 class="font-display text-lg font-semibold">{t("nav.users")}</h2>
72- <p class="mt-1 text-sm text-muted-foreground">{visibleUsers().length} / {users()?.length ?? 0}</p>97+ <p class="mt-1 text-sm text-muted-foreground">
98+ {visibleUsers().length} / {total()}
99+ </p>
73 </div>100 </div>
74- <Badge variant="outline" class="mono rounded-sm uppercase tracking-[0.08em]">{t("admin.directory")}</Badge>101+ <Badge variant="outline" class="mono rounded-sm uppercase tracking-[0.08em]">
102+ {t("admin.directory")}
103+ </Badge>
75 </div>104 </div>
76 <DataToolbar105 <DataToolbar
77 filters={106 filters={
@@ -79,7 +108,10 @@ function AdminUsersContent() {
79 <UserSearchSelect108 <UserSearchSelect
80 id="admin-user-search"109 id="admin-user-search"
81 value={selectedUserId()}110 value={selectedUserId()}
82- onChange={setSelectedUserId}111+ onChange={(value) => {
112+ setSelectedUserId(value);
113+ setPage(0);
114+ }}
83 placeholder={t("common.searchPlaceholder")}115 placeholder={t("common.searchPlaceholder")}
84 selectPlaceholder={t("admin.username")}116 selectPlaceholder={t("admin.username")}
85 emptyMessage={t("admin.noUsers")}117 emptyMessage={t("admin.noUsers")}
@@ -88,16 +120,12 @@ function AdminUsersContent() {
88 }120 }
89 />121 />
90 <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>122 <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>
91- <Show when={users()}>123+ <Show when={list()}>
92- <Show124+ <Show when={visibleUsers().length > 0} fallback={<DataTableEmpty>{t("admin.noUsers")}</DataTableEmpty>}>
93- when={visibleUsers().length > 0}125+ <UserTable users={visibleUsers() as User[]} currentUserId={auth.user()!.id} onRoleChange={onRoleChange} />
94- fallback={<DataTableEmpty>{t("admin.noUsers")}</DataTableEmpty>}126+ <Show when={!selectedUserId().trim() && total() > USER_PAGE_SIZE}>
95- >127+ <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
96- <UserTable128+ </Show>
97- users={visibleUsers()}
98- currentUserId={auth.user()!.id}
99- onRoleChange={onRoleChange}
100- />
101 </Show>129 </Show>
102 </Show>130 </Show>
103 </Suspense>131 </Suspense>
src/pages/course-detail-page.tsxmodified+4 -4
@@ -65,8 +65,8 @@ function CourseDetailContent() {
65 });65 });
66 66
67 const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId));67 const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId));
68- const [terms] = createResource(() => getTerms());68+ const [terms] = createResource(async () => (await getTerms()).items);
69- const [exams, { refetch: refetchExams }] = createResource(id, (courseId) => getCourseExams(courseId));69+ const [exams, { refetch: refetchExams }] = createResource(id, async (courseId) => (await getCourseExams(courseId)).items);
70 const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher");70 const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher");
71 const hasCourseManagementRights = () => {71 const hasCourseManagementRights = () => {
72 const c = course();72 const c = course();
@@ -76,11 +76,11 @@ function CourseDetailContent() {
76 };76 };
77 const [roster, { refetch: refetchRoster }] = createResource(77 const [roster, { refetch: refetchRoster }] = createResource(
78 () => (hasCourseManagementRights() ? id() : null),78 () => (hasCourseManagementRights() ? id() : null),
79- async (courseId) => (courseId ? getCourseEnrollments(courseId) : []),79+ async (courseId) => (courseId ? (await getCourseEnrollments(courseId)).items : []),
80 );80 );
81 const [mine] = createResource(81 const [mine] = createResource(
82 () => (auth.user()?.role === "student" ? true : null),82 () => (auth.user()?.role === "student" ? true : null),
83- async (enabled) => (enabled ? getMyCourses() : []),83+ async (enabled) => (enabled ? (await getMyCourses()).items : []),
84 );84 );
85 85
86 const [editing, setEditing] = createSignal(false);86 const [editing, setEditing] = createSignal(false);
src/pages/courses-page.tsxmodified+115 -112
@@ -6,6 +6,7 @@ import { getTerms } from "@/api/getTerms";
6 import { getUsers } from "@/api/getUsers";6 import { getUsers } from "@/api/getUsers";
7 import { postCourse } from "@/api/postCourse";7 import { postCourse } from "@/api/postCourse";
8 import { formatApiError } from "@/api/client";8 import { formatApiError } from "@/api/client";
9+import type { Course } from "@/api/types";
9 import { Alert } from "@/components/ui/alert";10 import { Alert } from "@/components/ui/alert";
10 import { RouteGuard } from "@/components/layout/route-guard";11 import { RouteGuard } from "@/components/layout/route-guard";
11 import { PageHeader } from "@/components/layout/page-header";12 import { PageHeader } from "@/components/layout/page-header";
@@ -22,6 +23,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
22 import { TableRowActions } from "@/components/ui/table-row-actions";23 import { TableRowActions } from "@/components/ui/table-row-actions";
23 import { Textarea } from "@/components/ui/textarea";24 import { Textarea } from "@/components/ui/textarea";
24 import { PaginationControls } from "@/components/ui/pagination-controls";25 import { PaginationControls } from "@/components/ui/pagination-controls";
26+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
25 import { useAuth } from "@/stores/auth-context";27 import { useAuth } from "@/stores/auth-context";
26 import { useT } from "@/stores/preferences-context";28 import { useT } from "@/stores/preferences-context";
27 import { hasMinRole } from "@/lib/roles";29 import { hasMinRole } from "@/lib/roles";
@@ -40,20 +42,6 @@ function CoursesContent() {
40 const auth = useAuth();42 const auth = useAuth();
41 const navigate = useNavigate();43 const navigate = useNavigate();
42 const t = useT();44 const t = useT();
43- const [courses, { refetch }] = createResource(
44- () => (auth.user()?.role && auth.user()?.role !== "student" ? true : null),
45- async (enabled) => (enabled ? getCourses() : []),
46- );
47- const [terms] = createResource(() => getTerms());
48- const [users] = createResource(
49- () => (hasMinRole(auth.user()?.role, "manager") ? true : null),
50- async (enabled) => (enabled ? getUsers().catch(() => []) : []),
51- );
52- const [mine] = createResource(
53- () => (auth.user()?.role === "student" ? true : null),
54- async (enabled) => (enabled ? getMyCourses() : []),
55- );
56- const enrolled = () => new Set((mine() ?? []).map((c) => c.id));
57 const [showForm, setShowForm] = createSignal(false);45 const [showForm, setShowForm] = createSignal(false);
58 const [title, setTitle] = createSignal("");46 const [title, setTitle] = createSignal("");
59 const [description, setDescription] = createSignal("");47 const [description, setDescription] = createSignal("");
@@ -63,18 +51,27 @@ function CoursesContent() {
63 const [query, setQuery] = createSignal("");51 const [query, setQuery] = createSignal("");
64 const [termFilter, setTermFilter] = createSignal("all");52 const [termFilter, setTermFilter] = createSignal("all");
65 const [page, setPage] = createSignal(0);53 const [page, setPage] = createSignal(0);
54+
66 const canCreate = () => hasMinRole(auth.user()?.role, "teacher");55 const canCreate = () => hasMinRole(auth.user()?.role, "teacher");
67 const isStudent = () => auth.user()?.role === "student";56 const isStudent = () => auth.user()?.role === "student";
68- const courseList = createMemo(() => (isStudent() ? mine() : courses()) ?? []);57+ const clientFilterActive = () => query().trim() !== "" || termFilter() !== "all";
69- const termName = (termId: string | null | undefined) => terms()?.find((term) => term.id === termId)?.name ?? t("terms.unassigned");58+
59+ const [terms] = createResource(async () => (await getTerms()).items);
60+ const [users] = createResource(
61+ () => (hasMinRole(auth.user()?.role, "manager") ? true : null),
62+ async (enabled) => (enabled ? (await getUsers().catch(() => ({ items: [] as Awaited<ReturnType<typeof getUsers>>["items"] }))).items : []),
63+ );
64+
65+ const termName = (id: string | null | undefined) => terms()?.find((term) => term.id === id)?.name ?? t("terms.unassigned");
70 const creatorName = (creatorId: string) => {66 const creatorName = (creatorId: string) => {
71 if (creatorId === auth.user()?.id) return auth.user()?.username ?? creatorId;67 if (creatorId === auth.user()?.id) return auth.user()?.username ?? creatorId;
72 return users()?.find((user) => user.id === creatorId)?.username ?? creatorId;68 return users()?.find((user) => user.id === creatorId)?.username ?? creatorId;
73 };69 };
74- const filteredCourses = createMemo(() => {70+
71+ const filterCourses = (items: Course[]) => {
75 const needle = query().trim().toLocaleLowerCase();72 const needle = query().trim().toLocaleLowerCase();
76 const selectedTerm = termFilter();73 const selectedTerm = termFilter();
77- return courseList().filter((course) => {74+ return items.filter((course) => {
78 if (selectedTerm === "unassigned" && course.term_id) return false;75 if (selectedTerm === "unassigned" && course.term_id) return false;
79 if (selectedTerm !== "all" && selectedTerm !== "unassigned" && course.term_id !== selectedTerm) return false;76 if (selectedTerm !== "all" && selectedTerm !== "unassigned" && course.term_id !== selectedTerm) return false;
80 if (!needle) return true;77 if (!needle) return true;
@@ -83,13 +80,32 @@ function CoursesContent() {
83 .toLocaleLowerCase()80 .toLocaleLowerCase()
84 .includes(needle);81 .includes(needle);
85 });82 });
86- });83+ };
87- const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredCourses().length / COURSE_PAGE_SIZE)));84+
85+ const [list, { refetch }] = createResource(
86+ () => {
87+ const role = auth.user()?.role;
88+ if (!role) return null;
89+ return [role, page(), clientFilterActive() ? "1" : "0", query(), termFilter()].join("|");
90+ },
91+ async (key) => {
92+ const role = key.split("|")[0];
93+ const fetchPage = (params?: { limit?: number; offset?: number }) =>
94+ role === "student" ? getMyCourses(params) : getCourses(params);
95+ return loadListPage({
96+ page: page(),
97+ pageSize: COURSE_PAGE_SIZE,
98+ clientMode: clientFilterActive(),
99+ fetch: fetchPage,
100+ filter: filterCourses,
101+ });
102+ },
103+ );
104+
105+ const total = () => list()?.total ?? 0;
106+ const pageItems = () => list()?.items ?? [];
107+ const totalPages = createMemo(() => pagesOf(total(), COURSE_PAGE_SIZE));
88 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));108 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
89- const pageItems = createMemo(() => {
90- const start = safePage() * COURSE_PAGE_SIZE;
91- return filteredCourses().slice(start, start + COURSE_PAGE_SIZE);
92- });
93 109
94 const onCreate = async (e: SubmitEvent) => {110 const onCreate = async (e: SubmitEvent) => {
95 e.preventDefault();111 e.preventDefault();
@@ -141,23 +157,11 @@ function CoursesContent() {
141 <form class="space-y-3" onSubmit={onCreate}>157 <form class="space-y-3" onSubmit={onCreate}>
142 <div class="space-y-1.5">158 <div class="space-y-1.5">
143 <Label for="course-title">{t("form.title")}</Label>159 <Label for="course-title">{t("form.title")}</Label>
144- <Input160+ <Input id="course-title" required maxlength={200} value={title()} onInput={(e) => setTitle(e.currentTarget.value)} />
145- id="course-title"
146- required
147- maxlength={200}
148- value={title()}
149- onInput={(e) => setTitle(e.currentTarget.value)}
150- />
151 </div>161 </div>
152 <div class="space-y-1.5">162 <div class="space-y-1.5">
153 <Label for="course-desc">{t("form.description")}</Label>163 <Label for="course-desc">{t("form.description")}</Label>
154- <Textarea164+ <Textarea id="course-desc" maxlength={2000} rows={3} value={description()} onInput={(e) => setDescription(e.currentTarget.value)} />
155- id="course-desc"
156- maxlength={2000}
157- rows={3}
158- value={description()}
159- onInput={(e) => setDescription(e.currentTarget.value)}
160- />
161 </div>165 </div>
162 <div class="space-y-1.5">166 <div class="space-y-1.5">
163 <Label for="course-term">{t("terms.term")}</Label>167 <Label for="course-term">{t("terms.term")}</Label>
@@ -208,82 +212,81 @@ function CoursesContent() {
208 }212 }
209 />213 />
210 214
211- <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}>215+ <Suspense fallback={<DataTableSkeleton columns={5} rows={8} />}>
212- <Show when={courses.error}>216+ <Show when={list.error}>
213- <Alert variant="destructive">{formatApiError(courses.error)}</Alert>217+ <Alert variant="destructive">{formatApiError(list.error)}</Alert>
214- </Show>218+ </Show>
215- <Show219+ <Show when={pageItems().length > 0} fallback={<DataTableEmpty>{t("courses.empty")}</DataTableEmpty>}>
216- when={filteredCourses().length > 0}220+ <div class="space-y-4">
217- fallback={<DataTableEmpty>{t("courses.empty")}</DataTableEmpty>}221+ <div class="flex flex-wrap items-center justify-between gap-3">
218- >222+ <div>
219- <div class="space-y-4">223+ <h2 class="font-display text-lg font-semibold">{t("courses.title")}</h2>
220- <div class="flex flex-wrap items-center justify-between gap-3">224+ <p class="mt-1 text-sm text-muted-foreground">
221- <div>225+ {pageItems().length} / {total()} {t("nav.courses")}
222- <h2 class="font-display text-lg font-semibold">{t("courses.title")}</h2>226+ </p>
223- <p class="mt-1 text-sm text-muted-foreground">{filteredCourses().length} / {courseList().length} {t("nav.courses")}</p>227+ </div>
224 </div>228 </div>
229+ <DataTableFrame>
230+ <Table class="data-table table-fixed min-w-[56rem]">
231+ <colgroup>
232+ <col class="w-[28%]" />
233+ <col class="w-[30%]" />
234+ <col class="w-[14rem]" />
235+ <col class="w-[11rem]" />
236+ <col class="w-[3.5rem]" />
237+ </colgroup>
238+ <TableHeader>
239+ <TableRow>
240+ <TableHead>{t("courses.title")}</TableHead>
241+ <TableHead>{t("form.description")}</TableHead>
242+ <TableHead>{t("terms.term")}</TableHead>
243+ <TableHead>{t("common.creator")}</TableHead>
244+ <TableHead class="text-center">{t("common.actions")}</TableHead>
245+ </TableRow>
246+ </TableHeader>
247+ <TableBody>
248+ <For each={pageItems()}>
249+ {(course) => (
250+ <TableRow>
251+ <TableCell>
252+ <div class="min-w-0 space-y-1">
253+ <p class="truncate font-medium">{course.title}</p>
254+ <Show when={isStudent()}>
255+ <Badge variant="secondary" class="rounded-sm">{t("courses.enrolled")}</Badge>
256+ </Show>
257+ </div>
258+ </TableCell>
259+ <TableCell class="truncate text-muted-foreground">{course.description || "—"}</TableCell>
260+ <TableCell>
261+ <Badge variant="outline" class="mono max-w-full rounded-sm text-[11px]">
262+ <span class="truncate">{termName(course.term_id)}</span>
263+ </Badge>
264+ </TableCell>
265+ <TableCell class="truncate text-muted-foreground">{creatorName(course.creator)}</TableCell>
266+ <TableCell class="px-1 text-center">
267+ <TableRowActions
268+ label={t("common.actions")}
269+ actions={[
270+ {
271+ label: t("common.view"),
272+ icon: <IconEye class="h-4 w-4" />,
273+ onSelect: () => void navigate({ to: "/courses/$id", params: { id: course.id } }),
274+ },
275+ ]}
276+ />
277+ </TableCell>
278+ </TableRow>
279+ )}
280+ </For>
281+ </TableBody>
282+ </Table>
283+ </DataTableFrame>
284+ <Show when={total() > COURSE_PAGE_SIZE}>
285+ <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
286+ </Show>
225 </div>287 </div>
226- <DataTableFrame>288+ </Show>
227- <Table class="data-table table-fixed min-w-[56rem]">289+ </Suspense>
228- <colgroup>
229- <col class="w-[28%]" />
230- <col class="w-[30%]" />
231- <col class="w-[14rem]" />
232- <col class="w-[11rem]" />
233- <col class="w-[3.5rem]" />
234- </colgroup>
235- <TableHeader>
236- <TableRow>
237- <TableHead>{t("courses.title")}</TableHead>
238- <TableHead>{t("form.description")}</TableHead>
239- <TableHead>{t("terms.term")}</TableHead>
240- <TableHead>{t("common.creator")}</TableHead>
241- <TableHead class="text-center">{t("common.actions")}</TableHead>
242- </TableRow>
243- </TableHeader>
244- <TableBody>
245- <For each={pageItems()}>
246- {(course) => (
247- <TableRow>
248- <TableCell>
249- <div class="min-w-0 space-y-1">
250- <p class="truncate font-medium">{course.title}</p>
251- <Show when={enrolled().has(course.id)}>
252- <Badge variant="secondary" class="rounded-sm">{t("courses.enrolled")}</Badge>
253- </Show>
254- </div>
255- </TableCell>
256- <TableCell class="truncate text-muted-foreground">{course.description || "—"}</TableCell>
257- <TableCell>
258- <Badge variant="outline" class="mono max-w-full rounded-sm text-[11px]">
259- <span class="truncate">{termName(course.term_id)}</span>
260- </Badge>
261- </TableCell>
262- <TableCell class="truncate text-muted-foreground">{creatorName(course.creator)}</TableCell>
263- <TableCell class="px-1 text-center">
264- <TableRowActions
265- label={t("common.actions")}
266- actions={[
267- {
268- label: t("common.view"),
269- icon: <IconEye class="h-4 w-4" />,
270- onSelect: () => void navigate({ to: "/courses/$id", params: { id: course.id } }),
271- },
272- ]}
273- />
274- </TableCell>
275- </TableRow>
276- )}
277- </For>
278- </TableBody>
279- </Table>
280- </DataTableFrame>
281- <Show when={filteredCourses().length > COURSE_PAGE_SIZE}>
282- <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
283- </Show>
284- </div>
285- </Show>
286- </Suspense>
287 </section>290 </section>
288 </div>291 </div>
289 );292 );
src/pages/dashboard-page.tsxmodified+13 -11
@@ -89,15 +89,22 @@ function DashboardContent() {
89 89
90 const [courses] = createResource(90 const [courses] = createResource(
91 () => (role() !== "student" ? true : null),91 () => (role() !== "student" ? true : null),
92- async (enabled) => (enabled ? getCourses() : []),92+ async (enabled) => (enabled ? (await getCourses()).items : []),
93 );93 );
94 const [myCourses] = createResource(94 const [myCourses] = createResource(
95 () => (role() === "student" ? true : null),95 () => (role() === "student" ? true : null),
96- async (enabled) => (enabled ? getMyCourses().catch(() => []) : []),96+ async (enabled) => {
97+ if (!enabled) return [];
98+ try {
99+ return (await getMyCourses()).items;
100+ } catch {
101+ return [];
102+ }
103+ },
97 );104 );
98- const [events] = createResource(() => getEvents());105+ const [events] = createResource(async () => (await getEvents()).items);
99- const [exams] = createResource(() => getExams());106+ const [exams] = createResource(async () => (await getExams()).items);
100- const [notes] = createResource(() => getNotes());107+ const [notes] = createResource(async () => (await getNotes()).items);
101 const [marks] = createResource(108 const [marks] = createResource(
102 () => (role() === "student" ? true : null),109 () => (role() === "student" ? true : null),
103 async (enabled) => (enabled ? getMyMarks() : null),110 async (enabled) => (enabled ? getMyMarks() : null),
@@ -356,12 +363,7 @@ function UpcomingTimeline(props: {
356 <Show363 <Show
357 when={props.timeline.length > 0}364 when={props.timeline.length > 0}
358 fallback={365 fallback={
359- <div class="flex flex-col items-center gap-2 py-6 text-center">366+ <p class="py-6 text-center text-sm text-muted-foreground">{props.t("dashboard.upcomingEmpty")}</p>
360- <p class="text-sm text-muted-foreground">{props.t("dashboard.emptyEventsTitle")}</p>
361- <Link to="/events" class="text-sm font-medium text-primary hover:underline">
362- {props.t("dashboard.emptyEventsCta")}
363- </Link>
364- </div>
365 }367 }
366 >368 >
367 <div class="space-y-3">369 <div class="space-y-3">
src/pages/event-detail-page.tsxmodified+1 -1
@@ -59,7 +59,7 @@ function EventDetailContent() {
59 const [event, { refetch: refetchEvent }] = createResource(id, (eventId) => getEventById(eventId));59 const [event, { refetch: refetchEvent }] = createResource(id, (eventId) => getEventById(eventId));
60 const [attendance, { refetch: refetchAttendance }] = createResource(60 const [attendance, { refetch: refetchAttendance }] = createResource(
61 () => (isTeacherPlus() && attendanceOpen() ? id() : null),61 () => (isTeacherPlus() && attendanceOpen() ? id() : null),
62- async (eventId) => (eventId ? getEventAttendance(eventId) : []),62+ async (eventId) => (eventId ? (await getEventAttendance(eventId)).items : []),
63 );63 );
64 64
65 const canManage = () => {65 const canManage = () => {
src/pages/events-page.tsxmodified+57 -42
@@ -2,6 +2,7 @@ import { For, Show, Suspense, createMemo, createResource, createSignal } from "s
2 import { getEvents } from "@/api/getEvents";2 import { getEvents } from "@/api/getEvents";
3 import { postEvent } from "@/api/postEvent";3 import { postEvent } from "@/api/postEvent";
4 import { formatApiError } from "@/api/client";4 import { formatApiError } from "@/api/client";
5+import type { Event } from "@/api/types";
5 import { Alert } from "@/components/ui/alert";6 import { Alert } from "@/components/ui/alert";
6 import { Button } from "@/components/ui/button";7 import { Button } from "@/components/ui/button";
7 import { EventCard } from "@/components/events/event-card";8 import { EventCard } from "@/components/events/event-card";
@@ -14,10 +15,11 @@ import { PageSpinner } from "@/components/ui/page-spinner";
14 import { PaginationControls } from "@/components/ui/pagination-controls";15 import { PaginationControls } from "@/components/ui/pagination-controls";
15 import { Select } from "@/components/ui/select";16 import { Select } from "@/components/ui/select";
16 import { SidePanel } from "@/components/ui/side-panel";17 import { SidePanel } from "@/components/ui/side-panel";
17-import { useAuth } from "@/stores/auth-context";
18-import { usePreferences, useT } from "@/stores/preferences-context";
19 import { formatDateTime } from "@/lib/format";18 import { formatDateTime } from "@/lib/format";
19+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
20 import { hasMinRole } from "@/lib/roles";20 import { hasMinRole } from "@/lib/roles";
21+import { useAuth } from "@/stores/auth-context";
22+import { usePreferences, useT } from "@/stores/preferences-context";
21 23
22 const EVENT_PAGE_SIZE = 9;24 const EVENT_PAGE_SIZE = 9;
23 25
@@ -33,19 +35,19 @@ function EventsContent() {
33 const auth = useAuth();35 const auth = useAuth();
34 const { locale } = usePreferences();36 const { locale } = usePreferences();
35 const t = useT();37 const t = useT();
36- const [events, { refetch }] = createResource(() => getEvents());
37 const [error, setError] = createSignal("");38 const [error, setError] = createSignal("");
38 const [showForm, setShowForm] = createSignal(false);39 const [showForm, setShowForm] = createSignal(false);
39 const [query, setQuery] = createSignal("");40 const [query, setQuery] = createSignal("");
40 const [timeFilter, setTimeFilter] = createSignal("all");41 const [timeFilter, setTimeFilter] = createSignal("all");
41 const [page, setPage] = createSignal(0);42 const [page, setPage] = createSignal(0);
42 const canCreate = () => hasMinRole(auth.user()?.role, "teacher");43 const canCreate = () => hasMinRole(auth.user()?.role, "teacher");
43- const eventList = createMemo(() => events() ?? []);44+ const clientFilterActive = () => query().trim() !== "" || timeFilter() !== "all";
44- const filteredEvents = createMemo(() => {45+
46+ const filterEvents = (items: Event[]) => {
45 const needle = query().trim().toLocaleLowerCase();47 const needle = query().trim().toLocaleLowerCase();
46 const scope = timeFilter();48 const scope = timeFilter();
47 const now = Date.now();49 const now = Date.now();
48- return eventList().filter((event) => {50+ return items.filter((event) => {
49 if (scope === "upcoming" && event.ends_at != null && event.ends_at < now) return false;51 if (scope === "upcoming" && event.ends_at != null && event.ends_at < now) return false;
50 if (scope === "past" && (event.ends_at == null || event.ends_at >= now)) return false;52 if (scope === "past" && (event.ends_at == null || event.ends_at >= now)) return false;
51 if (!needle) return true;53 if (!needle) return true;
@@ -54,13 +56,24 @@ function EventsContent() {
54 .toLocaleLowerCase()56 .toLocaleLowerCase()
55 .includes(needle);57 .includes(needle);
56 });58 });
57- });59+ };
58- const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredEvents().length / EVENT_PAGE_SIZE)));60+
61+ const [list, { refetch }] = createResource(
62+ () => [page(), clientFilterActive() ? "1" : "0", query(), timeFilter()].join("|"),
63+ async () =>
64+ loadListPage({
65+ page: page(),
66+ pageSize: EVENT_PAGE_SIZE,
67+ clientMode: clientFilterActive(),
68+ fetch: getEvents,
69+ filter: filterEvents,
70+ }),
71+ );
72+
73+ const total = () => list()?.total ?? 0;
74+ const pageItems = () => list()?.items ?? [];
75+ const totalPages = createMemo(() => pagesOf(total(), EVENT_PAGE_SIZE));
59 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));76 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
60- const pageItems = createMemo(() => {
61- const start = safePage() * EVENT_PAGE_SIZE;
62- return filteredEvents().slice(start, start + EVENT_PAGE_SIZE);
63- });
64 77
65 return (78 return (
66 <div class="space-y-6">79 <div class="space-y-6">
@@ -87,30 +100,30 @@ function EventsContent() {
87 </div>100 </div>
88 101
89 <SidePanel open={canCreate() && showForm()} onOpenChange={setShowForm} title={t("events.create")} description={t("events.subtitle")}>102 <SidePanel open={canCreate() && showForm()} onOpenChange={setShowForm} title={t("events.create")} description={t("events.subtitle")}>
90- <EventForm103+ <EventForm
91- submitLabel={t("common.create")}104+ submitLabel={t("common.create")}
92- onCancel={() => setShowForm(false)}105+ onCancel={() => setShowForm(false)}
93- onSubmit={async (values) => {106+ onSubmit={async (values) => {
94- setError("");107+ setError("");
95- try {108+ try {
96- const body: {109+ const body: {
97- title: string;110+ title: string;
98- description?: string;111+ description?: string;
99- starts_at?: number | null;112+ starts_at?: number | null;
100- ends_at?: number | null;113+ ends_at?: number | null;
101- } = { title: values.title };114+ } = { title: values.title };
102- if (values.description) body.description = values.description;115+ if (values.description) body.description = values.description;
103- if (values.starts_at !== undefined) body.starts_at = values.starts_at;116+ if (values.starts_at !== undefined) body.starts_at = values.starts_at;
104- if (values.ends_at !== undefined) body.ends_at = values.ends_at;117+ if (values.ends_at !== undefined) body.ends_at = values.ends_at;
105- await postEvent(body);118+ await postEvent(body);
106- setShowForm(false);119+ setShowForm(false);
107- await refetch();120+ await refetch();
108- } catch (err) {121+ } catch (err) {
109- setError(formatApiError(err));122+ setError(formatApiError(err));
110- throw err;123+ throw err;
111- }124+ }
112- }}125+ }}
113- />126+ />
114 </SidePanel>127 </SidePanel>
115 128
116 {error() && <p class="text-sm text-destructive">{error()}</p>}129 {error() && <p class="text-sm text-destructive">{error()}</p>}
@@ -141,12 +154,12 @@ function EventsContent() {
141 />154 />
142 155
143 <Suspense fallback={<PageSpinner />}>156 <Suspense fallback={<PageSpinner />}>
144- <Show when={events.error}>157+ <Show when={list.error}>
145- <Alert variant="destructive">{formatApiError(events.error)}</Alert>158+ <Alert variant="destructive">{formatApiError(list.error)}</Alert>
146 </Show>159 </Show>
147- <Show when={events() !== undefined}>160+ <Show when={list() !== undefined}>
148 <Show161 <Show
149- when={filteredEvents().length > 0}162+ when={pageItems().length > 0}
150 fallback={163 fallback={
151 <div class="rounded-sm border border-dashed border-border bg-muted/20 px-6 py-16 text-center text-sm text-muted-foreground">164 <div class="rounded-sm border border-dashed border-border bg-muted/20 px-6 py-16 text-center text-sm text-muted-foreground">
152 {t("events.empty")}165 {t("events.empty")}
@@ -157,7 +170,9 @@ function EventsContent() {
157 <div class="flex flex-wrap items-center justify-between gap-3">170 <div class="flex flex-wrap items-center justify-between gap-3">
158 <div>171 <div>
159 <h2 class="font-display text-lg font-semibold">{t("events.title")}</h2>172 <h2 class="font-display text-lg font-semibold">{t("events.title")}</h2>
160- <p class="mt-1 text-sm text-muted-foreground">{filteredEvents().length} / {eventList().length} {t("nav.events")}</p>173+ <p class="mt-1 text-sm text-muted-foreground">
174+ {pageItems().length} / {total()} {t("nav.events")}
175+ </p>
161 </div>176 </div>
162 </div>177 </div>
163 <ul class="grid grid-cols-2 gap-3 xl:grid-cols-3">178 <ul class="grid grid-cols-2 gap-3 xl:grid-cols-3">
@@ -169,7 +184,7 @@ function EventsContent() {
169 )}184 )}
170 </For>185 </For>
171 </ul>186 </ul>
172- <Show when={filteredEvents().length > EVENT_PAGE_SIZE}>187+ <Show when={total() > EVENT_PAGE_SIZE}>
173 <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />188 <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
174 </Show>189 </Show>
175 </div>190 </div>
src/pages/exam-detail-page.tsxmodified+3 -3
@@ -110,7 +110,7 @@ function ExamDetailContent() {
110 () => (hasCourseManagementRights() && (openSections().results || gradeOpen() || sheetUserId()) ? id() : null),110 () => (hasCourseManagementRights() && (openSections().results || gradeOpen() || sheetUserId()) ? id() : null),
111 async (examId) => {111 async (examId) => {
112 if (!examId) return [];112 if (!examId) return [];
113- return getExamResults(examId);113+ return (await getExamResults(examId)).items;
114 },114 },
115 );115 );
116 const [stats] = createResource(116 const [stats] = createResource(
@@ -126,11 +126,11 @@ function ExamDetailContent() {
126 );126 );
127 const [roster] = createResource(127 const [roster] = createResource(
128 () => (hasCourseManagementRights() && gradeOpen() ? exam()?.course ?? null : null),128 () => (hasCourseManagementRights() && gradeOpen() ? exam()?.course ?? null : null),
129- async (courseId) => (courseId ? getCourseEnrollments(courseId) : []),129+ async (courseId) => (courseId ? (await getCourseEnrollments(courseId)).items : []),
130 );130 );
131 const [mine] = createResource(131 const [mine] = createResource(
132 () => (auth.user()?.role === "student" ? true : null),132 () => (auth.user()?.role === "student" ? true : null),
133- async (enabled) => (enabled ? getMyCourses() : []),133+ async (enabled) => (enabled ? (await getMyCourses()).items : []),
134 );134 );
135 135
136 const examStatus = () => {136 const examStatus = () => {
src/pages/exam-room-page.tsxmodified+1 -1
@@ -33,7 +33,7 @@ function ExamRoomContent() {
33 const [exam] = createResource(id, (examId) => getExamById(examId));33 const [exam] = createResource(id, (examId) => getExamById(examId));
34 const [mine] = createResource(34 const [mine] = createResource(
35 () => (auth.user()?.role === "student" ? true : null),35 () => (auth.user()?.role === "student" ? true : null),
36- async (enabled) => (enabled ? getMyCourses() : []),36+ async (enabled) => (enabled ? (await getMyCourses()).items : []),
37 );37 );
38 const canViewExam = () => {38 const canViewExam = () => {
39 const e = exam();39 const e = exam();
src/pages/exams-page.tsxmodified+75 -52
@@ -24,6 +24,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions";
24 import { createNow } from "@/lib/create-now";24 import { createNow } from "@/lib/create-now";
25 import { examKindLabel } from "@/lib/exam-labels";25 import { examKindLabel } from "@/lib/exam-labels";
26 import { formatDateTime } from "@/lib/format";26 import { formatDateTime } from "@/lib/format";
27+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
27 import { hasMinRole } from "@/lib/roles";28 import { hasMinRole } from "@/lib/roles";
28 import { cn } from "@/lib/cn";29 import { cn } from "@/lib/cn";
29 import { useAuth } from "@/stores/auth-context";30 import { useAuth } from "@/stores/auth-context";
@@ -47,15 +48,6 @@ function ExamsContent() {
47 const t = useT();48 const t = useT();
48 const { locale } = usePreferences();49 const { locale } = usePreferences();
49 const now = createNow();50 const now = createNow();
50- const [exams, { refetch: refetchExams }] = createResource(() => getExams());
51- const [courses] = createResource(
52- () => (auth.user()?.role && auth.user()?.role !== "student" ? true : null),
53- async (enabled) => (enabled ? getCourses() : []),
54- );
55- const [mine] = createResource(
56- () => (auth.user()?.role === "student" ? true : null),
57- async (enabled) => (enabled ? getMyCourses() : []),
58- );
59 const [query, setQuery] = createSignal("");51 const [query, setQuery] = createSignal("");
60 const [statusFilter, setStatusFilter] = createSignal<ExamStatus | "all">("all");52 const [statusFilter, setStatusFilter] = createSignal<ExamStatus | "all">("all");
61 const [courseFilter, setCourseFilter] = createSignal("all");53 const [courseFilter, setCourseFilter] = createSignal("all");
@@ -65,7 +57,15 @@ function ExamsContent() {
65 const [editingExam, setEditingExam] = createSignal<Exam | null>(null);57 const [editingExam, setEditingExam] = createSignal<Exam | null>(null);
66 const [page, setPage] = createSignal(0);58 const [page, setPage] = createSignal(0);
67 59
68- const canCreate = () => hasMinRole(auth.user()?.role, "teacher") && manageableCourses().length > 0;60+ const [courses] = createResource(
61+ () => (auth.user()?.role && auth.user()?.role !== "student" ? true : null),
62+ async (enabled) => (enabled ? (await getCourses()).items : []),
63+ );
64+ const [mine] = createResource(
65+ () => (auth.user()?.role === "student" ? true : null),
66+ async (enabled) => (enabled ? (await getMyCourses()).items : []),
67+ );
68+
69 const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher");69 const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher");
70 const isStudent = () => auth.user()?.role === "student";70 const isStudent = () => auth.user()?.role === "student";
71 const canEditExam = (exam: Exam) => exam.creator === auth.user()?.id || hasMinRole(auth.user()?.role, "manager");71 const canEditExam = (exam: Exam) => exam.creator === auth.user()?.id || hasMinRole(auth.user()?.role, "manager");
@@ -73,18 +73,9 @@ function ExamsContent() {
73 const manageableCourses = createMemo(() =>73 const manageableCourses = createMemo(() =>
74 visibleCourses().filter((course) => course.creator === auth.user()?.id || hasMinRole(auth.user()?.role, "manager")),74 visibleCourses().filter((course) => course.creator === auth.user()?.id || hasMinRole(auth.user()?.role, "manager")),
75 );75 );
76+ const canCreate = () => hasMinRole(auth.user()?.role, "teacher") && manageableCourses().length > 0;
76 const courseById = createMemo(() => new Map(visibleCourses().map((course) => [course.id, course])));77 const courseById = createMemo(() => new Map(visibleCourses().map((course) => [course.id, course])));
77- const visibleExams = createMemo(() => {78+ const courseTitle = (courseId: string) => courseById().get(courseId)?.title ?? courseId;
78- const all = exams() ?? [];
79- if (!isStudent()) return all;
80- const allowed = new Set(visibleCourses().map((course) => course.id));
81- return all.filter((exam) => allowed.has(exam.course));
82- });
83-
84- createEffect(() => {
85- if (!createOpen() || selectedCourseId()) return;
86- setSelectedCourseId(manageableCourses()[0]?.id ?? "");
87- });
88 79
89 const examStatus = (exam: Exam): ExamStatus => {80 const examStatus = (exam: Exam): ExamStatus => {
90 if (exam.mode !== "sync" && exam.mode !== "async" && exam.mode !== "open") return "unscheduled";81 if (exam.mode !== "sync" && exam.mode !== "async" && exam.mode !== "open") return "unscheduled";
@@ -95,6 +86,53 @@ function ExamsContent() {
95 return "active";86 return "active";
96 };87 };
97 88
89+ const clientFilterActive = () =>
90+ query().trim() !== "" || statusFilter() !== "all" || courseFilter() !== "all" || isStudent();
91+
92+ const filterExams = (items: Exam[]) => {
93+ const allowed = isStudent() ? new Set(visibleCourses().map((course) => course.id)) : null;
94+ const needle = query().trim().toLocaleLowerCase(locale());
95+ return items.filter((exam) => {
96+ if (allowed && !allowed.has(exam.course)) return false;
97+ if (statusFilter() !== "all" && examStatus(exam) !== statusFilter()) return false;
98+ if (courseFilter() !== "all" && exam.course !== courseFilter()) return false;
99+ if (!needle) return true;
100+ return [exam.title, exam.description, courseTitle(exam.course), examKindLabel(String(exam.kind), t)]
101+ .join(" ")
102+ .toLocaleLowerCase(locale())
103+ .includes(needle);
104+ });
105+ };
106+
107+ const [list, { refetch: refetchExams }] = createResource(
108+ () => {
109+ // Do not track now() here — it ticks every second and would re-fetch forever.
110+ if (isStudent() && mine() === undefined) return null;
111+ return [
112+ page(),
113+ clientFilterActive() ? "1" : "0",
114+ query(),
115+ statusFilter(),
116+ courseFilter(),
117+ isStudent() ? "s" : "t",
118+ (mine() ?? []).map((c) => c.id).join(","),
119+ ].join("|");
120+ },
121+ async () =>
122+ loadListPage({
123+ page: page(),
124+ pageSize: EXAM_PAGE_SIZE,
125+ clientMode: clientFilterActive(),
126+ fetch: getExams,
127+ filter: filterExams,
128+ }),
129+ );
130+
131+ createEffect(() => {
132+ if (!createOpen() || selectedCourseId()) return;
133+ setSelectedCourseId(manageableCourses()[0]?.id ?? "");
134+ });
135+
98 const statusLabel = (status: ExamStatus) => {136 const statusLabel = (status: ExamStatus) => {
99 if (status === "unscheduled") return t("exams.unscheduled");137 if (status === "unscheduled") return t("exams.unscheduled");
100 if (status === "finished") return t("exams.finished");138 if (status === "finished") return t("exams.finished");
@@ -108,29 +146,10 @@ function ExamsContent() {
108 return "border-muted bg-muted/50 text-muted-foreground";146 return "border-muted bg-muted/50 text-muted-foreground";
109 };147 };
110 148
111- const courseTitle = (courseId: string) => courseById().get(courseId)?.title ?? courseId;149+ const total = () => list()?.total ?? 0;
112- const matchesQuery = (exam: Exam) => {150+ const pageItems = () => list()?.items ?? [];
113- const needle = query().trim().toLocaleLowerCase(locale());151+ const totalPages = createMemo(() => pagesOf(total(), EXAM_PAGE_SIZE));
114- if (!needle) return true;
115- return [exam.title, exam.description, courseTitle(exam.course), examKindLabel(String(exam.kind), t)]
116- .join(" ")
117- .toLocaleLowerCase(locale())
118- .includes(needle);
119- };
120- const filteredExams = createMemo(() =>
121- visibleExams().filter((exam) => {
122- if (!matchesQuery(exam)) return false;
123- if (statusFilter() !== "all" && examStatus(exam) !== statusFilter()) return false;
124- if (courseFilter() !== "all" && exam.course !== courseFilter()) return false;
125- return true;
126- }),
127- );
128- const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredExams().length / EXAM_PAGE_SIZE)));
129 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));152 const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
130- const pageItems = createMemo(() => {
131- const start = safePage() * EXAM_PAGE_SIZE;
132- return filteredExams().slice(start, start + EXAM_PAGE_SIZE);
133- });
134 153
135 const createExam = async (values: ExamFormValues) => {154 const createExam = async (values: ExamFormValues) => {
136 const courseId = selectedCourseId();155 const courseId = selectedCourseId();
@@ -220,8 +239,8 @@ function ExamsContent() {
220 />239 />
221 240
222 <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>241 <Suspense fallback={<DataTableSkeleton columns={6} rows={8} />}>
223- <Show when={exams.error}>242+ <Show when={list.error}>
224- <Alert variant="destructive">{formatApiError(exams.error)}</Alert>243+ <Alert variant="destructive">{formatApiError(list.error)}</Alert>
225 </Show>244 </Show>
226 <Show when={pageItems().length > 0} fallback={<DataTableEmpty>{t("exams.empty")}</DataTableEmpty>}>245 <Show when={pageItems().length > 0} fallback={<DataTableEmpty>{t("exams.empty")}</DataTableEmpty>}>
227 <DataTableFrame>246 <DataTableFrame>
@@ -274,11 +293,13 @@ function ExamsContent() {
274 onSelect: () => void navigate({ to: "/exams/$id", params: { id: exam.id } }),293 onSelect: () => void navigate({ to: "/exams/$id", params: { id: exam.id } }),
275 },294 },
276 ...(isTeacherPlus() && canEditExam(exam)295 ...(isTeacherPlus() && canEditExam(exam)
277- ? [{296+ ? [
278- label: t("common.edit"),297+ {
279- icon: <IconEdit class="h-4 w-4" />,298+ label: t("common.edit"),
280- onSelect: () => setEditingExam(exam),299+ icon: <IconEdit class="h-4 w-4" />,
281- }]300+ onSelect: () => setEditingExam(exam),
301+ },
302+ ]
282 : []),303 : []),
283 ]}304 ]}
284 />305 />
@@ -293,14 +314,16 @@ function ExamsContent() {
293 </Show>314 </Show>
294 </Suspense>315 </Suspense>
295 316
296- <Show when={filteredExams().length > EXAM_PAGE_SIZE}>317+ <Show when={total() > EXAM_PAGE_SIZE}>
297 <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />318 <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
298 </Show>319 </Show>
299 </section>320 </section>
300 321
301 <SidePanel open={createOpen()} onOpenChange={setCreateOpen} title={t("exams.create")} description={t("exams.subtitle")}>322 <SidePanel open={createOpen()} onOpenChange={setCreateOpen} title={t("exams.create")} description={t("exams.subtitle")}>
302 <div class="mb-4 space-y-1.5">323 <div class="mb-4 space-y-1.5">
303- <label class="text-sm font-medium" for="exam-course">{t("exams.selectCourse")}</label>324+ <label class="text-sm font-medium" for="exam-course">
325+ {t("exams.selectCourse")}
326+ </label>
304 <Select id="exam-course" class="rounded-sm" value={selectedCourseId()} required onChange={(event) => setSelectedCourseId(event.currentTarget.value)}>327 <Select id="exam-course" class="rounded-sm" value={selectedCourseId()} required onChange={(event) => setSelectedCourseId(event.currentTarget.value)}>
305 <option value="">{t("exams.selectCourse")}</option>328 <option value="">{t("exams.selectCourse")}</option>
306 <For each={manageableCourses()}>{(course: Course) => <option value={course.id}>{course.title}</option>}</For>329 <For each={manageableCourses()}>{(course: Course) => <option value={course.id}>{course.title}</option>}</For>
src/pages/notes-page.tsxmodified+45 -29
@@ -1,4 +1,4 @@
1-import { createResource, Show, Suspense, createSignal } from "solid-js";1+import { Show, Suspense, createMemo, createResource, createSignal } from "solid-js";
2 import { deleteNoteById } from "@/api/deleteNoteById";2 import { deleteNoteById } from "@/api/deleteNoteById";
3 import { getNotes } from "@/api/getNotes";3 import { getNotes } from "@/api/getNotes";
4 import { patchNoteById } from "@/api/patchNoteById";4 import { patchNoteById } from "@/api/patchNoteById";
@@ -13,8 +13,12 @@ import { Button } from "@/components/ui/button";
13 import { FormDialog } from "@/components/ui/form-dialog";13 import { FormDialog } from "@/components/ui/form-dialog";
14 import { IconPlus } from "@/components/ui/icons";14 import { IconPlus } from "@/components/ui/icons";
15 import { PageSpinner } from "@/components/ui/page-spinner";15 import { PageSpinner } from "@/components/ui/page-spinner";
16+import { PaginationControls } from "@/components/ui/pagination-controls";
17+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
16 import { useT } from "@/stores/preferences-context";18 import { useT } from "@/stores/preferences-context";
17 19
20+const NOTE_PAGE_SIZE = 12;
21+
18 export default function NotesPage() {22 export default function NotesPage() {
19 return (23 return (
20 <RouteGuard>24 <RouteGuard>
@@ -25,9 +29,25 @@ export default function NotesPage() {
25 29
26 function NotesContent() {30 function NotesContent() {
27 const t = useT();31 const t = useT();
28- const [notes, { refetch }] = createResource(() => getNotes());
29 const [error, setError] = createSignal("");32 const [error, setError] = createSignal("");
30 const [createOpen, setCreateOpen] = createSignal(false);33 const [createOpen, setCreateOpen] = createSignal(false);
34+ const [page, setPage] = createSignal(0);
35+
36+ const [list, { refetch }] = createResource(
37+ () => page(),
38+ async (currentPage) =>
39+ loadListPage({
40+ page: currentPage,
41+ pageSize: NOTE_PAGE_SIZE,
42+ clientMode: false,
43+ fetch: getNotes,
44+ }),
45+ );
46+
47+ const total = () => list()?.total ?? 0;
48+ const pageItems = () => list()?.items ?? [];
49+ const totalPages = createMemo(() => pagesOf(total(), NOTE_PAGE_SIZE));
50+ const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
31 51
32 const wrap = async (fn: () => Promise<void>) => {52 const wrap = async (fn: () => Promise<void>) => {
33 setError("");53 setError("");
@@ -59,12 +79,7 @@ function NotesContent() {
59 />79 />
60 </div>80 </div>
61 81
62- <FormDialog82+ <FormDialog open={createOpen()} onOpenChange={setCreateOpen} title={t("notes.new")} description={t("notes.subtitle")}>
63- open={createOpen()}
64- onOpenChange={setCreateOpen}
65- title={t("notes.new")}
66- description={t("notes.subtitle")}
67- >
68 <NoteForm83 <NoteForm
69 submitLabel={t("common.create")}84 submitLabel={t("common.create")}
70 onCancel={() => setCreateOpen(false)}85 onCancel={() => setCreateOpen(false)}
@@ -80,29 +95,30 @@ function NotesContent() {
80 </FormDialog>95 </FormDialog>
81 96
82 <div class="space-y-5">97 <div class="space-y-5">
83- <section class="min-w-0">98+ <section class="min-w-0 space-y-4">
84- {error() && <p class="mb-3 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}99+ {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>}
85 <Suspense fallback={<PageSpinner />}>100 <Suspense fallback={<PageSpinner />}>
86- <Show when={notes.error}>101+ <Show when={list.error}>
87- <Alert variant="destructive">{formatApiError(notes.error)}</Alert>102+ <Alert variant="destructive">{formatApiError(list.error)}</Alert>
88 </Show>103 </Show>
89- <Show when={notes()}>104+ <Show when={list()}>
90- {(list) => (105+ <NoteList
91- <NoteList106+ notes={pageItems()}
92- notes={list()}107+ emptyLabel={t("notes.empty")}
93- emptyLabel={t("notes.empty")}108+ onUpdate={(id, values) =>
94- onUpdate={(id, values) =>109+ wrap(async () => {
95- wrap(async () => {110+ await patchNoteById(id, values);
96- await patchNoteById(id, values);111+ })
97- })112+ }
98- }113+ onDelete={(id) =>
99- onDelete={(id) =>114+ wrap(async () => {
100- wrap(async () => {115+ await deleteNoteById(id);
101- await deleteNoteById(id);116+ })
102- })117+ }
103- }118+ />
104- />119+ <Show when={total() > NOTE_PAGE_SIZE}>
105- )}120+ <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
121+ </Show>
106 </Show>122 </Show>
107 </Suspense>123 </Suspense>
108 </section>124 </section>
src/pages/terms-page.tsxmodified+27 -6
@@ -1,4 +1,4 @@
1-import { For, Show, Suspense, createResource, createSignal } from "solid-js";1+import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js";
2 import { deleteTermById } from "@/api/deleteTermById";2 import { deleteTermById } from "@/api/deleteTermById";
3 import { getTerms } from "@/api/getTerms";3 import { getTerms } from "@/api/getTerms";
4 import { patchTermById } from "@/api/patchTermById";4 import { patchTermById } from "@/api/patchTermById";
@@ -16,12 +16,16 @@ import { ErrorAlert } from "@/components/ui/error-alert";
16 import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";16 import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
17 import { Input } from "@/components/ui/input";17 import { Input } from "@/components/ui/input";
18 import { Label } from "@/components/ui/label";18 import { Label } from "@/components/ui/label";
19+import { PaginationControls } from "@/components/ui/pagination-controls";
19 import { SidePanel } from "@/components/ui/side-panel";20 import { SidePanel } from "@/components/ui/side-panel";
20 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";21 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
21 import { TableRowActions } from "@/components/ui/table-row-actions";22 import { TableRowActions } from "@/components/ui/table-row-actions";
22 import { formatDateTime } from "@/lib/format";23 import { formatDateTime } from "@/lib/format";
24+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
23 import { usePreferences, useT } from "@/stores/preferences-context";25 import { usePreferences, useT } from "@/stores/preferences-context";
24 26
27+const TERM_PAGE_SIZE = 12;
28+
25 function dateInputFromMs(ms: number): string {29 function dateInputFromMs(ms: number): string {
26 const date = new Date(ms);30 const date = new Date(ms);
27 const pad = (n: number) => String(n).padStart(2, "0");31 const pad = (n: number) => String(n).padStart(2, "0");
@@ -51,7 +55,21 @@ export default function TermsPage() {
51 function TermsContent() {55 function TermsContent() {
52 const t = useT();56 const t = useT();
53 const { locale } = usePreferences();57 const { locale } = usePreferences();
54- const [terms, { refetch }] = createResource(() => getTerms());58+ const [page, setPage] = createSignal(0);
59+ const [list, { refetch }] = createResource(
60+ () => page(),
61+ async (currentPage) =>
62+ loadListPage({
63+ page: currentPage,
64+ pageSize: TERM_PAGE_SIZE,
65+ clientMode: false,
66+ fetch: getTerms,
67+ }),
68+ );
69+ const total = () => list()?.total ?? 0;
70+ const terms = () => list()?.items ?? [];
71+ const totalPages = createMemo(() => pagesOf(total(), TERM_PAGE_SIZE));
72+ const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
55 const [panelOpen, setPanelOpen] = createSignal(false);73 const [panelOpen, setPanelOpen] = createSignal(false);
56 const [name, setName] = createSignal("");74 const [name, setName] = createSignal("");
57 const [starts, setStarts] = createSignal("");75 const [starts, setStarts] = createSignal("");
@@ -142,10 +160,10 @@ function TermsContent() {
142 160
143 <section class="data-shell space-y-4 p-4">161 <section class="data-shell space-y-4 p-4">
144 <Suspense fallback={<DataTableSkeleton columns={4} rows={6} />}>162 <Suspense fallback={<DataTableSkeleton columns={4} rows={6} />}>
145- <Show when={terms.error}>163+ <Show when={list.error}>
146- <ErrorAlert message={formatApiError(terms.error)} onRetry={() => void refetch()} />164+ <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} />
147 </Show>165 </Show>
148- <Show when={(terms() ?? []).length > 0} fallback={<DataTableEmpty>{t("terms.empty")}</DataTableEmpty>}>166+ <Show when={terms().length > 0} fallback={<DataTableEmpty>{t("terms.empty")}</DataTableEmpty>}>
149 <DataTableFrame>167 <DataTableFrame>
150 <Table class="data-table min-w-[40rem]">168 <Table class="data-table min-w-[40rem]">
151 <TableHeader>169 <TableHeader>
@@ -157,7 +175,7 @@ function TermsContent() {
157 </TableRow>175 </TableRow>
158 </TableHeader>176 </TableHeader>
159 <TableBody>177 <TableBody>
160- <For each={terms() ?? []}>178+ <For each={terms()}>
161 {(term) => (179 {(term) => (
162 <TableRow>180 <TableRow>
163 <TableCell class="font-medium">{term.name}</TableCell>181 <TableCell class="font-medium">{term.name}</TableCell>
@@ -187,6 +205,9 @@ function TermsContent() {
187 </TableBody>205 </TableBody>
188 </Table>206 </Table>
189 </DataTableFrame>207 </DataTableFrame>
208+ <Show when={total() > TERM_PAGE_SIZE}>
209+ <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
210+ </Show>
190 </Show>211 </Show>
191 </Suspense>212 </Suspense>
192 </section>213 </section>
src/pages/work-log-page.tsxmodified+44 -9
@@ -11,10 +11,14 @@ import { Button } from "@/components/ui/button";
11 import { DataTableFrame } from "@/components/ui/data-table";11 import { DataTableFrame } from "@/components/ui/data-table";
12 import { ErrorAlert } from "@/components/ui/error-alert";12 import { ErrorAlert } from "@/components/ui/error-alert";
13 import { PageSpinner } from "@/components/ui/page-spinner";13 import { PageSpinner } from "@/components/ui/page-spinner";
14+import { PaginationControls } from "@/components/ui/pagination-controls";
14 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";15 import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
15 import { formatDateTime, formatDurationMinutes } from "@/lib/format";16 import { formatDateTime, formatDurationMinutes } from "@/lib/format";
17+import { loadListPage, totalPages as pagesOf } from "@/lib/list-page";
16 import { usePreferences, useT } from "@/stores/preferences-context";18 import { usePreferences, useT } from "@/stores/preferences-context";
17 19
20+const WORK_PAGE_SIZE = 15;
21+
18 export default function WorkLogPage() {22 export default function WorkLogPage() {
19 return (23 return (
20 <RouteGuard minRole="teacher">24 <RouteGuard minRole="teacher">
@@ -26,10 +30,32 @@ export default function WorkLogPage() {
26 function WorkLogContent() {30 function WorkLogContent() {
27 const t = useT();31 const t = useT();
28 const { locale } = usePreferences();32 const { locale } = usePreferences();
29- const [entries, { refetch }] = createResource(() => getMyWorkLog());
30 const [error, setError] = createSignal("");33 const [error, setError] = createSignal("");
31 const [pending, setPending] = createSignal(false);34 const [pending, setPending] = createSignal(false);
32- const openEntry = createMemo(() => (entries() ?? []).find((entry) => entry.check_out == null) ?? null);35+ const [page, setPage] = createSignal(0);
36+ const [version, setVersion] = createSignal(0);
37+
38+ const [openProbe, { refetch: refetchOpen }] = createResource(
39+ () => version(),
40+ async () => (await getMyWorkLog({ limit: 1, offset: 0 })).items,
41+ );
42+ const openEntry = createMemo(() => (openProbe() ?? []).find((entry) => entry.check_out == null) ?? null);
43+
44+ const [list, { refetch }] = createResource(
45+ () => ({ page: page(), version: version() }),
46+ async (key) =>
47+ loadListPage({
48+ page: key.page,
49+ pageSize: WORK_PAGE_SIZE,
50+ clientMode: false,
51+ fetch: getMyWorkLog,
52+ }),
53+ );
54+
55+ const total = () => list()?.total ?? 0;
56+ const pageItems = () => list()?.items ?? [];
57+ const totalPages = createMemo(() => pagesOf(total(), WORK_PAGE_SIZE));
58+ const safePage = createMemo(() => Math.min(page(), totalPages() - 1));
33 59
34 const toggle = async () => {60 const toggle = async () => {
35 setError("");61 setError("");
@@ -40,7 +66,9 @@ function WorkLogContent() {
40 } else {66 } else {
41 await postWorkCheckIn();67 await postWorkCheckIn();
42 }68 }
43- await refetch();69+ setPage(0);
70+ setVersion((value) => value + 1);
71+ await Promise.all([refetch(), refetchOpen()]);
44 } catch (err) {72 } catch (err) {
45 setError(formatApiError(err));73 setError(formatApiError(err));
46 } finally {74 } finally {
@@ -66,7 +94,9 @@ function WorkLogContent() {
66 <div>94 <div>
67 <h2 class="font-display text-xl font-semibold">{openEntry() ? t("work.checkedIn") : t("work.notCheckedIn")}</h2>95 <h2 class="font-display text-xl font-semibold">{openEntry() ? t("work.checkedIn") : t("work.notCheckedIn")}</h2>
68 <p class="mt-1 text-sm text-muted-foreground">96 <p class="mt-1 text-sm text-muted-foreground">
69- <Show when={openEntry()} fallback={t("work.ready")}>{(entry) => t("work.since", { time: formatDateTime(entry().check_in, locale()) })}</Show>97+ <Show when={openEntry()} fallback={t("work.ready")}>
98+ {(entry) => t("work.since", { time: formatDateTime(entry().check_in, locale()) })}
99+ </Show>
70 </p>100 </p>
71 </div>101 </div>
72 <Button type="button" size="lg" class="rounded-sm" variant={openEntry() ? "destructive" : "default"} disabled={pending()} onClick={() => void toggle()}>102 <Button type="button" size="lg" class="rounded-sm" variant={openEntry() ? "destructive" : "default"} disabled={pending()} onClick={() => void toggle()}>
@@ -78,14 +108,16 @@ function WorkLogContent() {
78 <section class="data-shell space-y-4 p-4">108 <section class="data-shell space-y-4 p-4">
79 <div class="flex flex-wrap items-center justify-between gap-2">109 <div class="flex flex-wrap items-center justify-between gap-2">
80 <h2 class="font-display text-lg font-semibold">{t("work.entries")}</h2>110 <h2 class="font-display text-lg font-semibold">{t("work.entries")}</h2>
81- <Badge variant="secondary" class="mono rounded-sm px-3 py-1">{entries()?.length ?? 0}</Badge>111+ <Badge variant="secondary" class="mono rounded-sm px-3 py-1">
112+ {total()}
113+ </Badge>
82 </div>114 </div>
83 <Suspense fallback={<PageSpinner />}>115 <Suspense fallback={<PageSpinner />}>
84- <Show when={entries.error}>116+ <Show when={list.error}>
85- <ErrorAlert message={formatApiError(entries.error)} onRetry={() => void refetch()} />117+ <ErrorAlert message={formatApiError(list.error)} onRetry={() => void refetch()} />
86 </Show>118 </Show>
87 <Show119 <Show
88- when={(entries() ?? []).length > 0}120+ when={pageItems().length > 0}
89 fallback={<div class="rounded-lg border border-dashed border-border/80 bg-muted/20 px-4 py-8 text-center text-sm text-muted-foreground">{t("work.empty")}</div>}121 fallback={<div class="rounded-lg border border-dashed border-border/80 bg-muted/20 px-4 py-8 text-center text-sm text-muted-foreground">{t("work.empty")}</div>}
90 >122 >
91 <DataTableFrame>123 <DataTableFrame>
@@ -99,7 +131,7 @@ function WorkLogContent() {
99 </TableRow>131 </TableRow>
100 </TableHeader>132 </TableHeader>
101 <TableBody>133 <TableBody>
102- <For each={entries() ?? []}>134+ <For each={pageItems()}>
103 {(entry) => (135 {(entry) => (
104 <TableRow>136 <TableRow>
105 <TableCell class="mono">{formatDateTime(entry.check_in, locale())}</TableCell>137 <TableCell class="mono">{formatDateTime(entry.check_in, locale())}</TableCell>
@@ -116,6 +148,9 @@ function WorkLogContent() {
116 </TableBody>148 </TableBody>
117 </Table>149 </Table>
118 </DataTableFrame>150 </DataTableFrame>
151+ <Show when={total() > WORK_PAGE_SIZE}>
152+ <PaginationControls page={safePage()} totalPages={totalPages()} onPageChange={setPage} />
153+ </Show>
119 </Show>154 </Show>
120 </Suspense>155 </Suspense>
121 </section>156 </section>