import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { useNavigate } from "@tanstack/solid-router"; import { getClasses, getClassMembers, postClass } from "@/api/classes"; import { getAcademicYears } from "@/api/academic-years"; import { getCourses } from "@/api/courses"; import { getLimits } from "@/api/limits"; import { formatApiError, type BlueprintSkip, type ClassGroup } from "@/api/client"; import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report"; import { RouteGuard } from "@/components/layout/route-guard"; import { DataToolbar } from "@/components/ui/data-toolbar"; import { DropdownSelect, Select } from "@/components/ui/select"; import { Alert } from "@/components/ui/alert"; import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { DataTableSkeleton } from "@/components/ui/data-table"; import { EmptyState } from "@/components/ui/empty-state"; import { IconChevronRight, IconPlus } from "@/components/ui/icons"; import { Input } from "@/components/ui/input"; 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"; import { personLabel } from "@/lib/person"; import { hasMinRole } from "@/lib/roles"; import { useAuth } from "@/stores/auth-context"; import { useT } from "@/stores/preferences-context"; // A class's member count has no aggregate field on ClassGroup and no bulk // endpoint — each card's count is one `getClassMembers(id, {limit:1})` read // for its `total`, same "N+1 bounded by the visible set" shape already used // for payments roster balances and staff-work people. Capped so a school with // an unusually large roster of classes doesn't fire hundreds of requests. const MEMBER_COUNT_FETCH_CAP = 200; export default function ClassesPage() { return ; } function ClassesContent() { const auth = useAuth(); const navigate = useNavigate(); const t = useT(); const canManage = () => hasMinRole(auth.user()?.role, "manager"); const [tab, setTab] = createSignal("classes"); const [gradeFilter, setGradeFilter] = createSignal("all"); const [query, setQuery] = createSignal(""); const [showForm, setShowForm] = createSignal(false); const [name, setName] = createSignal(""); const [grade, setGrade] = createSignal(""); const [yearId, setYearId] = createSignal(""); const [teacherId, setTeacherId] = createSignal(""); const [error, setError] = createSignal(""); const [nameError, setNameError] = createSignal(""); const [pending, setPending] = createSignal(false); // A create whose grade's blueprint left pairs behind reports them here before // it opens the class: the response is the only place those rows ever appear. const [createdClass, setCreatedClass] = createSignal(null); const [skipped, setSkipped] = createSignal([]); const [skippedCourseTitles, setSkippedCourseTitles] = createSignal>({}); const [reportOpen, setReportOpen] = createSignal(false); const [flash, setFlash] = createFlash(); const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); const [limits] = createResource(() => canManage() ? getLimits() : null); const [list, { refetch }] = createResource(async () => (await getClasses()).items); const courseTitle = (id: string) => skippedCourseTitles()[id] ?? id; const listData = () => list.latest ?? list() ?? []; const yearName = (id: string | null) => years.latest?.find((year) => year.id === id)?.name ?? (id || t("academicYears.unassigned")); // Grade tabs mirror Figma's Tümü/Lise/Ortaokul row structurally, but the // labels are read from whatever `grade` values this school actually uses // (freeform text on ClassGroup) instead of assuming a Turkish lise/ortaokul // split that may not hold for every institution. const grades = createMemo(() => { const seen = new Set(); for (const cls of listData()) if (cls.grade) seen.add(cls.grade); return [...seen].sort((a, b) => a.localeCompare(b, "tr")); }); const gradeFiltered = createMemo(() => { const g = gradeFilter(); return g === "all" ? listData() : listData().filter((cls) => cls.grade === g); }); const searched = createMemo(() => { const needle = query().trim(); if (!needle) return gradeFiltered(); return gradeFiltered().filter((cls) => matchesSearch(needle, cls.name, cls.grade, cls.teacher ? personLabel(cls.teacher) : null), ); }); const memberCountIds = createMemo(() => { const ids = listData().map((cls) => cls.id); return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null; }); const [memberCounts] = createResource(memberCountIds, async (ids) => { const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => { try { return [id, (await getClassMembers(id, { limit: 1 })).total] as const; } catch { return [id, null] as const; } }); return new Map(entries); }); const memberCountsCapped = () => listData().length > MEMBER_COUNT_FETCH_CAP; const createClass = async (event: SubmitEvent) => { event.preventDefault(); setError(""); // Checked here rather than by the browser, so the message sits under the // field in the app's own words — and a name of only spaces is caught too. if (!name().trim()) { setNameError(t("form.fieldRequired")); document.getElementById("class-name")?.focus(); return; } setPending(true); try { const created = await postClass({ name: name().trim(), grade: grade().trim() || undefined, year: yearId() || undefined, teacher_id: teacherId() || undefined, }); setName(""); setGrade(""); setYearId(""); setTeacherId(""); setShowForm(false); // Reloading the list is housekeeping for a page we are leaving anyway: a // failure here used to be reported as if the class had not been created, // and it swallowed the navigation to the class that plainly existed. try { await refetch(); } catch { // The list reloads on the next visit; the class was created. } setFlash(t("common.created")); if (created.skipped.length > 0) { // The class exists either way; its grade's template just could not // take every course. The report names each skipped course, so the one // catalog read happens before the panel can open; a failed read leaves // the ids in place rather than holding the report back. try { const courses = (await getCourses({ limit: 200 })).items; setSkippedCourseTitles(Object.fromEntries(courses.map((course) => [course.id, course.title]))); } catch { // The report still opens; the rows fall back to course ids. } setCreatedClass(created.class); setSkipped(created.skipped); setReportOpen(true); return; } void navigate({ to: "/management/classes/$id", params: { id: created.class.id } }); } catch (err) { setError(formatApiError(err)); } finally { setPending(false); } }; // Closing the report is what opens the class, however it closes (button, // Escape, backdrop): the create already happened, so there is nowhere else // to go back to. const closeSkippedReport = (open: boolean) => { setReportOpen(open); if (open) return; const created = createdClass(); setCreatedClass(null); setSkipped([]); setSkippedCourseTitles({}); if (created) void navigate({ to: "/management/classes/$id", params: { id: created.id } }); }; return (
{ setName(e.currentTarget.value); setNameError(""); }} />
setGrade(e.currentTarget.value)} />
{error()}
{flash()} 0}> {t("classBlueprints.skippedSummary", { count: skipped().length })} {/* Every blueprint endpoint is manager+, so a teacher must not be shown a tab that would 403 the moment it opens. */} {t("classBlueprints.classesTab")} {t("classBlueprints.tab")}
0}> ({ value: g, label: g }))]} value={gradeFilter()} onChange={setGradeFilter} class="min-w-44" /> } actions={ } />
{t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })} }> 0} fallback={}>
{(cls) => ( void navigate({ to: "/management/classes/$id", params: { id: cls.id } })} /> )}
tab() === "blueprints"} />
); } function ClassCard(props: { cls: ClassGroup; yearName: string; memberCount: number | null; onClick: () => void }) { const t = useT(); return ( ); }