hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { useNavigate } from "@tanstack/solid-router"; |
| 4 | import { getClasses, getClassMembers, postClass } from "@/api/classes"; |
| 5 | import { getAcademicYears } from "@/api/academic-years"; |
| 6 | import { getCourses } from "@/api/courses"; |
| 7 | import { getLimits } from "@/api/limits"; |
| 8 | import { formatApiError, type BlueprintSkip, type ClassGroup } from "@/api/client"; |
| 9 | import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report"; |
| 10 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 11 | import { DataToolbar } from "@/components/ui/data-toolbar"; |
| 12 | import { DropdownSelect, Select } from "@/components/ui/select"; |
| 13 | import { Alert } from "@/components/ui/alert"; |
| 14 | import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; |
| 15 | import { Badge } from "@/components/ui/badge"; |
| 16 | import { Button } from "@/components/ui/button"; |
| 17 | import { DataTableSkeleton } from "@/components/ui/data-table"; |
| 18 | import { EmptyState } from "@/components/ui/empty-state"; |
| 19 | import { IconChevronRight, IconPlus } from "@/components/ui/icons"; |
| 20 | import { Input } from "@/components/ui/input"; |
| 21 | import { Label } from "@/components/ui/label"; |
| 22 | import { SidePanel } from "@/components/ui/side-panel"; |
| 23 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| 24 | import { BlueprintsTab } from "@/components/classes/blueprints-tab"; |
| 25 | import { ComingSoonBadge } from "@/components/ui/coming-soon"; |
| 26 | import { UserSearchSelect } from "@/components/users/user-search-select"; |
| 27 | import { createFlash } from "@/lib/flash"; |
| 28 | import { matchesSearch } from "@/lib/search-text"; |
| 29 | import { personLabel } from "@/lib/person"; |
| 30 | import { hasMinRole } from "@/lib/roles"; |
| 31 | import { useAuth } from "@/stores/auth-context"; |
| 32 | import { useT } from "@/stores/preferences-context"; |
| 33 | |
| 34 | // A class's member count has no aggregate field on ClassGroup and no bulk |
| 35 | // endpoint — each card's count is one `getClassMembers(id, {limit:1})` read |
| 36 | // for its `total`, same "N+1 bounded by the visible set" shape already used |
| 37 | // for payments roster balances and staff-work people. Capped so a school with |
| 38 | // an unusually large roster of classes doesn't fire hundreds of requests. |
| 39 | const MEMBER_COUNT_FETCH_CAP = 200; |
| 40 | |
| 41 | export default function ClassesPage() { |
| 42 | return <RouteGuard minRole="teacher"><ClassesContent /></RouteGuard>; |
| 43 | } |
| 44 | |
| 45 | function ClassesContent() { |
| 46 | const auth = useAuth(); |
| 47 | const navigate = useNavigate(); |
| 48 | const t = useT(); |
| 49 | const canManage = () => hasMinRole(auth.user()?.role, "manager"); |
| 50 | |
| 51 | const [tab, setTab] = createSignal("classes"); |
| 52 | const [gradeFilter, setGradeFilter] = createSignal("all"); |
| 53 | const [query, setQuery] = createSignal(""); |
| 54 | const [showForm, setShowForm] = createSignal(false); |
| 55 | const [name, setName] = createSignal(""); |
| 56 | const [grade, setGrade] = createSignal(""); |
| 57 | const [yearId, setYearId] = createSignal(""); |
| 58 | const [teacherId, setTeacherId] = createSignal(""); |
| 59 | const [error, setError] = createSignal(""); |
| 60 | const [nameError, setNameError] = createSignal(""); |
| 61 | const [pending, setPending] = createSignal(false); |
| 62 | // A create whose grade's blueprint left pairs behind reports them here before |
| 63 | // it opens the class: the response is the only place those rows ever appear. |
| 64 | const [createdClass, setCreatedClass] = createSignal<ClassGroup | null>(null); |
| 65 | const [skipped, setSkipped] = createSignal<BlueprintSkip[]>([]); |
| 66 | const [skippedCourseTitles, setSkippedCourseTitles] = createSignal<Record<string, string>>({}); |
| 67 | const [reportOpen, setReportOpen] = createSignal(false); |
| 68 | const [flash, setFlash] = createFlash(); |
| 69 | |
| 70 | const [years] = createResource(async () => (await getAcademicYears({ limit: 100 })).items); |
| 71 | const [limits] = createResource(() => canManage() ? getLimits() : null); |
| 72 | const [list, { refetch }] = createResource(async () => (await getClasses()).items); |
| 73 | const courseTitle = (id: string) => skippedCourseTitles()[id] ?? id; |
| 74 | const listData = () => list.latest ?? list() ?? []; |
| 75 | const yearName = (id: string | null) => years.latest?.find((year) => year.id === id)?.name ?? (id || t("academicYears.unassigned")); |
| 76 | |
| 77 | // Grade tabs mirror Figma's Tümü/Lise/Ortaokul row structurally, but the |
| 78 | // labels are read from whatever `grade` values this school actually uses |
| 79 | // (freeform text on ClassGroup) instead of assuming a Turkish lise/ortaokul |
| 80 | // split that may not hold for every institution. |
| 81 | const grades = createMemo(() => { |
| 82 | const seen = new Set<string>(); |
| 83 | for (const cls of listData()) if (cls.grade) seen.add(cls.grade); |
| 84 | return [...seen].sort((a, b) => a.localeCompare(b, "tr")); |
| 85 | }); |
| 86 | |
| 87 | const gradeFiltered = createMemo(() => { |
| 88 | const g = gradeFilter(); |
| 89 | return g === "all" ? listData() : listData().filter((cls) => cls.grade === g); |
| 90 | }); |
| 91 | |
| 92 | const searched = createMemo(() => { |
| 93 | const needle = query().trim(); |
| 94 | if (!needle) return gradeFiltered(); |
| 95 | return gradeFiltered().filter((cls) => |
| 96 | matchesSearch(needle, cls.name, cls.grade, cls.teacher ? personLabel(cls.teacher) : null), |
| 97 | ); |
| 98 | }); |
| 99 | |
| 100 | const memberCountIds = createMemo(() => { |
| 101 | const ids = listData().map((cls) => cls.id); |
| 102 | return ids.length > 0 && ids.length <= MEMBER_COUNT_FETCH_CAP ? ids : null; |
| 103 | }); |
| 104 | const [memberCounts] = createResource(memberCountIds, async (ids) => { |
| 105 | const entries = await mapConcurrent(ids, FAN_OUT_LIMIT, async (id) => { |
| 106 | try { |
| 107 | return [id, (await getClassMembers(id, { limit: 1 })).total] as const; |
| 108 | } catch { |
| 109 | return [id, null] as const; |
| 110 | } |
| 111 | }); |
| 112 | return new Map(entries); |
| 113 | }); |
| 114 | const memberCountsCapped = () => listData().length > MEMBER_COUNT_FETCH_CAP; |
| 115 | |
| 116 | const createClass = async (event: SubmitEvent) => { |
| 117 | event.preventDefault(); |
| 118 | setError(""); |
| 119 | // Checked here rather than by the browser, so the message sits under the |
| 120 | // field in the app's own words — and a name of only spaces is caught too. |
| 121 | if (!name().trim()) { |
| 122 | setNameError(t("form.fieldRequired")); |
| 123 | document.getElementById("class-name")?.focus(); |
| 124 | return; |
| 125 | } |
| 126 | setPending(true); |
| 127 | try { |
| 128 | const created = await postClass({ |
| 129 | name: name().trim(), |
| 130 | grade: grade().trim() || undefined, |
| 131 | year: yearId() || undefined, |
| 132 | teacher_id: teacherId() || undefined, |
| 133 | }); |
| 134 | setName(""); setGrade(""); setYearId(""); setTeacherId(""); setShowForm(false); |
| 135 | // Reloading the list is housekeeping for a page we are leaving anyway: a |
| 136 | // failure here used to be reported as if the class had not been created, |
| 137 | // and it swallowed the navigation to the class that plainly existed. |
| 138 | try { |
| 139 | await refetch(); |
| 140 | } catch { |
| 141 | // The list reloads on the next visit; the class was created. |
| 142 | } |
| 143 | setFlash(t("common.created")); |
| 144 | if (created.skipped.length > 0) { |
| 145 | // The class exists either way; its grade's template just could not |
| 146 | // take every course. The report names each skipped course, so the one |
| 147 | // catalog read happens before the panel can open; a failed read leaves |
| 148 | // the ids in place rather than holding the report back. |
| 149 | try { |
| 150 | const courses = (await getCourses({ limit: 200 })).items; |
| 151 | setSkippedCourseTitles(Object.fromEntries(courses.map((course) => [course.id, course.title]))); |
| 152 | } catch { |
| 153 | // The report still opens; the rows fall back to course ids. |
| 154 | } |
| 155 | setCreatedClass(created.class); |
| 156 | setSkipped(created.skipped); |
| 157 | setReportOpen(true); |
| 158 | return; |
| 159 | } |
| 160 | void navigate({ to: "/management/classes/$id", params: { id: created.class.id } }); |
| 161 | } catch (err) { |
| 162 | setError(formatApiError(err)); |
| 163 | } finally { |
| 164 | setPending(false); |
| 165 | } |
| 166 | }; |
| 167 | |
| 168 | // Closing the report is what opens the class, however it closes (button, |
| 169 | // Escape, backdrop): the create already happened, so there is nowhere else |
| 170 | // to go back to. |
| 171 | const closeSkippedReport = (open: boolean) => { |
| 172 | setReportOpen(open); |
| 173 | if (open) return; |
| 174 | const created = createdClass(); |
| 175 | setCreatedClass(null); |
| 176 | setSkipped([]); |
| 177 | setSkippedCourseTitles({}); |
| 178 | if (created) void navigate({ to: "/management/classes/$id", params: { id: created.id } }); |
| 179 | }; |
| 180 | |
| 181 | return ( |
| 182 | <div class="space-y-5"> |
| 183 | <SidePanel open={canManage() && showForm()} onOpenChange={setShowForm} guardUnsaved title={t("classGroups.newClass")} description={t("classGroups.subtitle")}> |
| 184 | <form class="space-y-4" noValidate onSubmit={createClass}> |
| 185 | <div class="space-y-3"> |
| 186 | <div class="space-y-1.5"><Label for="class-name">{t("classGroups.className")}<span class="ml-0.5 text-destructive-text">*</span></Label><Input id="class-name" required aria-required="true" maxlength={limits.latest?.course.max_class_name_len} value={name()} error={nameError()} onInput={(e) => { setName(e.currentTarget.value); setNameError(""); }} /></div> |
| 187 | <div class="space-y-1.5"><Label for="class-grade">{t("classGroups.grade")}</Label><Input id="class-grade" maxlength={limits.latest?.course.max_class_grade_len} value={grade()} onInput={(e) => setGrade(e.currentTarget.value)} /></div> |
| 188 | <div class="space-y-1.5"><Label for="class-year">{t("academicYears.year")}</Label><Select id="class-year" value={yearId()} onChange={(e) => setYearId(e.currentTarget.value)}><option value="">{t("academicYears.unassigned")}</option><For each={years.latest ?? []}>{(year) => <option value={year.id}>{year.name}</option>}</For></Select></div> |
| 189 | <UserSearchSelect id="class-teacher" label={t("classGroups.homeroomTeacher")} value={teacherId()} onChange={setTeacherId} placeholder={t("classGroups.selectTeacher")} role="teacher" /> |
| 190 | </div> |
| 191 | <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show> |
| 192 | <div class="flex gap-2 border-t border-border-hairline pt-4"><Button type="submit" disabled={pending()}>{t("common.create")}</Button><Button type="button" variant="outline" onClick={() => setShowForm(false)}>{t("common.cancel")}</Button></div> |
| 193 | </form> |
| 194 | </SidePanel> |
| 195 | |
| 196 | <Show when={flash()}><Alert variant="success">{flash()}</Alert></Show> |
| 197 | |
| 198 | <Show when={skipped().length > 0}> |
| 199 | <Alert class="flex flex-wrap items-center justify-between gap-3 border-amber-500/40 bg-amber-500/10 text-amber-900 dark:text-amber-200"> |
| 200 | <span class="min-w-0 flex-1">{t("classBlueprints.skippedSummary", { count: skipped().length })}</span> |
| 201 | <Button type="button" size="sm" variant="outline" class="shrink-0 rounded-lg" onClick={() => setReportOpen(true)}> |
| 202 | {t("classBlueprints.skippedDetails")} |
| 203 | </Button> |
| 204 | </Alert> |
| 205 | </Show> |
| 206 | |
| 207 | <BlueprintSkippedReport |
| 208 | open={reportOpen()} |
| 209 | onOpenChange={closeSkippedReport} |
| 210 | skipped={skipped()} |
| 211 | courseTitle={courseTitle} |
| 212 | /> |
| 213 | |
| 214 | <Tabs value={tab()} onChange={setTab}> |
| 215 | {/* Every blueprint endpoint is manager+, so a teacher must not be shown |
| 216 | a tab that would 403 the moment it opens. */} |
| 217 | <Show when={canManage()}> |
| 218 | <TabsList class="mb-4"> |
| 219 | <TabsTrigger value="classes">{t("classBlueprints.classesTab")}</TabsTrigger> |
| 220 | <TabsTrigger value="blueprints">{t("classBlueprints.tab")}</TabsTrigger> |
| 221 | </TabsList> |
| 222 | </Show> |
| 223 | |
| 224 | <TabsContent value="classes"> |
| 225 | <div class="space-y-4"> |
| 226 | <div class="rounded-xl border border-border-line bg-surface-base p-3 shadow-xs"> |
| 227 | <DataToolbar |
| 228 | searchValue={query()} |
| 229 | searchPlaceholder={t("classGroups.searchPlaceholder")} |
| 230 | searchHint={t("search.hint.classes")} |
| 231 | onSearchInput={setQuery} |
| 232 | filters={ |
| 233 | <Show when={grades().length > 0}> |
| 234 | <DropdownSelect |
| 235 | options={[{ value: "all", label: t("classGroups.allGrades") }, ...grades().map((g) => ({ value: g, label: g }))]} |
| 236 | value={gradeFilter()} |
| 237 | onChange={setGradeFilter} |
| 238 | class="min-w-44" |
| 239 | /> |
| 240 | </Show> |
| 241 | } |
| 242 | actions={ |
| 243 | <Show when={canManage()}> |
| 244 | <Button type="button" size="sm" variant="outline" class="rounded-lg" disabled title={t("comingSoon.title")}> |
| 245 | {t("classGroups.mergeClasses")} |
| 246 | <ComingSoonBadge class="ml-1.5" /> |
| 247 | </Button> |
| 248 | <Button type="button" size="sm" class="rounded-lg" onClick={() => setShowForm(true)}> |
| 249 | <IconPlus class="h-4 w-4" /> |
| 250 | {t("classGroups.newClass")} |
| 251 | </Button> |
| 252 | </Show> |
| 253 | } |
| 254 | /> |
| 255 | </div> |
| 256 | |
| 257 | <Show when={memberCountsCapped()}> |
| 258 | <Alert role="status">{t("classGroups.memberCountCapped", { cap: MEMBER_COUNT_FETCH_CAP })}</Alert> |
| 259 | </Show> |
| 260 | |
| 261 | <Suspense fallback={<DataTableSkeleton />}> |
| 262 | <Show when={searched().length > 0} fallback={<EmptyState kind="people" title={t("classGroups.empty")} />}> |
| 263 | <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3"> |
| 264 | <For each={searched()}> |
| 265 | {(cls) => ( |
| 266 | <ClassCard |
| 267 | cls={cls} |
| 268 | yearName={yearName(cls.year)} |
| 269 | memberCount={memberCounts()?.get(cls.id) ?? null} |
| 270 | onClick={() => void navigate({ to: "/management/classes/$id", params: { id: cls.id } })} |
| 271 | /> |
| 272 | )} |
| 273 | </For> |
| 274 | </div> |
| 275 | </Show> |
| 276 | </Suspense> |
| 277 | </div> |
| 278 | </TabsContent> |
| 279 | |
| 280 | <TabsContent value="blueprints"> |
| 281 | <BlueprintsTab canManage={canManage} active={() => tab() === "blueprints"} /> |
| 282 | </TabsContent> |
| 283 | </Tabs> |
| 284 | </div> |
| 285 | ); |
| 286 | } |
| 287 | |
| 288 | function ClassCard(props: { cls: ClassGroup; yearName: string; memberCount: number | null; onClick: () => void }) { |
| 289 | const t = useT(); |
| 290 | return ( |
| 291 | <button |
| 292 | type="button" |
| 293 | onClick={props.onClick} |
| 294 | class="group flex flex-col gap-4 rounded-2xl border border-border-line/80 bg-surface-base p-4 text-left shadow-xs transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" |
| 295 | > |
| 296 | <div class="flex items-start gap-3"> |
| 297 | <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-sm font-semibold text-primary-text"> |
| 298 | {props.cls.grade || "—"} |
| 299 | </span> |
| 300 | <div class="min-w-0 flex-1"> |
| 301 | <p class="truncate text-base font-semibold text-text-strong">{props.cls.name}</p> |
| 302 | <p class="mt-1 truncate text-xs text-text-subtle">{props.cls.teacher ? personLabel(props.cls.teacher) : t("classGroups.noTeacher")}</p> |
| 303 | </div> |
| 304 | <IconChevronRight class="h-4 w-4 shrink-0 text-text-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-primary-text" /> |
| 305 | </div> |
| 306 | <div class="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 text-xs text-text-subtle"> |
| 307 | <Badge variant="outline" class="min-w-0 max-w-full justify-start rounded-full bg-transparent" title={props.yearName}> |
| 308 | <span class="min-w-0 truncate">{props.yearName}</span> |
| 309 | </Badge> |
| 310 | <Show when={props.memberCount != null} fallback={<span class="shrink-0 text-xs text-text-subtle">—</span>}> |
| 311 | <span class="shrink-0">{t("classGroups.studentsCount", { count: String(props.memberCount) })}</span> |
| 312 | </Show> |
| 313 | </div> |
| 314 | </button> |
| 315 | ); |
| 316 | } |