forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

blueprints-tab.tsx265 lines, 9.6 KiBHistoryRawDownload
1import { Show, createMemo, createSignal } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import type { ColumnDef } from "@tanstack/solid-table";
4import { deleteClassBlueprintByGrade, getClassBlueprints, getClassBlueprintStatus } from "@/api/classes";
5import { getCourses } from "@/api/courses";
6import { getLimits } from "@/api/limits";
7import { formatApiError, type BlueprintResult, type BlueprintSectionStatus, type BlueprintSkip, type BlueprintStatus, type ClassBlueprint } from "@/api/client";
8import { BlueprintPanel } from "@/components/classes/blueprint-panel";
9import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report";
10import { Alert } from "@/components/ui/alert";
11import { Button } from "@/components/ui/button";
12import { ConfirmDialog } from "@/components/ui/confirm-dialog";
13import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
14import { IconClipboardCheck, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
15import { SidePanel } from "@/components/ui/side-panel";
16import { TableRowActions } from "@/components/ui/table-row-actions";
17import { createFlash } from "@/lib/flash";
18import { personLabel } from "@/lib/person";
19import { useT } from "@/stores/preferences-context";
20
21export function BlueprintsTab(props: {
22 /** Every blueprint route is manager+; below that the tab is not rendered. */
23 canManage: () => boolean;
24 /** Tabs keep both panels mounted, so the list is only fetched once opened. */
25 active: () => boolean;
26}) {
27 const t = useT();
28 const [error, setError] = createSignal("");
29 const [flash, setFlash] = createFlash();
30 const [panelOpen, setPanelOpen] = createSignal(false);
31 const [editing, setEditing] = createSignal<ClassBlueprint | null>(null);
32 const [deleting, setDeleting] = createSignal<ClassBlueprint | null>(null);
33 const [skipped, setSkipped] = createSignal<BlueprintSkip[]>([]);
34 const [unmatchedGrade, setUnmatchedGrade] = createSignal<string | null>(null);
35 const [reportOpen, setReportOpen] = createSignal(false);
36 const [status, setStatus] = createSignal<BlueprintStatus | null>(null);
37
38 const enabled = () => (props.active() && props.canManage() ? true : null);
39 const [list, { refetch }] = createResource(enabled, async () =>
40 (await getClassBlueprints({ limit: 200 })).items,
41 );
42 const [courses] = createResource(enabled, async () => (await getCourses({ limit: 200 })).items);
43 const [limits] = createResource(enabled, () => getLimits());
44
45 const courseTitle = (id: string) => courses.latest?.find((c) => c.id === id)?.title ?? id;
46
47 const columns = createMemo<ColumnDef<ClassBlueprint>[]>(() => [
48 {
49 id: "grade",
50 accessorFn: (row) => row.grade,
51 header: t("classBlueprints.grade"),
52 meta: { cellClass: "font-medium" },
53 },
54 {
55 id: "count",
56 accessorFn: (row) => t("classBlueprints.courseCount", { count: row.courses.length }),
57 header: t("classBlueprints.courseCountColumn"),
58 },
59 {
60 id: "titles",
61 accessorFn: (row) => {
62 const names = row.courses.slice(0, 3).map(courseTitle);
63 const rest = row.courses.length - names.length;
64 return rest > 0 ? `${names.join(", ")} +${rest}` : names.join(", ") || "—";
65 },
66 header: t("classBlueprints.courses"),
67 meta: { cellClass: "text-muted-foreground" },
68 },
69 {
70 id: "creator",
71 accessorFn: (row) => personLabel(row.creator),
72 header: t("common.creator"),
73 meta: { cellClass: "text-muted-foreground" },
74 },
75 {
76 id: "actions",
77 header: t("common.actions"),
78 meta: { headerClass: "w-14 text-center", cellClass: "px-1 text-center" },
79 cell: (cell) => (
80 <TableRowActions
81 label={t("common.actions")}
82 actions={[
83 {
84 label: t("classBlueprints.edit"),
85 icon: <IconEdit class="h-4 w-4" />,
86 onSelect: () => {
87 setEditing(cell.row.original);
88 setPanelOpen(true);
89 },
90 },
91 {
92 label: t("classBlueprints.delete"),
93 icon: <IconTrash class="h-4 w-4" />,
94 destructive: true,
95 onSelect: () => setDeleting(cell.row.original),
96 },
97 {
98 label: t("classBlueprints.status"),
99 icon: <IconClipboardCheck class="h-4 w-4" />,
100 onSelect: () => void checkStatus(cell.row.original.grade),
101 },
102 ]}
103 />
104 ),
105 },
106 ]);
107
108 // A saved blueprint is not an error even when some pairs did not attach: the
109 // template was written either way, so the toast fires and the shortfall is a
110 // separate, dismissible report.
111 const handleSaved = async (result: BlueprintResult) => {
112 setPanelOpen(false);
113 setEditing(null);
114 await refetch();
115 setSkipped(result.skipped);
116 // A grade label nobody carries is saved just the same, so it must not
117 // read as "applied" — that is the one outcome the admin needs to fix.
118 if (result.matched === 0) {
119 setUnmatchedGrade(result.blueprint.grade);
120 return;
121 }
122 setUnmatchedGrade(null);
123 setFlash(t("classBlueprints.savedMatched", { count: result.matched }));
124 };
125
126 const remove = async () => {
127 const bp = deleting();
128 if (!bp) return;
129 setError("");
130 try {
131 await deleteClassBlueprintByGrade(bp.grade);
132 setDeleting(null);
133 await refetch();
134 setFlash(t("classBlueprints.deleted"));
135 } catch (err) {
136 setError(formatApiError(err));
137 }
138 };
139 const checkStatus = async (grade: string) => {
140 setError("");
141 try {
142 setStatus(await getClassBlueprintStatus(grade));
143 } catch (err) {
144 setError(formatApiError(err));
145 }
146 };
147
148 const statusColumns = createMemo<ColumnDef<BlueprintSectionStatus>[]>(() => [
149 {
150 id: "section",
151 accessorFn: (row) => row.class_name || row.class,
152 header: t("classBlueprints.statusSection"),
153 meta: { cellClass: "font-medium" },
154 },
155 {
156 id: "missing",
157 accessorFn: (row) => row.missing.map(courseTitle).join(", ") || "—",
158 header: t("classBlueprints.statusMissing"),
159 meta: { cellClass: "text-muted-foreground" },
160 },
161 ]);
162
163 return (
164 <div class="space-y-4">
165 <Show when={flash()}>
166 <Alert variant="success">{flash()}</Alert>
167 </Show>
168 <Show when={error()}>
169 <Alert variant="destructive">{error()}</Alert>
170 </Show>
171 <Show when={unmatchedGrade()}>
172 {(grade) => (
173 <Alert class="border-amber-500/40 bg-amber-500/10 text-amber-900 dark:text-amber-200">
174 {t("classBlueprints.noMatch", { grade: grade() })}
175 </Alert>
176 )}
177 </Show>
178 <Show when={skipped().length > 0}>
179 <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">
180 <span class="min-w-0 flex-1">{t("classBlueprints.skippedSummary", { count: skipped().length })}</span>
181 <Button type="button" size="sm" variant="outline" class="shrink-0 rounded-lg" onClick={() => setReportOpen(true)}>
182 {t("classBlueprints.skippedDetails")}
183 </Button>
184 </Alert>
185 </Show>
186
187 {/* The list is read through `.latest`, so a refetch after a save never
188 re-suspends the tab; the skeleton only covers the first load. */}
189 <Show when={!list.loading || list.latest} fallback={<DataTableSkeleton />}>
190 <DataTable
191 columns={columns()}
192 data={list.latest ?? []}
193 filterColumn="grade"
194 enablePagination
195 pageSize={10}
196 title={t("classBlueprints.title")}
197 description={t("classBlueprints.subtitle")}
198 empty={t("classBlueprints.empty")}
199 actions={
200 <Button
201 size="sm"
202 class="rounded-lg"
203 onClick={() => {
204 setEditing(null);
205 setPanelOpen(true);
206 }}
207 >
208 <IconPlus class="h-4 w-4" />
209 {t("classBlueprints.new")}
210 </Button>
211 }
212 />
213 </Show>
214
215 <BlueprintPanel
216 open={panelOpen()}
217 onOpenChange={(open) => {
218 setPanelOpen(open);
219 if (!open) setEditing(null);
220 }}
221 blueprint={editing()}
222 courses={courses.latest ?? []}
223 maxCourses={limits.latest?.course.max_class_courses ?? 50}
224 maxGradeLen={limits.latest?.course.max_class_grade_len ?? 20}
225 onSaved={(result) => void handleSaved(result)}
226 />
227
228 <BlueprintSkippedReport
229 open={reportOpen()}
230 onOpenChange={setReportOpen}
231 skipped={skipped()}
232 courseTitle={courseTitle}
233 />
234
235 <SidePanel
236 open={status() != null}
237 onOpenChange={(open) => !open && setStatus(null)}
238 title={t("classBlueprints.statusTitle", { grade: status()?.grade ?? "" })}
239 size="wide"
240 >
241 <Show when={status()}>
242 {(current) => (
243 <Show
244 when={current().sections.some((section) => section.missing.length > 0)}
245 fallback={<p class="text-sm text-muted-foreground">{t("classBlueprints.statusEmpty")}</p>}
246 >
247 <DataTable
248 columns={statusColumns()}
249 data={current().sections.filter((section) => section.missing.length > 0)}
250 />
251 </Show>
252 )}
253 </Show>
254 </SidePanel>
255 <ConfirmDialog
256 open={deleting() !== null}
257 onOpenChange={(open) => !open && setDeleting(null)}
258 title={t("classBlueprints.delete")}
259 summary={t("classBlueprints.deleteConfirm", { grade: deleting()?.grade ?? "" })}
260 variant="destructive"
261 onConfirm={remove}
262 />
263 </div>
264 );
265}