diff --git a/src/components/ai/note-studio-panel.tsx b/src/components/ai/note-studio-panel.tsx index 4d8ee37..2cfb26c 100644 --- a/src/components/ai/note-studio-panel.tsx +++ b/src/components/ai/note-studio-panel.tsx @@ -126,7 +126,7 @@ export function NoteStudioPanel() {

{note().courseTitle}

-
+
{ const list = terms(); if (!list || list.length === 0 || term()) return; - // Newest first from the backend — the open dönem is what a teacher means. - setTerm((list.find((item) => item.archived_at == null) ?? list[0]).id); + // The dönem running today is what a teacher means; list order is newest first. + setTerm(pickCurrentTerm(list, Date.now())?.id ?? list[0].id); }); const examKinds = createMemo(() => { const names = settings()?.exam_kinds.map((item) => item.name) ?? EXAM_KINDS; @@ -225,7 +226,7 @@ export function ExamForm(props: {

{t("exams.sectionBasic")}

- + { setGradeTarget(row); - setStatus(row.result?.status ?? (row.missing ? "missing" : "done")); + setStatus(defaultGradeStatus(row)); setMark(row.result?.mark == null ? "" : String(row.result.mark)); setError(""); }; @@ -68,6 +69,10 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId event.preventDefault(); const target = gradeTarget(); if (!target) return; + if (!status()) { + setError(t("homework.gradeStatusRequired")); + return; + } const numericMark = mark().trim() === "" ? null : Number(mark()); if (numericMark != null && (!Number.isFinite(numericMark) || numericMark < 0 || numericMark > 100)) { setError(t("form.markRange")); @@ -165,6 +170,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; instanceId
setName(e.currentTarget.value)} />
setGrade(e.currentTarget.value)} />
- +
diff --git a/src/pages/course-detail-page.tsx b/src/pages/course-detail-page.tsx index 2b56b4f..b9dbc46 100644 --- a/src/pages/course-detail-page.tsx +++ b/src/pages/course-detail-page.tsx @@ -1,4 +1,4 @@ -import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; +import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; @@ -40,6 +40,7 @@ import { useAuth } from "@/stores/auth-context"; import { useModules } from "@/stores/modules-context"; import { useT } from "@/stores/preferences-context"; import { hasMinRole } from "@/lib/roles"; +import { createUrlString } from "@/lib/url-state"; import { cn } from "@/lib/cn"; import { matchesSearch } from "@/lib/search-text"; @@ -79,17 +80,20 @@ function CourseDetailContent() { sections: () => modules.isEnabled("classes"), notes: () => modules.isEnabled("course_notes"), }; - const [courseTab, setCourseTab] = createSignal("subjects"); + // `?tab=` is the open tab, so Back from a şube lands on "Şubeler" again. + const [requestedTab, setCourseTab] = createUrlString("tab", "subjects"); const availableTabs = () => [ ...(tabOn.subjects() ? ["subjects"] : []), ...(tabOn.sections() ? ["sections"] : []), ...(tabOn.notes() ? ["notes"] : []), ...(hasMembers() ? ["members"] : []), ]; - createEffect(() => { + // A tab not on offer falls back to the first one that is, without + // rewriting the URL: "members" only appears once the course has loaded. + const courseTab = () => { const tabs = availableTabs(); - if (tabs.length > 0 && !tabs.includes(courseTab())) setCourseTab(tabs[0]); - }); + return tabs.length === 0 || tabs.includes(requestedTab()) ? requestedTab() : tabs[0]; + }; const [course, { refetch: refetchCourse }] = createResource(id, (courseId) => getCourseById(courseId)); const [mine] = createResource( () => (auth.user()?.role === "student" ? true : null), @@ -154,7 +158,7 @@ function CourseDetailContent() { const [showNoteForm, setShowNoteForm] = createSignal(false); const [showMemberForm, setShowMemberForm] = createSignal(false); const [noteCount, setNoteCount] = createSignal(null); - const [sectionSearch, setSectionSearch] = createSignal(""); + const [sectionSearch, setSectionSearch] = createUrlString("sections.q"); const [memberUserId, setMemberUserId] = createSignal(""); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); diff --git a/src/pages/courses-page.test.tsx b/src/pages/courses-page.test.tsx index 3026b0a..c6072d9 100644 --- a/src/pages/courses-page.test.tsx +++ b/src/pages/courses-page.test.tsx @@ -14,6 +14,7 @@ vi.mock("@tanstack/solid-router", () => ({ Navigate: () => null, useNavigate: () => navigate, useSearch: () => () => ({ kind: undefined, action: undefined }), + useLocation: () => () => ({ pathname: "/courses", search: {}, searchStr: "", hash: "" }), })); vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ @@ -81,11 +82,11 @@ test("student class directory uses only enrolled-course data", async () => { expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); expect(getMyCourses).toHaveBeenCalledTimes(1); - expect(navigate).toHaveBeenCalledWith({ - to: "/courses", - search: { action: undefined, kind: "study" }, - replace: true, - }); + const tabNavigation = navigate.mock.calls.at(-1)?.[0] as { to: string; replace: boolean; search: (prev: Record) => Record }; + expect(tabNavigation.to).toBe("/courses"); + expect(tabNavigation.replace).toBe(true); + // The kind tab keeps the search text and restarts paging. + expect(tabNavigation.search({ q: "alg", page: 3, action: "new" })).toEqual({ q: "alg", taught: undefined, action: undefined, kind: "study", page: undefined }); fireEvent.click(screen.getByRole("tab", { name: "Club" })); expect(await screen.findByRole("link", { name: /Robotics/ })).toBeTruthy(); @@ -101,7 +102,11 @@ test("student class directory uses only enrolled-course data", async () => { expect(screen.queryByRole("link", { name: /Algebra/ })).toBeNull(); fireEvent.input(screen.getByPlaceholderText("Search…"), { target: { value: "" } }); - fireEvent.change(screen.getByLabelText("Taught in", { selector: "select" }), { target: { value: "untaught" } }); + fireEvent.pointerDown(screen.getByRole("button", { name: /Section:/ }), { button: 0, pointerType: "mouse" }); + const untaught = await screen.findByRole("menuitem", { name: "No sections" }); + fireEvent.pointerDown(untaught, { button: 0, pointerType: "mouse" }); + fireEvent.pointerUp(untaught, { button: 0, pointerType: "mouse" }); + fireEvent.click(untaught); expect(await screen.findByRole("link", { name: /Study Lab/ })).toBeTruthy(); expect(screen.queryByRole("link", { name: /Robotics/ })).toBeNull(); }); diff --git a/src/pages/courses-page.tsx b/src/pages/courses-page.tsx index fef8275..4584a93 100644 --- a/src/pages/courses-page.tsx +++ b/src/pages/courses-page.tsx @@ -1,4 +1,4 @@ -import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; +import { For, Show, Suspense, createEffect, createMemo, createSignal, on } from "solid-js"; import { createResponsivePageSize } from "@/lib/create-page-size"; import { createResource } from "@/lib/create-resource"; import { useNavigate, useSearch } from "@tanstack/solid-router"; @@ -18,7 +18,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { PageSpinner } from "@/components/ui/page-spinner"; import { TablePagination } from "@/components/ui/table-pagination"; -import { Select } from "@/components/ui/select"; +import { DropdownSelect } from "@/components/ui/select"; import { courseKindLabel } from "@/lib/course-kind"; import { SidePanel } from "@/components/ui/side-panel"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -27,6 +27,7 @@ import { createFlash } from "@/lib/flash"; import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; +import { createUrlEnum, createUrlPageIndex, createUrlString } from "@/lib/url-state"; import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -55,10 +56,17 @@ function CoursesContent() { // Catalog rows carry no term, capacity or staff any more — a şube decides // all three when it attaches the course. `taughtFilter` narrows by whether // any şube has. - const [taughtFilter, setTaughtFilter] = createSignal("all"); - const [page, setPage] = createSignal(0); + // Search, filter and page ride in the URL so Back from a course and a + // reload land where the list was left. + const [taughtFilter, setTaughtFilter] = createUrlEnum("taught", ["all", "taught", "untaught"] as const, "all"); + const [page, setPage] = createUrlPageIndex(); const pageSize = createResponsivePageSize(PAGE_SIZE); - const [search, setSearch] = createSignal(""); + const [search, setSearch] = createUrlString("q"); + const narrowed = () => search().trim() !== "" || taughtFilter() !== "all"; + const clearNarrowing = () => { + setSearch(""); + setTaughtFilter("all"); + }; const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [flash, setFlash] = createFlash(); @@ -69,9 +77,8 @@ function CoursesContent() { createEffect(() => { setPageKind(routeSearch().kind); }); - createEffect(() => { - pageKind(); taughtFilter(); search(); pageSize(); setPage(0); - }); + // Deferred: the page restored from the URL must survive the first run. + createEffect(on(() => [pageKind(), taughtFilter(), search(), pageSize()], () => setPage(0), { defer: true })); const [limits, { refetch: refetchLimits }] = createResource(() => canCreate() ? getLimits() : null); const [list, { refetch }] = createResource( @@ -90,6 +97,10 @@ function CoursesContent() { }); }); const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredCourses().length / pageSize()))); + // A stale `?page=` past the end slides back to the last page. + createEffect(() => { + if (filteredCourses().length > 0 && page() > totalPages() - 1) setPage(totalPages() - 1); + }); const visibleCourses = createMemo(() => filteredCourses().slice(page() * pageSize(), (page() + 1) * pageSize())); const createCourse = async (event: SubmitEvent) => { @@ -140,7 +151,7 @@ function CoursesContent() { setPageKind(kind); void navigate({ to: "/courses", - search: { action: undefined, kind }, + search: (prev) => ({ q: prev.q, taught: prev.taught, action: undefined, kind, page: undefined }), replace: true, }); }} @@ -161,11 +172,16 @@ function CoursesContent() { searchHint={t("search.hint.courses")} onSearchInput={setSearch} filters={ - + setTaughtFilter(value === "taught" || value === "untaught" ? value : "all")} + options={[ + { value: "all", label: t("common.all") }, + { value: "taught", label: t("courses.withSections") }, + { value: "untaught", label: t("courses.withoutSections") }, + ]} + /> } actions={ @@ -185,7 +201,22 @@ function CoursesContent() { > 0} - fallback={} + fallback={ + } + > + + {taughtFilter() !== "all" ? t("common.clearFilters") : t("common.clearSearch")} + + } + /> + + } >
diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index 74a9da1..a5dff0b 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -63,9 +63,11 @@ vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); vi.mock("@/api/courses", () => ({ getCourses: async () => page([course]), + getCourseById: async () => course, })); vi.mock("@/api/instances", () => ({ getMyInstances: async () => page([instance]), + getInstanceById: async () => instance, getInstanceEnrollments: async () => page([]), getInstanceSessions: async () => page([ { id: "session-today", class_course: "instance-1", teacher: { id: "u-1", username: "demo", display_name: null }, topic: "Fractions", starts_at: now, ends_at: now + 40 * 60 * 1000 }, @@ -130,6 +132,15 @@ vi.mock("@/api/exams", async () => { starts_at: now - 10 * DAY, ends_at: now - 10 * DAY + 3_000, }, + // Never scheduled, yet graded: it still belongs on the trend. + { + id: "exam-paper", + title: "Paper quiz", + class_course: "instance-1", + draft: false, + starts_at: null, + ends_at: null, + }, ]); }, getExamStatistics: async (examId: string) => ({ @@ -204,6 +215,8 @@ vi.mock("@/api/classes", () => ({ getMyClasses: async () => page([{ id: "class-1", name: "9-A" }]), getClassesByUserId: async () => page([]), getClasses: async () => page([]), + getClassById: async () => ({ id: "class-1", name: "9-A" }), + getClassMembers: async () => page([]), })); vi.mock("@/api/academic-years", () => ({ getAcademicYears: async () => page([{ id: "y-1", name: "2026-2027" }]), @@ -284,7 +297,9 @@ test("teacher sees real exam averages instead of capacities and resource links", expect(screen.getByText("Success trend")).toBeTruthy(); expect(screen.getByText("Average of recent exams, by course.")).toBeTruthy(); // The trend point and the per-course bar carry the backend's average. - expect(await screen.findByRole("img", { name: /Algebra: Midterm.*74\.5/ })).toBeTruthy(); + expect(await screen.findByRole("img", { name: /Algebra — 9-A: Midterm.*74\.5/ })).toBeTruthy(); + // An unscheduled exam with marks is charted too (it used to empty the panel). + expect(screen.getByRole("img", { name: /Algebra — 9-A: Paper quiz/ })).toBeTruthy(); expect((await screen.findAllByText("74.5")).length).toBeGreaterThanOrEqual(2); expect(screen.queryByText("Course capacities")).toBeNull(); expect(screen.queryByText("Workload split")).toBeNull(); diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 1bc9e6d..1cae6a9 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -5,7 +5,7 @@ import type { ColumnDef } from "@tanstack/solid-table"; import type { Role } from "@/api/client"; import { formatApiError, isModuleDisabledError } from "@/api/client"; import { getAppointments } from "@/api/appointments"; -import { getClasses, getClassesByUserId, getMyClasses } from "@/api/classes"; +import { getClasses, getClassesByUserId, getClassMembers, getMyClasses } from "@/api/classes"; import { getCourses } from "@/api/courses"; import { getInstanceEnrollments, getMyInstances } from "@/api/instances"; import { getEvents } from "@/api/events"; @@ -51,12 +51,15 @@ import { import { PageSpinner } from "@/components/ui/page-spinner"; import type { MessageKey } from "@/i18n/messages"; import { cn } from "@/lib/cn"; -import { formatDateTime } from "@/lib/format"; +import { formatDateTime, formatDecimal } from "@/lib/format"; +import { createInstanceLabels, loadInstanceLabels } from "@/lib/instance-labels"; +import { uuidV7Ms } from "@/lib/uuid-time"; import { formatTry } from "@/lib/meals"; import { matchesSearch } from "@/lib/search-text"; import { personLabel } from "@/lib/person"; import { packageLabel } from "@/lib/module-labels"; import { hasMinRole } from "@/lib/roles"; +import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { getModulesCatalog } from "@/api/modules"; import { useModules } from "@/stores/modules-context"; import { useAuth } from "@/stores/auth-context"; @@ -74,6 +77,16 @@ const HEATMAP_WEEKS = 26; const TREND_EXAM_CAP = 20; /** Marks plotted in a student's own trend. */ const TREND_MARK_CAP = 20; +/** Classes whose roster size the admin "Şubeler" quick links read. */ +const CLASS_LINK_CAP = 12; + +/** + * Chronological key for an exam: its schedule when it has one, else when it + * was created (the id is a UUIDv7). Used only to order points, never shown. + */ +function examOrder(exam: { id: string; starts_at: number | null }): number { + return exam.starts_at ?? uuidV7Ms(exam.id) ?? 0; +} type Status = "active" | "today" | "soon"; type DeadlineKind = "exam" | "event" | "appointment" | "homework" | "payment"; @@ -84,6 +97,10 @@ type DeadlineRow = { title: string; at: number; status: Status; + /** The şube×ders an exam or homework belongs to. */ + instance?: string; + /** Its " — <şube>" label, once read. */ + section?: string; }; type StatCardData = { @@ -230,9 +247,12 @@ function DashboardContent() { const [examStats] = createResource( () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null, async (items) => { + // An exam with no schedule (an untimed, paper or imported one) still + // gets graded — skipping unscheduled exams left the charts empty while + // real marks existed. Only a scheduled exam still in the future is out. const recent = items - .filter((exam) => !exam.draft && exam.starts_at != null && exam.starts_at <= now()) - .sort((a, b) => b.starts_at! - a.starts_at!) + .filter((exam) => !exam.draft && (exam.starts_at == null || exam.starts_at <= now())) + .sort((a, b) => examOrder(b) - examOrder(a)) .slice(0, TREND_EXAM_CAP); const settled = await Promise.all( recent.map(async (exam) => { @@ -246,9 +266,17 @@ function DashboardContent() { ); return settled .filter((row) => row.stats?.average != null) - .sort((a, b) => a.exam.starts_at! - b.exam.starts_at!); + .sort((a, b) => examOrder(a.exam) - examOrder(b.exam)); }, ); + // Exams name an instance (şube × ders). The trend labels " — <şube>" + // and the course bars group by the catalog course behind it; `/instances/me` + // is empty for the office, so each charted instance is read by id (bounded + // by TREND_EXAM_CAP, cached for the tab). + const [trendSections] = createResource( + () => examStats.latest ?? null, + (rows) => loadInstanceLabels(rows.map((row) => row.exam.class_course), role()), + ); const myClass = () => myClasses.latest?.items[0] ?? null; // TCH-01 "Öğrencim" stat — Course carries no enrolled-count field, so this @@ -341,9 +369,26 @@ function DashboardContent() { () => (isAdminHome() ? true : null), () => getUsers({ limit: 30 }), ); + // "Şubeler" quick links: the classes with the most students, each labelled + // with its roster size. A class carries no member count, so each one costs + // a `limit=1` roster read for its `total` — capped at CLASS_LINK_CAP classes + // (taken in name order) so a large school does not fan out on the homepage. const [recentClasses] = createResource( () => (isAdminHome() && on("classes") ? true : null), - () => quiet(getClasses({ limit: 2 })), + async () => { + const page = await quiet(getClasses({ limit: 200 })); + if (!page) return null; + const candidates = [...page.items] + .sort((a, b) => a.name.localeCompare(b.name, "tr", { numeric: true })) + .slice(0, CLASS_LINK_CAP); + const counted = await mapConcurrent(candidates, FAN_OUT_LIMIT, async (cls) => ({ + cls, + students: await getClassMembers(cls.id, { limit: 1 }).then((members) => members.total, () => null), + })); + return counted + .sort((a, b) => (b.students ?? -1) - (a.students ?? -1) || a.cls.name.localeCompare(b.cls.name, "tr", { numeric: true })) + .slice(0, 2); + }, ); const studentQuickLinks = createMemo(() => (recentStudents()?.items ?? []) @@ -357,10 +402,10 @@ function DashboardContent() { })), ); const classQuickLinks = createMemo(() => - (recentClasses()?.items ?? []).slice(0, 2).map((cls) => ({ - id: cls.id, - primary: cls.name, - secondary: cls.grade ?? undefined, + (recentClasses() ?? []).map((row) => ({ + id: row.cls.id, + primary: row.cls.name, + secondary: row.students == null ? undefined : t("classGroups.studentsCount", { count: row.students }), Icon: IconBook, })), ); @@ -433,7 +478,7 @@ function DashboardContent() { return [ { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook }, { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam }, - { labelKey: "dashboard.stats.average", module: "marks", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, + { labelKey: "dashboard.stats.average", module: "marks", value: formatDecimal(marks()?.overall_average, locale()), Icon: IconChart }, { labelKey: "dashboard.stats.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, ]; } @@ -468,68 +513,70 @@ function DashboardContent() { const myMarkTrend = createMemo(() => { const report = marks(); if (!report) return []; + // A mark's exam may have no schedule; it still belongs on the line, + // ordered by when the exam was created, just without a date caption. const examDates = new Map((exams()?.items ?? []).map((exam) => [exam.id, exam.starts_at])); return report.courses .flatMap((course) => - course.results.map((result) => ({ - id: `${course.course.id}:${result.exam}`, - label: `${course.course.title}: ${result.title}`, - value: result.mark, - at: examDates.get(result.exam) ?? null, - })), + course.results.map((result) => { + const at = examDates.get(result.exam) ?? null; + return { + id: `${course.course.id}:${result.exam}`, + label: `${course.course.title}: ${result.title}`, + value: result.mark, + at, + order: examOrder({ id: result.exam, starts_at: at }), + }; + }), ) - .filter((row): row is typeof row & { at: number } => row.at != null) - .sort((a, b) => a.at - b.at) + .sort((a, b) => a.order - b.order) .slice(-TREND_MARK_CAP) .map((row) => ({ id: row.id, label: row.label, value: row.value, - formattedValue: row.value.toFixed(1), - caption: formatTrendDate(row.at), + formattedValue: formatDecimal(row.value, locale()), + caption: row.at == null ? undefined : formatTrendDate(row.at), })); }); - // Exams name an instance; the catalog course behind it is what a chart label - // should read, and `/instances/me` already covers the teacher's own sections. - const [myInstances] = createResource( - () => (role() && role() !== "parent" ? true : null), - async () => (await getMyInstances({ limit: 200 })).items, - ); - const instanceCourse = (instanceId: string) => - (myInstances.latest ?? []).find((instance) => instance.id === instanceId)?.course ?? null; + const sectionOf = (instanceId: string) => trendSections.latest?.get(instanceId) ?? null; // Teacher+ trend — the backend's own per-exam average, oldest exam first. - const examAverageTrend = createMemo(() => { - const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title])); - return (examStats() ?? []).map((row) => ({ - id: row.exam.id, - label: `${titles.get(instanceCourse(row.exam.class_course) ?? "") ?? row.exam.class_course}: ${row.exam.title}`, - value: row.stats!.average!, - formattedValue: row.stats!.average!.toFixed(1), - caption: formatTrendDate(row.exam.starts_at!), - })); - }); + const examAverageTrend = createMemo(() => + (examStats() ?? []).map((row) => { + const section = sectionOf(row.exam.class_course); + return { + id: row.exam.id, + label: section ? `${section.label}: ${row.exam.title}` : row.exam.title, + value: row.stats!.average!, + formattedValue: formatDecimal(row.stats!.average!, locale()), + caption: row.exam.starts_at == null ? undefined : formatTrendDate(row.exam.starts_at), + }; + }), + ); // Teacher+ comparison — the same exam averages grouped by course, so a weak // subject stands out rather than being averaged into one school-wide number. + // An exam whose section could not be read has no course to go under and is + // left out of the bars rather than filed under a raw id. const courseAverageBars = createMemo(() => { - const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title])); - const buckets = new Map(); + const buckets = new Map(); for (const row of examStats() ?? []) { - const courseId = instanceCourse(row.exam.class_course) ?? row.exam.class_course; - const list = buckets.get(courseId) ?? []; - list.push(row.stats!.average!); - buckets.set(courseId, list); + const section = sectionOf(row.exam.class_course); + if (!section?.courseTitle) continue; + const bucket = buckets.get(section.course) ?? { label: section.courseTitle, averages: [] }; + bucket.averages.push(row.stats!.average!); + buckets.set(section.course, bucket); } return [...buckets.entries()] - .map(([courseId, averages]) => { - const mean = averages.reduce((sum, value) => sum + value, 0) / averages.length; + .map(([courseId, bucket]) => { + const mean = bucket.averages.reduce((sum, value) => sum + value, 0) / bucket.averages.length; return { id: courseId, - label: titles.get(courseId) ?? courseId, + label: bucket.label, value: mean, - formattedValue: mean.toFixed(1), + formattedValue: formatDecimal(mean, locale()), }; }) .sort((a, b) => b.value - a.value); @@ -539,7 +586,7 @@ function DashboardContent() { const courseAverages = createMemo(() => (marks()?.courses ?? []) .filter((c) => c.average != null) - .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })), + .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: formatDecimal(c.average!, locale()) })), ); // Weekly activity split — student attendance breakdown (events + sessions). @@ -589,11 +636,11 @@ function DashboardContent() { .reduce((sum, entry) => sum + entry.value, 0); }); - const deadlines = createMemo(() => { + const rawDeadlines = createMemo(() => { const items: DeadlineRow[] = []; for (const exam of exams()?.items ?? []) { const status = scheduleStatus(exam.starts_at, exam.ends_at, now()); - if (status) items.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at!, status }); + if (status) items.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at!, status, instance: exam.class_course }); } for (const event of events()?.items ?? []) { const status = scheduleStatus(event.starts_at, event.ends_at, now()); @@ -601,7 +648,7 @@ function DashboardContent() { } for (const hw of homework()?.items ?? []) { const status = scheduleStatus(hw.due_at, hw.due_at, now()); - if (status) items.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, status }); + if (status) items.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, status, instance: hw.class_course }); } for (const appointment of appointments()?.items ?? []) { if (appointment.starts_at == null || !["pending", "approved"].includes(appointment.status)) continue; @@ -622,6 +669,19 @@ function DashboardContent() { } return items.sort((a, b) => a.at - b.at); }); + // One ders taught in two şubeler gives two rows with the same title, so a + // row names " — <şube>" under its title. + // The label is folded into the row (a new array) rather than read in the + // cell: the table caches cells by data identity and would not repaint. + const deadlineSections = createInstanceLabels( + () => rawDeadlines().flatMap((row) => (row.instance ? [row.instance] : [])), + role, + ); + const deadlines = createMemo(() => { + const labels = deadlineSections(); + return rawDeadlines().map((row) => (row.instance && labels[row.instance] ? { ...row, section: labels[row.instance].label } : row)); + }); + const deadlineSection = (row: DeadlineRow) => row.section; const headerClass = "text-xs font-medium text-muted-foreground"; const deadlineColumns = createMemo[]>(() => [ @@ -630,7 +690,14 @@ function DashboardContent() { header: t("dashboard.col.task"), enableSorting: false, meta: { headerClass }, - cell: (info) => {info.row.original.title}, + cell: (info) => ( +
+ {info.row.original.title} + + {(section) => {section()}} + +
+ ), }, { accessorKey: "kind", @@ -663,7 +730,7 @@ function DashboardContent() { }, ]); - const deadlineSearch = (row: DeadlineRow, q: string) => matchesSearch(q, row.title); + const deadlineSearch = (row: DeadlineRow, q: string) => matchesSearch(q, row.title, deadlineSection(row)); const openDeadline = (row: DeadlineRow) => { switch (row.kind) { case "exam": diff --git a/src/pages/event-detail-page.tsx b/src/pages/event-detail-page.tsx index 5b3c8d3..973bb52 100644 --- a/src/pages/event-detail-page.tsx +++ b/src/pages/event-detail-page.tsx @@ -40,6 +40,7 @@ import { formatDateTime } from "@/lib/format"; import { personId, personLabel } from "@/lib/person"; import { matchesSearch } from "@/lib/search-text"; import { hasMinRole } from "@/lib/roles"; +import { createUrlString } from "@/lib/url-state"; import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -77,7 +78,7 @@ function EventDetailContent() { const [deleteOpen, setDeleteOpen] = createSignal(false); const [registrationTarget, setRegistrationTarget] = createSignal(null); const [rosterSearch, setRosterSearch] = createSignal(""); - const [eventTab, setEventTab] = createSignal("studentAttendance"); + const [eventTab, setEventTab] = createUrlString("tab", "studentAttendance"); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); diff --git a/src/pages/events-page.tsx b/src/pages/events-page.tsx index ebeba11..321585a 100644 --- a/src/pages/events-page.tsx +++ b/src/pages/events-page.tsx @@ -18,6 +18,7 @@ import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { TruncationNotice } from "@/components/ui/truncation-notice"; import { cn } from "@/lib/cn"; +import { createUrlEnum } from "@/lib/url-state"; import { createNow } from "@/lib/create-now"; import { LIST_CAP, loadCappedList } from "@/lib/capped-list"; import { createFlash } from "@/lib/flash"; @@ -52,18 +53,34 @@ function EventsContent() { setShowForm(true); } }); - const [timeFilter, setTimeFilter] = createSignal("all"); + const [timeFilter, setTimeFilter] = createUrlEnum("when", ["all", "upcoming", "past"] as const, "all"); const now = createNow(); const canCreate = () => hasMinRole(auth.user()?.role, "teacher"); const filterEvents = (items: Event[]) => { const scope = timeFilter(); const nowMs = now(); - return items.filter((event) => { - if (scope === "upcoming" && event.ends_at != null && event.ends_at < nowMs) return false; - if (scope === "past" && (event.ends_at == null || event.ends_at >= nowMs)) return false; - return true; - }); + const isPast = (event: Event) => event.ends_at != null && event.ends_at < nowMs; + const at = (event: Event) => event.starts_at ?? event.ends_at ?? null; + // Default order, before any header sort: what is still ahead comes first, + // soonest first; what is over follows, most recent first. The API lists + // newest first, which put a far-off event above next week's. + const byDefault = (a: Event, b: Event) => { + const pastA = isPast(a); + const pastB = isPast(b); + if (pastA !== pastB) return pastA ? 1 : -1; + const atA = at(a); + const atB = at(b); + if (atA == null || atB == null) return atA == null ? (atB == null ? 0 : 1) : -1; + return pastA ? atB - atA : atA - atB; + }; + return items + .filter((event) => { + if (scope === "upcoming" && isPast(event)) return false; + if (scope === "past" && !isPast(event)) return false; + return true; + }) + .sort(byDefault); }; const [loadAll, setLoadAll] = createSignal(false); @@ -71,7 +88,7 @@ function EventsContent() { () => (loadAll() ? "all" : "capped"), (scope) => loadCappedList(getEvents, LIST_CAP, scope === "all"), ); - const rows = () => filterEvents(list()?.items ?? []); + const rows = createMemo(() => filterEvents(list()?.items ?? [])); const eventStatus = (event: Event) => { const nowMs = now(); if (event.ends_at != null && event.ends_at < nowMs) return "past"; @@ -214,6 +231,7 @@ function EventsContent() { onLoadAll={() => setLoadAll(true)} /> setTimeFilter("all")} storageKey="events" onRowClick={(event) => void navigate({ to: "/events/$id", params: { id: event.id } })} filters={ setTimeFilter(val)} + onChange={(val) => setTimeFilter(val === "upcoming" || val === "past" ? val : "all")} options={[ { value: "all", label: t("common.all") }, { value: "upcoming", label: t("events.upcoming") }, diff --git a/src/pages/exam-detail-page.tsx b/src/pages/exam-detail-page.tsx index 80e6529..08a329d 100644 --- a/src/pages/exam-detail-page.tsx +++ b/src/pages/exam-detail-page.tsx @@ -39,6 +39,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { hasMinRole } from "@/lib/roles"; +import { createUrlString } from "@/lib/url-state"; import { createNow } from "@/lib/create-now"; import { examKindLabel } from "@/lib/exam-labels"; import { examDisplayStatus, examStatusMessageKey, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status"; @@ -123,7 +124,9 @@ function ExamDetailContent() { const [answerMark, setAnswerMark] = createSignal("0"); const [answerError, setAnswerError] = createSignal(""); const [answerPending, setAnswerPending] = createSignal(false); - const [examTab, setExamTab] = createSignal("questions"); + // `?tab=` when the user picked one, so Back from an answer sheet or a + // student lands on the same tab; otherwise the exam's own default below. + const [pickedTab, setExamTab] = createUrlString("tab"); const isSittable = () => { const e = exam(); return e ? isSittableExam(e) : false; @@ -210,13 +213,13 @@ function ExamDetailContent() { }; const isFinished = () => examStatus().finished; const isUpcoming = () => examStatus().upcoming; - let defaultTabExamId = ""; - createEffect(() => { + // A finished exam opens on its results, any other on its questions. Fixed + // per exam when it loads, so the clock passing ends_at does not switch tabs. + const defaultTab = createMemo(on(() => exam()?.id, () => { const current = exam(); - if (!current || current.id === defaultTabExamId) return; - defaultTabExamId = current.id; - setExamTab(current.ends_at != null && current.ends_at < now() ? "results" : "questions"); - }); + return current && current.ends_at != null && current.ends_at < now() ? "results" : "questions"; + })); + const examTab = () => pickedTab() || defaultTab(); const ownAttemptSummary = (): ExamAttemptSummary | null => { const attempt = ownAttempt(); return attempt ? { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } : null; @@ -399,7 +402,7 @@ function ExamDetailContent() { diff --git a/src/pages/exams-page.tsx b/src/pages/exams-page.tsx index 4c55381..b50c828 100644 --- a/src/pages/exams-page.tsx +++ b/src/pages/exams-page.tsx @@ -34,6 +34,7 @@ import { hasMinRole } from "@/lib/roles"; import { matchesSearch } from "@/lib/search-text"; import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status"; import { cn } from "@/lib/cn"; +import { createUrlEnum, createUrlString } from "@/lib/url-state"; import { useAuth } from "@/stores/auth-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -62,9 +63,24 @@ function ExamsContent() { if (status === "upcoming" || status === "active" || status === "unscheduled") return "upcoming"; return "completed"; }; - const [tab, setTab] = createSignal("all"); - const [courseFilter, setCourseFilter] = createSignal("all"); - const [kindFilter, setKindFilter] = createSignal("all"); + // Tab and filters live in the URL beside the table's own search/page/sort, + // so Back from an exam lands on the same slice of the list. + const [tab, setTab] = createUrlEnum("tab", ["all", "upcoming", "completed", "draft"], "all"); + const [courseFilter, setCourseFilter] = createUrlString("course", "all"); + const [kindFilter, setKindFilter] = createUrlString("kind", "all"); + const filtersActive = () => courseFilter() !== "all" || kindFilter() !== "all"; + const clearFilters = () => { + setCourseFilter("all"); + setKindFilter("all"); + }; + const emptyMessage = () => + tab() === "upcoming" + ? t("exams.emptyUpcoming") + : tab() === "completed" + ? t("exams.emptyCompleted") + : tab() === "draft" + ? t("exams.emptyDraft") + : t("exams.empty"); const [createOpen, setCreateOpen] = createSignal(location().searchStr.includes("action=new")); createEffect(() => { if (location().searchStr.includes("action=new")) { @@ -172,13 +188,15 @@ function ExamsContent() { const statusLabel = (status: ExamDisplayStatus) => { return t(examStatusMessageKey(status)); }; - const rows = (): ExamRow[] => filterExams(list()?.items ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) })); + // A memo, not a function: the table must see one array per change, not a + // fresh one on every read. + const rows = createMemo((): ExamRow[] => filterExams(list()?.items ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }))); const columns = createMemo[]>(() => [ { accessorKey: "title", header: t("exams.title"), size: 220, - minSize: 180, + minSize: 160, cell: (cell) => (

{cell.row.original.title}

@@ -206,13 +224,14 @@ function ExamsContent() { id: "status", accessorFn: (exam) => statusLabel(exam.displayStatus), header: t("attempt.status"), - size: 130, - minSize: 110, + // The pill is min-w-24 plus cell padding: narrower clips it. + size: 140, + minSize: 120, meta: { headerClass: "text-center", cellClass: "text-center" }, cell: (cell) => { const status = cell.row.original.displayStatus; return ( - + {statusLabel(status)} @@ -339,13 +358,16 @@ function ExamsContent() { } columns={columns()} data={rows()} - tableClass="table-fixed min-w-[46rem]" filterPlaceholder={t("exams.searchPlaceholder")} filterHint={t("search.hint.exams")} searchPredicate={searchExam} enablePagination pageSize={EXAM_PAGE_SIZE} - empty={t("exams.empty")} + empty={emptyMessage()} + urlState + pageResetKey={`${tab()}|${courseFilter()}|${kindFilter()}`} + filtersActive={filtersActive()} + onClearFilters={clearFilters} storageKey="exams" onRowClick={(exam) => void navigate({ to: "/exams/$id", params: { id: exam.id } })} filters={ @@ -370,16 +392,13 @@ function ExamsContent() { ]} /> - + + + + {t("instances.policySaved")} + +
@@ -351,11 +398,20 @@ function InstanceDetailContent() { checked={countsTowardKarne()} disabled={savingPolicy()} aria-label={t("instances.countsTowardKarne")} - onChange={(event) => void toggleKarne(event.currentTarget.checked)} + onChange={(event) => { + // Keep the switch where it is until the change is confirmed. + const next = event.currentTarget.checked; + event.currentTarget.checked = !next; + setKarneConfirm(next); + }} /> + {countsTowardKarne() ? t("common.yes") : t("common.no")} + + {t("instances.policySaved")} +
@@ -383,12 +439,28 @@ function InstanceDetailContent() {
+ !open && setKarneConfirm(null)} + title={t("instances.karneConfirmTitle")} + description={karneConfirm() ? t("instances.karneOnHint") : t("instances.karneOffHint")} + summary={`${course.latest?.title ?? ""} — ${klass.latest?.name ?? ""}`.replace(/^ — | — $/, "")} + confirmLabel={karneConfirm() ? t("instances.karneTurnOn") : t("instances.karneTurnOff")} + onConfirm={async () => { + const next = karneConfirm(); + if (next !== null) await toggleKarne(next); + }} + /> + setRemoveTarget(null)} - title={t("course.removeStudent")} + title={t("course.removeStudentTitle")} + description={t("course.removeStudentHint")} variant="destructive" - summary={`${t("course.removeStudentConfirm")} "${removeTarget()?.userName}"?`} + icon={} + confirmLabel={t("course.removeStudentAction")} + summary={removeTarget()?.userName ?? ""} onConfirm={async () => { const target = removeTarget(); if (!target) return; diff --git a/src/pages/license-modules-page.tsx b/src/pages/license-modules-page.tsx index abac786..ca8db5d 100644 --- a/src/pages/license-modules-page.tsx +++ b/src/pages/license-modules-page.tsx @@ -6,7 +6,7 @@ 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, ComingSoonValue } from "@/components/ui/coming-soon"; +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"; @@ -79,9 +79,9 @@ function LicenseModulesContent() { ), }, - { id: "unitPrice", header: t("modules.unitPrice"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => }, - { id: "seats", header: t("modules.activeSeats"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => }, - { id: "annual", header: t("modules.annualAmount"), meta: { align: "right", hideInCards: true }, enableSorting: false, cell: () => }, + // Unit price, seats and annual amount have no licensing/billing endpoint + // behind them, so those design columns are left out rather than filled + // with "yakında". ]); return ( @@ -100,7 +100,7 @@ function LicenseModulesContent() { - }> + }> void refetch()} /> @@ -118,24 +118,18 @@ function LicenseModulesContent() {

{enabledPackages().join(" + ") || "—"}

-
- -

{t("modules.annualTotal")}

-
{t("modules.enabledCount", { on: String(enabledCount()), total: String(totalCount()) })} - - {t("modules.renewal")}: -
} columns={columns()} data={value().rows} - tableClass="min-w-[760px]" + tableClass="min-w-md" enablePagination={false} storageKey="license-modules" /> diff --git a/src/pages/meal-detail-page.tsx b/src/pages/meal-detail-page.tsx index ef315a6..bea6d3b 100644 --- a/src/pages/meal-detail-page.tsx +++ b/src/pages/meal-detail-page.tsx @@ -47,7 +47,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import { UserSearchSelect } from "@/components/users/user-search-select"; import { formatDateTime } from "@/lib/format"; -import { formatTry, mealCutoffAt } from "@/lib/meals"; +import { dietaryTagLabel, formatTry, mealCutoffAt, mealSlotLabel } from "@/lib/meals"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; @@ -186,7 +186,7 @@ function MealDetailContent() { {(current) => (
- +

{dish.name}

{formatTry(dish.price_minor, moneyLocale())}

{dish.description || "—"}

-
{(tag) => {dish.conflicts.includes(tag) ? `⚠ ${tag}` : tag}}
+
{(tag) => {dish.conflicts.includes(tag) ? `⚠ ${dietaryTagLabel(tag, t)}` : dietaryTagLabel(tag, t)}}
)} @@ -242,7 +242,7 @@ function MealDetailContent() {
-

{t("meals.dietaryProfile")}

{(tag) => ⚠ {tag}}

{profile()?.note || t("meals.noDietaryNotes")}

+

{t("meals.dietaryProfile")}

{(tag) => ⚠ {dietaryTagLabel(tag, t)}}

{profile()?.note || t("meals.noDietaryNotes")}

{t("meals.balance")}

{formatTry(balance()?.balance_minor ?? 0, moneyLocale())}

{t("meals.ledger")}

{(line) =>

{t(`meals.ledger.${line.kind}` as never)}

{line.note || line.method || "—"} · {formatDateTime(line.created_at, locale())}

{line.kind === "charge" ? "−" : "+"}{formatTry(line.amount_minor, moneyLocale())}
}

{t("meals.noLedger")}

@@ -267,7 +267,7 @@ function MealDetailContent() {
-
{(tag) => }
+
{(tag) => }