diff --git a/docs/backend/attendance-pomodoro-summary-request.md b/docs/backend/attendance-pomodoro-summary-request.md new file mode 100644 index 0000000..f7a31de --- /dev/null +++ b/docs/backend/attendance-pomodoro-summary-request.md @@ -0,0 +1,179 @@ +# Feature request: list-level attendance and pomodoro summaries + +Status: requested by frontend · Date: 2026-09-22 +Contract checked: live OpenAPI at `https://hezarfen-backend.dizey.sh/api-docs/openapi.json` +(`info.version` 0.1.0, fetched 2026-09-22). + +## Problem + +Two management lists can only show a roster of students, not the numbers a +manager opens them for: + +| Page | What it shows today | What it should show | +| --- | --- | --- | +| `/management/student-attendance` | Student directory; a row opens that one student's report in a side panel | Per-student present / absent / late / excused counts and attendance rate, sortable, filterable by class and term | +| `/management/pomodoros` | Student directory; a row opens that one student's log | Per-student session count and focus minutes for a period, sortable, filterable by class | + +The API only offers these numbers one student at a time: + +- `GET /attendance/{user}` → `AttendanceReport` (`events`, `sessions`, + `courses[]`, `devamsizlik[]`), teacher+ or linked parent. +- `GET /pomodoro/{user}` → `PomodoroLog` (paged sessions + unpaged + `total_focus_ms`), teacher+ or linked parent. + +Filling a list of N students would take N requests per page view (and per +filter change). For a school of several hundred students that is not +acceptable, so the frontend deliberately does not do it: it shows no numbers +rather than firing a request storm, and it never shows made-up figures. + +## Verified: no such endpoint exists yet + +Every path in the live contract was checked. Nothing returns attendance or +pomodoro figures for more than one user: + +- Attendance paths: `/attendance/me`, `/attendance/{user}`, + `/events/{id}/attendance[/{user}]`, `/events/{id}/roster`, + `/sessions/{id}/attendance[/{user}]`, `/meals/attendance/{user}`, + `/meals/menus/{id}/attendance`. The event/session ones are per-event or + per-lesson rosters, not per-student totals. +- Pomodoro paths: `/pomodoro/me`, `/pomodoro/{user}`, `/pomodoro/start`, + `/pomodoro/finish`. +- No `summary`, `stats` or `report` path covers either domain. The nearest + ones are unrelated: `/exams/{id}/statistics`, `/homework/report/{user}` + (per user), `/insights/*` (AI insight runs), `/marks/karne[/{user}]`. + +## Proposal + +Two read-only endpoints. Both page with the standard `?limit=&offset=` and +return the standard `{items, total, limit, offset}` envelope; `total` counts +students, not attendance rows. + +Naming follows the existing contract: filters are named after the resource +without an `_id` suffix (`term`, `course`, as on `/marks/karne` and +`/course-notes`), and times are UTC unix milliseconds. + +### 1. `GET /attendance/summary` + +Per-student attendance tallies for a set of students. + +Query parameters: + +| Name | Type | Required | Meaning | +| --- | --- | --- | --- | +| `class` | string | no | Only students currently in this class section (`GET /classes/{id}/members`). Omit for every student the caller may see. | +| `term` | string | no | Count only rows dated inside this term (`GET /terms/{id}`). Omit for the newest term, like `/marks/karne`. | +| `q` | string | no | Name / username / student number search, as on the existing `q` filters. | +| `sort` | string | no | `name` (default), `rate`, `absent`, `late`; prefix `-` for descending. | +| `limit`, `offset` | int | no | Standard paging; same bounds as every other list (`1..500`). | + +Response `200` — `Page_AttendanceSummaryEntry`: + +```json +{ + "items": [ + { + "user": { "id": "0192…", "username": "ada.y", "display_name": "Ada Yılmaz", "student_number": "1043" }, + "sessions": { "present": 118, "absent": 4, "late": 3, "excused": 2, "custom": {}, "total": 127, "rate": 0.968 }, + "events": { "present": 6, "absent": 1, "late": 0, "excused": 0, "custom": {}, "total": 7, "rate": 0.857 }, + "absence": { + "term": "0191…", + "name": "2026-2027 1. Dönem", + "absent_days": 3, + "excused_days": 1, + "unexcused_days": 3, + "over_limit": false + } + } + ], + "total": 32, + "limit": 50, + "offset": 0 +} +``` + +- `sessions` / `events` reuse the existing `StatusCounts` schema unchanged + (same `rate` formula: `(present + late) / (present + absent + late)`, + `null` when there is nothing to rate). +- `absence` is the requested term's `TermAbsence` row (the same object as one + entry of `AttendanceReport.devamsizlik`; `limits` may be dropped here since + it is school-wide), or `null` when the student has no rows in that term. +- A student with no attendance rows at all still appears, with zero counts — + the list is a roster first. + +### 2. `GET /pomodoro/summary` + +Per-student pomodoro totals for a period. + +Query parameters: + +| Name | Type | Required | Meaning | +| --- | --- | --- | --- | +| `class` | string | no | Only students currently in this class section. Omit for every student the caller may see. | +| `from` | int (ms) | no | Count sessions that started at or after this instant. | +| `to` | int (ms) | no | Count sessions that started before this instant. | +| `q` | string | no | Name / username / student number search. | +| `sort` | string | no | `name` (default), `focus`, `sessions`, `last`; prefix `-` for descending. | +| `limit`, `offset` | int | no | Standard paging. | + +Omitting both `from` and `to` means the whole log, matching what +`GET /pomodoro/{user}` sums today. + +Response `200` — `Page_PomodoroSummaryEntry`: + +```json +{ + "items": [ + { + "user": { "id": "0192…", "username": "ada.y", "display_name": "Ada Yılmaz", "student_number": "1043" }, + "sessions": 14, + "counted_sessions": 12, + "total_focus_ms": 20400000, + "last_started_at": 1758540000000 + } + ], + "total": 32, + "limit": 50, + "offset": 0 +} +``` + +- `sessions`: finished sessions in the window. A running session is not + counted, as in `PomodoroLog.total_focus_ms`. +- `counted_sessions`: of those, how many had `counted = true` (moved the + badge / streak counters). Optional; useful for oversight, not required. +- `total_focus_ms`: sum of `duration_ms` over those sessions. Milliseconds, + like every other duration in the contract; the UI converts to minutes. +- `last_started_at`: newest session start in the window, `null` if none. +- Students with no sessions appear with zeros. + +## Role scoping + +Same rules as the per-student endpoints they summarise, applied per row: + +| Caller | `class` omitted | `class` given | +| --- | --- | --- | +| admin, manager | every student | that class | +| teacher | students of the classes they are homeroom teacher of (`ClassResponse.teacher`) or teach an instance in | allowed only if they are that class's homeroom teacher or teach an instance of it; otherwise `403` | +| student, parent | `403` (they already have `/attendance/me`, `/pomodoro/me` and the per-child endpoints) | `403` | + +For `/attendance/summary`, a teacher's `sessions` tally should follow the +`GET /attendance/{user}` rule: only the roll-call rows of instances the +teacher runs, plus event tallies. Managers and admins see every instance. + +## Errors + +- `400` — invalid `limit`/`offset`/`sort`, `from > to`, unknown `term`. +- `401` — not authenticated. +- `403` — role not allowed, or a teacher asking for a class outside their scope. +- `404` — `class` or `term` does not exist. + +## Frontend plan once available + +- `src/api/reports/getAttendanceSummary.ts` and + `src/api/reports/getPomodoroSummary.ts`, with tests in + `src/api/__tests__/reports/`. +- `/management/student-attendance`: server-paged `DataTable` with rate, + absent, late, excused and unexcused-days columns, class and term filters; + the row action keeps opening the full per-student report. +- `/management/pomodoros`: server-paged `DataTable` with session count, focus + minutes and last session, class filter and a period picker. diff --git a/docs/frontend/sitemap.md b/docs/frontend/sitemap.md index 8448a88..815a94b 100644 --- a/docs/frontend/sitemap.md +++ b/docs/frontend/sitemap.md @@ -6,7 +6,8 @@ Every route in the app, how it is reached, and who may enter it. same commit when either changes: - `src/routes/router.tsx` — the route table (paths, params, redirects) -- `src/components/layout/nav-items.ts` — sidebar grouping and per-role visibility +- `src/components/layout/nav-items.ts` — sidebar groups per role, module gates, + the mobile tab bar - `src/pages/*.tsx` — the `` each page wraps itself in Role rank (`src/lib/roles.ts`): `parent (-1) < student (0) < teacher (1) < manager (2) < admin (3)`. @@ -22,73 +23,73 @@ flowchart LR Login -- "no account" --> Register["/register"] Register --> Login Login --> Home + Builder(["Platform operator"]) --> BLogin["/builder/login"] --> BHome["/builder"] --> BSchool["/builder/schools/$slug"] ``` `RouteGuard` sends any unauthenticated visitor to `/login`; `guest-guard.tsx` does -the reverse for `/login` and `/register`. Neither auth page is in the sidebar. +the reverse for `/login`, `/register` and `/builder/login`. The `/builder/*` +pages sit behind `BuilderGuard` (the platform-operator session), not a school +role. None of these are in the sidebar. -## Main sitemap +## Sidebar per role -Grouped exactly as the sidebar groups them. Bracketed labels are the role gate — -unmarked entries are visible to every signed-in role except `parent` (see -[Parent visibility](#parent-visibility)). +Each role has its own tree in `nav-items.ts` (`GROUPS_BY_ROLE`); manager and +admin share one tree and the manager simply qualifies for fewer items. An item +with a `module` is also hidden when the school has that module switched off +(`moduleVisible`). The Çelebi and "Ayarlar" rows open shell panels instead of +navigating, so they have no route. -```mermaid -flowchart TD - Home["/ — Dashboard"] - - Home --> Classes["Dersler"] - Home --> Planning["Planlama"] - Home --> Workspace["Çalışma alanı"] - Home --> Students["Öğrenciler"] - Home --> Services["Hizmetler"] - Home --> Community["Topluluk"] - Home --> School["Okul"] - - Classes --> C1["/courses"] - Classes --> C2["/homework"] - Classes --> C3["/exams"] - Classes --> C4["/question-bank
teacher+"] - Classes --> C5["/marks
student only"] - - Planning --> P1["/events"] - Planning --> P2["/calendar"] - Planning --> P3["/appointments"] - - Workspace --> W1["/notes"] - Workspace --> W2["/whiteboards
student+"] - Workspace --> W3["/pomodoro
student only"] - - Students --> S1["/students
parent only"] - Students --> S2["/management/classes
teacher+"] - Students --> S3["/management/student-marks
teacher+"] - Students --> S4["/management/student-attendance
teacher+"] - Students --> S5["/management/pomodoros
teacher+"] - - Services --> V1["/meals"] - Services --> V2["/payments
parent + student"] - - Community --> M1["/messages"] - Community --> M2["/questions
student+"] - Community --> M3["/work
teacher..manager"] - - School --> K1["/management/staff-work
manager+"] - School --> K2["/management/settings
manager+"] - School --> K3["/management/terms
manager+"] - School --> K4["/management/payments
manager+"] - School --> K5["/admin/users
admin"] -``` +### Admin / manager + +| Group | Entries | +| --- | --- | +| Yapay zekâ | `/ai/studio` · `/ai/study` · `/ai/insights` · Çelebi | +| Okul yönetimi | `/management/students` (manager+) · `/management/teachers` (manager+) · `/management/classes` · `/management/academic-years` (manager+) · `/management/terms` (manager+) · `/calendar` | +| Eğitim ve içerik | `/courses` · `/homework` · `/exams` · `/question-bank` · `/questions` · `/notes` · `/whiteboards` | +| Öğrenci takibi | `/management/student-attendance` · `/management/student-marks` · `/management/pomodoros` | +| Okul hizmetleri | `/events` · `/appointments` · `/meals` | +| Kurum | `/management/payments` · `/management/staff-work` · `/work` · `/admin/users` (admin) · `/management/modules` (admin) · `/management/settings` | +| Yakında (folded) | `/coming-soon/deneme-sinavlari` · `/coming-soon/optik-okuma` · `/coming-soon/raporlar` · `/coming-soon/kvkk-denetim` (admin) | -### Primary strip +### Teacher -`PRIMARY_BY_ROLE` lifts a few of the above into the top strip / mobile tab bar -instead of the grouped sidebar: +| Group | Entries | +| --- | --- | +| Yapay zekâ | `/ai/studio` · `/ai/study` · Çelebi | +| Sınıfım | `/management/classes` · `/calendar` · `/courses` | +| Öğrenci takibi | `/management/student-attendance` · `/management/student-marks` · `/management/pomodoros` · `/ai/insights` ("Öğrenci analizi") | +| Eğitim ve içerik | `/homework` · `/exams` · `/question-bank` · `/ai/question-generation` · `/questions` · `/questions?status=pending` · `/notes` · `/whiteboards` | +| Diğer | `/messages` · `/appointments` · `/events` · `/meals` · `/work` · Ayarlar | + +### Student -| Role | Primary items | +| Group | Entries | | --- | --- | -| student | `/` · `/courses` · `/calendar` · `/marks` | -| teacher, manager, admin | `/` · `/courses` · `/calendar` | -| parent | `/` · `/students` · `/calendar` | +| Yapay zekâ | `/ai/studio` · `/ai/study` · `/ai/insights` · Çelebi | +| Çalışma | `/marks` · `/exams` · `/homework` · `/pomodoro` | +| Eğitim ve içerik | `/courses` · `/notes` · `/questions` · `/whiteboards` | +| Diğer | `/calendar` · `/events` · `/messages` · `/appointments` · `/meals` · Ayarlar | +| Yakında (folded) | `/coming-soon/calisma-programim` | + +### Parent + +| Group | Entries | +| --- | --- | +| Yapay zekâ | `/ai/insights` | +| Öğrencim | `/students` · `/students/attendance` · `/students/exams` · `/students/study` | +| Kurum | `/payments` · `/appointments` · `/messages` · `/calendar` · `/events` · `/meals` · Ayarlar | + +### Mobile tab bar + +`PRIMARY_IDS_BY_ROLE` picks Home plus two entries from the role's own tree for +the phone tab bar (then the bar's own Search and Menu buttons): + +| Role | Tabs | +| --- | --- | +| student | `/` · `/homework` · `/exams` | +| teacher | `/` · `/management/classes` · `/management/student-attendance` | +| manager, admin | `/` · `/management/students` · `/management/classes` | +| parent | `/` · `/students` · `/appointments` | ## Detail and nested routes @@ -103,16 +104,29 @@ flowchart LR C1 --> C3["/exam-room/$id
student only"] D["/question-bank
teacher+"] --> D1["/question-bank/$id
teacher+"] E["/courses"] --> E1["/courses/$id"] + E1 --> E2["/instances/$id"] F["/questions
student+"] --> F1["/questions/$id
student+"] G["/meals"] --> G1["/meals/$id"] - H["/management/classes
teacher+"] --> H1["/management/classes/$id"] + H["/management/classes
teacher+"] --> H1["/management/classes/$id
teacher+"] I["/admin/users
admin"] --> I1["/admin/users/$id
admin"] J["/whiteboards
student+"] --> J1["/whiteboards/$id
student+"] K["/management/payments
manager+"] --> K1["/management/payments/$userId
manager+"] + L["/notes"] --> L1["/notes/new"] + L --> L2["/notes/$id"] + M["/ai/insights"] --> M1["/ai/insights/$userId"] + N["/builder"] --> N1["/builder/schools/$slug"] ``` -`/management/payments/$userId` renders the same `PaymentsPage` component as the -list route — the param only deep-links a selected student. +- `/courses/$id` is the catalog row; `/instances/$id` is a şube×ders instance + (enrollments, exams, homework, sessions, roll call), reached from a course or + a class. +- `/management/payments/$userId` renders the same `PaymentsPage` component as + the list route — the param only deep-links a selected student. +- `/students/attendance`, `/students/exams` and `/students/study` render the + same `MyStudentsPage` as `/students`, each on its own tab. +- `/notes/new` and `/notes/$id` share `NoteEditorPage`. +- `/profile/me` and `/profile/$userId` share `ProfilePage`; `/profile/me` is + opened from the account menu, `/profile/$userId` from a person link. ## Redirects @@ -120,40 +134,38 @@ list route — the param only deep-links a selected student. | --- | --- | --- | | `/studies` | `/courses?kind=study` | Courses page filters by `kind` | | `/clubs` | `/courses?kind=club` | same | -| `/attendance` | `/marks?tab=attendance` | attendance is a tab on the marks page | +| `/ai` | `/ai/studio` | the old AI hub; each AI module has its own page now | +| `/sound-studio` | `/ai/studio` | the audio studio moved into AI Studio | +| `/attendance` | per role: student → `/marks?tab=attendance`, parent → `/students/attendance`, staff → `/management/student-attendance` | old link every role may still hold | -All three are `beforeLoad` redirects with no component of their own. +The first four are `beforeLoad` redirects with no component of their own; +`/attendance` waits for the session (`AttendanceRedirect`) because the target +depends on the role. ## Route guards at a glance -Route-level enforcement only — the sidebar hides more than this table blocks. +Route-level enforcement only — the sidebar hides more than this table blocks, +and the backend still scopes every read. | Guard | Routes | | --- | --- | -| `admin` | `/admin/users`, `/admin/users/$id` | -| `manager+` | `/management/settings`, `/management/terms`, `/management/staff-work`, `/management/payments`, `/management/payments/$userId` | -| `teacher+` | `/question-bank`, `/question-bank/$id`, `/management/student-marks`, `/management/student-attendance`, `/management/pomodoros`, `/exams/$id/live` | -| `teacher..manager` | `/work` | -| `student+` | `/questions`, `/questions/$id`, `/whiteboards`, `/whiteboards/$id` | +| `admin` | `/admin/users`, `/admin/users/$id`, `/management/modules` | +| `manager+` | `/management/students`, `/management/teachers`, `/management/academic-years`, `/management/terms`, `/management/settings`, `/management/staff-work`, `/management/payments`, `/management/payments/$userId` | +| `teacher+` | `/management/classes`, `/management/classes/$id`, `/management/student-marks`, `/management/student-attendance`, `/management/pomodoros`, `/question-bank`, `/question-bank/$id`, `/ai/question-generation`, `/exams/$id/live`, `/work` | +| `student+` | `/questions`, `/questions/$id`, `/whiteboards`, `/whiteboards/$id`, `/ai/studio`, `/ai/study` | | `student` only | `/marks`, `/pomodoro`, `/exam-room/$id` | -| `parent` only | `/students` | -| signed-in, no role gate | `/`, `/notes`, `/events`, `/events/$id`, `/homework`, `/homework/$id`, `/exams`, `/exams/$id`, `/courses`, `/courses/$id`, `/management/classes`, `/management/classes/$id`, `/calendar`, `/appointments`, `/meals`, `/meals/$id`, `/messages`, `/payments`, `/guide` | - -### Parent visibility - -`itemVisible()` in `nav-items.ts` ends with an allowlist: a `parent` sees an -otherwise-ungated item only when its path is `/`, `/calendar`, `/appointments`, -`/meals` or `/messages`. Every other ungated route above is hidden from a parent's -sidebar but has no `RouteGuard`, so it stays reachable by typing the URL — the -data those pages show is scoped by the backend, not by the router. +| `parent` only | `/students`, `/students/attendance`, `/students/exams`, `/students/study` | +| signed-in, no role gate | `/`, `/notes`, `/notes/new`, `/notes/$id`, `/events`, `/events/$id`, `/homework`, `/homework/$id`, `/exams`, `/exams/$id`, `/courses`, `/courses/$id`, `/instances/$id`, `/calendar`, `/appointments`, `/meals`, `/meals/$id`, `/messages`, `/payments`, `/ai/insights`, `/ai/insights/$userId`, `/profile/me`, `/profile/$userId`, `/guide`, `/coming-soon/*` | +| builder session | `/builder`, `/builder/schools/$slug` | +| guest only | `/login`, `/register`, `/builder/login` | -The same gap applies to `/payments` (the personal statement page): the sidebar -shows it at `maxRole: "student"` (parent and student), while the route itself is -ungated. +Ungated routes that a role's sidebar does not list (a parent typing `/notes`, +say) stay reachable by URL — the data those pages show is scoped by the +backend, not by the router. -## Not in the sitemap +## Not in the sidebar -- `/guide` — the in-app help page, reached from the account dropdown at the foot - of the sidebar (`sidebar-account.tsx`), not from a nav group. -- `/login`, `/register` — pre-auth, covered in [Entry flow](#entry-flow). +- `/guide` and `/profile/me` — opened from the account menu (`account-menu.ts`), + shared by the desktop dropdown and the phone menu sheet. +- `/login`, `/register`, `/builder/*` — covered in [Entry flow](#entry-flow). - 404 — `notFoundComponent` on the root route, links back to `/`. diff --git a/src/components/events/attendance-status-picker.tsx b/src/components/events/attendance-status-picker.tsx deleted file mode 100644 index 0dbb4ee..0000000 --- a/src/components/events/attendance-status-picker.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { For, Show, createMemo } from "solid-js"; -import { createResource } from "@/lib/create-resource"; -import { getSettings } from "@/api/settings"; -import type { AttendanceStatus } from "@/api/client"; -import { Label } from "@/components/ui/label"; -import { Select } from "@/components/ui/select"; -import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status"; -import { useT } from "@/stores/preferences-context"; - -export function AttendanceStatusPicker(props: { - id?: string; - value: AttendanceStatus; - onChange: (status: AttendanceStatus) => void; - label?: string; - hideLabel?: boolean; - hideDetail?: boolean; -}) { - const t = useT(); - const [settings] = createResource(() => getSettings()); - const statuses = createMemo(() => { - const values = settings()?.attendance_statuses ?? ATTENDANCE_STATUSES.map((item) => item.value); - return values.includes(props.value) ? values : [props.value, ...values]; - }); - const selectedMeta = createMemo(() => getAttendanceStatusMeta(props.value)); - return ( -
- - - - - -

- {selectedMeta() ? `${t(selectedMeta()!.key)}: ${t(selectedMeta()!.detailKey)}` : props.value} -

-
-
- ); -} diff --git a/src/components/events/attendance-table.tsx b/src/components/events/attendance-table.tsx index cd481c4..eaf130d 100644 --- a/src/components/events/attendance-table.tsx +++ b/src/components/events/attendance-table.tsx @@ -8,6 +8,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; import { Badge } from "@/components/ui/badge"; import { getAttendanceStatusMeta } from "@/lib/attendance-status"; import { cn } from "@/lib/cn"; +import { eventStatusLabelKey } from "@/lib/event-roll-call"; import { personId, personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; @@ -30,11 +31,13 @@ export function AttendanceTable(props: { accessorKey: "status", header: t("events.status"), cell: (cell) => { - const meta = getAttendanceStatusMeta(cell.row.original.status); + const status = cell.row.original.status; + const meta = getAttendanceStatusMeta(status); + // Event wording ("Katıldı"), not the lesson one ("Var · Derste"). + const key = eventStatusLabelKey(status) ?? meta?.key; return ( - {meta ? t(meta.key) : cell.row.original.status} - {(known) => · {t(known().detailKey)}} + {key ? t(key) : status} ); }, diff --git a/src/components/events/event-roll-call.test.tsx b/src/components/events/event-roll-call.test.tsx new file mode 100644 index 0000000..842f28f --- /dev/null +++ b/src/components/events/event-roll-call.test.tsx @@ -0,0 +1,68 @@ +import { fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; +import { EventRollCall } from "@/components/events/event-roll-call"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const { postEventAttendance } = vi.hoisted(() => ({ + postEventAttendance: vi.fn(async (_eventId: string, body: { user_id: string; status: string }) => { + if (body.user_id === "s-3") throw new Error("outside audience"); + return { id: `a-${body.user_id}`, event: "event-1", user: { id: body.user_id, username: body.user_id, display_name: null }, status: body.status, marked_by: { id: "t", username: "t", display_name: null } }; + }), +})); + +vi.mock("@/api/events", () => ({ postEventAttendance })); +vi.mock("@/api/settings", () => ({ + getSettings: async () => ({ attendance_statuses: ["present", "absent", "late", "excused"] }), +})); + +const person = (id: string, name: string) => ({ id, username: id, display_name: name }); +const roster = [ + { user: person("s-1", "Ada"), status: "present", marked_by: person("t", "Öğretmen") }, + { user: person("s-2", "Bora"), status: null, marked_by: null }, + { user: person("s-3", "Cem"), status: null, marked_by: null }, +]; + +afterEach(() => { + vi.clearAllMocks(); +}); + +const mount = (open = true, onSaved = vi.fn()) => + render(() => ( + + + + )); +const row = (name: string) => within(screen.getByRole("radiogroup", { name })); +const saveButton = () => screen.getByRole("button", { name: /Yoklamayı kaydet|Save roll call|Save attendance/ }); + +test("lists the whole audience with recorded statuses and nothing sent on pick", async () => { + mount(); + expect(await screen.findByText("Ada")).toBeTruthy(); + expect(row("Ada").getByRole("radio", { name: /Katıldı|Attended/ }).getAttribute("aria-checked")).toBe("true"); + fireEvent.click(row("Bora").getByRole("radio", { name: /Katılmadı|Did not attend/ })); + expect(postEventAttendance).not.toHaveBeenCalled(); +}); + +test("saves only changed rows and reports a failed row on that row", async () => { + const onSaved = vi.fn(); + mount(true, onSaved); + await screen.findByText("Ada"); + fireEvent.click(row("Ada").getByRole("radio", { name: /Katıldı|Attended/ })); // unchanged: no-op + fireEvent.click(row("Bora").getByRole("radio", { name: /Katılmadı|Did not attend/ })); + fireEvent.click(row("Cem").getByRole("radio", { name: /Geç geldi|Arrived late/ })); + fireEvent.click(saveButton()); + + await waitFor(() => expect(postEventAttendance).toHaveBeenCalledTimes(2)); + expect(postEventAttendance).toHaveBeenNthCalledWith(1, "event-1", { user_id: "s-2", status: "absent" }); + expect(postEventAttendance).toHaveBeenNthCalledWith(2, "event-1", { user_id: "s-3", status: "late" }); + // The failed row keeps its pick and carries its own error line. + expect(await screen.findByText(/İşlem tamamlanamadı|Something went wrong/)).toBeTruthy(); + expect(screen.getByText(/1 of 2 rows|2 satırdan 1/)).toBeTruthy(); + expect(onSaved).toHaveBeenCalledTimes(1); +}); + +test("before the event starts nothing can be picked or saved", async () => { + mount(false); + await screen.findByText("Ada"); + expect((row("Bora").getByRole("radio", { name: /Katıldı|Attended/ }) as HTMLButtonElement).disabled).toBe(true); + expect((saveButton() as HTMLButtonElement).disabled).toBe(true); +}); diff --git a/src/components/events/event-roll-call.tsx b/src/components/events/event-roll-call.tsx new file mode 100644 index 0000000..01013e7 --- /dev/null +++ b/src/components/events/event-roll-call.tsx @@ -0,0 +1,336 @@ +import { For, Show, createEffect, createMemo, createSignal, on } from "solid-js"; +import { createResource } from "@/lib/create-resource"; +import { postEventAttendance } from "@/api/events"; +import { getSettings } from "@/api/settings"; +import { formatApiError } from "@/api/client"; +import type { AttendanceStatus, EventRosterEntry } from "@/api/client"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { DataTableSearch } from "@/components/ui/data-table-search"; +import { EmptyState } from "@/components/ui/empty-state"; +import { IconCheck } from "@/components/ui/icons"; +import { TablePagination } from "@/components/ui/table-pagination"; +import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status"; +import { cn } from "@/lib/cn"; +import { + eventStatusLabelKey, + orderRollCallStatuses, + rollCallChanges, + saveRollCallChanges, +} from "@/lib/event-roll-call"; +import { personLabel } from "@/lib/person"; +import { matchesSearch } from "@/lib/search-text"; +import { useT } from "@/stores/preferences-context"; + +const PAGE_SIZE = 20; + +/** + * Event roll call as one roster: every expected attendee (resolved by the + * backend from the event's audience) with a status row. Picks stay local + * until "Yoklamayı kaydet" sends the changed rows — the API marks one user per + * call, so rows go one at a time with progress, and a row that fails keeps its + * pick and shows its own error. + */ +export function EventRollCall(props: { + eventId: string; + roster: EventRosterEntry[]; + /** False before the event starts: statuses show, nothing can be picked. */ + open: boolean; + closedReason?: string; + onSaved: () => void | Promise; +}) { + const t = useT(); + const [settings] = createResource(() => getSettings()); + const statuses = createMemo(() => + orderRollCallStatuses(settings.latest?.attendance_statuses ?? ATTENDANCE_STATUSES.map((item) => item.value)), + ); + + // Marks this component saved, shown until the refetched roster carries them. + const [savedLocal, setSavedLocal] = createSignal>({}); + createEffect(on(() => props.roster, () => setSavedLocal({}), { defer: true })); + const saved = createMemo>(() => { + const map: Record = {}; + for (const row of props.roster) map[row.user.id] = row.status; + return { ...map, ...savedLocal() }; + }); + + const [draft, setDraft] = createSignal>({}); + const [rowErrors, setRowErrors] = createSignal>({}); + const [progress, setProgress] = createSignal<{ done: number; total: number } | null>(null); + const [summary, setSummary] = createSignal<{ kind: "success" | "destructive"; text: string } | null>(null); + const [query, setQuery] = createSignal(""); + const [onlyUnmarked, setOnlyUnmarked] = createSignal(false); + const [page, setPage] = createSignal(0); + + const effective = (userId: string) => draft()[userId] ?? saved()[userId] ?? undefined; + const changes = createMemo(() => rollCallChanges(saved(), draft())); + const markedCount = createMemo(() => props.roster.filter((row) => effective(row.user.id) != null).length); + const counts = createMemo(() => { + const tally: Record = {}; + for (const row of props.roster) { + const status = effective(row.user.id); + if (status) tally[status] = (tally[status] ?? 0) + 1; + } + return tally; + }); + const unmarkedIds = createMemo(() => props.roster.filter((row) => effective(row.user.id) == null).map((row) => row.user.id)); + + const visible = createMemo(() => { + const q = query().trim(); + return props.roster.filter((row) => { + if (onlyUnmarked() && effective(row.user.id) != null) return false; + return !q || matchesSearch(q, personLabel(row.user), row.user.username, row.user.student_number); + }); + }); + const pageCount = () => Math.max(1, Math.ceil(visible().length / PAGE_SIZE)); + createEffect(on([query, onlyUnmarked], () => setPage(0), { defer: true })); + createEffect(() => { + if (page() >= pageCount()) setPage(pageCount() - 1); + }); + const pageRows = createMemo(() => visible().slice(page() * PAGE_SIZE, (page() + 1) * PAGE_SIZE)); + + const busy = () => progress() != null; + const locked = () => !props.open || busy(); + + const statusLabel = (status: AttendanceStatus) => { + const key = eventStatusLabelKey(status); + if (key) return t(key); + const meta = getAttendanceStatusMeta(status); + return meta ? t(meta.key) : status; + }; + + const pick = (userId: string, status: AttendanceStatus) => { + if (locked()) return; + setSummary(null); + setDraft((current) => { + const next = { ...current }; + // Tapping the drafted status again drops the pick back to the saved one. + if (current[userId] === status || saved()[userId] === status) delete next[userId]; + else next[userId] = status; + return next; + }); + setRowErrors((current) => { + if (!(userId in current)) return current; + const next = { ...current }; + delete next[userId]; + return next; + }); + }; + + const markRestPresent = () => { + if (locked()) return; + setSummary(null); + setDraft((current) => { + const next = { ...current }; + for (const userId of unmarkedIds()) next[userId] = "present"; + return next; + }); + }; + + const save = async () => { + const queue = changes(); + if (queue.length === 0 || locked()) return; + setSummary(null); + setRowErrors({}); + setProgress({ done: 0, total: queue.length }); + const result = await saveRollCallChanges( + queue, + (change) => postEventAttendance(props.eventId, { user_id: change.userId, status: change.status }), + (done, total) => setProgress({ done, total }), + ); + setProgress(null); + if (result.saved.length > 0) { + setSavedLocal((current) => ({ + ...current, + ...Object.fromEntries(result.saved.map((change) => [change.userId, change.status])), + })); + setDraft((current) => { + const next = { ...current }; + for (const change of result.saved) delete next[change.userId]; + return next; + }); + } + setRowErrors(Object.fromEntries(result.failed.map((item) => [item.change.userId, formatApiError(item.error)]))); + if (result.failed.length > 0) { + setSummary({ + kind: "destructive", + text: t("events.rollCall.saveFailed", { failed: result.failed.length, total: queue.length }), + }); + } else { + setSummary({ kind: "success", text: t("events.rollCall.saved", { count: result.saved.length }) }); + } + if (result.saved.length > 0) await props.onSaved(); + }; + + return ( +
+ + {props.closedReason ?? t("events.rollCall.notStarted")} + + 0} + fallback={} + > +
+
+

+ {t("rollCall.progress", { marked: markedCount(), total: props.roster.length })} +

+
+ + {(status) => ( + + + {statusLabel(status)} {counts()[status]} + + + )} + +
+
+ + + 0} + fallback={ +

+ {query().trim() ? t("events.noAttendees") : t("rollCall.allMarked")} +

+ } + > +
    + + {(row) => { + const userId = row.user.id; + const current = () => effective(userId); + const pending = () => draft()[userId] != null && draft()[userId] !== saved()[userId]; + const rowError = () => rowErrors()[userId]; + const name = () => personLabel(row.user); + return ( +
  • +
    +
    +
    + + {(status) => { + const selected = () => current() === status; + return ( + + ); + }} + +
    +
  • + ); + }} +
    +
+
+ + + + {(item) => {item().text}} + + +
+

+ {progress() + ? t("rollCall.marking", { done: progress()!.done, total: progress()!.total }) + : changes().length > 0 + ? t("events.rollCall.pendingChanges", { count: changes().length }) + : t("events.rollCall.noChanges")} +

+ 0 && !busy()}> + + + +
+ +
+ ); +} diff --git a/src/components/exams/exam-form.tsx b/src/components/exams/exam-form.tsx index dbe55e5..8822f8a 100644 --- a/src/components/exams/exam-form.tsx +++ b/src/components/exams/exam-form.tsx @@ -16,6 +16,7 @@ import { Select } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; import { examKindLabel } from "@/lib/exam-labels"; import { pickCurrentTerm } from "@/lib/terms"; +import { countExamQuestions, isPublishing } from "@/lib/exam-publish"; import { useT } from "@/stores/preferences-context"; function dateInputFromMs(ms: number | null | undefined): string { @@ -87,7 +88,9 @@ export function ExamForm(props: { const [maxAttempts, setMaxAttempts] = createSignal(String(props.initial?.max_attempts ?? 1)); const [allowRejoin, setAllowRejoin] = createSignal(props.initial?.allow_rejoin ?? true); const [allowReview, setAllowReview] = createSignal(props.initial?.allow_review ?? false); - const [draft, setDraft] = createSignal(props.initial?.draft ?? false); + // A new exam starts as a draft: its questions are only added in step 2, so + // publishing on create would put an empty exam in front of students. + const [draft, setDraft] = createSignal(props.initial?.draft ?? true); const [startsDate, setStartsDate] = createSignal(dateInputFromMs(props.initial?.starts_at)); const [startsTime, setStartsTime] = createSignal(timeInputFromMs(props.initial?.starts_at)); const [endsDate, setEndsDate] = createSignal(dateInputFromMs(props.initial?.ends_at)); @@ -103,6 +106,8 @@ export function ExamForm(props: { const [pending, setPending] = createSignal(false); const [confirmOpen, setConfirmOpen] = createSignal(false); const [pendingValues, setPendingValues] = createSignal(null); + /** Set when the pending update would publish an exam that has no questions. */ + const [publishingEmpty, setPublishingEmpty] = createSignal(false); const isEdit = () => !!props.initial?.id; const [settings] = createResource(() => getSettings()); const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); @@ -160,7 +165,7 @@ export function ExamForm(props: { setHasRetakes(false); setMaxAttempts("1"); setAllowRejoin(true); - setDraft(false); + setDraft(true); setStartsDate(""); setStartsTime(""); setEndsDate(""); @@ -212,6 +217,16 @@ export function ExamForm(props: { } satisfies ExamFormValues; if (isEdit()) { + let empty = false; + const examId = props.initial?.id; + if (examId && isPublishing(props.initial, values.draft)) { + try { + empty = (await countExamQuestions(examId)) === 0; + } catch { + // The count is advisory; the update confirmation still guards the save. + } + } + setPublishingEmpty(empty); setPendingValues(values); setConfirmOpen(true); return; @@ -448,6 +463,9 @@ export function ExamForm(props: {
{t("exams.draft")}

{t("exams.draftHelp")}

+ +

{t("exams.publishOnCreateWarning")}

+
@@ -470,7 +488,12 @@ export function ExamForm(props: { open={confirmOpen()} onOpenChange={setConfirmOpen} title={t("confirm.updateTitle")} - summary={t("confirm.updateExam", { title: pendingValues()?.title ?? "" })} + summary={ + + {t("confirm.updateExam", { title: pendingValues()?.title ?? "" })} + {t("exams.publishEmptyWarning")} + + } onConfirm={async () => { const values = pendingValues(); if (!values) return; diff --git a/src/components/insights/insight-student-analysis-tabs.tsx b/src/components/insights/insight-student-analysis-tabs.tsx index bdec9b9..970a7ca 100644 --- a/src/components/insights/insight-student-analysis-tabs.tsx +++ b/src/components/insights/insight-student-analysis-tabs.tsx @@ -7,6 +7,7 @@ import { ChartProgressRing, type ProgressRingSegment } from "@/components/ui/cha import { EmptyInline } from "@/components/ui/empty-inline"; import { IconAlert, IconChevronDown } from "@/components/ui/icons"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { formatNumber } from "@/lib/format"; import { isRecord, type UnknownRecord } from "@/lib/is-record"; import { usePreferences } from "@/stores/preferences-context"; @@ -38,6 +39,7 @@ function AttendanceChart(props: { value: unknown; t: (key: string) => string }) } function MarksChart(props: { value: unknown; t: (key: string) => string }) { + const { locale } = usePreferences(); const courses = () => Object.entries(obj(obj(props.value).courses)); const items = (): ChartBarItem[] => courses().flatMap(([id, raw]) => { const stat = obj(raw); @@ -47,7 +49,7 @@ function MarksChart(props: { value: unknown; t: (key: string) => string }) { label: String(stat.course_title ?? id).slice(0, 32), value, max: 100, - formattedValue: value.toLocaleString("tr-TR", { maximumFractionDigits: 1 }), + formattedValue: formatNumber(value, locale()), }]; }); return ( @@ -62,6 +64,7 @@ function MarksChart(props: { value: unknown; t: (key: string) => string }) { } function StudyChart(props: { value: unknown; t: (key: string) => string }) { + const { locale } = usePreferences(); const recent = () => obj(obj(props.value).recent_28d); const hours = () => { const milliseconds = num(recent().total_focus_ms); @@ -78,7 +81,7 @@ function StudyChart(props: { value: unknown; t: (key: string) => string }) { id: "current", label: props.t("insights.analysis.currentPeriod"), value: currentHours, - formattedValue: currentHours.toLocaleString("tr-TR", { maximumFractionDigits: 1 }), + formattedValue: formatNumber(currentHours, locale()), colorClass: "bg-primary", }); } @@ -87,7 +90,7 @@ function StudyChart(props: { value: unknown; t: (key: string) => string }) { id: "previous", label: props.t("insights.analysis.previousPeriod"), value: previousHours, - formattedValue: previousHours.toLocaleString("tr-TR", { maximumFractionDigits: 1 }), + formattedValue: formatNumber(previousHours, locale()), colorClass: "bg-info", }); } diff --git a/src/components/insights/insight-students-table.tsx b/src/components/insights/insight-students-table.tsx index 2920e26..b475119 100644 --- a/src/components/insights/insight-students-table.tsx +++ b/src/components/insights/insight-students-table.tsx @@ -63,7 +63,7 @@ export function InsightStudentsTable(props: { id: "student", accessorFn: (row) => row.name, header: rt("student"), - size: 130, + size: 120, meta: { align: "center" }, cell: (cell) => ( @@ -73,7 +73,7 @@ export function InsightStudentsTable(props: { }, { id: "status", - size: 110, + size: 108, accessorFn: (row) => row.state, header: rt("status" as never), meta: { align: "center" }, @@ -117,7 +117,7 @@ export function InsightStudentsTable(props: { }, { id: "marks", - size: 135, + size: 148, accessorFn: (row) => row.marks.average ?? -1, header: rt("marksAverage"), meta: { align: "center" }, @@ -125,7 +125,7 @@ export function InsightStudentsTable(props: { }, { id: "attendance", - size: 125, + size: 133, accessorFn: (row) => (row.attendance.observed > 0 ? row.attendance.rate ?? -1 : -1), header: rt("attendanceRate"), meta: { align: "center" }, @@ -145,7 +145,7 @@ export function InsightStudentsTable(props: { }, { id: "confidence", - size: 105, + size: 97, accessorFn: (row) => row.confidence ?? "", header: rt("confidence"), meta: { align: "center" }, @@ -153,7 +153,7 @@ export function InsightStudentsTable(props: { }, { id: "computedAt", - size: 95, + size: 100, accessorFn: (row) => row.computed_at ?? 0, header: t("insights.computedAt"), meta: { align: "center", cellClass: "text-xs text-muted-foreground whitespace-nowrap" }, diff --git a/src/components/layout/command-palette.test.tsx b/src/components/layout/command-palette.test.tsx index f706884..383331f 100644 --- a/src/components/layout/command-palette.test.tsx +++ b/src/components/layout/command-palette.test.tsx @@ -16,6 +16,14 @@ vi.mock("@/stores/modules-context", () => ({ })); vi.mock("@/api/users", () => ({ getUserSearch: vi.fn(async () => ({ items: [], total: 0, limit: 10, offset: 0 })) })); vi.mock("@/api/classes", () => ({ getMyClasses: vi.fn(async () => ({ items: [], total: 0, limit: 10, offset: 0 })) })); +vi.mock("@/lib/command-search", async (importOriginal) => ({ + ...(await importOriginal()), + loadCommandRecords: vi.fn(async () => [ + { kind: "course", id: "c1", title: "Biyoloji", context: null, description: null, courseKind: "course", at: null }, + { kind: "exam", id: "e1", title: "1. Yazılı", context: "Biyoloji — 10-B", description: null, at: null }, + { kind: "course", id: "c2", title: "Kimya", context: null, description: null, courseKind: "course", at: null }, + ]), +})); beforeEach(() => { vi.spyOn(window, "scrollTo").mockImplementation(() => {}); @@ -46,3 +54,21 @@ test("the palette is a combobox whose active option follows the arrow keys", asy expect(field.getAttribute("aria-activedescendant")).toBe(options[1].id); expect(options[1].getAttribute("aria-selected")).toBe("true"); }); + +test("typing a course name lists matching courses and exams as their own groups", async () => { + render(() => ( + + {}} /> + + )); + + const field = await screen.findByRole("combobox"); + fireEvent.input(field, { target: { value: "biyoloji" } }); + + const courseOption = await screen.findByRole("option", { name: /^Biyoloji/ }); + expect(courseOption).toBeTruthy(); + expect(screen.getByRole("option", { name: /1\. Yazılı/ })).toBeTruthy(); + expect(screen.queryByRole("option", { name: /Kimya/ })).toBeNull(); + expect(screen.getByText("Courses")).toBeTruthy(); + expect(screen.getByText("Exams")).toBeTruthy(); +}); diff --git a/src/components/layout/command-palette.tsx b/src/components/layout/command-palette.tsx index c93fa5c..e3b2fb4 100644 --- a/src/components/layout/command-palette.tsx +++ b/src/components/layout/command-palette.tsx @@ -19,6 +19,18 @@ import { IconX, } from "@/components/ui/icons"; import { getUserSearch } from "@/api/users"; +import { + COMMAND_RECORD_KINDS, + COMMAND_RECORD_MIN_QUERY, + COMMAND_RECORD_ROUTES, + filterCommandRecords, + loadCommandRecords, + type CommandRecord, + type CommandRecordKind, +} from "@/lib/command-search"; +import { courseKindLabel } from "@/lib/course-kind"; +import { formatDate, formatDateTime } from "@/lib/format"; +import type { MessageKey } from "@/i18n/messages"; import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items"; import { createStudentClassLabels } from "@/lib/student-classes"; import { hasMinRole } from "@/lib/roles"; @@ -35,7 +47,21 @@ export type CommandPaletteProps = { onOpenProfile?: () => void; }; -type CommandCategory = "people" | "actions" | "pages" | "system"; +type CommandCategory = "people" | CommandRecordKind | "actions" | "pages" | "system"; + +const RECORD_GROUP_KEY: Record = { + course: "command.group.courses", + exam: "command.group.exams", + homework: "command.group.homework", + event: "command.group.events", +}; + +const RECORD_ICON: Record = { + course: IconBook, + exam: IconExam, + homework: IconHomework, + event: IconCalendar, +}; type CommandItem = { id: string; @@ -83,6 +109,48 @@ export function CommandPalette(props: CommandPaletteProps) { // each visible match is resolved to one (see `student-classes`). const classLabels = createStudentClassLabels(() => (people.latest?.items ?? []).map((person) => person.id)); + // Courses, exams, homework and events the user's own list pages show. Only + // kinds whose list page is in this user's nav are searched, read once per + // open (cached briefly across reopens) and filtered client-side per keystroke. + const recordKinds = createMemo(() => { + const routes = new Set( + visibleNavGroups(role(), modules.enabled()).flatMap((group) => group.items.map((item) => item.to)), + ); + return COMMAND_RECORD_KINDS.filter((kind) => routes.has(COMMAND_RECORD_ROUTES[kind])); + }); + const [records] = createResource( + () => { + const userRole = role(); + const kinds = recordKinds(); + return props.open && userRole && kinds.length > 0 ? { role: userRole, kinds } : null; + }, + (source) => loadCommandRecords(source.role, source.kinds), + ); + const recordDescription = (record: CommandRecord): string | undefined => { + const locale = prefs.locale(); + switch (record.kind) { + case "course": + return record.courseKind ? courseKindLabel(record.courseKind, t) : undefined; + case "exam": + return [record.context, record.at != null ? formatDateTime(record.at, locale) : null].filter(Boolean).join(" · ") || undefined; + case "homework": + return [record.context, record.at != null ? t("command.homeworkDue", { date: formatDate(record.at, locale) }) : null] + .filter(Boolean) + .join(" · ") || undefined; + case "event": + return record.at != null ? formatDateTime(record.at, locale) : undefined; + } + }; + const openRecord = (record: CommandRecord) => { + const params = { id: record.id }; + if (record.kind === "course") void navigate({ to: "/courses/$id", params }); + else if (record.kind === "exam") void navigate({ to: "/exams/$id", params }); + else if (record.kind === "homework") void navigate({ to: "/homework/$id", params }); + else void navigate({ to: "/events/$id", params }); + }; + const recordsLoading = () => + records.loading && query().trim().length >= COMMAND_RECORD_MIN_QUERY && records.latest === undefined; + const items = createMemo(() => { const list: CommandItem[] = []; const userRole = role(); @@ -300,9 +368,19 @@ export function CommandPalette(props: CommandPaletteProps) { title: person.display_name || person.username, description: classLabels()[person.id] ? `${classLabels()[person.id]} · ${person.username}` : person.username, icon: IconUsers, - onSelect: () => void navigate({ to: "/admin/users/$id", params: { id: person.id } }), + // Same destination as a row on the students list. + onSelect: () => void navigate({ to: "/profile/$userId", params: { userId: person.id } }), + })); + const matchedRecords: CommandItem[] = filterCommandRecords(records.latest ?? [], q).map((record) => ({ + id: `${record.kind}-${record.id}`, + category: record.kind, + categoryLabel: t(RECORD_GROUP_KEY[record.kind]), + title: record.title, + description: recordDescription(record), + icon: RECORD_ICON[record.kind], + onSelect: () => openRecord(record), })); - return [...found, ...items().filter((item) => + return [...found, ...matchedRecords, ...items().filter((item) => matchesSearch(q, item.title, item.description, item.keywords, item.categoryLabel), )]; }); @@ -321,7 +399,7 @@ export function CommandPalette(props: CommandPaletteProps) { map.get(item.category)!.push({ item, globalIndex: idx }); }); - const order: CommandCategory[] = ["people", "actions", "pages", "system"]; + const order: CommandCategory[] = ["people", ...COMMAND_RECORD_KINDS, "actions", "pages", "system"]; for (const cat of order) { const itemsInCat = map.get(cat); if (itemsInCat && itemsInCat.length > 0) { @@ -396,6 +474,9 @@ export function CommandPalette(props: CommandPaletteProps) { {t("common.searchPlaceholder")} {/* Search Bar Header */} -
+
- - {filteredItems().length} {t("dashboard.ready").toLowerCase()} + + {t("command.resultCount", { count: filteredItems().length })} +
{/* What the field accepts — the palette takes names, pages and @@ -452,6 +544,19 @@ export function CommandPalette(props: CommandPaletteProps) {

{role() === "admin" ? t("search.hint.commandAdmin") : t("search.hint.command")} + 0}> + {" "} + {t("search.hint.commandRecords", { + kinds: recordKinds() + .map((kind) => t(RECORD_GROUP_KEY[kind]).toLocaleLowerCase(prefs.locale() === "tr" ? "tr-TR" : "en-US")) + .join(", "), + })} + +

+
+ +

+ {t("command.recordsLoading")}

diff --git a/src/components/layout/floating-action-button.tsx b/src/components/layout/floating-action-button.tsx index 8472195..de421fa 100644 --- a/src/components/layout/floating-action-button.tsx +++ b/src/components/layout/floating-action-button.tsx @@ -1,6 +1,7 @@ import { Index, Show, createEffect, createSignal, onCleanup, onMount, type Component } from "solid-js"; import { IconChevronLeft, IconChevronRight, IconPlus, IconX } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; +import { formatUnreadCount } from "@/lib/notifications"; import { clamp01, radialOffsets, readFloatingButton, writeFloatingButton } from "@/lib/floating-button"; import { useT } from "@/stores/preferences-context"; @@ -25,7 +26,7 @@ const TAP_SLOP = 8; /** How close the button centre has to come to the hide target to snap into it. */ const HIDE_REACH = 64; -const badgeText = (count: number) => (count > 9 ? "9+" : String(count)); +const badgeText = formatUnreadCount; const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)); /** diff --git a/src/components/layout/notification-center.tsx b/src/components/layout/notification-center.tsx index eb3d0ae..b6e562a 100644 --- a/src/components/layout/notification-center.tsx +++ b/src/components/layout/notification-center.tsx @@ -3,6 +3,7 @@ import { useNavigate } from "@tanstack/solid-router"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { IconBell } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; +import { formatUnreadCount } from "@/lib/notifications"; import { createNotificationFeed } from "@/components/layout/notification-feed"; import { NotificationList } from "@/components/layout/notification-list"; import { useT } from "@/stores/preferences-context"; @@ -34,12 +35,16 @@ export function NotificationCenter() { open() && "bg-muted text-foreground" )} title={t("notifications.title")} - aria-label={t("notifications.title")} + aria-label={ + unreadCount() > 0 + ? `${t("notifications.title")} — ${t("notifications.unreadCount", { count: unreadCount() })}` + : t("notifications.title") + } > 0}> - - {unreadCount() > 9 ? "9+" : unreadCount()} + diff --git a/src/components/layout/notification-list.tsx b/src/components/layout/notification-list.tsx index 90faca8..629408e 100644 --- a/src/components/layout/notification-list.tsx +++ b/src/components/layout/notification-list.tsx @@ -1,21 +1,18 @@ import { For, Show, Suspense, createSignal } from "solid-js"; import { Button } from "@/components/ui/button"; -import { ComingSoonPanel } from "@/components/ui/coming-soon"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { IconBell, IconCalendar, IconChevronLeft, IconExam, - IconExternalLink, IconHomework, IconMessage, IconTrash, IconX, } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; -import type { NotificationItem, NotificationType } from "@/lib/notifications"; +import { formatUnreadCount, type NotificationItem, type NotificationType } from "@/lib/notifications"; import type { NotificationFeed } from "@/components/layout/notification-feed"; import { useT } from "@/stores/preferences-context"; @@ -63,16 +60,12 @@ export function NotificationList(props: { props.feed.dismiss(id); }; - const select = async (item: NotificationItem) => { - await props.feed.markRead(item); - setPreviewNotification(item); - }; - - const goTo = () => { - const item = previewNotification(); - if (!item) return; - setPreviewNotification(null); - props.onNavigate(item.targetUrl); + // A row with a target page goes straight there (marked read on the way); + // only a row with nowhere to go opens the in-list preview. + const select = (item: NotificationItem) => { + void props.feed.markRead(item); + if (item.targetUrl) props.onNavigate(item.targetUrl); + else setPreviewNotification(item); }; return ( @@ -86,8 +79,11 @@ export function NotificationList(props: {

{t("notifications.title")}

0}> - - {props.feed.unreadCount()} + + {formatUnreadCount(props.feed.unreadCount())}
@@ -111,13 +107,8 @@ export function NotificationList(props: { - - {t("notifications.tabAll")} - {t("notifications.tabSystem")} - - - +
+
@@ -171,7 +162,16 @@ export function NotificationList(props: { {(item) => (
select(item)} + onKeyDown={(event) => { + if (event.target !== event.currentTarget) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + select(item); + } + }} class="group relative flex cursor-pointer select-none items-start gap-3 rounded-lg p-2 text-xs transition-colors hover:bg-background/70" >
@@ -219,12 +219,8 @@ export function NotificationList(props: {
- - - - - - +
+
} > {(item) => ( @@ -267,10 +263,6 @@ export function NotificationList(props: {
- )}
diff --git a/src/components/layout/shell-unread-badge.test.tsx b/src/components/layout/shell-unread-badge.test.tsx index be38d97..436d9dc 100644 --- a/src/components/layout/shell-unread-badge.test.tsx +++ b/src/components/layout/shell-unread-badge.test.tsx @@ -6,13 +6,14 @@ import { PreferencesProvider } from "@/stores/preferences-context"; // The shell feed is the single source of truth for both badges; the test drives // it through signals so a refetch (new message arriving) is reproducible. -const h = vi.hoisted(() => ({ feed: null as never })); +const h = vi.hoisted(() => ({ feed: null as never, navigate: vi.fn() })); vi.mock("@/stores/shell-feed-context", () => ({ useShellFeed: () => h.feed })); +vi.mock("@/api/messages", () => ({ patchMessageById: vi.fn(async () => ({})) })); vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user: () => ({ id: "u-1" }) }) })); vi.mock("@tanstack/solid-router", () => ({ Link: (props: never) => {(props as { children: unknown }).children}, - useNavigate: () => () => undefined, + useNavigate: () => h.navigate, })); // Kobalte's popover keeps its content unmounted in jsdom; the badge and the // "dismiss all" button are the surfaces under test, so render both inline. @@ -95,3 +96,36 @@ test("dismiss all clears the badge, a later message raises it again", async () = setUnreadMessages({ ...emptyPage, items: [msg("new"), ...listed.slice(0, 9)], total: 12 }); expect(badges()).toEqual(["1"]); }); + +test("the bell badge and the list header show the same capped unread count", () => { + const listed = Array.from({ length: 10 }, (_, i) => msg(`m${i}`)); + mountFeed([], { items: listed, total: 20 }); + + render(() => ( + + + + )); + + expect(badges()).toEqual(["9+"]); + const header = screen.getByLabelText("20 unread"); + expect(header.textContent).toBe("9+"); +}); + +test("a notification with a target page opens it directly and is marked read", async () => { + h.navigate.mockClear(); + mountFeed([], { items: [msg("m1")], total: 1 }); + + render(() => ( + + + + )); + + expect(badges()).toEqual(["1"]); + fireEvent.click(screen.getByText("subject m1")); + expect(h.navigate).toHaveBeenCalledWith({ to: "/messages" }); + // No intermediate "go to page" step. + expect(screen.queryByText("Go to page")).toBeNull(); + await vi.waitFor(() => expect(badges()).toEqual([])); +}); diff --git a/src/components/meals/meal-menu-card.tsx b/src/components/meals/meal-menu-card.tsx index 0ab59dc..0916eff 100644 --- a/src/components/meals/meal-menu-card.tsx +++ b/src/components/meals/meal-menu-card.tsx @@ -2,7 +2,6 @@ import { For, Show } from "solid-js"; import { Link } from "@tanstack/solid-router"; import type { MealMenu } from "@/api/client"; import { Badge } from "@/components/ui/badge"; -import { ComingSoonBadge, ComingSoonValue } from "@/components/ui/coming-soon"; import { IconAlert, IconUtensils } from "@/components/ui/icons"; import { dietaryTagLabel, formatTry, mealSlotLabel } from "@/lib/meals"; import { useT } from "@/stores/preferences-context"; @@ -10,7 +9,7 @@ import { useT } from "@/stores/preferences-context"; export function MealMenuCard(props: { menu: MealMenu; locale: string; - labels: { dishes: string; capacity: string; conflict: string; reservations?: string; topPick: string }; + labels: { dishes: string; capacity: string; conflict: string; reservations?: string }; /** * Confirmed booking count for this menu (`getMealMenuBookings(...).total`), * manager+ only per the backend's booking-audit scope. Undefined for @@ -37,7 +36,6 @@ export function MealMenuCard(props: { {formatTry(total(), props.locale)} -
{(dish) => {dish.name}}
0}>
@@ -59,10 +57,6 @@ export function MealMenuCard(props: { {props.menu.dishes.length} {props.labels.dishes} {props.labels.capacity}: {props.menu.capacity ?? "∞"}
-
- {props.labels.topPick} - -
); } diff --git a/src/components/messages/gmail-compose-box.test.tsx b/src/components/messages/gmail-compose-box.test.tsx new file mode 100644 index 0000000..7ab1bf7 --- /dev/null +++ b/src/components/messages/gmail-compose-box.test.tsx @@ -0,0 +1,40 @@ +import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library"; +import { GmailComposeBox } from "@/components/messages/gmail-compose-box"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ user: () => ({ id: "user-1", username: "teacher", role: "teacher" }) }), +})); +vi.mock("@/api/messages", () => ({ postMessage: vi.fn() })); +// The real picker searches the API; a plain button stands in for choosing someone. +vi.mock("@/components/users/user-search-select", () => ({ + UserSearchSelect: (props: { onChange: (id: string) => void }) => ( + + ), +})); +vi.mock("@/components/ui/rich-text-editor", () => ({ RichTextEditor: () =>
})); + +afterEach(cleanup); + +test("send stays disabled until there is a recipient and a subject, and says what is missing", () => { + render(() => ( + + {}} onSuccess={() => {}} /> + + )); + + const send = screen.getByRole("button", { name: "Send" }) as HTMLButtonElement; + expect(send.disabled).toBe(true); + expect(screen.getByText("Choose a recipient to send.")).toBeTruthy(); + + fireEvent.click(screen.getByText("pick recipient")); + expect(send.disabled).toBe(true); + expect(screen.getByText("Add a subject to send.")).toBeTruthy(); + + fireEvent.input(screen.getByLabelText("Subject"), { target: { value: " " } }); + expect(send.disabled).toBe(true); + + fireEvent.input(screen.getByLabelText("Subject"), { target: { value: "Veli toplantısı" } }); + expect(send.disabled).toBe(false); + expect(screen.queryByText("Add a subject to send.")).toBeNull(); +}); diff --git a/src/components/messages/gmail-compose-box.tsx b/src/components/messages/gmail-compose-box.tsx index be96d42..f5cdd2e 100644 --- a/src/components/messages/gmail-compose-box.tsx +++ b/src/components/messages/gmail-compose-box.tsx @@ -70,10 +70,18 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { else handleClose(); }; + // The backend needs a recipient and a subject (the body is optional), so + // "Gönder" stays off until both are there and says which one is missing. + const sendBlocker = () => { + if (!recipient()) return t("messages.sendHintRecipient"); + if (!subject().trim()) return t("messages.sendHintSubject"); + return ""; + }; + const handleSend = async (e: SubmitEvent) => { e.preventDefault(); - if (!recipient()) { - setError(t("messages.selectRecipient")); + if (sendBlocker()) { + setError(sendBlocker()); return; } setError(""); @@ -154,12 +162,13 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { {/* Subject Line */}
- {t("form.title")}: + {t("messages.subject")}: setSubject(e.currentTarget.value)} @@ -169,10 +178,11 @@ export function GmailComposeBox(props: GmailComposeBoxProps) { {/* Optional Label Tag Line */}
- Etiket: + {t("messages.label")}: {/* Gmail Bottom Action Toolbar */} -
- +
+
+ + +

+ {sendBlocker()} +

+
+
@@ -102,7 +105,7 @@ export const ChartBar: Component = (props) => {
- {item.label}: {item.formattedValue ?? item.value} ({Math.round(pct())}%) + {item.label}: {display(item)} ({Math.round(pct())}%)
); diff --git a/src/components/ui/chart-line.tsx b/src/components/ui/chart-line.tsx index 4b56e34..893d2d8 100644 --- a/src/components/ui/chart-line.tsx +++ b/src/components/ui/chart-line.tsx @@ -1,6 +1,7 @@ import { For, Show, createMemo, type Component } from "solid-js"; import { cn } from "@/lib/cn"; -import { useT } from "@/stores/preferences-context"; +import { usePreferences } from "@/stores/preferences-context"; +import { formatDecimal } from "@/lib/format"; import { EmptyInline } from "@/components/ui/empty-inline"; export type ChartLineItem = { @@ -25,9 +26,11 @@ const PADDING = { top: 18, right: 18, bottom: 34, left: 38 }; const Y_TICKS = [0, 25, 50, 75, 100]; const TOOLTIP_WIDTH = 190; const TOOLTIP_HEIGHT = 62; +const TICK_MAX_CHARS = 14; export const ChartLine: Component = (props) => { - const t = useT(); + const { t, locale } = usePreferences(); + const decimal = (value: number) => formatDecimal(value, locale()); const maxValue = () => props.maxScale != null && props.maxScale > 0 ? props.maxScale : Math.max(...props.items.map((item) => item.value), 1); @@ -67,6 +70,14 @@ export const ChartLine: Component = (props) => { if (indexes[indexes.length - 1] !== props.items.length - 1) indexes.push(props.items.length - 1); return indexes; }); + // An axis tick has ~1/6 of the width, so it carries the item's caption (a + // short date) or, when there is none, its position. Full labels overlap + // each other and are already in the tooltip and the "latest" line. + const tickLabel = (index: number) => { + const caption = props.items[index].caption; + if (!caption) return String(index + 1); + return caption.length > TICK_MAX_CHARS ? `${caption.slice(0, TICK_MAX_CHARS - 1)}…` : caption; + }; const averageY = () => PADDING.top + (1 - Math.min(1, summary()!.average / maxValue())) * plotHeight; return ( @@ -99,11 +110,11 @@ export const ChartLine: Component = (props) => {
{t("dashboard.chartAverage")}
-
{stats().average.toFixed(1)}
+
{decimal(stats().average)}
{t("dashboard.chartRange")}
-
{stats().minimum.toFixed(1)}–{stats().maximum.toFixed(1)}
+
{decimal(stats().minimum)}–{decimal(stats().maximum)}
@@ -137,9 +148,6 @@ export const ChartLine: Component = (props) => { stroke-width="1" stroke-dasharray="4 4" /> - - {t("dashboard.chartAverage")}: {stats().average.toFixed(1)} - @@ -198,7 +206,7 @@ export const ChartLine: Component = (props) => { text-anchor={index === 0 ? "start" : index === props.items.length - 1 ? "end" : "middle"} class="fill-muted-foreground text-[11px]" > - {props.items[index].caption ?? props.items[index].label} + {tickLabel(index)} ); }} diff --git a/src/components/ui/chart-progress-ring.tsx b/src/components/ui/chart-progress-ring.tsx index 08e1422..dea46ef 100644 --- a/src/components/ui/chart-progress-ring.tsx +++ b/src/components/ui/chart-progress-ring.tsx @@ -2,7 +2,8 @@ import { For, Show, createEffect, createMemo, createSignal, type Component } fro import { cn } from "@/lib/cn"; import { EmptyInline } from "@/components/ui/empty-inline"; import { TablePagination } from "@/components/ui/table-pagination"; -import { useT } from "@/stores/preferences-context"; +import { formatNumber } from "@/lib/format"; +import { usePreferences, useT } from "@/stores/preferences-context"; export type ProgressRingSegment = { id: string; @@ -25,6 +26,8 @@ export type ChartProgressRingProps = { export const ChartProgressRing: Component = (props) => { const t = useT(); + const { locale } = usePreferences(); + const num = (value: number) => formatNumber(value, locale()); const [pageIndex, setPageIndex] = createSignal(0); // The gauge bar above always renders every segment's share of the total — // only the legend cards below it are paged. @@ -65,7 +68,7 @@ export const ChartProgressRing: Component = (props) => { {/* Total Stat Highlight */}
- {props.valueText ?? calculatedTotal()} + {props.valueText ?? num(calculatedTotal())} {props.subtext} @@ -82,7 +85,7 @@ export const ChartProgressRing: Component = (props) => {
); @@ -99,7 +102,7 @@ export const ChartProgressRing: Component = (props) => { {segment.label}
- {segment.value} + {num(segment.value)}
)} diff --git a/src/components/ui/combobox.tsx b/src/components/ui/combobox.tsx index dfba06d..ccb4f57 100644 --- a/src/components/ui/combobox.tsx +++ b/src/components/ui/combobox.tsx @@ -5,7 +5,30 @@ import { IconCheck, IconChevronDown } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; import { useT } from "@/stores/preferences-context"; -export const Combobox = ComboboxPrimitive; +/** + * Kobalte's Combobox root with its screen-reader strings (listbox name, + * trigger name, focus/selection/count announcements) in the app language — + * Kobalte ships them in English only. A call site can still pass its own + * `translations`, which wins. + */ +function ComboboxRoot(props: ComponentProps) { + const t = useT(); + const translations = () => ({ + focusAnnouncement: (optionText: string, isSelected: boolean) => + isSelected ? t("combobox.optionSelected", { option: optionText }) : optionText, + // Kobalte's type narrows this to its own English literal; the runtime + // only needs a string (or undefined for "say nothing"). + countAnnouncement: ((optionCount: number) => t("combobox.optionCount", { count: optionCount })) as unknown as ( + optionCount: number, + ) => "one option available" | undefined, + selectedAnnouncement: (optionText: string) => t("combobox.optionSelected", { option: optionText }), + triggerLabel: t("combobox.showSuggestions"), + listboxLabel: t("combobox.suggestions"), + }); + return ; +} + +export const Combobox = Object.assign(ComboboxRoot, ComboboxPrimitive) as unknown as typeof ComboboxPrimitive; export const ComboboxItemLabel = ComboboxPrimitive.ItemLabel; export const ComboboxHiddenSelect = ComboboxPrimitive.HiddenSelect; diff --git a/src/components/ui/coming-soon.tsx b/src/components/ui/coming-soon.tsx deleted file mode 100644 index 2d86972..0000000 --- a/src/components/ui/coming-soon.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import type { ParentProps } from "solid-js"; -import { Badge } from "@/components/ui/badge"; -import { cn } from "@/lib/cn"; -import { useT } from "@/stores/preferences-context"; - -export function ComingSoonBadge(props: { class?: string }) { - const t = useT(); - return ( - // `data-coming-soon` lets a toolbar find the control carrying it — phones - // drop a button that can only say "not yet" (see DataTable's toolbar). - - {t("comingSoon.title")} - - ); -} - -/** - * Stands in for a value the design shows but no endpoint can fill yet. Renders - * the slot the design allots so the layout keeps its shape, and says plainly - * that the number is not here rather than printing a placeholder digit a - * reader would take for real. - */ -export function ComingSoonValue(props: { class?: string }) { - const t = useT(); - return ( - - - {t("comingSoon.title")} - - ); -} - -export function ComingSoonPanel(props: ParentProps<{ title: string; class?: string }>) { - const t = useT(); - return ( -
-
-

{props.title}

- -
-

{t("comingSoon.description")}

- {props.children} -
- ); -} diff --git a/src/components/ui/data-table.test.tsx b/src/components/ui/data-table.test.tsx index 1f5e3f1..1170c4d 100644 --- a/src/components/ui/data-table.test.tsx +++ b/src/components/ui/data-table.test.tsx @@ -58,7 +58,7 @@ test("keeps only the rightmost action column sticky and fixed at 110x45", () => expect(roleHeader?.classList).not.toContain("table-sticky-head-right"); }); -test("freezes the meta.stickyLeft column and keeps the table centered", () => { +test("freezes the meta.stickyLeft column and centres headers and left-aligns cells", () => { const alignedColumns: ColumnDef[] = [ { accessorKey: "name", header: "Name", meta: { stickyLeft: true } }, { accessorKey: "role", header: "Role", meta: { align: "right" } }, @@ -78,7 +78,7 @@ test("freezes the meta.stickyLeft column and keeps the table centered", () => { const roleCell = screen.getByRole("cell", { name: "Admin" }); // List tables use one consistent centered alignment, including numeric columns. expect(roleHeader?.classList).toContain("text-center"); - expect(roleCell.classList).toContain("text-center"); + expect(roleCell.classList).toContain("text-left"); }); test("paginates tables by default", () => { diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index 6588323..20fa795 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -40,7 +40,7 @@ declare module "@tanstack/solid-table" { stickyLeft?: boolean; /** Vertical divider on the given edge — separates frozen label from metric columns. */ divider?: "left" | "right"; - /** Leave this column out of the phone card layout (e.g. a "yakında" placeholder). */ + /** Leave this column out of the phone card layout (e.g. a column that only matters on a wide table). */ hideInCards?: boolean; } } @@ -220,7 +220,17 @@ export function DataTable(props: DataTableProps columnId === "actions" || (columnId === "update" && table.getColumn("actions") == null); const isStickyLeft = (column: Column) => column.columnDef.meta?.stickyLeft === true; - const alignOf = (_column: Column) => "center" as const; + // Headers stay centred; body cells read from the left edge. System columns + // (row actions, checkboxes) keep their controls centred under the header. + const isSystemColumnId = (columnId: string) => ["actions", "update", "select"].includes(columnId); + const alignOf = (column: Column) => isSystemColumnId(column.id) ? "center" as const : "left" as const; + // Cell renderers written for the old centred layout carry their own + // mx-auto / justify-center / text-center on their root; pull those to the + // start. Direct children only: deeper centring (avatar initials, icon + // buttons) is the widget's own layout, not the column's. + const leftCellClass = (column: Column) => isSystemColumnId(column.id) + ? undefined + : "[&>.mx-auto]:mx-0 [&>.justify-center]:justify-start [&>.text-center]:text-left"; const dividerClass = (column: Column) => { const divider = column.columnDef.meta?.divider; return divider === "left" ? "border-l border-border/70" : divider === "right" ? "border-r border-border/70" : undefined; @@ -438,9 +448,7 @@ export function DataTable(props: DataTableProps - {/* A "yakında" button does nothing yet; on a phone it only - pushes the working action off the search row. */} -
{props.actions}
+
{props.actions}
@@ -610,6 +618,7 @@ export function DataTable(props: DataTableProps) { // frame's bottom edge it covered the last row's action button. return (
-
+
{props.children}
diff --git a/src/components/ui/data-toolbar.tsx b/src/components/ui/data-toolbar.tsx index 836d315..7efe7c4 100644 --- a/src/components/ui/data-toolbar.tsx +++ b/src/components/ui/data-toolbar.tsx @@ -36,7 +36,7 @@ export function DataToolbar(props: {
{props.filters}
-
{props.actions}
+
{props.actions}
); diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index 04d7b48..9741c16 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -1,6 +1,6 @@ import { Dialog as DialogPrimitive } from "@kobalte/core/dialog"; import type { ComponentProps, ParentProps, ValidComponent } from "solid-js"; -import { splitProps } from "solid-js"; +import { Show, splitProps } from "solid-js"; import { IconX } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; @@ -9,13 +9,12 @@ export const DialogTrigger = DialogPrimitive.Trigger; export const DialogClose = DialogPrimitive.CloseButton; export function DialogContent( - props: ComponentProps> & { dismissable?: boolean }, + props: ComponentProps> & { dismissable?: boolean; closeButton?: boolean }, ) { - const [local, rest] = splitProps(props as ComponentProps & { dismissable?: boolean }, [ - "class", - "children", - "dismissable", - ]); + const [local, rest] = splitProps( + props as ComponentProps & { dismissable?: boolean; closeButton?: boolean }, + ["class", "children", "dismissable", "closeButton"], + ); return ( {/* z-[70]: above the mobile nav sheet (z-60) and tab bar (z-40). */} @@ -39,6 +38,9 @@ export function DialogContent( onEscapeKeyDown={local.dismissable === false ? (e) => e.preventDefault() : undefined} {...rest} > + {/* `closeButton={false}` lets a dialog draw its own close control + (the command palette labels it, beside its clear-search ×). */} + ( > + {local.children}
diff --git a/src/components/whiteboard/whiteboard-canvas.tsx b/src/components/whiteboard/whiteboard-canvas.tsx index 6e89833..811880b 100644 --- a/src/components/whiteboard/whiteboard-canvas.tsx +++ b/src/components/whiteboard/whiteboard-canvas.tsx @@ -9,9 +9,18 @@ import { type Point, type Stroke, } from "@/lib/draw-stroke"; +import type { MessageKey } from "@/i18n/messages"; import { useT } from "@/stores/preferences-context"; const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; +/** Spoken name of each swatch — a hex code is no accessible name. */ +const COLOR_NAMES: Record = { + "#1f2937": "draw.colorName.black", + "#dc2626": "draw.colorName.red", + "#2563eb": "draw.colorName.blue", + "#16a34a": "draw.colorName.green", + "#ca8a04": "draw.colorName.yellow", +}; const WIDTHS = [2, 6, 14]; const ZOOM_MIN = 0.25; const ZOOM_MAX = 4; @@ -55,7 +64,10 @@ export function WhiteboardCanvas(props: { const [color, setColor] = createSignal(COLORS[0]); const [width, setWidth] = createSignal(WIDTHS[1]); const [erasing, setErasing] = createSignal(false); - const [hand, setHand] = createSignal(false); + // The board opens on the hand tool: it is a shared live canvas, so a stray + // tap or scroll must not leave a mark for everyone — drawing starts only + // once the pen (or a colour) is picked. + const [hand, setHand] = createSignal(true); const [override, setOverride] = createSignal(null); const [pan, setPan] = createSignal({ x: 0, y: 0 }); const [panning, setPanning] = createSignal(false); @@ -238,6 +250,7 @@ export function WhiteboardCanvas(props: { type="button" class={toolClass(activeTool() === "pen")} title={t("draw.pen")} + aria-pressed={activeTool() === "pen"} onClick={() => { setErasing(false); setHand(false); @@ -250,6 +263,7 @@ export function WhiteboardCanvas(props: { type="button" class={toolClass(activeTool() === "erase")} title={t("draw.eraser")} + aria-pressed={activeTool() === "erase"} onClick={() => { setErasing(true); setHand(false); @@ -262,6 +276,7 @@ export function WhiteboardCanvas(props: { type="button" class={toolClass(activeTool() === "pan")} title={t("draw.pan")} + aria-pressed={activeTool() === "pan"} onClick={() => setHand(true)} > @@ -275,7 +290,9 @@ export function WhiteboardCanvas(props: { {(swatch) => ( + /> )} ); @@ -300,12 +315,13 @@ export function WhiteboardCanvas(props: { {(size) => ( )} @@ -347,7 +363,7 @@ export function WhiteboardCanvas(props: { />

- {t("whiteboard.canvasHint")} + {activeTool() === "pan" && !props.disabled ? t("whiteboard.canvasHintPickPen") : t("whiteboard.canvasHint")}

diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index f85f754..bc2fc63 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -377,7 +377,7 @@ export const en: Dict = { "notifications.empty": "No new notifications yet.", "notifications.tabAll": "All", "notifications.tabSystem": "System", - "notifications.goToPage": "Go to page", + "notifications.unreadCount": "{count} unread", "errors.notFoundDescription": "The page you're looking for may have moved or been deleted.", "errors.accessDeniedDescription": "Your role can't view this section. Ask an administrator if you need access.", "network.offlineTitle": "You're offline", @@ -801,6 +801,11 @@ export const en: Dict = { "auth.passwordHint": "6–128 characters", "auth.showPassword": "Show password", "auth.hidePassword": "Hide password", + "auth.showConfirmPassword": "Show password confirmation", + "auth.hideConfirmPassword": "Hide password confirmation", + "auth.schoolCodeHint": "The school code your school gave you (not the school's name): lowercase letters, digits and hyphens, {min}–{max} characters.", + "auth.passwordMinHint": "At least {min} characters.", + "auth.passwordTooShort": "The password needs at least {min} characters.", "auth.welcomeBack": "Good to see you again", "auth.createStudent": "Create student account", "dashboard.greeting": "Hello, {name}", @@ -841,11 +846,11 @@ export const en: Dict = { "command.action.createExamDesc": "Prepare new exam for students", "command.action.createNote": "Create note", "command.action.createNoteDesc": "Save a personal or class note", - "command.action.importNote": "Import note assistant", + "command.action.importNote": "Note import assistant", "command.action.importNoteDesc": "Convert PDF or text files to note", "command.action.askQuestion": "Ask / add question", "command.action.askQuestionDesc": "Ask question or add to community pool", - "command.action.askCelebi": "Ask Çelebi AI", + "command.action.askCelebi": "Chat with Çelebi", "command.action.askCelebiDesc": "Chat with smart AI assistant", "command.action.myProfile": "My profile", "command.action.myProfileDesc": "User account and profile details", @@ -860,6 +865,14 @@ export const en: Dict = { "command.key.navigate": "navigate", "command.key.select": "select", "command.key.close": "close", + "command.group.courses": "Courses", + "command.group.exams": "Exams", + "command.group.homework": "Homework", + "command.group.events": "Events", + "command.recordsLoading": "Loading courses, exams and other records…", + "command.resultCount": "{count} results", + "command.homeworkDue": "Due {date}", + "search.hint.commandRecords": "You can also search by name: {kinds}.", "command.action.themeDarkDesc": "Switch to dark mode", "command.action.themeLightDesc": "Switch to light mode", "command.action.langTrDesc": "Switch to Turkish", @@ -1180,6 +1193,32 @@ export const en: Dict = { "draw.bgNone": "Plain", "draw.bgLines": "Lines", "draw.bgGrid": "Grid", + "draw.colorName.black": "Black", + "draw.colorName.red": "Red", + "draw.colorName.blue": "Blue", + "draw.colorName.green": "Green", + "draw.colorName.yellow": "Yellow", + "whiteboard.canvasHintPickPen": "Pick the pen to draw — everyone on the board sees it live.", + "exams.publishOnCreateWarning": "Not a draft: the exam opens to students before any question is added.", + "exams.publishEmptyTitle": "Publish without questions?", + "exams.publishEmptyWarning": "This exam has no questions. If you publish it, students will see an empty exam.", + "exams.publishAnyway": "Publish anyway", + "exams.savedAsDraftHint": "The exam is saved as a draft; publish it from the list when it is ready.", + "events.status.present": "Attended", + "events.status.absent": "Did not attend", + "events.status.late": "Arrived late", + "events.status.excused": "Excused", + "events.rollCall.notStarted": "Roll call opens when the event starts.", + "events.rollCall.opensAt": "Roll call opens when the event starts ({date}). Recorded statuses are shown below.", + "events.rollCall.emptyRoster": "Nobody is in this event's audience.", + "events.rollCall.searchHint": "Searches name, username or student number.", + "events.rollCall.markRestPresent": "Mark the rest Attended", + "events.rollCall.unsaved": "{status} · not saved", + "events.rollCall.saveFailed": "{failed} of {total} rows could not be saved. The errors are shown on those rows.", + "events.rollCall.saved": "{count} attendance marks saved.", + "events.rollCall.pendingChanges": "{count} unsaved changes", + "events.rollCall.noChanges": "No unsaved changes", + "events.rollCall.discard": "Discard changes", "notes.downloadFile": "Download", "notes.noFiles": "No files attached.", "notes.fileLimit": "This note already has 10 files.", @@ -1201,7 +1240,7 @@ export const en: Dict = { "events.myAttendance": "My attendance", "events.myAttendanceHelp": "Choose your event status and save it.", "events.studentAttendance": "Student attendance", - "events.studentAttendanceHelp": "Select a student, choose a status, then save the record.", + "events.studentAttendanceHelp": "Everyone in the event's audience is listed. Pick a status on each row, then save them all at once.", "events.saveStudentAttendance": "Save attendance", "events.attendance": "Attendance roster", "events.attendanceRecords": "Attendance records", @@ -2346,6 +2385,9 @@ export const en: Dict = { "homework.gradeStatusPlaceholder": "Choose a status", "homework.gradeStatusRequired": "Choose a status before saving.", "combobox.showSuggestions": "Show suggestions", + "combobox.suggestions": "Suggestions", + "combobox.optionSelected": "{option}, selected", + "combobox.optionCount": "Options available: {count}", "course.removeStudentTitle": "Remove the student from this course?", "course.removeStudentHint": "Their enrollment in this class's course is removed; the account itself is not deleted.", "course.removeStudentAction": "Remove from course", @@ -2359,6 +2401,12 @@ export const en: Dict = { "instances.karneTurnOff": "Stop counting", "messages.discardDraftTitle": "Discard this draft?", "messages.discardDraftHint": "What you wrote in this message has not been sent and will be lost.", + "messages.folders": "Folders", + "messages.subject": "Subject", + "messages.subjectPlaceholder": "What the message is about", + "messages.label": "Label", + "messages.sendHintRecipient": "Choose a recipient to send.", + "messages.sendHintSubject": "Add a subject to send.", "errors.studentOnlyTitle": "This page is for students", "errors.parentOnlyTitle": "This page is for parents", "errors.audienceOnlyDescription": "This view is shown only to the student or parent signed in to their own account; staff accounts do not open it.", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index 52a17d7..01d7db4 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -373,7 +373,7 @@ export const tr: Dict = { "notifications.empty": "Henüz yeni bir bildiriminiz yok.", "notifications.tabAll": "Tümü", "notifications.tabSystem": "Sistem", - "notifications.goToPage": "Sayfaya git", + "notifications.unreadCount": "{count} okunmamış", "errors.notFoundDescription": "Aradığın sayfa taşınmış ya da silinmiş olabilir.", "errors.accessDeniedDescription": "Rolün bu bölümü görüntülemeye yetkili değil. Gerekliyse kurum yöneticinden yetki iste.", "network.offlineTitle": "Bağlantın koptu", @@ -797,6 +797,11 @@ export const tr: Dict = { "auth.passwordHint": "6–128 karakter", "auth.showPassword": "Şifreyi göster", "auth.hidePassword": "Şifreyi gizle", + "auth.showConfirmPassword": "Şifre onayını göster", + "auth.hideConfirmPassword": "Şifre onayını gizle", + "auth.schoolCodeHint": "Okulunun sana ilettiği okul kodu (okul adı değil): küçük harf, rakam ve tire, {min}–{max} karakter.", + "auth.passwordMinHint": "En az {min} karakter.", + "auth.passwordTooShort": "Şifre en az {min} karakter olmalı.", "auth.welcomeBack": "Seni yeniden görmek güzel", "auth.createStudent": "Öğrenci hesabı oluştur", "dashboard.greeting": "Merhaba, {name}", @@ -837,11 +842,11 @@ export const tr: Dict = { "command.action.createExamDesc": "Öğrenciler için yeni sınav tanımla", "command.action.createNote": "Ders notu ekle", "command.action.createNoteDesc": "Kişisel veya ders notu kaydet", - "command.action.importNote": "Not içe aktar assistant", + "command.action.importNote": "Not içe aktarma yardımcısı", "command.action.importNoteDesc": "PDF veya metin belgesini not haline getir", "command.action.askQuestion": "Soru sor / havuza ekle", "command.action.askQuestionDesc": "Soru havuzuna yeni soru ekle", - "command.action.askCelebi": "Çelebi AI ile konuş", + "command.action.askCelebi": "Çelebi ile sohbet et", "command.action.askCelebiDesc": "Yapay zeka asistanı ile sohbet et", "command.action.myProfile": "Profil bilgilerim", "command.action.myProfileDesc": "Kullanıcı hesabı ve profil detayları", @@ -856,6 +861,14 @@ export const tr: Dict = { "command.key.navigate": "gezin", "command.key.select": "seç", "command.key.close": "kapat", + "command.group.courses": "Dersler", + "command.group.exams": "Sınavlar", + "command.group.homework": "Ödevler", + "command.group.events": "Etkinlikler", + "command.recordsLoading": "Dersler, sınavlar ve diğer kayıtlar yükleniyor…", + "command.resultCount": "{count} sonuç", + "command.homeworkDue": "Teslim: {date}", + "search.hint.commandRecords": "Adıyla da arayabilirsiniz: {kinds}.", "command.action.themeDarkDesc": "Koyu moda geç", "command.action.themeLightDesc": "Açık moda geç", "command.action.langTrDesc": "Türkçe diline geç", @@ -1176,6 +1189,32 @@ export const tr: Dict = { "draw.bgNone": "Düz", "draw.bgLines": "Çizgili", "draw.bgGrid": "Kareli", + "draw.colorName.black": "Siyah", + "draw.colorName.red": "Kırmızı", + "draw.colorName.blue": "Mavi", + "draw.colorName.green": "Yeşil", + "draw.colorName.yellow": "Sarı", + "whiteboard.canvasHintPickPen": "Çizmek için kalemi seç — tahtadaki herkes anlık görür.", + "exams.publishOnCreateWarning": "Taslak işaretli değil: sınav, soru eklenmeden öğrencilere açılır.", + "exams.publishEmptyTitle": "Soru olmadan yayınlansın mı?", + "exams.publishEmptyWarning": "Bu sınavda hiç soru yok. Yayınlarsan öğrenciler boş bir sınav görür.", + "exams.publishAnyway": "Yine de yayınla", + "exams.savedAsDraftHint": "Sınav taslak olarak kaydedildi; hazır olduğunda listeden yayınla.", + "events.status.present": "Katıldı", + "events.status.absent": "Katılmadı", + "events.status.late": "Geç geldi", + "events.status.excused": "Mazeretli", + "events.rollCall.notStarted": "Yoklama etkinlik başladığında açılır.", + "events.rollCall.opensAt": "Yoklama etkinlik başladığında açılır ({date}). Kayıtlı durumlar aşağıda görünür.", + "events.rollCall.emptyRoster": "Bu etkinliğin hedef kitlesinde kimse yok.", + "events.rollCall.searchHint": "Ad, kullanıcı adı veya öğrenci numarasında arar.", + "events.rollCall.markRestPresent": "Kalanları Katıldı işaretle", + "events.rollCall.unsaved": "{status} · kaydedilmedi", + "events.rollCall.saveFailed": "{total} satırdan {failed} tanesi kaydedilemedi. Hatalar ilgili satırlarda.", + "events.rollCall.saved": "{count} yoklama kaydedildi.", + "events.rollCall.pendingChanges": "{count} değişiklik kaydedilmedi", + "events.rollCall.noChanges": "Kaydedilmemiş değişiklik yok", + "events.rollCall.discard": "Değişiklikleri at", "notes.downloadFile": "İndir", "notes.noFiles": "Henüz dosya eklenmemiş.", "notes.fileLimit": "Bu notta zaten 10 dosya var.", @@ -1197,7 +1236,7 @@ export const tr: Dict = { "events.myAttendance": "Katılım durumum", "events.myAttendanceHelp": "Etkinlik durumunu seç ve kaydet.", "events.studentAttendance": "Öğrenci yoklaması", - "events.studentAttendanceHelp": "Öğrenciyi seç, durumunu belirle, kaydı kaydet.", + "events.studentAttendanceHelp": "Etkinliğin hedef kitlesindeki herkes listede. Her satırda durumu seç, sonra tek seferde kaydet.", "events.saveStudentAttendance": "Yoklamayı kaydet", "events.attendance": "Yoklama listesi", "events.attendanceRecords": "Yoklama kayıtları", @@ -2342,6 +2381,9 @@ export const tr: Dict = { "homework.gradeStatusPlaceholder": "Durum seç", "homework.gradeStatusRequired": "Kaydetmeden önce bir durum seç.", "combobox.showSuggestions": "Önerileri göster", + "combobox.suggestions": "Öneriler", + "combobox.optionSelected": "{option}, seçili", + "combobox.optionCount": "Seçenek sayısı: {count}", "course.removeStudentTitle": "Öğrenci bu dersten çıkarılsın mı?", "course.removeStudentHint": "Öğrencinin bu şubedeki ders kaydı kaldırılır; hesabı silinmez.", "course.removeStudentAction": "Dersten çıkar", @@ -2355,6 +2397,12 @@ export const tr: Dict = { "instances.karneTurnOff": "Karneye işleme", "messages.discardDraftTitle": "Taslak atılsın mı?", "messages.discardDraftHint": "Bu mesaja yazdıkların gönderilmedi ve kaybolacak.", + "messages.folders": "Klasörler", + "messages.subject": "Konu", + "messages.subjectPlaceholder": "Mesajın konusu", + "messages.label": "Etiket", + "messages.sendHintRecipient": "Göndermek için bir alıcı seçin.", + "messages.sendHintSubject": "Göndermek için bir konu yazın.", "errors.studentOnlyTitle": "Bu sayfa öğrenciler için", "errors.parentOnlyTitle": "Bu sayfa veliler için", "errors.audienceOnlyDescription": "Bu görünüm yalnızca kendi hesabıyla giriş yapan öğrenci ya da veliye gösterilir; personel hesaplarında açılmaz.", diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 9a534ce..d5cf92a 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -581,7 +581,7 @@ export type MessageKey = | "notifications.empty" | "notifications.tabAll" | "notifications.tabSystem" - | "notifications.goToPage" + | "notifications.unreadCount" | "errors.notFoundDescription" | "errors.accessDeniedDescription" | "network.offlineTitle" @@ -788,6 +788,11 @@ export type MessageKey = | "auth.passwordHint" | "auth.showPassword" | "auth.hidePassword" + | "auth.showConfirmPassword" + | "auth.hideConfirmPassword" + | "auth.schoolCodeHint" + | "auth.passwordMinHint" + | "auth.passwordTooShort" | "auth.welcomeBack" | "auth.createStudent" | "dashboard.greeting" @@ -851,6 +856,14 @@ export type MessageKey = | "command.key.navigate" | "command.key.select" | "command.key.close" + | "command.group.courses" + | "command.group.exams" + | "command.group.homework" + | "command.group.events" + | "command.recordsLoading" + | "command.resultCount" + | "command.homeworkDue" + | "search.hint.commandRecords" | "dashboard.observationOnly" | "dashboard.today" | "dashboard.reportCard" @@ -1167,6 +1180,32 @@ export type MessageKey = | "draw.bgNone" | "draw.bgLines" | "draw.bgGrid" + | "draw.colorName.black" + | "draw.colorName.red" + | "draw.colorName.blue" + | "draw.colorName.green" + | "draw.colorName.yellow" + | "whiteboard.canvasHintPickPen" + | "exams.publishOnCreateWarning" + | "exams.publishEmptyTitle" + | "exams.publishEmptyWarning" + | "exams.publishAnyway" + | "exams.savedAsDraftHint" + | "events.status.present" + | "events.status.absent" + | "events.status.late" + | "events.status.excused" + | "events.rollCall.notStarted" + | "events.rollCall.opensAt" + | "events.rollCall.emptyRoster" + | "events.rollCall.searchHint" + | "events.rollCall.markRestPresent" + | "events.rollCall.unsaved" + | "events.rollCall.saveFailed" + | "events.rollCall.saved" + | "events.rollCall.pendingChanges" + | "events.rollCall.noChanges" + | "events.rollCall.discard" | "notes.downloadFile" | "notes.noFiles" | "notes.fileLimit" @@ -2326,6 +2365,9 @@ export type MessageKey = | "homework.gradeStatusPlaceholder" | "homework.gradeStatusRequired" | "combobox.showSuggestions" + | "combobox.suggestions" + | "combobox.optionSelected" + | "combobox.optionCount" | "course.removeStudentTitle" | "course.removeStudentHint" | "course.removeStudentAction" @@ -2339,6 +2381,12 @@ export type MessageKey = | "instances.karneTurnOff" | "messages.discardDraftTitle" | "messages.discardDraftHint" + | "messages.folders" + | "messages.subject" + | "messages.subjectPlaceholder" + | "messages.label" + | "messages.sendHintRecipient" + | "messages.sendHintSubject" | "errors.studentOnlyTitle" | "errors.parentOnlyTitle" | "errors.audienceOnlyDescription" diff --git a/src/index.css b/src/index.css index 1209478..3f4eb5e 100644 --- a/src/index.css +++ b/src/index.css @@ -242,6 +242,19 @@ box-shadow: -4px 0 6px -6px color-mix(in srgb, hsl(var(--foreground)) 12%, transparent); } +/* Frozen columns only cast their seam when something can slide under them. + * On a table that fits, the shadow and heavier rule read as "more content to + * the side" and invite a scroll that goes nowhere. */ +.data-table-wrap:not([data-scrollable]) :is(.table-sticky-left, .table-sticky-right, .table-sticky-head-left, .table-sticky-head-right) { + box-shadow: none; +} +.data-table-wrap:not([data-scrollable]) :is(.table-sticky-right, .table-sticky-head-right) { + border-left-color: transparent; +} +.data-table-wrap:not([data-scrollable]) :is(.table-sticky-left, .table-sticky-head-left) { + border-right-color: var(--color-border-hairline); +} + /* İşlemler sütunu: sabit 110x45. */ .data-table td.table-action-cell, .data-table th.table-action-cell { @@ -261,6 +274,11 @@ text-align: center; } +/* Headers centred, values from the left edge, as on every other table. */ +.insight-grid-table td:not(.table-action-cell) { + text-align: left; +} + .insight-grid-table th:last-child, .insight-grid-table td:last-child { border-right: 0; diff --git a/src/lib/command-search.test.ts b/src/lib/command-search.test.ts new file mode 100644 index 0000000..4fec0de --- /dev/null +++ b/src/lib/command-search.test.ts @@ -0,0 +1,113 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +const api = vi.hoisted(() => ({ + getCourses: vi.fn(), + getMyCourses: vi.fn(), + getExams: vi.fn(), + getHomework: vi.fn(), + getEvents: vi.fn(), + getMyInstances: vi.fn(), + loadInstanceLabels: vi.fn(), +})); + +vi.mock("@/api/courses", () => ({ getCourses: api.getCourses })); +vi.mock("@/api/reports", () => ({ getMyCourses: api.getMyCourses })); +vi.mock("@/api/exams", () => ({ getExams: api.getExams })); +vi.mock("@/api/homework", () => ({ getHomework: api.getHomework })); +vi.mock("@/api/events", () => ({ getEvents: api.getEvents })); +vi.mock("@/api/instances", () => ({ getMyInstances: api.getMyInstances })); +vi.mock("@/lib/instance-labels", () => ({ loadInstanceLabels: api.loadInstanceLabels })); + +import { + filterCommandRecords, + loadCommandRecords, + resetCommandRecordCache, + type CommandRecord, +} from "@/lib/command-search"; + +const page = (items: T[]) => ({ items, total: items.length, limit: 100, offset: 0 }); +const record = (kind: CommandRecord["kind"], id: string, title: string, context: string | null = null): CommandRecord => ({ + kind, + id, + title, + context, + description: null, + at: null, +}); + +describe("filterCommandRecords", () => { + const records = [ + record("event", "ev1", "Biyoloji gezisi"), + record("course", "c1", "Biyoloji"), + record("course", "c2", "Kimya"), + record("exam", "e1", "1. Yazılı", "Biyoloji — 10-B"), + record("homework", "h1", "Hücre ödevi", "Biyoloji — 9-A"), + ]; + + test("matches titles and section labels, Turkish-folded, grouped in kind order", () => { + expect(filterCommandRecords(records, "biyoloji").map((r) => r.id)).toEqual(["c1", "e1", "h1", "ev1"]); + expect(filterCommandRecords(records, "BİYOLOJİ").map((r) => r.id)).toEqual(["c1", "e1", "h1", "ev1"]); + expect(filterCommandRecords(records, "yazili").map((r) => r.id)).toEqual(["e1"]); + expect(filterCommandRecords(records, "hucre 9a").map((r) => r.id)).toEqual(["h1"]); + }); + + test("a one-letter query matches nothing", () => { + expect(filterCommandRecords(records, "b")).toEqual([]); + expect(filterCommandRecords(records, " ")).toEqual([]); + }); + + test("caps each kind", () => { + const many = Array.from({ length: 8 }, (_, i) => record("course", `c${i}`, `Matematik ${i}`)); + expect(filterCommandRecords(many, "matematik", 3).map((r) => r.id)).toEqual(["c0", "c1", "c2"]); + }); +}); + +describe("loadCommandRecords", () => { + beforeEach(() => { + resetCommandRecordCache(); + api.getCourses.mockResolvedValue(page([{ id: "c1", title: "Biyoloji", description: "", kind: "course" }])); + api.getMyCourses.mockResolvedValue(page([{ id: "c9", title: "Fizik", description: "", kind: "course" }])); + api.getExams.mockResolvedValue( + page([ + { id: "e1", title: "Yazılı", description: "", class_course: "i1", starts_at: 5 }, + { id: "e2", title: "Quiz", description: "", class_course: "i2", starts_at: null }, + ]), + ); + api.getHomework.mockResolvedValue(page([{ id: "h1", title: "Ödev", description: null, class_course: "i1", due_at: 7 }])); + api.getEvents.mockResolvedValue(page([{ id: "ev1", title: "Gezi", description: "", starts_at: 9 }])); + api.getMyInstances.mockResolvedValue(page([{ id: "i1" }])); + api.loadInstanceLabels.mockResolvedValue(new Map([["i1", { label: "Biyoloji — 10-B" }]])); + }); + afterEach(() => vi.clearAllMocks()); + + test("a student reads their own courses and only exams in their own sections", async () => { + const out = await loadCommandRecords("student", ["course", "exam"]); + expect(api.getMyCourses).toHaveBeenCalled(); + expect(api.getCourses).not.toHaveBeenCalled(); + expect(out.map((r) => r.id)).toEqual(["c9", "e1"]); + expect(out[1].context).toBe("Biyoloji — 10-B"); + }); + + test("staff read the full catalog and every exam the backend returns", async () => { + const out = await loadCommandRecords("teacher", ["course", "exam"]); + expect(api.getCourses).toHaveBeenCalled(); + expect(api.getMyInstances).not.toHaveBeenCalled(); + expect(out.map((r) => r.id)).toEqual(["c1", "e1", "e2"]); + }); + + test("only the requested kinds are read, and a failing kind leaves the others", async () => { + api.getEvents.mockRejectedValue(new Error("boom")); + const out = await loadCommandRecords("parent", ["event", "homework"]); + expect(api.getCourses).not.toHaveBeenCalled(); + expect(api.getExams).not.toHaveBeenCalled(); + expect(out.map((r) => r.id)).toEqual(["h1"]); + }); + + test("reopening within the cache window reuses the last read", async () => { + await loadCommandRecords("teacher", ["course"], 1_000); + await loadCommandRecords("teacher", ["course"], 30_000); + expect(api.getCourses).toHaveBeenCalledTimes(1); + await loadCommandRecords("teacher", ["course"], 120_000); + expect(api.getCourses).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/lib/command-search.ts b/src/lib/command-search.ts new file mode 100644 index 0000000..f1892aa --- /dev/null +++ b/src/lib/command-search.ts @@ -0,0 +1,163 @@ +import { getCourses } from "@/api/courses"; +import { getExams } from "@/api/exams"; +import { getEvents } from "@/api/events"; +import { getHomework } from "@/api/homework"; +import { getMyInstances } from "@/api/instances"; +import { getMyCourses } from "@/api/reports"; +import type { Role } from "@/api/client"; +import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; +import { loadInstanceLabels } from "@/lib/instance-labels"; +import { matchesSearch } from "@/lib/search-text"; + +/** + * Records the command palette can search besides pages and actions: the + * courses, exams, homework and events the user's own list pages show. + * + * Each kind is read the way its list page reads it (same endpoint, same cap, + * same role scoping), once when the palette opens — never per keystroke — and + * the typed query is matched client-side with the app's Turkish folding. + */ +export type CommandRecordKind = "course" | "exam" | "homework" | "event"; + +export const COMMAND_RECORD_KINDS: readonly CommandRecordKind[] = ["course", "exam", "homework", "event"]; + +/** The list route each kind lives under; a kind is searched only when its route is in the user's nav. */ +export const COMMAND_RECORD_ROUTES: Record = { + course: "/courses", + exam: "/exams", + homework: "/homework", + event: "/events", +}; + +export type CommandRecord = { + kind: CommandRecordKind; + id: string; + title: string; + /** " — <şube>" for exams and homework; null when it could not be read. */ + context: string | null; + description: string | null; + /** Course kind (course / study / club) for catalog rows. */ + courseKind?: string; + /** Start time (exam, event) or due time (homework). */ + at: number | null; +}; + +/** Below this many characters a query would match nearly every record. */ +export const COMMAND_RECORD_MIN_QUERY = 2; +export const COMMAND_RECORDS_PER_KIND = 5; + +/** + * Records matching `query`, in kind order, at most `perKind` of each — the + * palette is a jump list, not a results page, and the list page holds the rest. + */ +export function filterCommandRecords( + records: readonly CommandRecord[], + query: string, + perKind = COMMAND_RECORDS_PER_KIND, +): CommandRecord[] { + const q = query.trim(); + if (q.length < COMMAND_RECORD_MIN_QUERY) return []; + const counts = new Map(); + const out: CommandRecord[] = []; + for (const kind of COMMAND_RECORD_KINDS) { + for (const record of records) { + if (record.kind !== kind) continue; + if ((counts.get(kind) ?? 0) >= perKind) break; + if (!matchesSearch(q, record.title, record.context, record.description)) continue; + counts.set(kind, (counts.get(kind) ?? 0) + 1); + out.push(record); + } + } + return out; +} + +async function loadCourses(role: Role): Promise { + // As on /courses: a student's list is their own enrolments. + const page = role === "student" ? await getMyCourses() : await getCourses(); + return page.items.map((course) => ({ + kind: "course", + id: course.id, + title: course.title, + context: null, + description: course.description || null, + courseKind: course.kind, + at: null, + })); +} + +async function loadExams(role: Role): Promise { + const [page, mine] = await Promise.all([ + loadCappedList(getExams, LIST_CAP, false), + // As on /exams: a student only sees exams set in their own sections. + role === "student" ? getMyInstances({ limit: 200 }).then((p) => new Set(p.items.map((i) => i.id))) : null, + ]); + const items = mine ? page.items.filter((exam) => mine.has(exam.class_course)) : page.items; + const labels = await loadInstanceLabels(items.map((exam) => exam.class_course), role).catch(() => new Map()); + return items.map((exam) => ({ + kind: "exam", + id: exam.id, + title: exam.title, + context: labels.get(exam.class_course)?.label ?? null, + description: exam.description || null, + at: exam.starts_at, + })); +} + +async function loadHomework(role: Role): Promise { + const items = (await getHomework({ limit: LIST_CAP })).items; + const labels = await loadInstanceLabels(items.map((item) => item.class_course), role).catch(() => new Map()); + return items.map((item) => ({ + kind: "homework", + id: item.id, + title: item.title, + context: labels.get(item.class_course)?.label ?? null, + description: item.description || null, + at: item.due_at, + })); +} + +async function loadEvents(): Promise { + const page = await loadCappedList(getEvents, LIST_CAP, false); + return page.items.map((event) => ({ + kind: "event", + id: event.id, + title: event.title, + context: null, + description: event.description || null, + at: event.starts_at, + })); +} + +const LOADERS: Record Promise> = { + course: loadCourses, + exam: loadExams, + homework: loadHomework, + event: loadEvents, +}; + +/** Reopening the palette within this window reuses the last read. */ +const CACHE_MS = 60_000; +let cache: { key: string; at: number; records: Promise } | null = null; + +/** + * Every searchable record for `role`, limited to `kinds`. A kind that fails to + * load is left out rather than emptying the others. + */ +export function loadCommandRecords( + role: Role, + kinds: readonly CommandRecordKind[], + now: number = Date.now(), +): Promise { + const key = `${role}|${[...kinds].sort().join(",")}`; + if (cache && cache.key === key && now - cache.at < CACHE_MS) return cache.records; + const records = Promise.allSettled(kinds.map((kind) => LOADERS[kind](role))).then((results) => + results.flatMap((result) => (result.status === "fulfilled" ? result.value : [])), + ); + cache = { key, at: now, records }; + return records; +} + +/** Test hook: forget the last read. */ +export function resetCommandRecordCache(): void { + cache = null; +} diff --git a/src/lib/event-roll-call.test.ts b/src/lib/event-roll-call.test.ts new file mode 100644 index 0000000..bdaba82 --- /dev/null +++ b/src/lib/event-roll-call.test.ts @@ -0,0 +1,65 @@ +import { + eventStatusLabelKey, + isRollCallOpen, + orderRollCallStatuses, + rollCallChanges, + saveRollCallChanges, +} from "@/lib/event-roll-call"; + +test("core statuses get event wording, school-defined ones do not", () => { + expect(eventStatusLabelKey("present")).toBe("events.status.present"); + expect(eventStatusLabelKey("absent")).toBe("events.status.absent"); + expect(eventStatusLabelKey("late")).toBe("events.status.late"); + expect(eventStatusLabelKey("excused")).toBe("events.status.excused"); + expect(eventStatusLabelKey("medical")).toBeNull(); +}); + +test("present leads the status list, the rest keep the school's order", () => { + expect(orderRollCallStatuses(["absent", "late", "present", "excused"])).toEqual(["present", "absent", "late", "excused"]); + expect(orderRollCallStatuses(["absent", "late"])).toEqual(["absent", "late"]); +}); + +test("only drafted statuses that differ from the saved mark are sent", () => { + const saved = { a: "present", b: null, c: "late" }; + const draft = { a: "present", b: "absent", c: "excused", d: "present" }; + expect(rollCallChanges(saved, draft)).toEqual([ + { userId: "b", status: "absent" }, + { userId: "c", status: "excused" }, + { userId: "d", status: "present" }, + ]); +}); + +test("an empty draft has nothing to save", () => { + expect(rollCallChanges({ a: "present" }, {})).toEqual([]); + expect(rollCallChanges({ a: "present" }, { a: undefined })).toEqual([]); +}); + +test("roll call opens at the start time, or at once without one", () => { + expect(isRollCallOpen(2000, 1000)).toBe(false); + expect(isRollCallOpen(1000, 1000)).toBe(true); + expect(isRollCallOpen(1000, 2000)).toBe(true); + expect(isRollCallOpen(null, 0)).toBe(true); + expect(isRollCallOpen(undefined, 0)).toBe(true); +}); + +test("saving sends rows in order, keeps going past a failure and reports progress", async () => { + const sent: string[] = []; + const progress: [number, number][] = []; + const boom = new Error("outside audience"); + const result = await saveRollCallChanges( + [ + { userId: "a", status: "present" }, + { userId: "b", status: "absent" }, + { userId: "c", status: "late" }, + ], + async (change) => { + sent.push(change.userId); + if (change.userId === "b") throw boom; + }, + (done, total) => progress.push([done, total]), + ); + expect(sent).toEqual(["a", "b", "c"]); + expect(result.saved.map((change) => change.userId)).toEqual(["a", "c"]); + expect(result.failed).toEqual([{ change: { userId: "b", status: "absent" }, error: boom }]); + expect(progress).toEqual([[1, 3], [2, 3], [3, 3]]); +}); diff --git a/src/lib/event-roll-call.ts b/src/lib/event-roll-call.ts new file mode 100644 index 0000000..459dad0 --- /dev/null +++ b/src/lib/event-roll-call.ts @@ -0,0 +1,83 @@ +import type { AttendanceStatus } from "@/api/client"; +import type { MessageKey } from "@/i18n/messages"; + +/** + * Event wording for the core attendance statuses. The backend knows the same + * status values for lessons and events; only the label changes ("Var" reads + * as "in class" — at an event the student "attended"). Unknown school-defined + * statuses have no entry and fall back to the shared lesson label or the raw + * value. + */ +const EVENT_STATUS_KEYS: Record = { + present: "events.status.present", + absent: "events.status.absent", + late: "events.status.late", + excused: "events.status.excused", +}; + +export function eventStatusLabelKey(status: AttendanceStatus): MessageKey | null { + return EVENT_STATUS_KEYS[status] ?? null; +} + +/** + * The school's statuses in its own order, except "present" leads — it is the + * status taken most, so it sits first on every row (as in lesson roll call). + */ +export function orderRollCallStatuses(list: readonly AttendanceStatus[]): AttendanceStatus[] { + return list.includes("present") ? ["present", ...list.filter((status) => status !== "present")] : [...list]; +} + +export type RollCallChange = { userId: string; status: AttendanceStatus }; + +/** + * The rows a save has to send: every drafted status that differs from what + * the server already holds. A draft equal to the saved mark is a no-op. + */ +export function rollCallChanges( + saved: Readonly>, + draft: Readonly>, +): RollCallChange[] { + const changes: RollCallChange[] = []; + for (const [userId, status] of Object.entries(draft)) { + if (status && saved[userId] !== status) changes.push({ userId, status }); + } + return changes; +} + +/** + * Roll call opens once the event has started. An event with no start time + * has nothing to wait for and is always open. + */ +export function isRollCallOpen(startsAt: number | null | undefined, now: number): boolean { + return startsAt == null || startsAt <= now; +} + +export type RollCallSaveResult = { + saved: RollCallChange[]; + failed: { change: RollCallChange; error: unknown }[]; +}; + +/** + * Sends the changes one at a time — the API marks a single user per call and + * has no bulk endpoint. A failed row does not stop the rest; each outcome is + * reported so the caller can show per-row errors. + */ +export async function saveRollCallChanges( + changes: readonly RollCallChange[], + send: (change: RollCallChange) => Promise, + onProgress?: (done: number, total: number) => void, +): Promise { + const result: RollCallSaveResult = { saved: [], failed: [] }; + let done = 0; + for (const change of changes) { + try { + await send(change); + result.saved.push(change); + } catch (error) { + result.failed.push({ change, error }); + } + done += 1; + onProgress?.(done, changes.length); + } + return result; +} diff --git a/src/lib/exam-publish.test.ts b/src/lib/exam-publish.test.ts new file mode 100644 index 0000000..d71cfa3 --- /dev/null +++ b/src/lib/exam-publish.test.ts @@ -0,0 +1,35 @@ +import { countExamQuestions, isPublishing } from "@/lib/exam-publish"; + +const { getExamQuestions } = vi.hoisted(() => ({ + getExamQuestions: vi.fn(async () => ({ items: [], total: 3, limit: 1, offset: 0 })), +})); + +vi.mock("@/api/exams", () => ({ getExamQuestions })); + +afterEach(() => { + vi.clearAllMocks(); +}); + +test("clearing the draft flag on a draft exam publishes it", () => { + expect(isPublishing({ draft: true }, false)).toBe(true); +}); + +test("creating an exam without the draft flag publishes it", () => { + expect(isPublishing(null, false)).toBe(true); + expect(isPublishing(undefined, false)).toBe(true); +}); + +test("an exam that stays or becomes a draft is not published", () => { + expect(isPublishing({ draft: true }, true)).toBe(false); + expect(isPublishing({ draft: false }, true)).toBe(false); + expect(isPublishing(null, true)).toBe(false); +}); + +test("editing an exam that is already live is not a publish", () => { + expect(isPublishing({ draft: false }, false)).toBe(false); +}); + +test("countExamQuestions reads the total of a one-row page", async () => { + await expect(countExamQuestions("exam-1")).resolves.toBe(3); + expect(getExamQuestions).toHaveBeenCalledWith("exam-1", { limit: 1 }); +}); diff --git a/src/lib/exam-publish.ts b/src/lib/exam-publish.ts new file mode 100644 index 0000000..1fa791c --- /dev/null +++ b/src/lib/exam-publish.ts @@ -0,0 +1,19 @@ +import { getExamQuestions } from "@/api/exams"; + +/** + * True when a save takes a draft exam live: it was a draft before and the + * new values clear the flag. Creating straight into live (no `before`) also + * counts — a brand-new exam never has questions yet. + */ +export function isPublishing(before: { draft?: boolean } | null | undefined, nextDraft: boolean): boolean { + if (nextDraft) return false; + return before == null || before.draft === true; +} + +/** + * How many questions an exam holds. The exam row carries no count, so this + * asks the questions list for a one-row page and reads its `total`. + */ +export async function countExamQuestions(examId: string): Promise { + return (await getExamQuestions(examId, { limit: 1 })).total; +} diff --git a/src/lib/format.ts b/src/lib/format.ts index f5a0572..72dfa50 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -61,3 +61,12 @@ export function formatDecimal(value: number | null | undefined, locale: Locale = maximumFractionDigits: digits, }).format(value); } + +/** + * A chart or count value in the reader's locale with up to `maxDigits` + * decimals: "1.234,5" in Turkish, "1,234.5" in English. Whole numbers stay whole. + */ +export function formatNumber(value: number | null | undefined, locale: Locale = "en", maxDigits = 1): string { + if (value == null || !Number.isFinite(value)) return "—"; + return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US", { maximumFractionDigits: maxDigits }).format(value); +} diff --git a/src/lib/notifications.ts b/src/lib/notifications.ts index 4ab1ad2..e13a639 100644 --- a/src/lib/notifications.ts +++ b/src/lib/notifications.ts @@ -6,10 +6,23 @@ export interface NotificationItem { title: string; description: string; preview?: string; - targetUrl: string; + /** Where a click goes; a row without one opens the in-list preview instead. */ + targetUrl?: string; timestamp: number; } +/** + * An unread count as every shell surface shows it — the bell and messages + * badges, the phone action button and the notification list header share one + * cap, so a badge never reads "9+" over a header that says "20". The exact + * number goes in the accessible label. + */ +export const UNREAD_DISPLAY_CAP = 9; + +export function formatUnreadCount(count: number): string { + return count > UNREAD_DISPLAY_CAP ? `${UNREAD_DISPLAY_CAP}+` : String(Math.max(0, count)); +} + const STORAGE_KEY = "hezarfen.dismissedNotifications"; const READ_STORAGE_KEY = "hezarfen.readNotifications"; diff --git a/src/lib/student-directory.test.ts b/src/lib/student-directory.test.ts new file mode 100644 index 0000000..9467a9a --- /dev/null +++ b/src/lib/student-directory.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "vitest"; +import type { ClassGroup, PersonRef } from "@/api/client"; +import { sortByClass } from "@/lib/student-directory"; + +const cls = (name: string, grade: string | null): ClassGroup => ({ + id: name, creator: null, name, grade, year: null, teacher: null, +}); +const person = (name: string): PersonRef => ({ + id: name, username: name.toLowerCase(), display_name: name, student_number: null, +} as PersonRef); + +describe("sortByClass", () => { + test("orders by grade, then şube, then name; classless students last", () => { + const rows = [ + { person: person("Zeynep"), classes: [cls("10-B", "10")] }, + { person: person("Ali"), classes: [] }, + { person: person("Can"), classes: [cls("9-A", "9")] }, + { person: person("Ayşe"), classes: [cls("10-A", "10")] }, + { person: person("Burak"), classes: [cls("10-B", "10")] }, + { person: person("Deniz"), classes: [cls("9-B", "9")] }, + ]; + expect(sortByClass(rows).map((row) => row.person.display_name)) + .toEqual(["Can", "Deniz", "Ayşe", "Burak", "Zeynep", "Ali"]); + }); + + test("files a student in several classes under the earliest one", () => { + const rows = [ + { person: person("Ece"), classes: [cls("10-B", "10"), cls("9-A", "9")] }, + { person: person("Mert"), classes: [cls("9-B", "9")] }, + ]; + const sorted = sortByClass(rows); + expect(sorted.map((row) => row.person.display_name)).toEqual(["Ece", "Mert"]); + expect(sorted[0].classes.map((c) => c.name)).toEqual(["9-A", "10-B"]); + }); +}); diff --git a/src/lib/student-directory.ts b/src/lib/student-directory.ts index 981da83..1a9e9e1 100644 --- a/src/lib/student-directory.ts +++ b/src/lib/student-directory.ts @@ -22,5 +22,35 @@ export async function getStudentDirectory(): Promise { byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]); } } - return students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })); + return sortByClass(students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] }))); +} + +const collator = new Intl.Collator("tr", { numeric: true, sensitivity: "base" }); + +/** Class order a school reads rosters in: grade (9 before 10), then the şube name. */ +export function compareClasses(a: ClassGroup, b: ClassGroup): number { + const gradeA = Number.parseInt(a.grade ?? a.name, 10); + const gradeB = Number.parseInt(b.grade ?? b.name, 10); + if (Number.isFinite(gradeA) && Number.isFinite(gradeB) && gradeA !== gradeB) return gradeA - gradeB; + return collator.compare(a.name, b.name); +} + +/** + * Rows ordered class by class (9-A, 9-B, 10-A…) and by name inside a class. + * A student in several classes files under the first of them; students with + * no class come last. The row's own `classes` are put in the same order. + */ +export function sortByClass(rows: Row[]): Row[] { + const ordered = rows.map((row) => ({ ...row, classes: [...row.classes].sort(compareClasses) })); + return ordered.sort((a, b) => { + const classA = a.classes[0]; + const classB = b.classes[0]; + if (classA && !classB) return -1; + if (!classA && classB) return 1; + if (classA && classB) { + const byClass = compareClasses(classA, classB); + if (byClass !== 0) return byClass; + } + return collator.compare(a.person.display_name || a.person.username, b.person.display_name || b.person.username); + }); } diff --git a/src/pages/admin-users-page.tsx b/src/pages/admin-users-page.tsx index 5ba6471..df6349e 100644 --- a/src/pages/admin-users-page.tsx +++ b/src/pages/admin-users-page.tsx @@ -11,7 +11,6 @@ import { CreateUserPanel } from "@/components/users/create-user-panel"; import { ParentStudentsPanel } from "@/components/users/parent-students-panel"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; -import { ComingSoonBadge } from "@/components/ui/coming-soon"; import { DataTableSkeleton } from "@/components/ui/data-table"; import { IconPlus } from "@/components/ui/icons"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -83,10 +82,6 @@ function AdminUsersContent() { {t("admin.tabTeachers")} {t("admin.tabParents")} {t("admin.tabStudents")} - - {t("admin.tabInvites")} - - @@ -103,16 +98,10 @@ function AdminUsersContent() { title={t("admin.title")} description={t("admin.subtitle")} actions={ - <> - - - + } users={visibleUsers() as User[]} currentUserId={auth.user()!.id} diff --git a/src/pages/ai-insight-student-page.tsx b/src/pages/ai-insight-student-page.tsx index 9681525..f898658 100644 --- a/src/pages/ai-insight-student-page.tsx +++ b/src/pages/ai-insight-student-page.tsx @@ -10,7 +10,7 @@ import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { ErrorAlert } from "@/components/ui/error-alert"; import { Badge } from "@/components/ui/badge"; -import { IconDownload, IconSparkles } from "@/components/ui/icons"; +import { IconSparkles } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import { createFlash } from "@/lib/flash"; import { loadInsightStudents } from "@/lib/insight-students"; @@ -135,10 +135,6 @@ function AiInsightStudentContent() {
-
diff --git a/src/pages/classes-page.tsx b/src/pages/classes-page.tsx index 7b8a262..11a07b5 100644 --- a/src/pages/classes-page.tsx +++ b/src/pages/classes-page.tsx @@ -22,7 +22,6 @@ import { Label } from "@/components/ui/label"; import { SidePanel } from "@/components/ui/side-panel"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { BlueprintsTab } from "@/components/classes/blueprints-tab"; -import { ComingSoonBadge } from "@/components/ui/coming-soon"; import { UserSearchSelect } from "@/components/users/user-search-select"; import { createFlash } from "@/lib/flash"; import { matchesSearch } from "@/lib/search-text"; @@ -241,10 +240,6 @@ function ClassesContent() { } actions={ - - - +

{t("events.studentAttendanceHelp")}

+ }> + + {formatApiError(roster.error)} + + }> + {(rows) => ( + Promise.all([refetchRoster(), refetchAttendance()])} + /> + )} +
+ diff --git a/src/pages/exams-page.tsx b/src/pages/exams-page.tsx index b50c828..e08214f 100644 --- a/src/pages/exams-page.tsx +++ b/src/pages/exams-page.tsx @@ -15,6 +15,7 @@ import { RouteGuard } from "@/components/layout/route-guard"; import { Alert } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { IconCheck, IconEdit, IconEye, IconPlus, IconRotateCcw } from "@/components/ui/icons"; import { DropdownSelect } from "@/components/ui/select"; @@ -29,6 +30,7 @@ import { examKindLabel } from "@/lib/exam-labels"; import { examDisplayStatus, examStatusMessageKey, examStatusTone, type ExamDisplayStatus } from "@/lib/exam-status"; import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; import { createFlash } from "@/lib/flash"; +import { countExamQuestions } from "@/lib/exam-publish"; import { formatDateTime } from "@/lib/format"; import { hasMinRole } from "@/lib/roles"; import { matchesSearch } from "@/lib/search-text"; @@ -92,6 +94,8 @@ function ExamsContent() { const [flash, setFlash] = createFlash(); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); + /** A draft exam with no questions, waiting on "publish anyway". */ + const [emptyPublishTarget, setEmptyPublishTarget] = createSignal(null); const [createStep, setCreateStep] = createSignal<"details" | "questions">("details"); const [createdExam, setCreatedExam] = createSignal(null); @@ -302,10 +306,15 @@ function ExamsContent() { setFlash(t("common.saved")); }; - const publishExam = async (exam: Exam) => { + const publishExam = async (exam: Exam, force = false) => { setPending(true); setError(""); try { + // An exam with no questions is almost always a mistake — ask first. + if (!force && (await countExamQuestions(exam.id)) === 0) { + setEmptyPublishTarget(exam); + return; + } await patchExamById(exam.id, { draft: false }); await refetchExams(); setFlash(t("exams.published")); @@ -482,7 +491,10 @@ function ExamsContent() { courseId={examCourseId(createdExam()!)} embedded /> -
+
+ +

{t("exams.savedAsDraftHint")}

+
@@ -491,6 +503,20 @@ function ExamsContent() { + { + if (!open) setEmptyPublishTarget(null); + }} + title={t("exams.publishEmptyTitle")} + summary={t("exams.publishEmptyWarning")} + confirmLabel={t("exams.publishAnyway")} + onConfirm={async () => { + const exam = emptyPublishTarget(); + if (exam) await publishExam(exam, true); + }} + /> + { diff --git a/src/pages/license-modules-page.tsx b/src/pages/license-modules-page.tsx index ca8db5d..fb50d9b 100644 --- a/src/pages/license-modules-page.tsx +++ b/src/pages/license-modules-page.tsx @@ -1,16 +1,13 @@ import type { ColumnDef } from "@tanstack/solid-table"; -import { For, Show, Suspense, createMemo } from "solid-js"; +import { Show, Suspense, createMemo } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { getModules, getModulesCatalog } from "@/api/modules"; import { formatApiError } from "@/api/client"; import { RouteGuard } from "@/components/layout/route-guard"; import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { ComingSoonBadge, ComingSoonPanel } from "@/components/ui/coming-soon"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { ErrorAlert } from "@/components/ui/error-alert"; -import { IconDownload, IconPackage, IconPlus } from "@/components/ui/icons"; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { IconPackage } from "@/components/ui/icons"; import { moduleLabel, packageLabel } from "@/lib/module-labels"; import { useT } from "@/stores/preferences-context"; @@ -86,20 +83,6 @@ function LicenseModulesContent() { return (
- - - {t("modules.tabOverview")} - - {(key) => ( - - {t(key)} - - - )} - - - - }> void refetch()} /> @@ -132,16 +115,6 @@ function LicenseModulesContent() { urlState title={t("nav.licenseModules")} description={t("modules.subtitle")} - actions={<> - } columns={columns()} data={value().rows} tableClass="min-w-md" @@ -149,8 +122,6 @@ function LicenseModulesContent() { storageKey="license-modules" /> - - )} diff --git a/src/pages/meals-page.tsx b/src/pages/meals-page.tsx index c1db198..6c29c6c 100644 --- a/src/pages/meals-page.tsx +++ b/src/pages/meals-page.tsx @@ -114,7 +114,7 @@ function MealsContent() { }> void refetch()} /> 0} fallback={}> -
{(menu) => }
+
{(menu) => }
diff --git a/src/pages/messages-page.tsx b/src/pages/messages-page.tsx index 68165c5..d31973a 100644 --- a/src/pages/messages-page.tsx +++ b/src/pages/messages-page.tsx @@ -30,15 +30,22 @@ import { deleteMessageById, } from "@/api/messages"; import type { Message, MessageFolder } from "@/api/client"; +import type { MessageKey } from "@/i18n/messages"; import { formatApiError } from "@/api/client"; import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; import { createFlash } from "@/lib/flash"; -import { Badge } from "@/components/ui/badge"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +const folders: { id: MessageFolder; labelKey: MessageKey; icon: typeof IconMessage }[] = [ + { id: "inbox", labelKey: "messages.inbox", icon: IconMessage }, + { id: "sent", labelKey: "messages.sent", icon: IconSend }, + { id: "archive", labelKey: "messages.archive", icon: IconArchive }, + { id: "trash", labelKey: "messages.trash", icon: IconTrash }, +]; + export default function MessagesPage() { const t = useT(); const auth = useAuth(); @@ -169,129 +176,71 @@ export default function MessagesPage() { } }; - const folderLabel = () => { - const f = folder(); - if (f === "sent") return t("messages.sent"); - if (f === "archive") return t("messages.archive"); - if (f === "trash") return t("messages.trash"); - return t("messages.inbox"); - }; - return (
- {/* Card header — folder name + unread chip, matching Figma's "Gelen kutusu" card. */} + {/* Card header names the page; the active folder is already the + highlighted tab below, and the inbox tab carries the unread count. */}
-

{folderLabel()}

- 0}> - - {unreadCount()} {t("messages.unread")} - - +

{t("nav.messages")}

{/* Folder toolbar — the app shell already owns the global sidebar. */}
@@ -107,11 +139,14 @@ function RegisterForm() { class="h-9 pr-10" type={showPassword() ? "text" : "password"} autocomplete="new-password" - minlength={limits()?.user.min_password_len} + minlength={minPasswordLength()} maxlength={limits()?.user.max_password_len} required + aria-invalid={passwordError() ? true : undefined} + aria-describedby="register-password-hint" value={password()} onInput={(e) => setPassword(e.currentTarget.value)} + onBlur={() => setPasswordTouched(true)} />
+

+ {passwordError() ?? t("auth.passwordMinHint", { min: minPasswordLength() })} +

- setConfirmPassword(e.currentTarget.value)} - /> +
+ setConfirmPassword(e.currentTarget.value)} + onBlur={() => setConfirmTouched(true)} + /> + +
+ + {(message) => ( + + )} +
{error() && ( diff --git a/src/pages/staff-work-page.tsx b/src/pages/staff-work-page.tsx index f17c94c..1f79d07 100644 --- a/src/pages/staff-work-page.tsx +++ b/src/pages/staff-work-page.tsx @@ -15,7 +15,6 @@ import { DataToolbar } from "@/components/ui/data-toolbar"; import { Alert } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; -import { ComingSoonBadge } from "@/components/ui/coming-soon"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { EmptyState } from "@/components/ui/empty-state"; @@ -296,18 +295,6 @@ function StaffWorkContent() { searchPlaceholder={t("work.searchPlaceholder")} searchHint={t("search.hint.people")} onSearchInput={setStaffSearch} - actions={ - <> - - - - } />
diff --git a/src/pages/students-roster-page.tsx b/src/pages/students-roster-page.tsx index 7a8f355..8a31e13 100644 --- a/src/pages/students-roster-page.tsx +++ b/src/pages/students-roster-page.tsx @@ -1,6 +1,6 @@ import { useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; -import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; +import { Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { matchesSearch } from "@/lib/search-text"; import { createUrlString } from "@/lib/url-state"; @@ -12,15 +12,14 @@ import { RouteGuard } from "@/components/layout/route-guard"; import { CreateUserPanel } from "@/components/users/create-user-panel"; import { RosterPersonCell } from "@/components/users/roster-person-cell"; import { Button } from "@/components/ui/button"; -import { ComingSoonBadge } from "@/components/ui/coming-soon"; import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; import { ErrorAlert } from "@/components/ui/error-alert"; -import { IconEye, IconPlus, IconUploadCloud } from "@/components/ui/icons"; +import { IconEye, IconPlus } from "@/components/ui/icons"; import { DropdownSelect } from "@/components/ui/select"; import { TableRowActions } from "@/components/ui/table-row-actions"; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { useT } from "@/stores/preferences-context"; import { useAuth } from "@/stores/auth-context"; +import { sortByClass } from "@/lib/student-directory"; const ROSTER_PAGE_SIZE = 10; @@ -61,7 +60,7 @@ function StudentsRosterContent() { for (const { cls, members } of memberships) { for (const member of members) byStudent.set(member.user.id, [...(byStudent.get(member.user.id) ?? []), cls]); } - const rows: StudentRow[] = students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] })); + const rows: StudentRow[] = sortByClass(students.items.map((person) => ({ person, classes: byStudent.get(person.id) ?? [] }))); return { rows, classes: classes.items, years: years.items }; }); @@ -104,21 +103,6 @@ function StudentsRosterContent() { return (
- - - {t("roster.tabAll")} - - {(key) => ( - - {t(key)} - - - )} - - - - -
}> @@ -137,12 +121,7 @@ function StudentsRosterContent() { surfaceSections title={t("nav.studentsRoster")} description={t("roster.studentsSubtitle")} - actions={<> - + actions={<> - + actions={<>