forge
Explore
Log in

Don't you dare go Hollow

🧩 failures stop reading as empty data

Browse files at this commit

391e2382bca889b2d99ea466725dcfa1bac32950Burak BoduroğluParent: e0d37b1
  • fix
    • 🧩 failures stop reading as empty data
Show full message
fix: 🧩 failures stop reading as empty data
- createBoardResources: a failed source reads as undefined instead of
  throwing, keeps its .error, and retryFailed refetches only what failed
- dashboard: one failed request no longer takes every panel down; stats
  over a failed source show a dash instead of a made-up 0, and the notice
  says panels are missing data and offers Try again
- calendar: each feed stands alone; a failed one is named above the grid
  with Try again, and a loading line shows while feeds are in flight
  (feeds used to start as [] and read as an empty calendar)
- DataTable: a search that matches nothing says so and offers Clear search,
  instead of the list's own empty-state copy
- calendar prev/next buttons get accessible labels
- tests for each case
src/components/ui/data-table.test.tsxmodified+22 -1
@@ -1,4 +1,4 @@
1-import { fireEvent, render, screen } from "@solidjs/testing-library";
1+import { fireEvent, render, screen, within } from "@solidjs/testing-library";
22 import type { ColumnDef } from "@tanstack/solid-table";
33 import { DataTable } from "@/components/ui/data-table";
44 import { DataSection } from "@/components/ui/data-section";
@@ -149,3 +149,24 @@ test("the header action toolbar of every shared host can shrink below its max-co
149149 expect(toolbar.classList).not.toContain("shrink-0");
150150 }
151151 });
152+
153+test("a search that matches nothing says so and clears back to the list", () => {
154+ render(() => (
155+ <PreferencesProvider>
156+ <DataTable
157+ columns={columns}
158+ data={[{ name: "Ada" }]}
159+ empty="No people yet."
160+ enableColumnVisibility={false}
161+ searchPredicate={(row, query) => row.name.toLowerCase().includes(query.toLowerCase())}
162+ />
163+ </PreferencesProvider>
164+ ));
165+
166+ fireEvent.input(screen.getByRole("textbox"), { target: { value: "zzz" } });
167+ expect(screen.queryByText("No people yet.")).toBeNull();
168+ expect(screen.getByText(/Nothing matches|eşleşen kayıt yok/)).toBeTruthy();
169+
170+ fireEvent.click(within(screen.getByRole("table")).getByRole("button", { name: /Clear search|Aramayı temizle/ }));
171+ expect(screen.getByText("Ada")).toBeTruthy();
172+});
src/components/ui/data-table.tsxmodified+18 -4
@@ -332,10 +332,24 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
332332 fallback={
333333 <TableRow>
334334 <TableCell colSpan={colSpan()} class="py-8 text-center text-muted-foreground">
335- <div class="flex flex-col items-center gap-3">
336- <Illustration name={searchValue().trim() ? "no-results" : (props.emptyIllustration ?? "empty")} class="h-20 w-32" />
337- <span>{props.empty ?? t("common.noResults")}</span>
338- </div>
335+ {/* A search that matches nothing is not an empty list: say so and offer the way back. */}
336+ <Show
337+ when={searchFieldValue().trim()}
338+ fallback={
339+ <div class="flex flex-col items-center gap-3">
340+ <Illustration name={props.emptyIllustration ?? "empty"} class="h-20 w-32" />
341+ <span>{props.empty ?? t("common.noResults")}</span>
342+ </div>
343+ }
344+ >
345+ <div class="flex flex-col items-center gap-3">
346+ <Illustration name="no-results" class="h-20 w-32" />
347+ <span>{t("common.noMatches")}</span>
348+ <Button type="button" size="sm" variant="outline" onClick={() => handleSearch("")}>
349+ {t("common.clearSearch")}
350+ </Button>
351+ </div>
352+ </Show>
339353 </TableCell>
340354 </TableRow>
341355 }
src/i18n/messages.tsmodified+9 -0
@@ -606,6 +606,7 @@ export type MessageKey =
606606 | "common.next"
607607 | "common.pageOf"
608608 | "common.noResults"
609+ | "common.noMatches"
609610 | "common.creator"
610611 | "common.searchPlaceholder"
611612 | "common.all"
@@ -615,6 +616,7 @@ export type MessageKey =
615616 | "common.deleted"
616617 | "common.saved"
617618 | "common.loadAll"
619+ | "dashboard.partialError"
618620 | "common.breadcrumb"
619621 | "common.truncatedNotice"
620622 | "common.createItem"
@@ -1978,6 +1980,7 @@ export type MessageKey =
19781980 | "messages.emptyTrashSummary"
19791981 | "messages.emptyTrashPageSummary"
19801982 | "calendar.title"
1983+ | "calendar.feedsFailed"
19811984 | "calendar.today"
19821985 | "calendar.noEvents"
19831986 | "calendar.events"
@@ -2738,6 +2741,7 @@ const en: Dict = {
27382741 "common.next": "Next",
27392742 "common.pageOf": "{page} / {total}",
27402743 "common.noResults": "No results.",
2744+ "common.noMatches": "Nothing matches your search.",
27412745 "common.creator": "Created by",
27422746 "common.searchPlaceholder": "Search…",
27432747 "common.all": "All",
@@ -2747,6 +2751,7 @@ const en: Dict = {
27472751 "common.deleted": "Deleted.",
27482752 "common.saved": "Saved successfully.",
27492753 "common.loadAll": "Load all",
2754+ "dashboard.partialError": "Some panels could not load and show no data.",
27502755 "common.breadcrumb": "Breadcrumb",
27512756 "common.truncatedNotice": "Showing the first {shown} of {total} records.",
27522757 "common.createItem": "Create new {item}",
@@ -3195,6 +3200,7 @@ const en: Dict = {
31953200 "events.helpBody":
31963201 "Teachers and managers record attendance for students only. Managers can edit any event.",
31973202 "calendar.title": "Calendar",
3203+ "calendar.feedsFailed": "Could not load: {feeds}. The calendar is missing those items.",
31983204 "calendar.today": "Today",
31993205 "calendar.noEvents": "Nothing scheduled on this day.",
32003206 "calendar.events": "Events",
@@ -4872,6 +4878,7 @@ const tr: Dict = {
48724878 "common.next": "Sonraki",
48734879 "common.pageOf": "{page} / {total}",
48744880 "common.noResults": "Sonuç yok.",
4881+ "common.noMatches": "Aramanızla eşleşen kayıt yok.",
48754882 "common.creator": "Oluşturan",
48764883 "common.searchPlaceholder": "Ara…",
48774884 "common.all": "Tümü",
@@ -4881,6 +4888,7 @@ const tr: Dict = {
48814888 "common.deleted": "Silindi.",
48824889 "common.saved": "Başarıyla kaydedildi.",
48834890 "common.loadAll": "Tümünü yükle",
4891+ "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.",
48844892 "common.breadcrumb": "Sayfa konumu",
48854893 "common.truncatedNotice": "{total} kayıttan ilk {shown} tanesi gösteriliyor.",
48864894 "common.createItem": "Yeni {item} oluştur",
@@ -5329,6 +5337,7 @@ const tr: Dict = {
53295337 "events.helpBody":
53305338 "Öğretmenler ve yöneticiler yalnız öğrenciler için yoklama kaydeder. Yöneticiler her etkinliği düzenleyebilir.",
53315339 "calendar.title": "Takvim",
5340+ "calendar.feedsFailed": "Yüklenemedi: {feeds}. Takvimde bu kayıtlar eksik.",
53325341 "calendar.today": "Bugün",
53335342 "calendar.noEvents": "Bu güne ait bir şey yok.",
53345343 "calendar.events": "Etkinlikler",
src/lib/board-resources.test.tsxadded+36 -0
@@ -0,0 +1,36 @@
1+import { createRoot } from "solid-js";
2+import { expect, test, vi } from "vitest";
3+import { createBoardResources } from "@/lib/board-resources";
4+
5+const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
6+
7+test("a failed source reads as undefined and only it is retried", async () => {
8+ const good = vi.fn(async () => "ok");
9+ let fail = true;
10+ const flaky = vi.fn(async () => {
11+ if (fail) throw new Error("boom");
12+ return "recovered";
13+ });
14+
15+ await createRoot(async (dispose) => {
16+ const board = createBoardResources();
17+ const [a] = board.createResource(good);
18+ const [b] = board.createResource(flaky);
19+ await tick();
20+
21+ expect(a()).toBe("ok");
22+ expect(b()).toBeUndefined();
23+ expect(b.latest).toBeUndefined();
24+ expect(b.error).toBeInstanceOf(Error);
25+
26+ fail = false;
27+ board.retryFailed();
28+ await tick();
29+
30+ expect(b()).toBe("recovered");
31+ expect(b.error).toBeUndefined();
32+ expect(good).toHaveBeenCalledTimes(1);
33+ expect(flaky).toHaveBeenCalledTimes(2);
34+ dispose();
35+ });
36+});
src/lib/board-resources.tsadded+30 -0
@@ -0,0 +1,30 @@
1+import { createResource } from "@/lib/create-resource";
2+
3+/**
4+ * Resources for a board of independent panels (the dashboard).
5+ *
6+ * A plain resource rethrows its error on read, so one failed request took
7+ * down every panel with it. Here a failed source reads as `undefined` — its
8+ * panel shows its own empty/"—" state while `.error` stays available for the
9+ * board's notice — and `retryFailed` refetches only the sources that failed.
10+ */
11+export function createBoardResources() {
12+ const sources: { failed: () => boolean; refetch: () => unknown }[] = [];
13+
14+ const resource = ((...args: unknown[]) => {
15+ const [res, actions] = (createResource as unknown as (...a: unknown[]) => [Record<string, unknown> & (() => unknown), { refetch: () => unknown }])(...args);
16+ const read = () => (res.error ? undefined : res());
17+ for (const key of ["state", "loading", "error"] as const) {
18+ Object.defineProperty(read, key, { get: () => res[key] });
19+ }
20+ Object.defineProperty(read, "latest", { get: () => (res.error ? undefined : res.latest) });
21+ sources.push({ failed: () => !!res.error, refetch: actions.refetch });
22+ return [read, actions];
23+ }) as typeof createResource;
24+
25+ const retryFailed = () => {
26+ for (const source of sources) if (source.failed()) void source.refetch();
27+ };
28+
29+ return { createResource: resource, retryFailed };
30+}
src/pages/calendar-page.test.tsxadded+62 -0
@@ -0,0 +1,62 @@
1+import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";
2+import type { JSX } from "solid-js";
3+import CalendarPage from "@/pages/calendar-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+const { failExams, getExams } = vi.hoisted(() => ({ failExams: { times: 0 }, getExams: vi.fn() }));
7+
8+vi.mock("@tanstack/solid-router", () => ({
9+ Link: (props: { to: string; children: JSX.Element; class?: string }) => <a href={props.to} class={props.class}>{props.children}</a>,
10+ Navigate: () => null,
11+ useNavigate: () => vi.fn(),
12+}));
13+vi.mock("@/stores/auth-context", () => ({
14+ useAuth: () => ({
15+ user: () => ({ id: "u-1", username: "teacher", role: "teacher" }),
16+ loading: () => false,
17+ error: () => undefined,
18+ }),
19+}));
20+const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 100, offset: 0 });
21+vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) }));
22+vi.mock("@/api/events", () => ({ getEvents: vi.fn(async () => page([])) }));
23+vi.mock("@/api/exams", () => ({ getExams }));
24+vi.mock("@/api/homework", () => ({ getHomework: vi.fn(async () => page([])) }));
25+vi.mock("@/api/appointments", () => ({ getAppointments: vi.fn(async () => page([])) }));
26+vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) }));
27+vi.mock("@/api/reports", () => ({ getMyCourses: vi.fn(async () => page([])) }));
28+vi.mock("@/api/instances", () => ({
29+ getMyInstances: vi.fn(async () => page([])),
30+ getInstanceSessions: vi.fn(async () => page([])),
31+}));
32+
33+beforeEach(() => {
34+ getExams.mockImplementation(async () => {
35+ if (failExams.times > 0) {
36+ failExams.times -= 1;
37+ throw new Error("exams are down");
38+ }
39+ return page([]);
40+ });
41+});
42+afterEach(() => {
43+ cleanup();
44+ vi.clearAllMocks();
45+});
46+
47+test("a failed feed is named above the grid instead of reading as an empty calendar", async () => {
48+ failExams.times = 1;
49+ render(() => (
50+ <PreferencesProvider>
51+ <CalendarPage />
52+ </PreferencesProvider>
53+ ));
54+
55+ const notice = await screen.findByRole("alert");
56+ expect(notice.textContent).toMatch(/Exams|Sınavlar/);
57+ expect(screen.getByRole("heading", { level: 1 })).toBeTruthy();
58+
59+ fireEvent.click(within(notice).getByRole("button"));
60+ await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());
61+ expect(getExams).toHaveBeenCalledTimes(2);
62+});
src/pages/calendar-page.tsxmodified+36 -14
@@ -1,5 +1,5 @@
11 import { For, Show, Suspense, createMemo, createSignal } from "solid-js";
2-import { createResource } from "@/lib/create-resource";
2+import { createBoardResources } from "@/lib/board-resources";
33 import { getEvents } from "@/api/events";
44 import { getExams } from "@/api/exams";
55 import { getHomework } from "@/api/homework";
@@ -149,14 +149,17 @@ function CalendarContent() {
149149 const [selected, setSelected] = createSignal(dateKey(nowDate()));
150150 const [view, setView] = createSignal<CalendarView>("month");
151151
152- const [events] = createResource(async () => (await getEvents({ limit: 100 })).items, { initialValue: [] });
153- const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] });
154- const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] });
155- const [homework] = createResource(async () => (await getHomework({ limit: 100 })).items, { initialValue: [] });
152+ // Each feed stands alone: a failed one reads as empty and is named in the
153+ // notice above the grid, instead of blanking the whole calendar.
154+ const board = createBoardResources();
155+ const [events] = board.createResource(async () => (await getEvents({ limit: 100 })).items);
156+ const [exams] = board.createResource(async () => (await getExams({ limit: 100 })).items);
157+ const [appointments] = board.createResource(async () => (await getAppointments({ limit: 100 })).items);
158+ const [homework] = board.createResource(async () => (await getHomework({ limit: 100 })).items);
156159
157160 // Lessons and study/club meetings both come from course sessions; the course's
158161 // own `kind` is what separates them.
159- const [sessions] = createResource(
162+ const [sessions] = board.createResource(
160163 () => auth.user()?.role ?? null,
161164 async (role) => {
162165 // Sessions hang off the instance (şube × ders) now; the catalog course is
@@ -181,14 +184,22 @@ function CalendarContent() {
181184 );
182185 return pages.flat();
183186 },
184- { initialValue: [] },
185187 );
188+ const feeds = [
189+ { resource: sessions, labelKey: "calendar.lessons" },
190+ { resource: exams, labelKey: "calendar.exams" },
191+ { resource: homework, labelKey: "calendar.homework" },
192+ { resource: events, labelKey: "calendar.events" },
193+ { resource: appointments, labelKey: "calendar.appointments" },
194+ ] as const;
195+ const loadingFeeds = () => feeds.some((feed) => feed.resource.loading);
196+ const failedFeeds = () => feeds.filter((feed) => feed.resource.error).map((feed) => t(feed.labelKey));
186197
187198 const counterpart = (a: Appointment) => appointmentCounterpart(a, auth.user()?.id);
188199
189200 const items = createMemo<CalendarItem[]>(() => {
190201 const rows: CalendarItem[] = [];
191- for (const { session, course } of sessions()) {
202+ for (const { session, course } of sessions() ?? []) {
192203 rows.push({
193204 id: session.id,
194205 kind: course.kind === "course" ? "lesson" : "study",
@@ -198,18 +209,18 @@ function CalendarContent() {
198209 href: `/courses/${course.id}`,
199210 });
200211 }
201- for (const exam of exams()) {
212+ for (const exam of exams() ?? []) {
202213 if (!exam.starts_at || exam.draft) continue;
203214 rows.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at, endsAt: exam.ends_at, href: `/exams/${exam.id}` });
204215 }
205- for (const hw of homework()) {
216+ for (const hw of homework() ?? []) {
206217 rows.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, endsAt: null, href: `/homework/${hw.id}` });
207218 }
208- for (const event of events()) {
219+ for (const event of events() ?? []) {
209220 if (!event.starts_at) continue;
210221 rows.push({ id: event.id, kind: "event", title: event.title, at: event.starts_at, endsAt: event.ends_at, href: `/events/${event.id}` });
211222 }
212- for (const appointment of appointments()) {
223+ for (const appointment of appointments() ?? []) {
213224 if (!appointment.starts_at || (appointment.status !== "pending" && appointment.status !== "approved")) continue;
214225 rows.push({
215226 id: appointment.id,
@@ -333,11 +344,11 @@ function CalendarContent() {
333344 <div class="min-w-0">
334345 <h1 class="truncate text-lg font-semibold tracking-tight text-foreground sm:text-xl">{t("calendar.title")}</h1>
335346 <div class="mt-1.5 flex items-center gap-1 sm:gap-2">
336- <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={goPrev}>
347+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={goPrev} aria-label={t("common.prev")}>
337348 <IconChevronLeft class="h-4 w-4" />
338349 </Button>
339350 <span class="truncate text-sm font-semibold tracking-tight sm:text-base">{rangeLabel()}</span>
340- <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={goNext}>
351+ <Button type="button" variant="ghost" size="sm" class="h-8 w-8 rounded-lg p-0" onClick={goNext} aria-label={t("common.next")}>
341352 <IconChevronRight class="h-4 w-4" />
342353 </Button>
343354 </div>
@@ -380,6 +391,17 @@ function CalendarContent() {
380391 </For>
381392 </div>
382393
394+ <Show when={failedFeeds().length > 0}>
395+ <div role="alert" class="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
396+ <span class="min-w-0 flex-1">{t("calendar.feedsFailed", { feeds: failedFeeds().join(", ") })}</span>
397+ <Button type="button" size="sm" variant="outline" class="shrink-0 border-destructive/40" onClick={() => board.retryFailed()}>
398+ {t("common.tryAgain")}
399+ </Button>
400+ </div>
401+ </Show>
402+ <Show when={loadingFeeds()}>
403+ <p role="status" class="text-xs text-muted-foreground">{t("common.loading")}</p>
404+ </Show>
383405 <Suspense fallback={<PageSpinner />}>
384406 <div class={cn("grid min-h-0 flex-1 gap-4", view() === "month" && "xl:grid-cols-[minmax(0,1fr)_20rem]")}>
385407 <Show when={view() === "week"}>
src/pages/dashboard-page.test.tsxmodified+23 -2
@@ -1,15 +1,16 @@
1-import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library";
1+import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";
22 import type { JSX } from "solid-js";
33 import DashboardPage from "@/pages/dashboard-page";
44 import { PreferencesProvider } from "@/stores/preferences-context";
55
6-const { navigate, authUser, schoolModules, calls, refuseExams } = vi.hoisted(() => ({
6+const { navigate, authUser, schoolModules, calls, refuseExams, failExams } = vi.hoisted(() => ({
77 navigate: vi.fn(),
88 authUser: { authenticated: true, role: "student" },
99 // null = module state unknown (fail open, everything shown).
1010 schoolModules: { enabled: null as string[] | null },
1111 calls: [] as string[],
1212 refuseExams: { on: false },
13+ failExams: { times: 0 },
1314 }));
1415
1516 vi.mock("@tanstack/solid-router", () => ({
@@ -100,6 +101,11 @@ vi.mock("@/api/exams", async () => {
100101 getExams: async () => {
101102 // A builder switched exams off after the modules list was read.
102103 if (refuseExams.on) throw new ApiError(403, "forbidden", null, "exams");
104+ // A plain server failure, not a module refusal.
105+ if (failExams.times > 0) {
106+ failExams.times -= 1;
107+ throw new Error("exams are down");
108+ }
103109 return page([
104110 {
105111 id: "exam-1",
@@ -193,6 +199,7 @@ afterEach(() => {
193199 schoolModules.enabled = null;
194200 calls.length = 0;
195201 refuseExams.on = false;
202+ failExams.times = 0;
196203 });
197204
198205 function renderDashboard(role: string) {
@@ -302,3 +309,17 @@ test("a module refusal mid-session reads as no data instead of breaking the boar
302309 expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy();
303310 expect(screen.queryByText(/permission|switched off/i)).toBeNull();
304311 });
312+
313+test("a failed source leaves the other panels up and can be retried", async () => {
314+ failExams.times = 1;
315+ renderDashboard("manager");
316+
317+ const notice = await screen.findByRole("alert");
318+ expect(notice.textContent).toMatch(/could not load|yüklenemedi/);
319+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy();
320+ expect(await screen.findByText("Event deadline")).toBeTruthy();
321+
322+ fireEvent.click(within(notice).getByRole("button"));
323+ expect(await screen.findByText("Exam deadline")).toBeTruthy();
324+ await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());
325+});
src/pages/dashboard-page.tsxmodified+28 -15
@@ -1,5 +1,5 @@
11 import { For, Show, Suspense, createEffect, createMemo, createSignal, type Component } from "solid-js";
2-import { createResource } from "@/lib/create-resource";
2+import { createBoardResources } from "@/lib/board-resources";
33 import { useNavigate } from "@tanstack/solid-router";
44 import type { ColumnDef } from "@tanstack/solid-table";
55 import type { Role } from "@/api/client";
@@ -19,6 +19,7 @@ import { getMyAttendance, getMyCourses, getMyMarks, getUserAttendance } from "@/
1919 import { getTime } from "@/api/time/getTime";
2020 import { getUsers } from "@/api/users";
2121 import { RouteGuard } from "@/components/layout/route-guard";
22+import { Button } from "@/components/ui/button";
2223 import { EmptyInline } from "@/components/ui/empty-inline";
2324 import { Select } from "@/components/ui/select";
2425 import { Badge } from "@/components/ui/badge";
@@ -118,6 +119,10 @@ export default function DashboardPage() {
118119 }
119120
120121 function DashboardContent() {
122+ // Every panel reads its own source; one failed request must not take the
123+ // others down with it (see createBoardResources).
124+ const board = createBoardResources();
125+ const createResource = board.createResource;
121126 const auth = useAuth();
122127 const t = useT();
123128 const navigate = useNavigate();
@@ -142,7 +147,7 @@ function DashboardContent() {
142147 () => role() === "parent" || !on("courses") ? null : role(),
143148 (currentRole) => quiet(currentRole === "student" ? getMyCourses() : getCourses()),
144149 );
145- const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length;
150+ const courseCount = () => (courses.error ? "—" : String((courses()?.items ?? []).filter((course) => course.kind === "course").length));
146151 // `/events` has no role gate — a parent-teacher conference is a real PAR-01
147152 // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework`
148153 // below, which really are course-scoped and out of a parent's reach).
@@ -397,37 +402,40 @@ function DashboardContent() {
397402 return total ? Math.round((present / total) * 100) : null;
398403 });
399404
405+ /** A stat over a list total; a source that failed shows "—", never a made-up 0. */
406+ const countOf = (source: { (): { total: number } | null | undefined; error: unknown }) =>
407+ source.error ? "—" : String(source()?.total ?? 0);
400408 const allStats = createMemo<StatCardData[]>(() => {
401409 const r = role();
402410 if (r === "student") {
403411 return [
404- { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook },
405- { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam },
412+ { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook },
413+ { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam },
406414 { labelKey: "dashboard.stats.average", module: "marks", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart },
407415 { labelKey: "dashboard.stats.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck },
408416 ];
409417 }
410418 if (r === "teacher") {
411419 return [
412- { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook },
420+ { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook },
413421 { labelKey: "dashboard.stats.students", module: "courses", value: teacherStudentCount() == null ? "—" : String(teacherStudentCount()), Icon: IconUsers },
414- { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam },
415- { labelKey: "dashboard.stats.homework", module: "homework", value: String(homework()?.total ?? 0), Icon: IconHomework },
422+ { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam },
423+ { labelKey: "dashboard.stats.homework", module: "homework", value: countOf(homework), Icon: IconHomework },
416424 ];
417425 }
418426 if (r === "parent") {
419427 return [
420- { labelKey: "dashboard.stats.children", value: String(children()?.total ?? 0), Icon: IconUsers },
421- { labelKey: "dashboard.stats.appointments", module: "appointments", value: String(appointments()?.total ?? 0), Icon: IconCalendarDays },
422- { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils },
428+ { labelKey: "dashboard.stats.children", value: countOf(children), Icon: IconUsers },
429+ { labelKey: "dashboard.stats.appointments", module: "appointments", value: countOf(appointments), Icon: IconCalendarDays },
430+ { labelKey: "dashboard.stats.meals", module: "meals", value: countOf(menus), Icon: IconUtensils },
423431 { labelKey: "dashboard.stats.childAttendance", module: "attendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck },
424432 ];
425433 }
426434 return [
427- { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook },
428- { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam },
429- { labelKey: "dashboard.stats.events", module: "events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },
430- { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils },
435+ { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook },
436+ { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam },
437+ { labelKey: "dashboard.stats.events", module: "events", value: countOf(events), Icon: IconCalendarDays },
438+ { labelKey: "dashboard.stats.meals", module: "meals", value: countOf(menus), Icon: IconUtensils },
431439 ];
432440 });
433441 const stats = () => allStats().filter((stat) => !stat.module || on(stat.module));
@@ -716,7 +724,12 @@ function DashboardContent() {
716724
717725 <Suspense fallback={<PageSpinner />}>
718726 <Show when={error()}>
719- <p class="rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">{error()}</p>
727+ <div role="alert" class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
728+ <span class="min-w-0 flex-1">{t("dashboard.partialError")} {error()}</span>
729+ <Button type="button" size="sm" variant="outline" class="shrink-0 border-destructive/40" onClick={() => board.retryFailed()}>
730+ {t("common.tryAgain")}
731+ </Button>
732+ </div>
720733 </Show>
721734
722735 <section class="space-y-3" aria-labelledby="highlights-heading">