diff --git a/src/components/ui/data-table.test.tsx b/src/components/ui/data-table.test.tsx index 2fbe7f9..80fb209 100644 --- a/src/components/ui/data-table.test.tsx +++ b/src/components/ui/data-table.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen } from "@solidjs/testing-library"; +import { fireEvent, render, screen, within } from "@solidjs/testing-library"; import type { ColumnDef } from "@tanstack/solid-table"; import { DataTable } from "@/components/ui/data-table"; 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 expect(toolbar.classList).not.toContain("shrink-0"); } }); + +test("a search that matches nothing says so and clears back to the list", () => { + render(() => ( + + row.name.toLowerCase().includes(query.toLowerCase())} + /> + + )); + + fireEvent.input(screen.getByRole("textbox"), { target: { value: "zzz" } }); + expect(screen.queryByText("No people yet.")).toBeNull(); + expect(screen.getByText(/Nothing matches|eşleşen kayıt yok/)).toBeTruthy(); + + fireEvent.click(within(screen.getByRole("table")).getByRole("button", { name: /Clear search|Aramayı temizle/ })); + expect(screen.getByText("Ada")).toBeTruthy(); +}); diff --git a/src/components/ui/data-table.tsx b/src/components/ui/data-table.tsx index c5b1ac1..44028ea 100644 --- a/src/components/ui/data-table.tsx +++ b/src/components/ui/data-table.tsx @@ -332,10 +332,24 @@ export function DataTable(props: DataTableProps -
- - {props.empty ?? t("common.noResults")} -
+ {/* A search that matches nothing is not an empty list: say so and offer the way back. */} + + + {props.empty ?? t("common.noResults")} + + } + > +
+ + {t("common.noMatches")} + +
+
} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 49701bc..1b807ac 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -606,6 +606,7 @@ export type MessageKey = | "common.next" | "common.pageOf" | "common.noResults" + | "common.noMatches" | "common.creator" | "common.searchPlaceholder" | "common.all" @@ -615,6 +616,7 @@ export type MessageKey = | "common.deleted" | "common.saved" | "common.loadAll" + | "dashboard.partialError" | "common.breadcrumb" | "common.truncatedNotice" | "common.createItem" @@ -1978,6 +1980,7 @@ export type MessageKey = | "messages.emptyTrashSummary" | "messages.emptyTrashPageSummary" | "calendar.title" + | "calendar.feedsFailed" | "calendar.today" | "calendar.noEvents" | "calendar.events" @@ -2738,6 +2741,7 @@ const en: Dict = { "common.next": "Next", "common.pageOf": "{page} / {total}", "common.noResults": "No results.", + "common.noMatches": "Nothing matches your search.", "common.creator": "Created by", "common.searchPlaceholder": "Search…", "common.all": "All", @@ -2747,6 +2751,7 @@ const en: Dict = { "common.deleted": "Deleted.", "common.saved": "Saved successfully.", "common.loadAll": "Load all", + "dashboard.partialError": "Some panels could not load and show no data.", "common.breadcrumb": "Breadcrumb", "common.truncatedNotice": "Showing the first {shown} of {total} records.", "common.createItem": "Create new {item}", @@ -3195,6 +3200,7 @@ const en: Dict = { "events.helpBody": "Teachers and managers record attendance for students only. Managers can edit any event.", "calendar.title": "Calendar", + "calendar.feedsFailed": "Could not load: {feeds}. The calendar is missing those items.", "calendar.today": "Today", "calendar.noEvents": "Nothing scheduled on this day.", "calendar.events": "Events", @@ -4872,6 +4878,7 @@ const tr: Dict = { "common.next": "Sonraki", "common.pageOf": "{page} / {total}", "common.noResults": "Sonuç yok.", + "common.noMatches": "Aramanızla eşleşen kayıt yok.", "common.creator": "Oluşturan", "common.searchPlaceholder": "Ara…", "common.all": "Tümü", @@ -4881,6 +4888,7 @@ const tr: Dict = { "common.deleted": "Silindi.", "common.saved": "Başarıyla kaydedildi.", "common.loadAll": "Tümünü yükle", + "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.", "common.breadcrumb": "Sayfa konumu", "common.truncatedNotice": "{total} kayıttan ilk {shown} tanesi gösteriliyor.", "common.createItem": "Yeni {item} oluştur", @@ -5329,6 +5337,7 @@ const tr: Dict = { "events.helpBody": "Öğretmenler ve yöneticiler yalnız öğrenciler için yoklama kaydeder. Yöneticiler her etkinliği düzenleyebilir.", "calendar.title": "Takvim", + "calendar.feedsFailed": "Yüklenemedi: {feeds}. Takvimde bu kayıtlar eksik.", "calendar.today": "Bugün", "calendar.noEvents": "Bu güne ait bir şey yok.", "calendar.events": "Etkinlikler", diff --git a/src/lib/board-resources.test.tsx b/src/lib/board-resources.test.tsx new file mode 100644 index 0000000..f03a429 --- /dev/null +++ b/src/lib/board-resources.test.tsx @@ -0,0 +1,36 @@ +import { createRoot } from "solid-js"; +import { expect, test, vi } from "vitest"; +import { createBoardResources } from "@/lib/board-resources"; + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +test("a failed source reads as undefined and only it is retried", async () => { + const good = vi.fn(async () => "ok"); + let fail = true; + const flaky = vi.fn(async () => { + if (fail) throw new Error("boom"); + return "recovered"; + }); + + await createRoot(async (dispose) => { + const board = createBoardResources(); + const [a] = board.createResource(good); + const [b] = board.createResource(flaky); + await tick(); + + expect(a()).toBe("ok"); + expect(b()).toBeUndefined(); + expect(b.latest).toBeUndefined(); + expect(b.error).toBeInstanceOf(Error); + + fail = false; + board.retryFailed(); + await tick(); + + expect(b()).toBe("recovered"); + expect(b.error).toBeUndefined(); + expect(good).toHaveBeenCalledTimes(1); + expect(flaky).toHaveBeenCalledTimes(2); + dispose(); + }); +}); diff --git a/src/lib/board-resources.ts b/src/lib/board-resources.ts new file mode 100644 index 0000000..1ed0172 --- /dev/null +++ b/src/lib/board-resources.ts @@ -0,0 +1,30 @@ +import { createResource } from "@/lib/create-resource"; + +/** + * Resources for a board of independent panels (the dashboard). + * + * A plain resource rethrows its error on read, so one failed request took + * down every panel with it. Here a failed source reads as `undefined` — its + * panel shows its own empty/"—" state while `.error` stays available for the + * board's notice — and `retryFailed` refetches only the sources that failed. + */ +export function createBoardResources() { + const sources: { failed: () => boolean; refetch: () => unknown }[] = []; + + const resource = ((...args: unknown[]) => { + const [res, actions] = (createResource as unknown as (...a: unknown[]) => [Record & (() => unknown), { refetch: () => unknown }])(...args); + const read = () => (res.error ? undefined : res()); + for (const key of ["state", "loading", "error"] as const) { + Object.defineProperty(read, key, { get: () => res[key] }); + } + Object.defineProperty(read, "latest", { get: () => (res.error ? undefined : res.latest) }); + sources.push({ failed: () => !!res.error, refetch: actions.refetch }); + return [read, actions]; + }) as typeof createResource; + + const retryFailed = () => { + for (const source of sources) if (source.failed()) void source.refetch(); + }; + + return { createResource: resource, retryFailed }; +} diff --git a/src/pages/calendar-page.test.tsx b/src/pages/calendar-page.test.tsx new file mode 100644 index 0000000..7d1f464 --- /dev/null +++ b/src/pages/calendar-page.test.tsx @@ -0,0 +1,62 @@ +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; +import type { JSX } from "solid-js"; +import CalendarPage from "@/pages/calendar-page"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const { failExams, getExams } = vi.hoisted(() => ({ failExams: { times: 0 }, getExams: vi.fn() })); + +vi.mock("@tanstack/solid-router", () => ({ + Link: (props: { to: string; children: JSX.Element; class?: string }) => {props.children}, + Navigate: () => null, + useNavigate: () => vi.fn(), +})); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ + user: () => ({ id: "u-1", username: "teacher", role: "teacher" }), + loading: () => false, + error: () => undefined, + }), +})); +const page = (items: T[]) => ({ items, total: items.length, limit: 100, offset: 0 }); +vi.mock("@/api/time", () => ({ getTime: vi.fn(async () => ({ now: Date.now() })) })); +vi.mock("@/api/events", () => ({ getEvents: vi.fn(async () => page([])) })); +vi.mock("@/api/exams", () => ({ getExams })); +vi.mock("@/api/homework", () => ({ getHomework: vi.fn(async () => page([])) })); +vi.mock("@/api/appointments", () => ({ getAppointments: vi.fn(async () => page([])) })); +vi.mock("@/api/courses", () => ({ getCourses: vi.fn(async () => page([])) })); +vi.mock("@/api/reports", () => ({ getMyCourses: vi.fn(async () => page([])) })); +vi.mock("@/api/instances", () => ({ + getMyInstances: vi.fn(async () => page([])), + getInstanceSessions: vi.fn(async () => page([])), +})); + +beforeEach(() => { + getExams.mockImplementation(async () => { + if (failExams.times > 0) { + failExams.times -= 1; + throw new Error("exams are down"); + } + return page([]); + }); +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +test("a failed feed is named above the grid instead of reading as an empty calendar", async () => { + failExams.times = 1; + render(() => ( + + + + )); + + const notice = await screen.findByRole("alert"); + expect(notice.textContent).toMatch(/Exams|Sınavlar/); + expect(screen.getByRole("heading", { level: 1 })).toBeTruthy(); + + fireEvent.click(within(notice).getByRole("button")); + await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); + expect(getExams).toHaveBeenCalledTimes(2); +}); diff --git a/src/pages/calendar-page.tsx b/src/pages/calendar-page.tsx index e126cec..3152988 100644 --- a/src/pages/calendar-page.tsx +++ b/src/pages/calendar-page.tsx @@ -1,5 +1,5 @@ import { For, Show, Suspense, createMemo, createSignal } from "solid-js"; -import { createResource } from "@/lib/create-resource"; +import { createBoardResources } from "@/lib/board-resources"; import { getEvents } from "@/api/events"; import { getExams } from "@/api/exams"; import { getHomework } from "@/api/homework"; @@ -149,14 +149,17 @@ function CalendarContent() { const [selected, setSelected] = createSignal(dateKey(nowDate())); const [view, setView] = createSignal("month"); - const [events] = createResource(async () => (await getEvents({ limit: 100 })).items, { initialValue: [] }); - const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] }); - const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] }); - const [homework] = createResource(async () => (await getHomework({ limit: 100 })).items, { initialValue: [] }); + // Each feed stands alone: a failed one reads as empty and is named in the + // notice above the grid, instead of blanking the whole calendar. + const board = createBoardResources(); + const [events] = board.createResource(async () => (await getEvents({ limit: 100 })).items); + const [exams] = board.createResource(async () => (await getExams({ limit: 100 })).items); + const [appointments] = board.createResource(async () => (await getAppointments({ limit: 100 })).items); + const [homework] = board.createResource(async () => (await getHomework({ limit: 100 })).items); // Lessons and study/club meetings both come from course sessions; the course's // own `kind` is what separates them. - const [sessions] = createResource( + const [sessions] = board.createResource( () => auth.user()?.role ?? null, async (role) => { // Sessions hang off the instance (şube × ders) now; the catalog course is @@ -181,14 +184,22 @@ function CalendarContent() { ); return pages.flat(); }, - { initialValue: [] }, ); + const feeds = [ + { resource: sessions, labelKey: "calendar.lessons" }, + { resource: exams, labelKey: "calendar.exams" }, + { resource: homework, labelKey: "calendar.homework" }, + { resource: events, labelKey: "calendar.events" }, + { resource: appointments, labelKey: "calendar.appointments" }, + ] as const; + const loadingFeeds = () => feeds.some((feed) => feed.resource.loading); + const failedFeeds = () => feeds.filter((feed) => feed.resource.error).map((feed) => t(feed.labelKey)); const counterpart = (a: Appointment) => appointmentCounterpart(a, auth.user()?.id); const items = createMemo(() => { const rows: CalendarItem[] = []; - for (const { session, course } of sessions()) { + for (const { session, course } of sessions() ?? []) { rows.push({ id: session.id, kind: course.kind === "course" ? "lesson" : "study", @@ -198,18 +209,18 @@ function CalendarContent() { href: `/courses/${course.id}`, }); } - for (const exam of exams()) { + for (const exam of exams() ?? []) { if (!exam.starts_at || exam.draft) continue; rows.push({ id: exam.id, kind: "exam", title: exam.title, at: exam.starts_at, endsAt: exam.ends_at, href: `/exams/${exam.id}` }); } - for (const hw of homework()) { + for (const hw of homework() ?? []) { rows.push({ id: hw.id, kind: "homework", title: hw.title, at: hw.due_at, endsAt: null, href: `/homework/${hw.id}` }); } - for (const event of events()) { + for (const event of events() ?? []) { if (!event.starts_at) continue; rows.push({ id: event.id, kind: "event", title: event.title, at: event.starts_at, endsAt: event.ends_at, href: `/events/${event.id}` }); } - for (const appointment of appointments()) { + for (const appointment of appointments() ?? []) { if (!appointment.starts_at || (appointment.status !== "pending" && appointment.status !== "approved")) continue; rows.push({ id: appointment.id, @@ -333,11 +344,11 @@ function CalendarContent() {

{t("calendar.title")}

- {rangeLabel()} -
@@ -380,6 +391,17 @@ function CalendarContent() {
+ 0}> + + + +

{t("common.loading")}

+
}>
diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index d4243f2..5b71187 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -1,15 +1,16 @@ -import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library"; +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; import type { JSX } from "solid-js"; import DashboardPage from "@/pages/dashboard-page"; import { PreferencesProvider } from "@/stores/preferences-context"; -const { navigate, authUser, schoolModules, calls, refuseExams } = vi.hoisted(() => ({ +const { navigate, authUser, schoolModules, calls, refuseExams, failExams } = vi.hoisted(() => ({ navigate: vi.fn(), authUser: { authenticated: true, role: "student" }, // null = module state unknown (fail open, everything shown). schoolModules: { enabled: null as string[] | null }, calls: [] as string[], refuseExams: { on: false }, + failExams: { times: 0 }, })); vi.mock("@tanstack/solid-router", () => ({ @@ -100,6 +101,11 @@ vi.mock("@/api/exams", async () => { getExams: async () => { // A builder switched exams off after the modules list was read. if (refuseExams.on) throw new ApiError(403, "forbidden", null, "exams"); + // A plain server failure, not a module refusal. + if (failExams.times > 0) { + failExams.times -= 1; + throw new Error("exams are down"); + } return page([ { id: "exam-1", @@ -193,6 +199,7 @@ afterEach(() => { schoolModules.enabled = null; calls.length = 0; refuseExams.on = false; + failExams.times = 0; }); function renderDashboard(role: string) { @@ -302,3 +309,17 @@ test("a module refusal mid-session reads as no data instead of breaking the boar expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); expect(screen.queryByText(/permission|switched off/i)).toBeNull(); }); + +test("a failed source leaves the other panels up and can be retried", async () => { + failExams.times = 1; + renderDashboard("manager"); + + const notice = await screen.findByRole("alert"); + expect(notice.textContent).toMatch(/could not load|yüklenemedi/); + expect(screen.getByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); + expect(await screen.findByText("Event deadline")).toBeTruthy(); + + fireEvent.click(within(notice).getByRole("button")); + expect(await screen.findByText("Exam deadline")).toBeTruthy(); + await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); +}); diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 74de2c4..8db51af 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -1,5 +1,5 @@ import { For, Show, Suspense, createEffect, createMemo, createSignal, type Component } from "solid-js"; -import { createResource } from "@/lib/create-resource"; +import { createBoardResources } from "@/lib/board-resources"; import { useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; import type { Role } from "@/api/client"; @@ -19,6 +19,7 @@ import { getMyAttendance, getMyCourses, getMyMarks, getUserAttendance } from "@/ import { getTime } from "@/api/time/getTime"; import { getUsers } from "@/api/users"; import { RouteGuard } from "@/components/layout/route-guard"; +import { Button } from "@/components/ui/button"; import { EmptyInline } from "@/components/ui/empty-inline"; import { Select } from "@/components/ui/select"; import { Badge } from "@/components/ui/badge"; @@ -118,6 +119,10 @@ export default function DashboardPage() { } function DashboardContent() { + // Every panel reads its own source; one failed request must not take the + // others down with it (see createBoardResources). + const board = createBoardResources(); + const createResource = board.createResource; const auth = useAuth(); const t = useT(); const navigate = useNavigate(); @@ -142,7 +147,7 @@ function DashboardContent() { () => role() === "parent" || !on("courses") ? null : role(), (currentRole) => quiet(currentRole === "student" ? getMyCourses() : getCourses()), ); - const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length; + const courseCount = () => (courses.error ? "—" : String((courses()?.items ?? []).filter((course) => course.kind === "course").length)); // `/events` has no role gate — a parent-teacher conference is a real PAR-01 // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework` // below, which really are course-scoped and out of a parent's reach). @@ -397,37 +402,40 @@ function DashboardContent() { return total ? Math.round((present / total) * 100) : null; }); + /** A stat over a list total; a source that failed shows "—", never a made-up 0. */ + const countOf = (source: { (): { total: number } | null | undefined; error: unknown }) => + source.error ? "—" : String(source()?.total ?? 0); const allStats = createMemo(() => { const r = role(); if (r === "student") { return [ - { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, - { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, + { 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.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, ]; } if (r === "teacher") { return [ - { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, + { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook }, { labelKey: "dashboard.stats.students", module: "courses", value: teacherStudentCount() == null ? "—" : String(teacherStudentCount()), Icon: IconUsers }, - { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, - { labelKey: "dashboard.stats.homework", module: "homework", value: String(homework()?.total ?? 0), Icon: IconHomework }, + { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam }, + { labelKey: "dashboard.stats.homework", module: "homework", value: countOf(homework), Icon: IconHomework }, ]; } if (r === "parent") { return [ - { labelKey: "dashboard.stats.children", value: String(children()?.total ?? 0), Icon: IconUsers }, - { labelKey: "dashboard.stats.appointments", module: "appointments", value: String(appointments()?.total ?? 0), Icon: IconCalendarDays }, - { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, + { labelKey: "dashboard.stats.children", value: countOf(children), Icon: IconUsers }, + { labelKey: "dashboard.stats.appointments", module: "appointments", value: countOf(appointments), Icon: IconCalendarDays }, + { labelKey: "dashboard.stats.meals", module: "meals", value: countOf(menus), Icon: IconUtensils }, { labelKey: "dashboard.stats.childAttendance", module: "attendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck }, ]; } return [ - { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, - { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, - { labelKey: "dashboard.stats.events", module: "events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, - { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, + { labelKey: "dashboard.stats.courses", module: "courses", value: courseCount(), Icon: IconBook }, + { labelKey: "dashboard.stats.exams", module: "exams", value: countOf(exams), Icon: IconExam }, + { labelKey: "dashboard.stats.events", module: "events", value: countOf(events), Icon: IconCalendarDays }, + { labelKey: "dashboard.stats.meals", module: "meals", value: countOf(menus), Icon: IconUtensils }, ]; }); const stats = () => allStats().filter((stat) => !stat.module || on(stat.module)); @@ -716,7 +724,12 @@ function DashboardContent() { }> -

{error()}

+