From be0d677a5efeb5014a7e74b2ab6f098f538af281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Wed, 16 Sep 2026 00:11:41 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=A7=A9=20handle=20switched-off=20s?= =?UTF-8?q?chool=20modules=20without=20blank=20screens=20-=20client=20tags?= =?UTF-8?q?=20403=20{error,=20module}=20as=20a=20module=20refusal=20and=20?= =?UTF-8?q?notifies=20the=20=20=20modules=20context,=20which=20refetches?= =?UTF-8?q?=20so=20nav=20and=20gates=20catch=20up=20mid-session;=20=20=20t?= =?UTF-8?q?he=20list=20is=20also=20re-read=20when=20a=20tab=20comes=20back?= =?UTF-8?q?=20after=20a=20minute=20-=20ModuleGate=20shows=20a=20switched-o?= =?UTF-8?q?ff=20card=20for=20pages=20of=20an=20off=20module=20=20=20(route?= =?UTF-8?q?Module=20maps=20paths=20to=20modules)=20instead=20of=20a=20page?= =?UTF-8?q?=20that=20can=20only=20403=20-=20homepage=20and=20shell=20feed?= =?UTF-8?q?=20skip=20off=20modules=20and=20wait=20for=20the=20module=20lis?= =?UTF-8?q?t;=20=20=20refusals=20read=20as=20no=20data,=20off-module=20til?= =?UTF-8?q?es=20and=20panels=20are=20left=20out=20-=20class=20nav=20entrie?= =?UTF-8?q?s=20now=20carry=20the=20classes=20module?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/skills/dashboard-design/SKILL.md | 5 + src/api/__tests__/client/client.test.ts | 26 +++- src/api/client/client.ts | 44 +++++- src/components/layout/app-shell.tsx | 9 +- src/components/layout/module-gate.tsx | 54 +++++++ src/components/layout/nav-items.ts | 4 +- src/i18n/messages.ts | 9 +- src/lib/route-module.test.ts | 22 +++ src/lib/route-module.ts | 49 ++++++ src/pages/dashboard-page.test.tsx | 52 ++++++- src/pages/dashboard-page.tsx | 180 ++++++++++++++--------- src/stores/modules-context.tsx | 35 +++++ src/stores/shell-feed-context.test.tsx | 2 + src/stores/shell-feed-context.tsx | 17 ++- 14 files changed, 412 insertions(+), 96 deletions(-) create mode 100644 src/components/layout/module-gate.tsx create mode 100644 src/lib/route-module.test.ts create mode 100644 src/lib/route-module.ts diff --git a/.claude/skills/dashboard-design/SKILL.md b/.claude/skills/dashboard-design/SKILL.md index a4303c1..1e6387e 100644 --- a/.claude/skills/dashboard-design/SKILL.md +++ b/.claude/skills/dashboard-design/SKILL.md @@ -25,6 +25,11 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status - **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3`. - **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose data exists for the role, and never call an endpoint the role would 403 on. +- **Module scoping:** a school can switch any module off, and every route of an + off module answers `403 {error, module}`. Gate each resource source on + `on(module)` (waits for the module list, then `isEnabled`), wrap fetchers in + `quiet()` so a refusal racing a builder's switch reads as no data, and leave out + the stat tiles / panels of an off module rather than showing zeros. - **Deadlines table:** active / today / soon items only, semantic status badge, rows navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA. - **Chart semantics per role:** diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index 46ef0bf..dead7a6 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { ApiError, blobClient, client, formatApiError, formatApiErrorMessage, formClient } from "../../client"; +import { ApiError, blobClient, client, formatApiError, formatApiErrorMessage, formClient, isModuleDisabledError, onModuleDisabled } from "../../client"; import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch"; describe("client", () => { @@ -76,6 +76,30 @@ describe("client", () => { }); }); + describe("switched-off modules", () => { + it("tags a 403 carrying `module` and tells listeners", async () => { + const heard: string[] = []; + const stop = onModuleDisabled((module) => heard.push(module)); + mockFetchError(403, { error: "forbidden", module: "notes" }); + const err = await client("/notes").catch((e: unknown) => e); + stop(); + expect(isModuleDisabledError(err)).toBe(true); + expect((err as ApiError).module).toBe("notes"); + expect(heard).toEqual(["notes"]); + expect(formatApiError(err, "tr")).toBe("Bu özellik okulunuzda şu an kapalı."); + }); + + it("leaves an ordinary 403 as a permissions refusal", async () => { + const heard: string[] = []; + const stop = onModuleDisabled((module) => heard.push(module)); + mockFetchError(403, { error: "forbidden" }); + const err = await client("/users").catch((e: unknown) => e); + stop(); + expect(isModuleDisabledError(err)).toBe(false); + expect(heard).toEqual([]); + }); + }); + describe("client() timeout", () => { // hang until whatever signal fetch was given aborts const hangingFetch = () => diff --git a/src/api/client/client.ts b/src/api/client/client.ts index 84dc2ea..bd7f47c 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -3,15 +3,42 @@ import type { Locale } from "@/i18n/messages"; export class ApiError extends Error { readonly status: number; readonly retryAfter: number | null; + /** Set when the school has this route's module switched off (`403 {error, module}`). */ + readonly module: string | null; - constructor(status: number, message: string, retryAfter: number | null = null) { + constructor(status: number, message: string, retryAfter: number | null = null, module: string | null = null) { super(message); this.name = "ApiError"; this.status = status; this.retryAfter = retryAfter; + this.module = module; } } +/** True for a refusal because the school's module is off, not a role or record problem. */ +export function isModuleDisabledError(err: unknown): err is ApiError & { module: string } { + return err instanceof ApiError && err.status === 403 && err.module != null; +} + +// A builder can switch a module off mid-session; the backend then answers +// `403 {error, module}` on every route of it. Listeners (the modules context) +// hear about it on the first such refusal and refetch the enabled set, so the +// nav and route gate catch up without a reload. +const moduleDisabledListeners = new Set<(module: string) => void>(); + +export function onModuleDisabled(listener: (module: string) => void): () => void { + moduleDisabledListeners.add(listener); + return () => moduleDisabledListeners.delete(listener); +} + +function disabledModuleOf(status: number, data: unknown): string | null { + if (status !== 403 || !data || typeof data !== "object") return null; + const module = (data as { module?: unknown }).module; + if (typeof module !== "string" || !module) return null; + for (const listener of moduleDisabledListeners) listener(module); + return module; +} + type RequestOptions = { method?: "GET" | "POST" | "PATCH" | "DELETE"; body?: unknown; @@ -442,7 +469,7 @@ async function request(path: string, options: RequestOptions = {}): Promise(path: string, body: FormData, signal?: Abort if (!res.ok) { const message = errorMessageFromPayload(data, res.statusText || "Request failed"); - throw new ApiError(res.status, message); + throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data)); } return data as T; @@ -501,14 +528,16 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise
- + + +
diff --git a/src/components/layout/module-gate.tsx b/src/components/layout/module-gate.tsx new file mode 100644 index 0000000..6b3a5df --- /dev/null +++ b/src/components/layout/module-gate.tsx @@ -0,0 +1,54 @@ +import { Link, useLocation } from "@tanstack/solid-router"; +import { type ParentProps, Show } from "solid-js"; +import { IconHome, IconPackage } from "@/components/ui/icons"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { moduleLabel } from "@/lib/module-labels"; +import { routeModule } from "@/lib/route-module"; +import { useModules } from "@/stores/modules-context"; +import { useT } from "@/stores/preferences-context"; + +/** + * Stands in for a page whose module the school has switched off. Without it + * the page mounts, every call 403s, and the user lands on a blank or error + * screen — typically from a bookmark, a stale tab, or a module turned off + * mid-session. Unknown module state (loading, lookup failed) renders the page. + */ +export function ModuleGate(props: ParentProps) { + const t = useT(); + const location = useLocation(); + const modules = useModules(); + const off = () => { + const module = routeModule(location().pathname); + const enabled = modules.enabled(); + return module && enabled && !enabled.includes(module) ? module : null; + }; + + // Until the school's list arrives a module page would fire its reads blind; + // a spinner for that first beat keeps an off module from ever being asked. + return ( + }> + + {(module) => ( +
+
+
+ +
+
+

{t("modules.offTitle", { module: moduleLabel(module(), t) })}

+

{t("modules.offDescription")}

+
+ + + {t("common.goHome")} + +
+
+ )} +
+
+ ); +} diff --git a/src/components/layout/nav-items.ts b/src/components/layout/nav-items.ts index 438773a..a051e62 100644 --- a/src/components/layout/nav-items.ts +++ b/src/components/layout/nav-items.ts @@ -108,7 +108,7 @@ const ADMIN_GROUPS: NavGroup[] = [ items: [ { id: "students-roster", to: "/management/students", labelKey: "nav.studentsRoster", Icon: IconUsers, minRole: "manager" }, { id: "teachers-roster", to: "/management/teachers", labelKey: "nav.teachersRoster", Icon: IconChalkboardTeacher, minRole: "manager" }, - { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconSchool, minRole: "teacher" }, + { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconSchool, minRole: "teacher", module: "classes" }, { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendar, minRole: "manager" }, { id: "schedule", to: "/calendar", labelKey: "nav.schedule", Icon: IconCalendarDays, minRole: "manager" }, ], @@ -182,7 +182,7 @@ const TEACHER_GROUPS: NavGroup[] = [ labelKey: "nav.group.myClassroom", Icon: IconSchool, items: [ - { id: "my-classes", to: "/management/classes", labelKey: "nav.myClasses", Icon: IconSchool }, + { id: "my-classes", to: "/management/classes", labelKey: "nav.myClasses", Icon: IconSchool, module: "classes" }, { id: "my-schedule", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, { id: "courses", to: "/courses", labelKey: "nav.classes", Icon: IconBook, module: "courses" }, ], diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 0233f5f..aa97949 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -166,7 +166,6 @@ export type MessageKey = | "notes.backToNotebook" | "notes.titlePlaceholder" | "notes.bodyPlaceholder" - | "notes.saveShortcut" | "notes.unsaved" | "notes.allSaved" | "notes.saving" @@ -566,6 +565,8 @@ export type MessageKey = | "common.notFound" | "common.accessDenied" | "common.goHome" + | "modules.offTitle" + | "modules.offDescription" | "common.learnMore" | "common.gotIt" | "confirm.review" @@ -2082,7 +2083,6 @@ const en: Dict = { "notes.backToNotebook": "Notebook", "notes.titlePlaceholder": "Untitled note", "notes.bodyPlaceholder": "Start writing…", - "notes.saveShortcut": "{key}+S to save", "notes.unsaved": "Unsaved changes", "notes.allSaved": "All changes saved", "notes.saving": "Saving…", @@ -2484,6 +2484,8 @@ const en: Dict = { "common.notFound": "Page not found", "common.accessDenied": "You do not have access to this content.", "common.goHome": "Go home", + "modules.offTitle": "{module} is switched off", + "modules.offDescription": "Your school doesn't have this module turned on right now. Ask your school administrator if you need it.", "common.learnMore": "Learn more", "common.gotIt": "Got it", "confirm.review": "Please review your changes before saving.", @@ -4006,7 +4008,6 @@ const tr: Dict = { "notes.backToNotebook": "Defter", "notes.titlePlaceholder": "Başlıksız not", "notes.bodyPlaceholder": "Yazmaya başla…", - "notes.saveShortcut": "Kaydetmek için {key}+S", "notes.unsaved": "Kaydedilmemiş değişiklikler", "notes.allSaved": "Tüm değişiklikler kaydedildi", "notes.saving": "Kaydediliyor…", @@ -4408,6 +4409,8 @@ const tr: Dict = { "common.notFound": "Sayfa bulunamadı", "common.accessDenied": "Bu içeriğe erişimin yok.", "common.goHome": "Ana sayfaya dön", + "modules.offTitle": "{module} modülü kapalı", + "modules.offDescription": "Bu modül okulunuzda şu an kullanıma açık değil. İhtiyacınız varsa okul yöneticinizle iletişime geçin.", "common.learnMore": "Daha fazla", "common.gotIt": "Anladım", "confirm.review": "Lütfen kaydetmeden önce değişiklikleri gözden geçirin.", diff --git a/src/lib/route-module.test.ts b/src/lib/route-module.test.ts new file mode 100644 index 0000000..1a0179b --- /dev/null +++ b/src/lib/route-module.test.ts @@ -0,0 +1,22 @@ +import { routeModule } from "@/lib/route-module"; + +describe("routeModule", () => { + it("maps module pages and their detail routes", () => { + expect(routeModule("/notes")).toBe("notes"); + expect(routeModule("/notes/abc")).toBe("notes"); + expect(routeModule("/exam-room/1")).toBe("exams"); + expect(routeModule("/question-bank/9")).toBe("bank_questions"); + }); + + it("prefers the longest prefix", () => { + expect(routeModule("/students/exams")).toBe("marks"); + expect(routeModule("/management/classes/3")).toBe("classes"); + }); + + it("leaves core routes and look-alike prefixes unmapped", () => { + expect(routeModule("/")).toBeNull(); + expect(routeModule("/calendar")).toBeNull(); + expect(routeModule("/management/students")).toBeNull(); + expect(routeModule("/notebook")).toBeNull(); + }); +}); diff --git a/src/lib/route-module.ts b/src/lib/route-module.ts new file mode 100644 index 0000000..d1bb432 --- /dev/null +++ b/src/lib/route-module.ts @@ -0,0 +1,49 @@ +/** + * Which backend module a route's page is built on, by path prefix. A school + * with that module switched off gets `403 {error, module}` from every call the + * page would make, so the shell shows a "switched off" screen instead of + * rendering a page that can only fail. Routes built on core surfaces (home, + * calendar, users, settings, profile) map to nothing and always render. + * + * Longest prefix wins, so the `/management/*` and `/students/*` entries are + * matched ahead of the shorter ones. + */ +const ROUTE_MODULES: ReadonlyArray = [ + ["/management/student-attendance", "attendance"], + ["/management/student-marks", "marks"], + ["/management/pomodoros", "pomodoro"], + ["/management/payments", "payments"], + ["/management/staff-work", "work"], + ["/management/classes", "classes"], + ["/students/attendance", "attendance"], + ["/students/exams", "marks"], + ["/students/study", "pomodoro"], + ["/question-bank", "bank_questions"], + ["/appointments", "appointments"], + ["/whiteboards", "boards"], + ["/attendance", "attendance"], + ["/exam-room", "exams"], + ["/questions", "questions"], + ["/messages", "messages"], + ["/homework", "homework"], + ["/pomodoro", "pomodoro"], + ["/payments", "payments"], + ["/courses", "courses"], + ["/studies", "courses"], + ["/events", "events"], + ["/clubs", "courses"], + ["/exams", "exams"], + ["/marks", "marks"], + ["/meals", "meals"], + ["/notes", "notes"], + ["/work", "work"], +]; + +export function routeModule(pathname: string): string | null { + let best: readonly [string, string] | null = null; + for (const entry of ROUTE_MODULES) { + const [prefix] = entry; + if ((pathname === prefix || pathname.startsWith(`${prefix}/`)) && (!best || prefix.length > best[0].length)) best = entry; + } + return best?.[1] ?? null; +} diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index 242ecd1..bc8ec7a 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -3,9 +3,13 @@ import type { JSX } from "solid-js"; import DashboardPage from "@/pages/dashboard-page"; import { PreferencesProvider } from "@/stores/preferences-context"; -const { navigate, authUser } = vi.hoisted(() => ({ +const { navigate, authUser, schoolModules, calls, refuseExams } = 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 }, })); vi.mock("@tanstack/solid-router", () => ({ @@ -36,7 +40,12 @@ const page = (items: T[]) => ({ items, total: items.length, limit: 50, offse const course = { id: "course-1", title: "Algebra", capacity: 24 }; vi.mock("@/stores/modules-context", () => ({ - useModules: () => ({ enabled: () => null, isEnabled: () => true, refresh: () => {} }), + useModules: () => ({ + enabled: () => schoolModules.enabled, + loading: () => false, + isEnabled: (module: string) => schoolModules.enabled === null || schoolModules.enabled.includes(module), + refresh: () => {}, + }), })); vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], packages: [] }) })); vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); @@ -46,7 +55,7 @@ vi.mock("@/api/courses", () => ({ })); vi.mock("@/api/reports", () => ({ getMyCourses: async () => page([course]), - getMyMarks: async () => ({ + getMyMarks: async () => (calls.push("marks"), { overall_average: 82.5, courses: [{ course, @@ -70,8 +79,13 @@ vi.mock("@/api/payments", () => ({ balance_minor: 0, }), })); -vi.mock("@/api/exams", () => ({ - getExams: async () => page([ +vi.mock("@/api/exams", async () => { + const { ApiError } = await import("@/api/client"); + return { + getExams: async () => { + // A builder switched exams off after the modules list was read. + if (refuseExams.on) throw new ApiError(403, "forbidden", null, "exams"); + return page([ { id: "exam-1", title: "Exam deadline", @@ -88,7 +102,8 @@ vi.mock("@/api/exams", () => ({ starts_at: now - 10 * DAY, ends_at: now - 10 * DAY + 3_000, }, - ]), + ]); + }, getExamStatistics: async (examId: string) => ({ exam: examId, graded: 12, @@ -96,7 +111,8 @@ vi.mock("@/api/exams", () => ({ min: 40, max: 96, }), -})); + }; +}); vi.mock("@/api/pomodoro", () => ({ getPomodoroMe: async () => ({ items: [ @@ -159,6 +175,9 @@ afterEach(() => { cleanup(); navigate.mockReset(); authUser.authenticated = true; + schoolModules.enabled = null; + calls.length = 0; + refuseExams.on = false; }); function renderDashboard(role: string) { @@ -249,3 +268,22 @@ test("parent sees family highlights and appointment deadlines without staff char expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy(); expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); }); + +test("switched-off modules leave no tile, panel or request behind", async () => { + schoolModules.enabled = ["courses", "exams", "events", "homework", "appointments", "meals", "classes"]; + renderDashboard("student"); + + expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); + expect(screen.queryByText("Course averages")).toBeNull(); + expect(screen.queryByText("Attendance split")).toBeNull(); + expect(screen.queryByText("Focus activity")).toBeNull(); + expect(calls).not.toContain("marks"); +}); + +test("a module refusal mid-session reads as no data instead of breaking the board", async () => { + refuseExams.on = true; + renderDashboard("manager"); + + expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); + expect(screen.queryByText(/permission|switched off/i)).toBeNull(); +}); diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 2343212..026165e 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -3,7 +3,7 @@ import { createResource } from "@/lib/create-resource"; import { useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; import type { Role } from "@/api/client"; -import { formatApiError } from "@/api/client"; +import { formatApiError, isModuleDisabledError } from "@/api/client"; import { getAppointments } from "@/api/appointments"; import { getClasses, getClassesByUserId, getMyClasses } from "@/api/classes"; import { getCourseEnrollments, getCourses } from "@/api/courses"; @@ -81,6 +81,8 @@ type DeadlineRow = { type StatCardData = { labelKey: MessageKey; + /** The module the number comes from; the tile is left out when it is off. */ + module?: string; value: string; Icon: Component<{ class?: string }>; }; @@ -120,64 +122,78 @@ function DashboardContent() { const { locale } = usePreferences(); const user = () => auth.user()!; const role = () => user().role; + // A school can have any module switched off, and every route of an off + // module answers 403. The board never asks one (the source goes null), and + // a refusal that races a builder's switch reads as "no data" instead of + // throwing through the page — it used to blank the whole homepage. + const schoolModules = useModules(); + const on = (module: string) => !schoolModules.loading() && schoolModules.isEnabled(module); + const quiet = (request: Promise): Promise => + request.catch((err: unknown) => { + if (isModuleDisabledError(err)) return null; + throw err; + }); const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); // Unpaged: the backend has no `kind` filter, so a "courses" count that // excludes studies and clubs has to be counted here over the whole list. const [courses] = createResource( - () => role() === "parent" ? null : role(), - (currentRole) => currentRole === "student" ? getMyCourses() : getCourses(), + () => role() === "parent" || !on("courses") ? null : role(), + (currentRole) => quiet(currentRole === "student" ? getMyCourses() : getCourses()), ); const courseCount = () => (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). const [events] = createResource( - () => clock()?.now, - (now) => getEvents({ ends_after: now, limit: 50 }), + () => (on("events") ? clock()?.now : null), + (now) => quiet(getEvents({ ends_after: now, limit: 50 })), ); const [exams] = createResource( - () => role() === "parent" ? null : role(), - () => getExams({ limit: 100 }), + () => role() === "parent" || !on("exams") ? null : role(), + () => quiet(getExams({ limit: 100 })), ); // Unfiltered: `/homework` has no due-date window, so this one read serves both // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking // heatmap. const [homework] = createResource( - () => role() === "parent" ? null : role(), - () => getHomework({ limit: 100 }), + () => role() === "parent" || !on("homework") ? null : role(), + () => quiet(getHomework({ limit: 100 })), ); const [children] = createResource( () => role() === "parent" ? true : null, - () => getMyStudents({ limit: 12 }), + () => quiet(getMyStudents({ limit: 12 })), + ); + const [appointments] = createResource( + () => (on("appointments") ? true : null), + () => quiet(getAppointments({ limit: 20 })), ); - const [appointments] = createResource(() => getAppointments({ limit: 20 })); const [menus] = createResource( - () => clock()?.now, - (now) => getMealMenus({ from: new Date(now).toISOString().slice(0, 10), limit: 1 }), + () => (on("meals") ? clock()?.now : null), + (now) => quiet(getMealMenus({ from: new Date(now).toISOString().slice(0, 10), limit: 1 })), ); const [marks] = createResource( - () => role() === "student" ? true : null, - () => getMyMarks(), + () => role() === "student" && on("marks") ? true : null, + () => quiet(getMyMarks()), ); const [attendance] = createResource( - () => role() === "student" ? true : null, - () => getMyAttendance(), + () => role() === "student" && on("attendance") ? true : null, + () => quiet(getMyAttendance()), ); const [myClasses] = createResource( - () => role() === "student" ? true : null, - () => getMyClasses({ limit: 1 }), + () => role() === "student" && on("classes") ? true : null, + () => quiet(getMyClasses({ limit: 1 })), ); // Focus heatmap source. Only a student owns pomodoro sessions — reading // another user's log is the teacher+ /management/pomodoros page's job. const [pomodoro] = createResource( - () => role() === "student" ? true : null, - () => getPomodoroMe({ limit: 400 }), + () => role() === "student" && on("pomodoro") ? true : null, + () => quiet(getPomodoroMe({ limit: 400 })), ); // `/events` is the one list here that really is filtered server-side, by the // `ends_after` window the deadlines table needs. The heatmap looks backwards // and there is no "before" filter, so past events need their own read. const [pastEvents] = createResource( - () => hasMinRole(role(), "teacher") ? true : null, + () => hasMinRole(role(), "teacher") && on("events") ? true : null, () => getEvents({ limit: 100 }).catch(() => null), ); // Success trend source for teacher+. Exam statistics are grader-only, so this @@ -240,12 +256,12 @@ function DashboardContent() { if (first && !selectedChildId()) setSelectedChildId(first); }); const [childClasses] = createResource( - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), + () => (role() === "parent" && on("classes") && selectedChildId() ? selectedChildId() : null), (id) => getClassesByUserId(id, { limit: 1 }).catch(() => null), ); const homeroomTeacher = () => childClasses()?.items[0]?.teacher ?? null; const [childAttendance] = createResource( - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), + () => (role() === "parent" && on("attendance") && selectedChildId() ? selectedChildId() : null), (id) => getUserAttendance(id).catch(() => null), ); const childAttendanceBreakdown = createMemo(() => { @@ -262,7 +278,7 @@ function DashboardContent() { }; }); const [childStatement] = createResource( - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), + () => (role() === "parent" && on("payments") && selectedChildId() ? selectedChildId() : null), (id) => getPaymentStatementByUserId(id, { limit: 100 }).catch(() => null), ); const paymentSummary = createMemo(() => { @@ -294,8 +310,8 @@ function DashboardContent() { () => getUsers({ limit: 30 }), ); const [recentClasses] = createResource( - () => (isAdminHome() ? true : null), - () => getClasses({ limit: 2 }), + () => (isAdminHome() && on("classes") ? true : null), + () => quiet(getClasses({ limit: 2 })), ); const studentQuickLinks = createMemo(() => (recentStudents()?.items ?? []) @@ -319,7 +335,6 @@ function DashboardContent() { // The school's own entitlements per package: the catalog is deploy-constant, // the enabled set is already in the shell's modules context. - const schoolModules = useModules(); const [moduleCatalog] = createResource( () => (isAdminHome() ? true : null), () => getModulesCatalog().catch(() => null), @@ -377,39 +392,40 @@ function DashboardContent() { return total ? Math.round((present / total) * 100) : null; }); - const stats = createMemo(() => { + const allStats = createMemo(() => { const r = role(); if (r === "student") { return [ - { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, - { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, - { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, + { 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.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", value: String(courseCount()), Icon: IconBook }, - { labelKey: "dashboard.stats.students", value: teacherStudentCount() == null ? "—" : String(teacherStudentCount()), Icon: IconUsers }, - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, - { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework }, + { labelKey: "dashboard.stats.courses", module: "courses", value: String(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 }, ]; } if (r === "parent") { return [ { labelKey: "dashboard.stats.children", value: String(children()?.total ?? 0), Icon: IconUsers }, - { labelKey: "dashboard.stats.appointments", value: String(appointments()?.total ?? 0), Icon: IconCalendarDays }, - { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, - { labelKey: "dashboard.stats.childAttendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck }, + { 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.childAttendance", module: "attendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck }, ]; } return [ - { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, - { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, - { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, + { 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 }, ]; }); + const stats = () => allStats().filter((stat) => !stat.module || on(stat.module)); // Student trend — own marks ordered by their exam's date. Marks whose exam // falls outside the fetched exam page carry no date and are left out rather @@ -620,7 +636,7 @@ function DashboardContent() { const error = createMemo(() => { const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error || myClasses.error || pomodoro.error || childAttendance.error || childStatement.error; - return problem ? formatApiError(problem, locale()) : ""; + return problem && !isModuleDisabledError(problem) ? formatApiError(problem, locale()) : ""; }); return ( @@ -655,7 +671,7 @@ function DashboardContent() {

{t("dashboard.hero.heading")}

-
+
navigate({ to: "/admin/users/$id", params: { id: row.id } })} /> - navigate({ to: "/management/classes/$id", params: { id: row.id } })} - /> + + navigate({ to: "/management/classes/$id", params: { id: row.id } })} + /> +
- - - + + + + + + +
+
@@ -757,6 +780,7 @@ function DashboardContent() {

{t("dashboard.student.thisWeekTotal", { minutes: String(weeklyFocusTotal()) })}

+
@@ -774,6 +798,7 @@ function DashboardContent() { item behind that queue — a pending appointment request — gets the rail. */}
+
+
+
@@ -816,6 +843,7 @@ function DashboardContent() {
+
@@ -823,7 +851,7 @@ function DashboardContent() {
- +
+

{t("dashboard.parent.attendanceDetail")}

@@ -897,6 +926,8 @@ function DashboardContent() { )}
+ +

{t("dashboard.parent.payment")}

{t("dashboard.parent.paymentDesc")}

@@ -924,6 +955,7 @@ function DashboardContent() { )}
+
@@ -944,6 +976,7 @@ function DashboardContent() { /> + +
); diff --git a/src/stores/modules-context.tsx b/src/stores/modules-context.tsx index 39e4283..8247903 100644 --- a/src/stores/modules-context.tsx +++ b/src/stores/modules-context.tsx @@ -3,9 +3,12 @@ import { type ParentProps, createContext, createMemo, + onCleanup, + onMount, useContext, } from "solid-js"; import { createResource } from "@/lib/create-resource"; +import { onModuleDisabled } from "@/api/client"; import { getModules } from "@/api/modules"; import { useAuth } from "@/stores/auth-context"; @@ -16,6 +19,12 @@ type ModulesContextValue = { * shows everything (fail open), so a modules outage never blanks the shell. */ enabled: Accessor; + /** + * True until the first lookup for this account settles. Readers that would + * otherwise fire at a possibly-off module on first paint wait for it; after + * that a failed lookup still fails open. + */ + loading: Accessor; /** Fail-open membership test over `enabled`. */ isEnabled: (module: string) => boolean; refresh: () => void; @@ -42,8 +51,34 @@ export function ModulesProvider(props: ParentProps) { { initialValue: null }, ); + // The enabled set changes under a live session when a builder flips a + // module. Two cues bring it up to date without a reload: a route answering + // `403 {module}` (switched off), and the tab coming back into view after a + // while (switched on, or off where nothing was asked of it yet). + const REVISIT_AFTER_MS = 60_000; + let lastFetch = Date.now(); + const refreshNow = () => { + if (userId() === null || modules.loading) return; + lastFetch = Date.now(); + void refetch(); + }; + onMount(() => { + const stop = onModuleDisabled((module) => { + if (modules.latest?.includes(module) !== false) refreshNow(); + }); + const onVisible = () => { + if (document.visibilityState === "visible" && Date.now() - lastFetch > REVISIT_AFTER_MS) refreshNow(); + }; + document.addEventListener("visibilitychange", onVisible); + onCleanup(() => { + stop(); + document.removeEventListener("visibilitychange", onVisible); + }); + }); + const value: ModulesContextValue = { enabled: () => modules(), + loading: () => userId() !== null && modules.loading && modules.latest === null, isEnabled: (module: string) => { const enabled = modules(); return enabled === null || enabled.includes(module); diff --git a/src/stores/shell-feed-context.test.tsx b/src/stores/shell-feed-context.test.tsx index 6ecf5d3..897dc61 100644 --- a/src/stores/shell-feed-context.test.tsx +++ b/src/stores/shell-feed-context.test.tsx @@ -6,6 +6,8 @@ import { ShellFeedProvider, useShellFeed } from "@/stores/shell-feed-context"; // The provider only reads `auth.user()`; drive it from a signal the test owns. const [user, setUser] = createSignal(null); vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user }) })); +// Every module on: the feed skips switched-off modules, which is not what these cases test. +vi.mock("@/stores/modules-context", () => ({ useModules: () => ({ isEnabled: () => true, enabled: () => null, loading: () => false }) })); const page = (items: T[]) => ({ items, total: items.length, limit: null, offset: 0 }); diff --git a/src/stores/shell-feed-context.tsx b/src/stores/shell-feed-context.tsx index 226e2b9..268d044 100644 --- a/src/stores/shell-feed-context.tsx +++ b/src/stores/shell-feed-context.tsx @@ -15,6 +15,7 @@ import { getMessages } from "@/api/messages"; import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client"; import { createLivePoll } from "@/lib/create-live-poll"; import { useAuth } from "@/stores/auth-context"; +import { useModules } from "@/stores/modules-context"; // One shared poller for the always-mounted shell (NotificationCenter header + // header message/notification controls). Both used to `createResource` messages/events/exams @@ -55,15 +56,19 @@ type UserFeed = Omit; // can survive into the next session. Solid keeps a resource's last value when // its source goes falsy, so gating alone would leak user A's inbox into user // B's shell until the refetch resolved. -function createUserFeed(loggedIn: boolean): UserFeed { +function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnabled: (module: string) => boolean): UserFeed { // Only fetch for a logged-in user: source is false while logged out, so the // resource keeps its seeded empty value and never hits the network. - const source = () => loggedIn; + // It also waits for the school's module list, so a first paint never asks a + // switched-off module (and gets 403) before the list says it is off. + const source = () => loggedIn && !modulesLoading(); const [messagesRes, { refetch: refetchInbox }] = createResource( source, async () => { try { + // A switched-off module would only answer 403 on every poll. + if (!isEnabled("messages")) return emptyPage(); return await getMessages("inbox", { limit: 100 }); } catch { return emptyPage(); @@ -80,6 +85,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { source, async () => { try { + if (!isEnabled("messages")) return emptyPage(); return await getMessages("inbox", { read: false, limit: 10 }); } catch { return emptyPage(); @@ -105,6 +111,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { source, async () => { try { + if (!isEnabled("events")) return emptyPage(); return await getEvents(upcoming()); } catch { return emptyPage(); @@ -117,6 +124,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { source, async () => { try { + if (!isEnabled("exams")) return emptyPage(); return await getExams(upcoming()); } catch { return emptyPage(); @@ -129,6 +137,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { source, async () => { try { + if (!isEnabled("appointments")) return emptyPage(); return await getAppointments({ limit: 100 }); } catch { return emptyPage(); @@ -141,6 +150,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { source, async () => { try { + if (!isEnabled("homework")) return emptyPage(); return await getHomework(); } catch { return emptyPage(); @@ -186,7 +196,8 @@ export function ShellFeedProvider(props: ParentProps) { // the whole feed and builds a fresh one. Children never remount, so the // router tree below is untouched. const userId = createMemo(() => auth.user()?.id ?? null); - const feed = createMemo(() => createUserFeed(userId() !== null)); + const modules = useModules(); + const feed = createMemo(() => createUserFeed(userId() !== null, modules.loading, modules.isEnabled)); // Reactive clock so passed items drop off without a remount. Visibility-aware: // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is