From 7befd0c20afe9987a3e4cdf297a8931902372c62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Wed, 15 Jul 2026 15:48:41 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=F0=9F=94=84=20server-pagination=20?= =?UTF-8?q?api=20pattern=20+=20role-scope-matrix=20doc=20-=20src/api/page.?= =?UTF-8?q?ts:=20shared=20Page,=20PageParams,=20pageQuery,=20normalizeP?= =?UTF-8?q?age=20-=20src/lib/list-page.ts:=20loadListPage=20helper=20(serv?= =?UTF-8?q?er=20or=20client=20pagination)=20-=20all=20listing=20API=20func?= =?UTF-8?q?tions:=20accept=20PageParams,=20return=20Page=20-=20pages:?= =?UTF-8?q?=20adopt=20loadListPage=20for=20pagination=20state=20management?= =?UTF-8?q?=20-=20docs/role-scope-matrix.md:=20full=20role=20access=20matr?= =?UTF-8?q?ix=20per=20page/nav/dashboard=20-=20docs/frontend-next-steps:?= =?UTF-8?q?=20sync=20pagination=20audit=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/frontend-next-steps.md | 29 +-- docs/role-scope-matrix.md | 81 +++++++ src/api/getCourseEnrollments.ts | 9 +- src/api/getCourseExams.ts | 10 +- src/api/getCourseSessions.ts | 10 +- src/api/getCourses.ts | 6 +- src/api/getEventAttendance.ts | 9 +- src/api/getEvents.ts | 6 +- src/api/getExamQuestions.ts | 10 +- src/api/getExamResults.ts | 9 +- src/api/getExams.ts | 6 +- src/api/getMyCourses.ts | 6 +- src/api/getMyWorkLog.ts | 6 +- src/api/getNotes.ts | 6 +- src/api/getSessionAttendance.ts | 10 +- src/api/getTerms.ts | 6 +- src/api/getUserSearch.ts | 12 +- src/api/getUsers.ts | 6 +- src/api/page.ts | 44 ++++ src/api/types.ts | 2 + src/components/exams/exam-questions-panel.tsx | 2 +- .../sessions/course-sessions-panel.tsx | 7 +- src/components/users/user-search-select.tsx | 2 +- src/i18n/messages.ts | 3 + src/lib/list-page.ts | 38 +++ src/pages/admin-users-page.tsx | 74 ++++-- src/pages/course-detail-page.tsx | 8 +- src/pages/courses-page.tsx | 227 +++++++++--------- src/pages/dashboard-page.tsx | 24 +- src/pages/event-detail-page.tsx | 2 +- src/pages/events-page.tsx | 99 ++++---- src/pages/exam-detail-page.tsx | 6 +- src/pages/exam-room-page.tsx | 2 +- src/pages/exams-page.tsx | 127 ++++++---- src/pages/notes-page.tsx | 74 +++--- src/pages/terms-page.tsx | 33 ++- src/pages/work-log-page.tsx | 53 +++- 37 files changed, 714 insertions(+), 350 deletions(-) create mode 100644 docs/role-scope-matrix.md create mode 100644 src/api/page.ts create mode 100644 src/lib/list-page.ts diff --git a/docs/frontend-next-steps.md b/docs/frontend-next-steps.md index 7072117..2ace9ed 100644 --- a/docs/frontend-next-steps.md +++ b/docs/frontend-next-steps.md @@ -18,7 +18,7 @@ validation, and list filtering cleanup. - Settings requests are cached and refreshed after settings patches. - Sidebar icons use local SVG wrappers to avoid large icon package module graphs. - Notes use a paper-style notebook card layout, a paper-style read dialog, and dialog-based create/edit/delete flows. -- Courses use client-side table search plus term/unassigned filters while backend pagination/filter params are pending. +- List endpoints return `{ items, total, limit, offset }`. API helpers under `src/api/` accept optional `limit`/`offset` via `Page`. - Events keep card rendering with shared toolbar search and all/upcoming/past filters. - Event, exam, and lesson-session schedule forms use `GET /time` for server-clock-aware past-date warnings before submit. - Start/end date-time rows use equal-width date and time controls. @@ -40,29 +40,22 @@ validation, and list filtering cleanup. ## Request And Pagination Result -- `/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. -- `/exams`: client-paginated after `GET /exams`. Student filters use `GET /courses/me`; teacher+ filters use `GET /courses`. -- `/events`: client-paginated after `GET /events`. Toolbar search and all/upcoming/past filters are client-side. -- `/admin/users`: unpaginated `GET /users` plus client filtering/search UI. Admin-only. -- `/work`: unpaginated `GET /work/me`, newest first. Personal staff log. -- `/courses/:id` exams: unpaginated `GET /courses/{id}/exams`; course-scoped. -- `/courses/:id` sessions: unpaginated `GET /courses/{id}/sessions`, deferred until sessions section or create panel is opened. -- `/courses/:id` roster: unpaginated `GET /courses/{id}/enrollments`, course-management only. -- `/events/:id` attendance: unpaginated `GET /events/{id}/attendance`, teacher+ only and deferred until the attendance disclosure opens. -- `/exams/:id` results: unpaginated `GET /exams/{id}/results`, deferred until results/grade/answer-sheet workflow needs it. -- `/exams/:id` questions: unpaginated `GET /exams/{id}/questions`, deferred until questions section is opened. -- `/exams/:id/live`: client-paginated/sorted live roster over backend snapshot/SSE. -- `/attendance` and `/management/student-attendance`: unpaginated report payloads; backend returns aggregate report shape, not a raw row list. +- Backend list contract: `?limit=&offset=` → `{ items, total, limit, offset }` (opt-in; omit `limit` for full `items`). +- Shared helpers: `src/api/page.ts` + `src/lib/list-page.ts` (`loadListPage`). +- All paged list API files return `Page` and accept optional page params. +- Main lists use real server paging (`limit`/`offset` + `total`) when no client-only filter is active: + - courses, exams, events (hybrid: full fetch only while search/status/term filters need it) + - notes, terms, work log, admin users (server page; admin metrics still load full list once) +- Nested/deferred lists unwrap full `.items` (sessions, enrollments, attendance, exam results/questions). +- `/exams/:id/live`: client-paginated roster over snapshot/SSE (not the list envelope). +- `/attendance` and marks reports: not paged; aggregate report shapes. ## Backend-Dependent Follow-Up -- Backend pagination/search/filter params have been requested. -- Do not claim true server-side pagination until those params exist in the backend README/API contract. -- When backend params arrive, update `src/api/*` helpers first and then move toolbar/search/filter/page state into request params. +- Server-side search/filter params are still absent; hybrid full-fetch remains for client filters until the API adds them. ## Active Backlog -- Backend server-side pagination/search/filter params still pending (see Backend-Dependent Follow-Up). - Deferred product features (not started): exam `allow_rejoin` UI, manager work-log corrections, session edit (`PATCH`). ## UX polish batch (completed) diff --git a/docs/role-scope-matrix.md b/docs/role-scope-matrix.md new file mode 100644 index 0000000..5d5e577 --- /dev/null +++ b/docs/role-scope-matrix.md @@ -0,0 +1,81 @@ +# Rol Kapsamı Matrisi + +## Sayfa Bazında Erişim + +| Sayfa / Özellik | Öğrenci | Öğretmen | Müdür | Admin | +|---|---|---|---|---| +| Ana sayfa `/` | ✅ | ✅ | ✅ | ✅ | +| Profil `/profile` | ✅ | ✅ | ✅ | ✅ | +| Rehber `/guide` | ✅ | ✅ | ✅ | ✅ | +| Notlar `/notes` | ✅ | ✅ | ✅ | ✅ | +| Dersler `/courses` | ✅ | ✅ | ✅ | ✅ | +| Ders detay `/courses/:id` | ✅ | ✅ | ✅ | ✅ | +| Sınavlar `/exams` | ✅ | ✅ | ✅ | ✅ | +| Sınav detay `/exams/:id` | ✅ | ✅ | ✅ | ✅ | +| Sınav salonu `/exam-room/:id` | ✅ | ❌ | ❌ | ❌ | +| Canlı monitör `/exams/:id/live` | ❌ | ✅ | ✅ | ✅ | +| Etkinlikler `/events` | ✅ | ✅ | ✅ | ✅ | +| Etkinlik detay `/events/:id` | ✅ | ✅ | ✅ | ✅ | +| **Karnem `/marks`** | ✅ | ❌ | ❌ | ❌ | +| **Yoklamam `/attendance`** | ✅ | ❌ | ❌ | ❌ | +| Öğrenci not sorgula `/management/student-marks` | ❌ | ✅ | ✅ | ✅ | +| Öğrenci yoklama sorgula `/management/student-attendance` | ❌ | ✅ | ✅ | ✅ | +| Mesai `/work` | ❌ | ✅ | ✅ | ✅ | +| Ayarlar `/management/settings` | ❌ | ❌ | ✅ | ✅ | +| Dönemler `/management/terms` | ❌ | ❌ | ✅ | ✅ | +| Kullanıcı yönetimi `/admin/users` | ❌ | ❌ | ❌ | ✅ | + +## Sidebar’da Ne Görsün? + +| Sidebar grubu / item | Öğrenci | Öğretmen | Müdür | Admin | +|---|---|---|---|---| +| **classes** — Dersler / Sınavlar / Etkinlikler | ✅ | ✅ | ✅ | ✅ | +| **grades** — Karnem (`/marks`) | ✅ | ❌ | ❌ | ❌ | +| **grades** — Notlar | ✅ | ✅ | ✅ | ✅ | +| **students** — Yoklamam (`/attendance`) | ✅ | ❌ | ❌ | ❌ | +| **reports** — Öğrenci notları / yoklama / mesai | ❌ | ✅ | ✅ | ✅ | +| **settings** — Ayarlar / Dönemler | ❌ | ❌ | ✅ | ✅ | +| **admin** — Kullanıcılar | ❌ | ❌ | ❌ | ✅ | + +## Dashboard Portal Kartları + +| Kart | Öğrenci | Öğretmen | Müdür | Admin | +|---|---|---|---|---| +| Dersler | ✅ (kayıtlı) | ✅ | ✅ | ✅ | +| Sınavlar | ✅ (kayıtlı) | ✅ | ✅ | ✅ | +| Etkinlikler | ✅ | ✅ (teacher badge) | ✅ | ✅ | +| Karnem | ✅ | ❌ | ❌ | ❌ | +| Notlar | ✅ | ✅ | ✅ | ✅ | +| Öğrenci notları | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) | +| Öğrenci yoklaması | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) | +| Mesai | ❌ | ✅ (teacher badge) | ✅ (teacher badge) | ✅ (teacher badge) | +| Ayarlar | ❌ | ❌ | ✅ (manager badge) | ✅ (manager badge) | +| Dönemler | ❌ | ❌ | ✅ (manager badge) | ✅ (manager badge) | +| Kullanıcılar | ❌ | ❌ | ❌ | ✅ (admin badge) | + +## Tespit Edilen Hatalar + +| # | Hata | Dosya(lar) | Önem | +|---|---|---|---| +| 1 | `/marks` her role açık, RouteGuard yok, nav'da herkes görür | `marks-page.tsx`, `router.tsx`, `side-nav.tsx` | YÜKSEK | +| 2 | `/attendance` her role açık, RouteGuard yok, nav'da herkes görür | `attendance-page.tsx`, `router.tsx`, `side-nav.tsx` | YÜKSEK | +| 3 | `RouteGuard` student-only desteklemiyor (sadece `minRole` var) | `route-guard.tsx` | ORTA | +| 4 | `/work`, `/live`, `/settings`, `/terms` `beforeLoad` guard'ı yok (client-side RouteGuard var ama tutarsız) | `router.tsx` | DÜŞÜK | +| 5 | Sınav salonu butonu manager/admin'e görünüyor (tıklayınca hata) | `exam-detail-page.tsx` | DÜŞÜK | + +## Backend Notu + +Backend README Auth kolonunda: +- `GET /marks/me` = **student** +- `GET /attendance/me` = **student** +- `GET /marks/{user}` = **teacher** +- `GET /attendance/{user}` = **teacher** + +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ı. + +## Kullanılan Kısaltmalar + +- ✅ = erişim var +- ❌ = erişim yok +- FE = frontend (düzeltme sadece ön yüzde) +- BE = backend (düzeltme sunucu tarafında) diff --git a/src/api/getCourseEnrollments.ts b/src/api/getCourseEnrollments.ts index 42dda75..1b40451 100644 --- a/src/api/getCourseEnrollments.ts +++ b/src/api/getCourseEnrollments.ts @@ -1,9 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Enrollment } from "./types"; -export function getCourseEnrollments( +export async function getCourseEnrollments( courseId: string, + params?: PageParams, signal?: AbortSignal, -): Promise { - return client(`/courses/${courseId}/enrollments`, { signal }); +): Promise> { + const data = await client(`/courses/${courseId}/enrollments${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getCourseExams.ts b/src/api/getCourseExams.ts index 7d3ee36..c23b563 100644 --- a/src/api/getCourseExams.ts +++ b/src/api/getCourseExams.ts @@ -1,6 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Exam } from "./types"; -export function getCourseExams(courseId: string, signal?: AbortSignal): Promise { - return client(`/courses/${courseId}/exams`, { signal }); +export async function getCourseExams( + courseId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/courses/${courseId}/exams${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getCourseSessions.ts b/src/api/getCourseSessions.ts index 2a66cd4..c6fa49f 100644 --- a/src/api/getCourseSessions.ts +++ b/src/api/getCourseSessions.ts @@ -1,6 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { CourseSession } from "./types"; -export function getCourseSessions(courseId: string, signal?: AbortSignal): Promise { - return client(`/courses/${courseId}/sessions`, { signal }); +export async function getCourseSessions( + courseId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/courses/${courseId}/sessions${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getCourses.ts b/src/api/getCourses.ts index 87242ed..72bce4d 100644 --- a/src/api/getCourses.ts +++ b/src/api/getCourses.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Course } from "./types"; -export function getCourses(signal?: AbortSignal): Promise { - return client("/courses", { signal }); +export async function getCourses(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/courses${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getEventAttendance.ts b/src/api/getEventAttendance.ts index 85c99be..4d03e75 100644 --- a/src/api/getEventAttendance.ts +++ b/src/api/getEventAttendance.ts @@ -1,9 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Attendance } from "./types"; -export function getEventAttendance( +export async function getEventAttendance( eventId: string, + params?: PageParams, signal?: AbortSignal, -): Promise { - return client(`/events/${eventId}/attendance`, { signal }); +): Promise> { + const data = await client(`/events/${eventId}/attendance${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getEvents.ts b/src/api/getEvents.ts index be0d83b..1fec71b 100644 --- a/src/api/getEvents.ts +++ b/src/api/getEvents.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Event } from "./types"; -export function getEvents(signal?: AbortSignal): Promise { - return client("/events", { signal }); +export async function getEvents(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/events${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getExamQuestions.ts b/src/api/getExamQuestions.ts index d3c1b8d..098b2ca 100644 --- a/src/api/getExamQuestions.ts +++ b/src/api/getExamQuestions.ts @@ -1,6 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { ExamQuestion } from "./types"; -export function getExamQuestions(examId: string, signal?: AbortSignal): Promise { - return client(`/exams/${examId}/questions`, { signal }); +export async function getExamQuestions( + examId: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/exams/${examId}/questions${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getExamResults.ts b/src/api/getExamResults.ts index 9b6868b..d97333a 100644 --- a/src/api/getExamResults.ts +++ b/src/api/getExamResults.ts @@ -1,9 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { ExamResult } from "./types"; -export function getExamResults( +export async function getExamResults( examId: string, + params?: PageParams, signal?: AbortSignal, -): Promise { - return client(`/exams/${examId}/results`, { signal }); +): Promise> { + const data = await client(`/exams/${examId}/results${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getExams.ts b/src/api/getExams.ts index b010af4..04973bc 100644 --- a/src/api/getExams.ts +++ b/src/api/getExams.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Exam } from "./types"; -export function getExams(signal?: AbortSignal): Promise { - return client("/exams", { signal }); +export async function getExams(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/exams${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getMyCourses.ts b/src/api/getMyCourses.ts index e28969b..76341b1 100644 --- a/src/api/getMyCourses.ts +++ b/src/api/getMyCourses.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Course } from "./types"; -export function getMyCourses(signal?: AbortSignal): Promise { - return client("/courses/me", { signal }); +export async function getMyCourses(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/courses/me${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getMyWorkLog.ts b/src/api/getMyWorkLog.ts index ab7ee6b..903e747 100644 --- a/src/api/getMyWorkLog.ts +++ b/src/api/getMyWorkLog.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { WorkEntry } from "./types"; -export function getMyWorkLog(signal?: AbortSignal): Promise { - return client("/work/me", { signal }); +export async function getMyWorkLog(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/work/me${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getNotes.ts b/src/api/getNotes.ts index ca62705..451e659 100644 --- a/src/api/getNotes.ts +++ b/src/api/getNotes.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Note } from "./types"; -export function getNotes(signal?: AbortSignal): Promise { - return client("/notes", { signal }); +export async function getNotes(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/notes${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getSessionAttendance.ts b/src/api/getSessionAttendance.ts index 8599226..b323d7e 100644 --- a/src/api/getSessionAttendance.ts +++ b/src/api/getSessionAttendance.ts @@ -1,6 +1,12 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { SessionAttendance } from "./types"; -export function getSessionAttendance(id: string, signal?: AbortSignal): Promise { - return client(`/sessions/${id}/attendance`, { signal }); +export async function getSessionAttendance( + id: string, + params?: PageParams, + signal?: AbortSignal, +): Promise> { + const data = await client(`/sessions/${id}/attendance${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getTerms.ts b/src/api/getTerms.ts index f836f56..c82d133 100644 --- a/src/api/getTerms.ts +++ b/src/api/getTerms.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { Term } from "./types"; -export function getTerms(signal?: AbortSignal): Promise { - return client("/terms", { signal }); +export async function getTerms(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/terms${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getUserSearch.ts b/src/api/getUserSearch.ts index 4a3af3d..789e40b 100644 --- a/src/api/getUserSearch.ts +++ b/src/api/getUserSearch.ts @@ -1,8 +1,16 @@ import { client } from "./client"; +import { appendPageParams, normalizePage, type Page, type PageParams } from "./page"; import type { PersonRef, Role } from "./types"; -export function getUserSearch(query: string, signal?: AbortSignal, role?: Role): Promise { +export async function getUserSearch( + query: string, + signal?: AbortSignal, + role?: Role, + page?: PageParams, +): Promise> { const params = new URLSearchParams({ q: query }); if (role) params.set("role", role); - return client(`/users/search?${params.toString()}`, { signal }); + appendPageParams(params, page); + const data = await client(`/users/search?${params.toString()}`, { signal }); + return normalizePage(data); } diff --git a/src/api/getUsers.ts b/src/api/getUsers.ts index 4988640..9bdc415 100644 --- a/src/api/getUsers.ts +++ b/src/api/getUsers.ts @@ -1,6 +1,8 @@ import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; import type { User } from "./types"; -export function getUsers(signal?: AbortSignal): Promise { - return client("/users", { signal }); +export async function getUsers(params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/users${pageQuery(params)}`, { signal }); + return normalizePage(data); } diff --git a/src/api/page.ts b/src/api/page.ts new file mode 100644 index 0000000..0d93d9e --- /dev/null +++ b/src/api/page.ts @@ -0,0 +1,44 @@ +export type PageParams = { + limit?: number; + offset?: number; +}; + +export type Page = { + items: T[]; + total: number; + limit: number | null; + offset: number; +}; + +export function pageQuery(params?: PageParams): string { + if (!params) return ""; + const query = new URLSearchParams(); + if (params.limit != null) query.set("limit", String(params.limit)); + if (params.offset != null) query.set("offset", String(params.offset)); + const value = query.toString(); + return value ? `?${value}` : ""; +} + +export function appendPageParams(base: URLSearchParams, params?: PageParams): void { + if (!params) return; + if (params.limit != null) base.set("limit", String(params.limit)); + if (params.offset != null) base.set("offset", String(params.offset)); +} + +/** Accept Page envelope or legacy bare array so lists never crash on shape mismatch. */ +export function normalizePage(data: unknown): Page { + if (Array.isArray(data)) { + return { items: data as T[], total: data.length, limit: null, offset: 0 }; + } + if (data && typeof data === "object") { + const record = data as Record; + if (Array.isArray(record.items)) { + const items = record.items as T[]; + const total = typeof record.total === "number" ? record.total : items.length; + const limit = typeof record.limit === "number" ? record.limit : null; + const offset = typeof record.offset === "number" ? record.offset : 0; + return { items, total, limit, offset }; + } + } + return { items: [], total: 0, limit: null, offset: 0 }; +} diff --git a/src/api/types.ts b/src/api/types.ts index f43c1ed..05293d0 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,3 +1,5 @@ +export type { Page, PageParams } from "./page"; + export type Role = "student" | "teacher" | "manager" | "admin"; export type CoreAttendanceStatus = "present" | "absent" | "late" | "excused"; export type AttendanceStatus = CoreAttendanceStatus | string; diff --git a/src/components/exams/exam-questions-panel.tsx b/src/components/exams/exam-questions-panel.tsx index d5a2843..854f5cd 100644 --- a/src/components/exams/exam-questions-panel.tsx +++ b/src/components/exams/exam-questions-panel.tsx @@ -20,7 +20,7 @@ export function ExamQuestionsPanel(props: { examId: string; readOnly?: boolean; const t = useT(); const [questions, { refetch }] = createResource(() => props.examId, async (examId) => { try { - return await getExamQuestions(examId); + return (await getExamQuestions(examId)).items; } catch (err) { if (err instanceof ApiError && err.status === 404) return []; throw err; diff --git a/src/components/sessions/course-sessions-panel.tsx b/src/components/sessions/course-sessions-panel.tsx index b3e428c..9a93bca 100644 --- a/src/components/sessions/course-sessions-panel.tsx +++ b/src/components/sessions/course-sessions-panel.tsx @@ -53,7 +53,7 @@ export function CourseSessionsPanel(props: { const { locale } = usePreferences(); const [sessions, { refetch }] = createResource( () => (props.active || props.createOpen ? props.courseId : null), - async (courseId) => (courseId ? getCourseSessions(courseId) : []), + async (courseId) => (courseId ? (await getCourseSessions(courseId)).items : []), ); const [selectedSession, setSelectedSession] = createSignal(null); const [deleteTarget, setDeleteTarget] = createSignal(null); @@ -240,7 +240,10 @@ export function CourseSessionsPanel(props: { function RollCall(props: { sessionId: string; roster: Enrollment[] }) { const t = useT(); - const [attendance, { refetch }] = createResource(() => props.sessionId, (sessionId) => getSessionAttendance(sessionId)); + const [attendance, { refetch }] = createResource( + () => props.sessionId, + async (sessionId) => (await getSessionAttendance(sessionId)).items, + ); const rows = createMemo(() => new Map((attendance() ?? []).map((row) => [row.user.id, row]))); const [local, setLocal] = createSignal>({}); const [error, setError] = createSignal(""); diff --git a/src/components/users/user-search-select.tsx b/src/components/users/user-search-select.tsx index aff9080..83ba3c6 100644 --- a/src/components/users/user-search-select.tsx +++ b/src/components/users/user-search-select.tsx @@ -57,7 +57,7 @@ export function UserSearchSelect(props: { setLoading(true); try { const data = await getUserSearch(q, abortController.signal, props.role); - setUsers(data); + setUsers(data.items); } catch { if (!abortController?.signal.aborted) setUsers([]); } finally { diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 9cfce26..e9405f4 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -151,6 +151,7 @@ export type MessageKey = | "dashboard.emptyEventsTitle" | "dashboard.emptyNotesCta" | "dashboard.emptyEventsCta" + | "dashboard.upcomingEmpty" | "dashboard.viewAll" | "dashboard.getStarted" | "dashboard.helpTitle" @@ -635,6 +636,7 @@ const en: Dict = { "dashboard.emptyEventsTitle": "No events yet", "dashboard.emptyNotesCta": "Write a note", "dashboard.emptyEventsCta": "Browse events", + "dashboard.upcomingEmpty": "Nothing here.", "dashboard.viewAll": "View all", "dashboard.getStarted": "Get started", "dashboard.helpTitle": "Need a hand?", @@ -1131,6 +1133,7 @@ const tr: Dict = { "dashboard.emptyEventsTitle": "Henüz etkinlik yok", "dashboard.emptyNotesCta": "Not yaz", "dashboard.emptyEventsCta": "Etkinliklere git", + "dashboard.upcomingEmpty": "Burada bir şey yok.", "dashboard.viewAll": "Tümünü gör", "dashboard.getStarted": "Başla", "dashboard.helpTitle": "Yardıma mı ihtiyacın var?", diff --git a/src/lib/list-page.ts b/src/lib/list-page.ts new file mode 100644 index 0000000..9fef5f9 --- /dev/null +++ b/src/lib/list-page.ts @@ -0,0 +1,38 @@ +import type { Page, PageParams } from "@/api/page"; + +export type ListPageState = { + items: T[]; + total: number; +}; + +/** Server page when `clientMode` is false; full fetch + caller-supplied filter when true. */ +export async function loadListPage(options: { + page: number; + pageSize: number; + clientMode: boolean; + fetch: (params?: PageParams) => Promise>; + filter?: (items: T[]) => T[]; +}): Promise> { + if (options.clientMode) { + const all = await options.fetch(); + const source = Array.isArray(all.items) ? all.items : []; + const filtered = options.filter ? options.filter(source) : source; + const start = options.page * options.pageSize; + return { + items: filtered.slice(start, start + options.pageSize), + total: filtered.length, + }; + } + + const result = await options.fetch({ + limit: options.pageSize, + offset: options.page * options.pageSize, + }); + const items = Array.isArray(result.items) ? result.items : []; + const total = typeof result.total === "number" ? result.total : items.length; + return { items, total }; +} + +export function totalPages(total: number, pageSize: number): number { + return Math.max(1, Math.ceil(Math.max(0, total) / pageSize)); +} diff --git a/src/pages/admin-users-page.tsx b/src/pages/admin-users-page.tsx index c694ffb..e5e7e8b 100644 --- a/src/pages/admin-users-page.tsx +++ b/src/pages/admin-users-page.tsx @@ -2,7 +2,7 @@ import { For, Show, Suspense, createMemo, createResource, createSignal } from "s import { getUsers } from "@/api/getUsers"; import { patchUserRole } from "@/api/patchUserRole"; import { formatApiError } from "@/api/client"; -import type { Role } from "@/api/types"; +import type { Role, User } from "@/api/types"; import { RouteGuard } from "@/components/layout/route-guard"; import { PageHeader } from "@/components/layout/page-header"; import { UserSearchSelect } from "@/components/users/user-search-select"; @@ -10,11 +10,15 @@ import { UserTable } from "@/components/users/user-table"; import { Badge } from "@/components/ui/badge"; import { DataTableEmpty, DataTableSkeleton } from "@/components/ui/data-table"; import { DataToolbar } from "@/components/ui/data-toolbar"; +import { PaginationControls } from "@/components/ui/pagination-controls"; +import { loadListPage, totalPages as pagesOf } from "@/lib/list-page"; import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; import type { MessageKey } from "@/i18n/messages"; import { ROLES } from "@/lib/roles"; +const USER_PAGE_SIZE = 20; + export default function AdminUsersPage() { return ( @@ -26,16 +30,37 @@ export default function AdminUsersPage() { function AdminUsersContent() { const auth = useAuth(); const t = useT(); - const [users, { refetch }] = createResource(() => getUsers()); const [error, setError] = createSignal(""); const [selectedUserId, setSelectedUserId] = createSignal(""); - const visibleUsers = createMemo(() => { - const list = users() ?? []; - const id = selectedUserId().trim(); - if (!id) return list; - return list.filter((user) => user.id === id); - }); - const roleCount = (role: Role) => users()?.filter((user) => user.role === role).length ?? 0; + const [page, setPage] = createSignal(0); + + const [stats] = createResource(async () => (await getUsers()).items); + + const [list, { refetch }] = createResource( + () => ({ + page: page(), + selected: selectedUserId().trim(), + }), + async (key) => { + if (key.selected) { + const all = await getUsers(); + const match = all.items.filter((user) => user.id === key.selected); + return { items: match, total: match.length }; + } + return loadListPage({ + page: key.page, + pageSize: USER_PAGE_SIZE, + clientMode: false, + fetch: getUsers, + }); + }, + ); + + const total = () => list()?.total ?? 0; + const visibleUsers = () => list()?.items ?? []; + const totalPages = createMemo(() => pagesOf(total(), USER_PAGE_SIZE)); + const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); + const roleCount = (role: Role) => stats()?.filter((user) => user.role === role).length ?? 0; const onRoleChange = async (userId: string, role: Role) => { setError(""); @@ -61,7 +86,7 @@ function AdminUsersContent() { {error() &&

{error()}

}
- + {(role) => }
@@ -69,9 +94,13 @@ function AdminUsersContent() {

{t("nav.users")}

-

{visibleUsers().length} / {users()?.length ?? 0}

+

+ {visibleUsers().length} / {total()} +

- {t("admin.directory")} + + {t("admin.directory")} +
{ + setSelectedUserId(value); + setPage(0); + }} placeholder={t("common.searchPlaceholder")} selectPlaceholder={t("admin.username")} emptyMessage={t("admin.noUsers")} @@ -88,16 +120,12 @@ function AdminUsersContent() { } /> }> - - 0} - fallback={{t("admin.noUsers")}} - > - + + 0} fallback={{t("admin.noUsers")}}> + + USER_PAGE_SIZE}> + + diff --git a/src/pages/course-detail-page.tsx b/src/pages/course-detail-page.tsx index c19568b..37f964a 100644 --- a/src/pages/course-detail-page.tsx +++ b/src/pages/course-detail-page.tsx @@ -65,8 +65,8 @@ function CourseDetailContent() { }); const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId)); - const [terms] = createResource(() => getTerms()); - const [exams, { refetch: refetchExams }] = createResource(id, (courseId) => getCourseExams(courseId)); + const [terms] = createResource(async () => (await getTerms()).items); + const [exams, { refetch: refetchExams }] = createResource(id, async (courseId) => (await getCourseExams(courseId)).items); const isTeacherPlus = () => hasMinRole(auth.user()?.role, "teacher"); const hasCourseManagementRights = () => { const c = course(); @@ -76,11 +76,11 @@ function CourseDetailContent() { }; const [roster, { refetch: refetchRoster }] = createResource( () => (hasCourseManagementRights() ? id() : null), - async (courseId) => (courseId ? getCourseEnrollments(courseId) : []), + async (courseId) => (courseId ? (await getCourseEnrollments(courseId)).items : []), ); const [mine] = createResource( () => (auth.user()?.role === "student" ? true : null), - async (enabled) => (enabled ? getMyCourses() : []), + async (enabled) => (enabled ? (await getMyCourses()).items : []), ); const [editing, setEditing] = createSignal(false); diff --git a/src/pages/courses-page.tsx b/src/pages/courses-page.tsx index d809db7..f13e909 100644 --- a/src/pages/courses-page.tsx +++ b/src/pages/courses-page.tsx @@ -6,6 +6,7 @@ import { getTerms } from "@/api/getTerms"; import { getUsers } from "@/api/getUsers"; import { postCourse } from "@/api/postCourse"; import { formatApiError } from "@/api/client"; +import type { Course } from "@/api/types"; import { Alert } from "@/components/ui/alert"; import { RouteGuard } from "@/components/layout/route-guard"; import { PageHeader } from "@/components/layout/page-header"; @@ -22,6 +23,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { TableRowActions } from "@/components/ui/table-row-actions"; import { Textarea } from "@/components/ui/textarea"; import { PaginationControls } from "@/components/ui/pagination-controls"; +import { loadListPage, totalPages as pagesOf } from "@/lib/list-page"; import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; import { hasMinRole } from "@/lib/roles"; @@ -40,20 +42,6 @@ function CoursesContent() { const auth = useAuth(); const navigate = useNavigate(); const t = useT(); - const [courses, { refetch }] = createResource( - () => (auth.user()?.role && auth.user()?.role !== "student" ? true : null), - async (enabled) => (enabled ? getCourses() : []), - ); - const [terms] = createResource(() => getTerms()); - const [users] = createResource( - () => (hasMinRole(auth.user()?.role, "manager") ? true : null), - async (enabled) => (enabled ? getUsers().catch(() => []) : []), - ); - const [mine] = createResource( - () => (auth.user()?.role === "student" ? true : null), - async (enabled) => (enabled ? getMyCourses() : []), - ); - const enrolled = () => new Set((mine() ?? []).map((c) => c.id)); const [showForm, setShowForm] = createSignal(false); const [title, setTitle] = createSignal(""); const [description, setDescription] = createSignal(""); @@ -63,18 +51,27 @@ function CoursesContent() { const [query, setQuery] = createSignal(""); const [termFilter, setTermFilter] = createSignal("all"); const [page, setPage] = createSignal(0); + const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); const isStudent = () => auth.user()?.role === "student"; - const courseList = createMemo(() => (isStudent() ? mine() : courses()) ?? []); - const termName = (termId: string | null | undefined) => terms()?.find((term) => term.id === termId)?.name ?? t("terms.unassigned"); + const clientFilterActive = () => query().trim() !== "" || termFilter() !== "all"; + + const [terms] = createResource(async () => (await getTerms()).items); + const [users] = createResource( + () => (hasMinRole(auth.user()?.role, "manager") ? true : null), + async (enabled) => (enabled ? (await getUsers().catch(() => ({ items: [] as Awaited>["items"] }))).items : []), + ); + + const termName = (id: string | null | undefined) => terms()?.find((term) => term.id === id)?.name ?? t("terms.unassigned"); const creatorName = (creatorId: string) => { if (creatorId === auth.user()?.id) return auth.user()?.username ?? creatorId; return users()?.find((user) => user.id === creatorId)?.username ?? creatorId; }; - const filteredCourses = createMemo(() => { + + const filterCourses = (items: Course[]) => { const needle = query().trim().toLocaleLowerCase(); const selectedTerm = termFilter(); - return courseList().filter((course) => { + return items.filter((course) => { if (selectedTerm === "unassigned" && course.term_id) return false; if (selectedTerm !== "all" && selectedTerm !== "unassigned" && course.term_id !== selectedTerm) return false; if (!needle) return true; @@ -83,13 +80,32 @@ function CoursesContent() { .toLocaleLowerCase() .includes(needle); }); - }); - const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredCourses().length / COURSE_PAGE_SIZE))); + }; + + const [list, { refetch }] = createResource( + () => { + const role = auth.user()?.role; + if (!role) return null; + return [role, page(), clientFilterActive() ? "1" : "0", query(), termFilter()].join("|"); + }, + async (key) => { + const role = key.split("|")[0]; + const fetchPage = (params?: { limit?: number; offset?: number }) => + role === "student" ? getMyCourses(params) : getCourses(params); + return loadListPage({ + page: page(), + pageSize: COURSE_PAGE_SIZE, + clientMode: clientFilterActive(), + fetch: fetchPage, + filter: filterCourses, + }); + }, + ); + + const total = () => list()?.total ?? 0; + const pageItems = () => list()?.items ?? []; + const totalPages = createMemo(() => pagesOf(total(), COURSE_PAGE_SIZE)); const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); - const pageItems = createMemo(() => { - const start = safePage() * COURSE_PAGE_SIZE; - return filteredCourses().slice(start, start + COURSE_PAGE_SIZE); - }); const onCreate = async (e: SubmitEvent) => { e.preventDefault(); @@ -141,23 +157,11 @@ function CoursesContent() {
- setTitle(e.currentTarget.value)} - /> + setTitle(e.currentTarget.value)} />
-