🧩 handle switched-off school modules without blank screens
Browse files at this commitbe0d677a5efeb5014a7e74b2ab6f098f538af281Parent: 6cc39f3- fix
- 🧩 handle switched-off school modules without blank screens
14 changed files +412 -96
- .claude/skills/dashboard-design/SKILL.md +5 -0
- src/api/__tests__/client/client.test.ts +25 -1
- src/api/client/client.ts +39 -5
- src/components/layout/app-shell.tsx +7 -2
- src/components/layout/module-gate.tsx +54 -0
- src/components/layout/nav-items.ts +2 -2
- src/i18n/messages.ts +6 -3
- src/lib/route-module.test.ts +22 -0
- src/lib/route-module.ts +49 -0
- src/pages/dashboard-page.test.tsx +45 -7
- src/pages/dashboard-page.tsx +107 -73
- src/stores/modules-context.tsx +35 -0
- src/stores/shell-feed-context.test.tsx +2 -0
- src/stores/shell-feed-context.tsx +14 -3
.claude/skills/dashboard-design/SKILL.mdmodified+5 -0
| @@ -25,6 +25,11 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status | |||
| 25 | - **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3`. | 25 | - **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3`. |
| 26 | - **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose | 26 | - **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose |
| 27 | data exists for the role, and never call an endpoint the role would 403 on. | 27 | data exists for the role, and never call an endpoint the role would 403 on. |
| 28 | +- **Module scoping:** a school can switch any module off, and every route of an | ||
| 29 | + off module answers `403 {error, module}`. Gate each resource source on | ||
| 30 | + `on(module)` (waits for the module list, then `isEnabled`), wrap fetchers in | ||
| 31 | + `quiet()` so a refusal racing a builder's switch reads as no data, and leave out | ||
| 32 | + the stat tiles / panels of an off module rather than showing zeros. | ||
| 28 | - **Deadlines table:** active / today / soon items only, semantic status badge, rows | 33 | - **Deadlines table:** active / today / soon items only, semantic status badge, rows |
| 29 | navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA. | 34 | navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA. |
| 30 | - **Chart semantics per role:** | 35 | - **Chart semantics per role:** |
src/api/__tests__/client/client.test.tsmodified+25 -1
| @@ -1,5 +1,5 @@ | |||
| 1 | import { afterEach, describe, expect, it, vi } from "vitest"; | 1 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 2 | -import { ApiError, blobClient, client, formatApiError, formatApiErrorMessage, formClient } from "../../client"; | 2 | +import { ApiError, blobClient, client, formatApiError, formatApiErrorMessage, formClient, isModuleDisabledError, onModuleDisabled } from "../../client"; |
| 3 | import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch"; | 3 | import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch"; |
| 4 | 4 | ||
| 5 | describe("client", () => { | 5 | describe("client", () => { |
| @@ -76,6 +76,30 @@ describe("client", () => { | |||
| 76 | }); | 76 | }); |
| 77 | }); | 77 | }); |
| 78 | 78 | ||
| 79 | + describe("switched-off modules", () => { | ||
| 80 | + it("tags a 403 carrying `module` and tells listeners", async () => { | ||
| 81 | + const heard: string[] = []; | ||
| 82 | + const stop = onModuleDisabled((module) => heard.push(module)); | ||
| 83 | + mockFetchError(403, { error: "forbidden", module: "notes" }); | ||
| 84 | + const err = await client("/notes").catch((e: unknown) => e); | ||
| 85 | + stop(); | ||
| 86 | + expect(isModuleDisabledError(err)).toBe(true); | ||
| 87 | + expect((err as ApiError).module).toBe("notes"); | ||
| 88 | + expect(heard).toEqual(["notes"]); | ||
| 89 | + expect(formatApiError(err, "tr")).toBe("Bu özellik okulunuzda şu an kapalı."); | ||
| 90 | + }); | ||
| 91 | + | ||
| 92 | + it("leaves an ordinary 403 as a permissions refusal", async () => { | ||
| 93 | + const heard: string[] = []; | ||
| 94 | + const stop = onModuleDisabled((module) => heard.push(module)); | ||
| 95 | + mockFetchError(403, { error: "forbidden" }); | ||
| 96 | + const err = await client("/users").catch((e: unknown) => e); | ||
| 97 | + stop(); | ||
| 98 | + expect(isModuleDisabledError(err)).toBe(false); | ||
| 99 | + expect(heard).toEqual([]); | ||
| 100 | + }); | ||
| 101 | + }); | ||
| 102 | + | ||
| 79 | describe("client() timeout", () => { | 103 | describe("client() timeout", () => { |
| 80 | // hang until whatever signal fetch was given aborts | 104 | // hang until whatever signal fetch was given aborts |
| 81 | const hangingFetch = () => | 105 | const hangingFetch = () => |
src/api/client/client.tsmodified+39 -5
| @@ -3,15 +3,42 @@ import type { Locale } from "@/i18n/messages"; | |||
| 3 | export class ApiError extends Error { | 3 | export class ApiError extends Error { |
| 4 | readonly status: number; | 4 | readonly status: number; |
| 5 | readonly retryAfter: number | null; | 5 | readonly retryAfter: number | null; |
| 6 | + /** Set when the school has this route's module switched off (`403 {error, module}`). */ | ||
| 7 | + readonly module: string | null; | ||
| 6 | 8 | ||
| 7 | - constructor(status: number, message: string, retryAfter: number | null = null) { | 9 | + constructor(status: number, message: string, retryAfter: number | null = null, module: string | null = null) { |
| 8 | super(message); | 10 | super(message); |
| 9 | this.name = "ApiError"; | 11 | this.name = "ApiError"; |
| 10 | this.status = status; | 12 | this.status = status; |
| 11 | this.retryAfter = retryAfter; | 13 | this.retryAfter = retryAfter; |
| 14 | + this.module = module; | ||
| 12 | } | 15 | } |
| 13 | } | 16 | } |
| 14 | 17 | ||
| 18 | +/** True for a refusal because the school's module is off, not a role or record problem. */ | ||
| 19 | +export function isModuleDisabledError(err: unknown): err is ApiError & { module: string } { | ||
| 20 | + return err instanceof ApiError && err.status === 403 && err.module != null; | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +// A builder can switch a module off mid-session; the backend then answers | ||
| 24 | +// `403 {error, module}` on every route of it. Listeners (the modules context) | ||
| 25 | +// hear about it on the first such refusal and refetch the enabled set, so the | ||
| 26 | +// nav and route gate catch up without a reload. | ||
| 27 | +const moduleDisabledListeners = new Set<(module: string) => void>(); | ||
| 28 | + | ||
| 29 | +export function onModuleDisabled(listener: (module: string) => void): () => void { | ||
| 30 | + moduleDisabledListeners.add(listener); | ||
| 31 | + return () => moduleDisabledListeners.delete(listener); | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +function disabledModuleOf(status: number, data: unknown): string | null { | ||
| 35 | + if (status !== 403 || !data || typeof data !== "object") return null; | ||
| 36 | + const module = (data as { module?: unknown }).module; | ||
| 37 | + if (typeof module !== "string" || !module) return null; | ||
| 38 | + for (const listener of moduleDisabledListeners) listener(module); | ||
| 39 | + return module; | ||
| 40 | +} | ||
| 41 | + | ||
| 15 | type RequestOptions = { | 42 | type RequestOptions = { |
| 16 | method?: "GET" | "POST" | "PATCH" | "DELETE"; | 43 | method?: "GET" | "POST" | "PATCH" | "DELETE"; |
| 17 | body?: unknown; | 44 | body?: unknown; |
| @@ -442,7 +469,7 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T | |||
| 442 | } | 469 | } |
| 443 | } | 470 | } |
| 444 | 471 | ||
| 445 | - throw new ApiError(res.status, message, retryAfter); | 472 | + throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data)); |
| 446 | } | 473 | } |
| 447 | 474 | ||
| 448 | return data as T; | 475 | return data as T; |
| @@ -486,7 +513,7 @@ export async function formClient<T>(path: string, body: FormData, signal?: Abort | |||
| 486 | 513 | ||
| 487 | if (!res.ok) { | 514 | if (!res.ok) { |
| 488 | const message = errorMessageFromPayload(data, res.statusText || "Request failed"); | 515 | const message = errorMessageFromPayload(data, res.statusText || "Request failed"); |
| 489 | - throw new ApiError(res.status, message); | 516 | + throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data)); |
| 490 | } | 517 | } |
| 491 | 518 | ||
| 492 | return data as T; | 519 | return data as T; |
| @@ -501,14 +528,16 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise<Bl | |||
| 501 | if (!res.ok) { | 528 | if (!res.ok) { |
| 502 | const text = await res.text(); | 529 | const text = await res.text(); |
| 503 | let message = res.statusText || "Request failed"; | 530 | let message = res.statusText || "Request failed"; |
| 531 | + let payload: unknown = null; | ||
| 504 | if (text) { | 532 | if (text) { |
| 505 | try { | 533 | try { |
| 506 | - message = errorMessageFromPayload(JSON.parse(text), message); | 534 | + payload = JSON.parse(text); |
| 535 | + message = errorMessageFromPayload(payload, message); | ||
| 507 | } catch { | 536 | } catch { |
| 508 | message = text; | 537 | message = text; |
| 509 | } | 538 | } |
| 510 | } | 539 | } |
| 511 | - throw new ApiError(res.status, message); | 540 | + throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload)); |
| 512 | } | 541 | } |
| 513 | 542 | ||
| 514 | return res.blob(); | 543 | return res.blob(); |
| @@ -537,6 +566,11 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()): | |||
| 537 | } | 566 | } |
| 538 | // The specific backend message wins over the per-status generic one — | 567 | // The specific backend message wins over the per-status generic one — |
| 539 | // otherwise every 401/403/404/413/5xx entry in the table is dead code. | 568 | // otherwise every 401/403/404/413/5xx entry in the table is dead code. |
| 569 | + // Ahead of the message table: the backend's text for a switched-off | ||
| 570 | + // module may be a generic "forbidden", which reads as a permissions fault. | ||
| 571 | + if (err.module != null && err.status === 403) { | ||
| 572 | + return locale === "tr" ? "Bu özellik okulunuzda şu an kapalı." : "This feature is currently switched off for your school."; | ||
| 573 | + } | ||
| 540 | const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale]; | 574 | const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale]; |
| 541 | if (known) return known; | 575 | if (known) return known; |
| 542 | if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; | 576 | if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; |
src/components/layout/app-shell.tsxmodified+7 -2
| @@ -21,6 +21,7 @@ import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@ | |||
| 21 | import { ShellFeedProvider } from "@/stores/shell-feed-context"; | 21 | import { ShellFeedProvider } from "@/stores/shell-feed-context"; |
| 22 | import { usePreferences, useT } from "@/stores/preferences-context"; | 22 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 23 | import { cn } from "@/lib/cn"; | 23 | import { cn } from "@/lib/cn"; |
| 24 | +import { ModuleGate } from "@/components/layout/module-gate"; | ||
| 24 | 25 | ||
| 25 | const SIDEBAR_EXPANDED = "w-[260px]"; | 26 | const SIDEBAR_EXPANDED = "w-[260px]"; |
| 26 | const SIDEBAR_COLLAPSED = "w-24"; | 27 | const SIDEBAR_COLLAPSED = "w-24"; |
| @@ -143,7 +144,9 @@ export function AppShell(props: ParentProps) { | |||
| 143 | <div class="min-w-0 flex-1" /> | 144 | <div class="min-w-0 flex-1" /> |
| 144 | 145 | ||
| 145 | <div class="flex shrink-0 items-center justify-end gap-2"> | 146 | <div class="flex shrink-0 items-center justify-end gap-2"> |
| 146 | - <ShellMessagesButton /> | 147 | + <Show when={modules.isEnabled("messages")}> |
| 148 | + <ShellMessagesButton /> | ||
| 149 | + </Show> | ||
| 147 | <NotificationCenter /> | 150 | <NotificationCenter /> |
| 148 | <Show when={modules.isEnabled("chatbot")}> | 151 | <Show when={modules.isEnabled("chatbot")}> |
| 149 | <button | 152 | <button |
| @@ -171,7 +174,9 @@ export function AppShell(props: ParentProps) { | |||
| 171 | auth.user() && !fullScreen() && "pb-[calc(3.5rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] lg:pb-6", | 174 | auth.user() && !fullScreen() && "pb-[calc(3.5rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] lg:pb-6", |
| 172 | )} | 175 | )} |
| 173 | > | 176 | > |
| 174 | - {props.children} | 177 | + <Show when={auth.user()} fallback={props.children}> |
| 178 | + <ModuleGate>{props.children}</ModuleGate> | ||
| 179 | + </Show> | ||
| 175 | </div> | 180 | </div> |
| 176 | </main> | 181 | </main> |
| 177 | </div> | 182 | </div> |
src/components/layout/module-gate.tsxadded+54 -0
| @@ -0,0 +1,54 @@ | |||
| 1 | +import { Link, useLocation } from "@tanstack/solid-router"; | ||
| 2 | +import { type ParentProps, Show } from "solid-js"; | ||
| 3 | +import { IconHome, IconPackage } from "@/components/ui/icons"; | ||
| 4 | +import { PageSpinner } from "@/components/ui/page-spinner"; | ||
| 5 | +import { moduleLabel } from "@/lib/module-labels"; | ||
| 6 | +import { routeModule } from "@/lib/route-module"; | ||
| 7 | +import { useModules } from "@/stores/modules-context"; | ||
| 8 | +import { useT } from "@/stores/preferences-context"; | ||
| 9 | + | ||
| 10 | +/** | ||
| 11 | + * Stands in for a page whose module the school has switched off. Without it | ||
| 12 | + * the page mounts, every call 403s, and the user lands on a blank or error | ||
| 13 | + * screen — typically from a bookmark, a stale tab, or a module turned off | ||
| 14 | + * mid-session. Unknown module state (loading, lookup failed) renders the page. | ||
| 15 | + */ | ||
| 16 | +export function ModuleGate(props: ParentProps) { | ||
| 17 | + const t = useT(); | ||
| 18 | + const location = useLocation(); | ||
| 19 | + const modules = useModules(); | ||
| 20 | + const off = () => { | ||
| 21 | + const module = routeModule(location().pathname); | ||
| 22 | + const enabled = modules.enabled(); | ||
| 23 | + return module && enabled && !enabled.includes(module) ? module : null; | ||
| 24 | + }; | ||
| 25 | + | ||
| 26 | + // Until the school's list arrives a module page would fire its reads blind; | ||
| 27 | + // a spinner for that first beat keeps an off module from ever being asked. | ||
| 28 | + return ( | ||
| 29 | + <Show when={!(routeModule(location().pathname) && modules.loading())} fallback={<PageSpinner />}> | ||
| 30 | + <Show when={off()} fallback={props.children}> | ||
| 31 | + {(module) => ( | ||
| 32 | + <div class="flex min-h-[50vh] items-center justify-center px-4 py-16"> | ||
| 33 | + <div class="w-full max-w-[440px] space-y-5 rounded-xl border border-border-line bg-surface-base p-8 text-center shadow-[0_10px_24px_-4px_rgba(0,0,0,0.10)]"> | ||
| 34 | + <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted text-text-subtle"> | ||
| 35 | + <IconPackage class="h-6 w-6" /> | ||
| 36 | + </div> | ||
| 37 | + <div class="space-y-2"> | ||
| 38 | + <p class="text-base font-semibold text-text-strong">{t("modules.offTitle", { module: moduleLabel(module(), t) })}</p> | ||
| 39 | + <p class="text-sm leading-[21px] text-text-subtle">{t("modules.offDescription")}</p> | ||
| 40 | + </div> | ||
| 41 | + <Link | ||
| 42 | + to="/" | ||
| 43 | + class="inline-flex h-9 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90" | ||
| 44 | + > | ||
| 45 | + <IconHome class="mr-1 h-4 w-4" /> | ||
| 46 | + {t("common.goHome")} | ||
| 47 | + </Link> | ||
| 48 | + </div> | ||
| 49 | + </div> | ||
| 50 | + )} | ||
| 51 | + </Show> | ||
| 52 | + </Show> | ||
| 53 | + ); | ||
| 54 | +} | ||
src/components/layout/nav-items.tsmodified+2 -2
| @@ -108,7 +108,7 @@ const ADMIN_GROUPS: NavGroup[] = [ | |||
| 108 | items: [ | 108 | items: [ |
| 109 | { id: "students-roster", to: "/management/students", labelKey: "nav.studentsRoster", Icon: IconUsers, minRole: "manager" }, | 109 | { id: "students-roster", to: "/management/students", labelKey: "nav.studentsRoster", Icon: IconUsers, minRole: "manager" }, |
| 110 | { id: "teachers-roster", to: "/management/teachers", labelKey: "nav.teachersRoster", Icon: IconChalkboardTeacher, minRole: "manager" }, | 110 | { id: "teachers-roster", to: "/management/teachers", labelKey: "nav.teachersRoster", Icon: IconChalkboardTeacher, minRole: "manager" }, |
| 111 | - { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconSchool, minRole: "teacher" }, | 111 | + { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconSchool, minRole: "teacher", module: "classes" }, |
| 112 | { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendar, minRole: "manager" }, | 112 | { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendar, minRole: "manager" }, |
| 113 | { id: "schedule", to: "/calendar", labelKey: "nav.schedule", Icon: IconCalendarDays, minRole: "manager" }, | 113 | { id: "schedule", to: "/calendar", labelKey: "nav.schedule", Icon: IconCalendarDays, minRole: "manager" }, |
| 114 | ], | 114 | ], |
| @@ -182,7 +182,7 @@ const TEACHER_GROUPS: NavGroup[] = [ | |||
| 182 | labelKey: "nav.group.myClassroom", | 182 | labelKey: "nav.group.myClassroom", |
| 183 | Icon: IconSchool, | 183 | Icon: IconSchool, |
| 184 | items: [ | 184 | items: [ |
| 185 | - { id: "my-classes", to: "/management/classes", labelKey: "nav.myClasses", Icon: IconSchool }, | 185 | + { id: "my-classes", to: "/management/classes", labelKey: "nav.myClasses", Icon: IconSchool, module: "classes" }, |
| 186 | { id: "my-schedule", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, | 186 | { id: "my-schedule", to: "/calendar", labelKey: "nav.mySchedule", Icon: IconCalendarDays }, |
| 187 | { id: "courses", to: "/courses", labelKey: "nav.classes", Icon: IconBook, module: "courses" }, | 187 | { id: "courses", to: "/courses", labelKey: "nav.classes", Icon: IconBook, module: "courses" }, |
| 188 | ], | 188 | ], |
src/i18n/messages.tsmodified+6 -3
| @@ -166,7 +166,6 @@ export type MessageKey = | |||
| 166 | | "notes.backToNotebook" | 166 | | "notes.backToNotebook" |
| 167 | | "notes.titlePlaceholder" | 167 | | "notes.titlePlaceholder" |
| 168 | | "notes.bodyPlaceholder" | 168 | | "notes.bodyPlaceholder" |
| 169 | - | "notes.saveShortcut" | ||
| 170 | | "notes.unsaved" | 169 | | "notes.unsaved" |
| 171 | | "notes.allSaved" | 170 | | "notes.allSaved" |
| 172 | | "notes.saving" | 171 | | "notes.saving" |
| @@ -566,6 +565,8 @@ export type MessageKey = | |||
| 566 | | "common.notFound" | 565 | | "common.notFound" |
| 567 | | "common.accessDenied" | 566 | | "common.accessDenied" |
| 568 | | "common.goHome" | 567 | | "common.goHome" |
| 568 | + | "modules.offTitle" | ||
| 569 | + | "modules.offDescription" | ||
| 569 | | "common.learnMore" | 570 | | "common.learnMore" |
| 570 | | "common.gotIt" | 571 | | "common.gotIt" |
| 571 | | "confirm.review" | 572 | | "confirm.review" |
| @@ -2082,7 +2083,6 @@ const en: Dict = { | |||
| 2082 | "notes.backToNotebook": "Notebook", | 2083 | "notes.backToNotebook": "Notebook", |
| 2083 | "notes.titlePlaceholder": "Untitled note", | 2084 | "notes.titlePlaceholder": "Untitled note", |
| 2084 | "notes.bodyPlaceholder": "Start writing…", | 2085 | "notes.bodyPlaceholder": "Start writing…", |
| 2085 | - "notes.saveShortcut": "{key}+S to save", | ||
| 2086 | "notes.unsaved": "Unsaved changes", | 2086 | "notes.unsaved": "Unsaved changes", |
| 2087 | "notes.allSaved": "All changes saved", | 2087 | "notes.allSaved": "All changes saved", |
| 2088 | "notes.saving": "Saving…", | 2088 | "notes.saving": "Saving…", |
| @@ -2484,6 +2484,8 @@ const en: Dict = { | |||
| 2484 | "common.notFound": "Page not found", | 2484 | "common.notFound": "Page not found", |
| 2485 | "common.accessDenied": "You do not have access to this content.", | 2485 | "common.accessDenied": "You do not have access to this content.", |
| 2486 | "common.goHome": "Go home", | 2486 | "common.goHome": "Go home", |
| 2487 | + "modules.offTitle": "{module} is switched off", | ||
| 2488 | + "modules.offDescription": "Your school doesn't have this module turned on right now. Ask your school administrator if you need it.", | ||
| 2487 | "common.learnMore": "Learn more", | 2489 | "common.learnMore": "Learn more", |
| 2488 | "common.gotIt": "Got it", | 2490 | "common.gotIt": "Got it", |
| 2489 | "confirm.review": "Please review your changes before saving.", | 2491 | "confirm.review": "Please review your changes before saving.", |
| @@ -4006,7 +4008,6 @@ const tr: Dict = { | |||
| 4006 | "notes.backToNotebook": "Defter", | 4008 | "notes.backToNotebook": "Defter", |
| 4007 | "notes.titlePlaceholder": "Başlıksız not", | 4009 | "notes.titlePlaceholder": "Başlıksız not", |
| 4008 | "notes.bodyPlaceholder": "Yazmaya başla…", | 4010 | "notes.bodyPlaceholder": "Yazmaya başla…", |
| 4009 | - "notes.saveShortcut": "Kaydetmek için {key}+S", | ||
| 4010 | "notes.unsaved": "Kaydedilmemiş değişiklikler", | 4011 | "notes.unsaved": "Kaydedilmemiş değişiklikler", |
| 4011 | "notes.allSaved": "Tüm değişiklikler kaydedildi", | 4012 | "notes.allSaved": "Tüm değişiklikler kaydedildi", |
| 4012 | "notes.saving": "Kaydediliyor…", | 4013 | "notes.saving": "Kaydediliyor…", |
| @@ -4408,6 +4409,8 @@ const tr: Dict = { | |||
| 4408 | "common.notFound": "Sayfa bulunamadı", | 4409 | "common.notFound": "Sayfa bulunamadı", |
| 4409 | "common.accessDenied": "Bu içeriğe erişimin yok.", | 4410 | "common.accessDenied": "Bu içeriğe erişimin yok.", |
| 4410 | "common.goHome": "Ana sayfaya dön", | 4411 | "common.goHome": "Ana sayfaya dön", |
| 4412 | + "modules.offTitle": "{module} modülü kapalı", | ||
| 4413 | + "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.", | ||
| 4411 | "common.learnMore": "Daha fazla", | 4414 | "common.learnMore": "Daha fazla", |
| 4412 | "common.gotIt": "Anladım", | 4415 | "common.gotIt": "Anladım", |
| 4413 | "confirm.review": "Lütfen kaydetmeden önce değişiklikleri gözden geçirin.", | 4416 | "confirm.review": "Lütfen kaydetmeden önce değişiklikleri gözden geçirin.", |
src/lib/route-module.test.tsadded+22 -0
| @@ -0,0 +1,22 @@ | |||
| 1 | +import { routeModule } from "@/lib/route-module"; | ||
| 2 | + | ||
| 3 | +describe("routeModule", () => { | ||
| 4 | + it("maps module pages and their detail routes", () => { | ||
| 5 | + expect(routeModule("/notes")).toBe("notes"); | ||
| 6 | + expect(routeModule("/notes/abc")).toBe("notes"); | ||
| 7 | + expect(routeModule("/exam-room/1")).toBe("exams"); | ||
| 8 | + expect(routeModule("/question-bank/9")).toBe("bank_questions"); | ||
| 9 | + }); | ||
| 10 | + | ||
| 11 | + it("prefers the longest prefix", () => { | ||
| 12 | + expect(routeModule("/students/exams")).toBe("marks"); | ||
| 13 | + expect(routeModule("/management/classes/3")).toBe("classes"); | ||
| 14 | + }); | ||
| 15 | + | ||
| 16 | + it("leaves core routes and look-alike prefixes unmapped", () => { | ||
| 17 | + expect(routeModule("/")).toBeNull(); | ||
| 18 | + expect(routeModule("/calendar")).toBeNull(); | ||
| 19 | + expect(routeModule("/management/students")).toBeNull(); | ||
| 20 | + expect(routeModule("/notebook")).toBeNull(); | ||
| 21 | + }); | ||
| 22 | +}); | ||
src/lib/route-module.tsadded+49 -0
| @@ -0,0 +1,49 @@ | |||
| 1 | +/** | ||
| 2 | + * Which backend module a route's page is built on, by path prefix. A school | ||
| 3 | + * with that module switched off gets `403 {error, module}` from every call the | ||
| 4 | + * page would make, so the shell shows a "switched off" screen instead of | ||
| 5 | + * rendering a page that can only fail. Routes built on core surfaces (home, | ||
| 6 | + * calendar, users, settings, profile) map to nothing and always render. | ||
| 7 | + * | ||
| 8 | + * Longest prefix wins, so the `/management/*` and `/students/*` entries are | ||
| 9 | + * matched ahead of the shorter ones. | ||
| 10 | + */ | ||
| 11 | +const ROUTE_MODULES: ReadonlyArray<readonly [prefix: string, module: string]> = [ | ||
| 12 | + ["/management/student-attendance", "attendance"], | ||
| 13 | + ["/management/student-marks", "marks"], | ||
| 14 | + ["/management/pomodoros", "pomodoro"], | ||
| 15 | + ["/management/payments", "payments"], | ||
| 16 | + ["/management/staff-work", "work"], | ||
| 17 | + ["/management/classes", "classes"], | ||
| 18 | + ["/students/attendance", "attendance"], | ||
| 19 | + ["/students/exams", "marks"], | ||
| 20 | + ["/students/study", "pomodoro"], | ||
| 21 | + ["/question-bank", "bank_questions"], | ||
| 22 | + ["/appointments", "appointments"], | ||
| 23 | + ["/whiteboards", "boards"], | ||
| 24 | + ["/attendance", "attendance"], | ||
| 25 | + ["/exam-room", "exams"], | ||
| 26 | + ["/questions", "questions"], | ||
| 27 | + ["/messages", "messages"], | ||
| 28 | + ["/homework", "homework"], | ||
| 29 | + ["/pomodoro", "pomodoro"], | ||
| 30 | + ["/payments", "payments"], | ||
| 31 | + ["/courses", "courses"], | ||
| 32 | + ["/studies", "courses"], | ||
| 33 | + ["/events", "events"], | ||
| 34 | + ["/clubs", "courses"], | ||
| 35 | + ["/exams", "exams"], | ||
| 36 | + ["/marks", "marks"], | ||
| 37 | + ["/meals", "meals"], | ||
| 38 | + ["/notes", "notes"], | ||
| 39 | + ["/work", "work"], | ||
| 40 | +]; | ||
| 41 | + | ||
| 42 | +export function routeModule(pathname: string): string | null { | ||
| 43 | + let best: readonly [string, string] | null = null; | ||
| 44 | + for (const entry of ROUTE_MODULES) { | ||
| 45 | + const [prefix] = entry; | ||
| 46 | + if ((pathname === prefix || pathname.startsWith(`${prefix}/`)) && (!best || prefix.length > best[0].length)) best = entry; | ||
| 47 | + } | ||
| 48 | + return best?.[1] ?? null; | ||
| 49 | +} | ||
src/pages/dashboard-page.test.tsxmodified+45 -7
| @@ -3,9 +3,13 @@ import type { JSX } from "solid-js"; | |||
| 3 | import DashboardPage from "@/pages/dashboard-page"; | 3 | import DashboardPage from "@/pages/dashboard-page"; |
| 4 | import { PreferencesProvider } from "@/stores/preferences-context"; | 4 | import { PreferencesProvider } from "@/stores/preferences-context"; |
| 5 | 5 | ||
| 6 | -const { navigate, authUser } = vi.hoisted(() => ({ | 6 | +const { navigate, authUser, schoolModules, calls, refuseExams } = vi.hoisted(() => ({ |
| 7 | navigate: vi.fn(), | 7 | navigate: vi.fn(), |
| 8 | authUser: { authenticated: true, role: "student" }, | 8 | authUser: { authenticated: true, role: "student" }, |
| 9 | + // null = module state unknown (fail open, everything shown). | ||
| 10 | + schoolModules: { enabled: null as string[] | null }, | ||
| 11 | + calls: [] as string[], | ||
| 12 | + refuseExams: { on: false }, | ||
| 9 | })); | 13 | })); |
| 10 | 14 | ||
| 11 | vi.mock("@tanstack/solid-router", () => ({ | 15 | vi.mock("@tanstack/solid-router", () => ({ |
| @@ -36,7 +40,12 @@ const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 50, offse | |||
| 36 | const course = { id: "course-1", title: "Algebra", capacity: 24 }; | 40 | const course = { id: "course-1", title: "Algebra", capacity: 24 }; |
| 37 | 41 | ||
| 38 | vi.mock("@/stores/modules-context", () => ({ | 42 | vi.mock("@/stores/modules-context", () => ({ |
| 39 | - useModules: () => ({ enabled: () => null, isEnabled: () => true, refresh: () => {} }), | 43 | + useModules: () => ({ |
| 44 | + enabled: () => schoolModules.enabled, | ||
| 45 | + loading: () => false, | ||
| 46 | + isEnabled: (module: string) => schoolModules.enabled === null || schoolModules.enabled.includes(module), | ||
| 47 | + refresh: () => {}, | ||
| 48 | + }), | ||
| 40 | })); | 49 | })); |
| 41 | vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], packages: [] }) })); | 50 | vi.mock("@/api/modules", () => ({ getModulesCatalog: async () => ({ modules: [], packages: [] }) })); |
| 42 | vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); | 51 | vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) })); |
| @@ -46,7 +55,7 @@ vi.mock("@/api/courses", () => ({ | |||
| 46 | })); | 55 | })); |
| 47 | vi.mock("@/api/reports", () => ({ | 56 | vi.mock("@/api/reports", () => ({ |
| 48 | getMyCourses: async () => page([course]), | 57 | getMyCourses: async () => page([course]), |
| 49 | - getMyMarks: async () => ({ | 58 | + getMyMarks: async () => (calls.push("marks"), { |
| 50 | overall_average: 82.5, | 59 | overall_average: 82.5, |
| 51 | courses: [{ | 60 | courses: [{ |
| 52 | course, | 61 | course, |
| @@ -70,8 +79,13 @@ vi.mock("@/api/payments", () => ({ | |||
| 70 | balance_minor: 0, | 79 | balance_minor: 0, |
| 71 | }), | 80 | }), |
| 72 | })); | 81 | })); |
| 73 | -vi.mock("@/api/exams", () => ({ | 82 | +vi.mock("@/api/exams", async () => { |
| 74 | - getExams: async () => page([ | 83 | + const { ApiError } = await import("@/api/client"); |
| 84 | + return { | ||
| 85 | + getExams: async () => { | ||
| 86 | + // A builder switched exams off after the modules list was read. | ||
| 87 | + if (refuseExams.on) throw new ApiError(403, "forbidden", null, "exams"); | ||
| 88 | + return page([ | ||
| 75 | { | 89 | { |
| 76 | id: "exam-1", | 90 | id: "exam-1", |
| 77 | title: "Exam deadline", | 91 | title: "Exam deadline", |
| @@ -88,7 +102,8 @@ vi.mock("@/api/exams", () => ({ | |||
| 88 | starts_at: now - 10 * DAY, | 102 | starts_at: now - 10 * DAY, |
| 89 | ends_at: now - 10 * DAY + 3_000, | 103 | ends_at: now - 10 * DAY + 3_000, |
| 90 | }, | 104 | }, |
| 91 | - ]), | 105 | + ]); |
| 106 | + }, | ||
| 92 | getExamStatistics: async (examId: string) => ({ | 107 | getExamStatistics: async (examId: string) => ({ |
| 93 | exam: examId, | 108 | exam: examId, |
| 94 | graded: 12, | 109 | graded: 12, |
| @@ -96,7 +111,8 @@ vi.mock("@/api/exams", () => ({ | |||
| 96 | min: 40, | 111 | min: 40, |
| 97 | max: 96, | 112 | max: 96, |
| 98 | }), | 113 | }), |
| 99 | -})); | 114 | + }; |
| 115 | +}); | ||
| 100 | vi.mock("@/api/pomodoro", () => ({ | 116 | vi.mock("@/api/pomodoro", () => ({ |
| 101 | getPomodoroMe: async () => ({ | 117 | getPomodoroMe: async () => ({ |
| 102 | items: [ | 118 | items: [ |
| @@ -159,6 +175,9 @@ afterEach(() => { | |||
| 159 | cleanup(); | 175 | cleanup(); |
| 160 | navigate.mockReset(); | 176 | navigate.mockReset(); |
| 161 | authUser.authenticated = true; | 177 | authUser.authenticated = true; |
| 178 | + schoolModules.enabled = null; | ||
| 179 | + calls.length = 0; | ||
| 180 | + refuseExams.on = false; | ||
| 162 | }); | 181 | }); |
| 163 | 182 | ||
| 164 | function renderDashboard(role: string) { | 183 | function renderDashboard(role: string) { |
| @@ -249,3 +268,22 @@ test("parent sees family highlights and appointment deadlines without staff char | |||
| 249 | expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy(); | 268 | expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy(); |
| 250 | expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); | 269 | expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); |
| 251 | }); | 270 | }); |
| 271 | + | ||
| 272 | +test("switched-off modules leave no tile, panel or request behind", async () => { | ||
| 273 | + schoolModules.enabled = ["courses", "exams", "events", "homework", "appointments", "meals", "classes"]; | ||
| 274 | + renderDashboard("student"); | ||
| 275 | + | ||
| 276 | + expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); | ||
| 277 | + expect(screen.queryByText("Course averages")).toBeNull(); | ||
| 278 | + expect(screen.queryByText("Attendance split")).toBeNull(); | ||
| 279 | + expect(screen.queryByText("Focus activity")).toBeNull(); | ||
| 280 | + expect(calls).not.toContain("marks"); | ||
| 281 | +}); | ||
| 282 | + | ||
| 283 | +test("a module refusal mid-session reads as no data instead of breaking the board", async () => { | ||
| 284 | + refuseExams.on = true; | ||
| 285 | + renderDashboard("manager"); | ||
| 286 | + | ||
| 287 | + expect(await screen.findByRole("heading", { name: "Upcoming deadlines" })).toBeTruthy(); | ||
| 288 | + expect(screen.queryByText(/permission|switched off/i)).toBeNull(); | ||
| 289 | +}); | ||
src/pages/dashboard-page.tsxmodified+107 -73
| @@ -3,7 +3,7 @@ import { createResource } from "@/lib/create-resource"; | |||
| 3 | import { useNavigate } from "@tanstack/solid-router"; | 3 | import { useNavigate } from "@tanstack/solid-router"; |
| 4 | import type { ColumnDef } from "@tanstack/solid-table"; | 4 | import type { ColumnDef } from "@tanstack/solid-table"; |
| 5 | import type { Role } from "@/api/client"; | 5 | import type { Role } from "@/api/client"; |
| 6 | -import { formatApiError } from "@/api/client"; | 6 | +import { formatApiError, isModuleDisabledError } from "@/api/client"; |
| 7 | import { getAppointments } from "@/api/appointments"; | 7 | import { getAppointments } from "@/api/appointments"; |
| 8 | import { getClasses, getClassesByUserId, getMyClasses } from "@/api/classes"; | 8 | import { getClasses, getClassesByUserId, getMyClasses } from "@/api/classes"; |
| 9 | import { getCourseEnrollments, getCourses } from "@/api/courses"; | 9 | import { getCourseEnrollments, getCourses } from "@/api/courses"; |
| @@ -81,6 +81,8 @@ type DeadlineRow = { | |||
| 81 | 81 | ||
| 82 | type StatCardData = { | 82 | type StatCardData = { |
| 83 | labelKey: MessageKey; | 83 | labelKey: MessageKey; |
| 84 | + /** The module the number comes from; the tile is left out when it is off. */ | ||
| 85 | + module?: string; | ||
| 84 | value: string; | 86 | value: string; |
| 85 | Icon: Component<{ class?: string }>; | 87 | Icon: Component<{ class?: string }>; |
| 86 | }; | 88 | }; |
| @@ -120,64 +122,78 @@ function DashboardContent() { | |||
| 120 | const { locale } = usePreferences(); | 122 | const { locale } = usePreferences(); |
| 121 | const user = () => auth.user()!; | 123 | const user = () => auth.user()!; |
| 122 | const role = () => user().role; | 124 | const role = () => user().role; |
| 125 | + // A school can have any module switched off, and every route of an off | ||
| 126 | + // module answers 403. The board never asks one (the source goes null), and | ||
| 127 | + // a refusal that races a builder's switch reads as "no data" instead of | ||
| 128 | + // throwing through the page — it used to blank the whole homepage. | ||
| 129 | + const schoolModules = useModules(); | ||
| 130 | + const on = (module: string) => !schoolModules.loading() && schoolModules.isEnabled(module); | ||
| 131 | + const quiet = <T,>(request: Promise<T>): Promise<T | null> => | ||
| 132 | + request.catch((err: unknown) => { | ||
| 133 | + if (isModuleDisabledError(err)) return null; | ||
| 134 | + throw err; | ||
| 135 | + }); | ||
| 123 | const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); | 136 | const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); |
| 124 | // Unpaged: the backend has no `kind` filter, so a "courses" count that | 137 | // Unpaged: the backend has no `kind` filter, so a "courses" count that |
| 125 | // excludes studies and clubs has to be counted here over the whole list. | 138 | // excludes studies and clubs has to be counted here over the whole list. |
| 126 | const [courses] = createResource( | 139 | const [courses] = createResource( |
| 127 | - () => role() === "parent" ? null : role(), | 140 | + () => role() === "parent" || !on("courses") ? null : role(), |
| 128 | - (currentRole) => currentRole === "student" ? getMyCourses() : getCourses(), | 141 | + (currentRole) => quiet(currentRole === "student" ? getMyCourses() : getCourses()), |
| 129 | ); | 142 | ); |
| 130 | const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length; | 143 | const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length; |
| 131 | // `/events` has no role gate — a parent-teacher conference is a real PAR-01 | 144 | // `/events` has no role gate — a parent-teacher conference is a real PAR-01 |
| 132 | // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework` | 145 | // "Yaklaşan" item, so parent reads this too (unlike `exams`/`homework` |
| 133 | // below, which really are course-scoped and out of a parent's reach). | 146 | // below, which really are course-scoped and out of a parent's reach). |
| 134 | const [events] = createResource( | 147 | const [events] = createResource( |
| 135 | - () => clock()?.now, | 148 | + () => (on("events") ? clock()?.now : null), |
| 136 | - (now) => getEvents({ ends_after: now, limit: 50 }), | 149 | + (now) => quiet(getEvents({ ends_after: now, limit: 50 })), |
| 137 | ); | 150 | ); |
| 138 | const [exams] = createResource( | 151 | const [exams] = createResource( |
| 139 | - () => role() === "parent" ? null : role(), | 152 | + () => role() === "parent" || !on("exams") ? null : role(), |
| 140 | - () => getExams({ limit: 100 }), | 153 | + () => quiet(getExams({ limit: 100 })), |
| 141 | ); | 154 | ); |
| 142 | // Unfiltered: `/homework` has no due-date window, so this one read serves both | 155 | // Unfiltered: `/homework` has no due-date window, so this one read serves both |
| 143 | // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking | 156 | // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking |
| 144 | // heatmap. | 157 | // heatmap. |
| 145 | const [homework] = createResource( | 158 | const [homework] = createResource( |
| 146 | - () => role() === "parent" ? null : role(), | 159 | + () => role() === "parent" || !on("homework") ? null : role(), |
| 147 | - () => getHomework({ limit: 100 }), | 160 | + () => quiet(getHomework({ limit: 100 })), |
| 148 | ); | 161 | ); |
| 149 | const [children] = createResource( | 162 | const [children] = createResource( |
| 150 | () => role() === "parent" ? true : null, | 163 | () => role() === "parent" ? true : null, |
| 151 | - () => getMyStudents({ limit: 12 }), | 164 | + () => quiet(getMyStudents({ limit: 12 })), |
| 165 | + ); | ||
| 166 | + const [appointments] = createResource( | ||
| 167 | + () => (on("appointments") ? true : null), | ||
| 168 | + () => quiet(getAppointments({ limit: 20 })), | ||
| 152 | ); | 169 | ); |
| 153 | - const [appointments] = createResource(() => getAppointments({ limit: 20 })); | ||
| 154 | const [menus] = createResource( | 170 | const [menus] = createResource( |
| 155 | - () => clock()?.now, | 171 | + () => (on("meals") ? clock()?.now : null), |
| 156 | - (now) => getMealMenus({ from: new Date(now).toISOString().slice(0, 10), limit: 1 }), | 172 | + (now) => quiet(getMealMenus({ from: new Date(now).toISOString().slice(0, 10), limit: 1 })), |
| 157 | ); | 173 | ); |
| 158 | const [marks] = createResource( | 174 | const [marks] = createResource( |
| 159 | - () => role() === "student" ? true : null, | 175 | + () => role() === "student" && on("marks") ? true : null, |
| 160 | - () => getMyMarks(), | 176 | + () => quiet(getMyMarks()), |
| 161 | ); | 177 | ); |
| 162 | const [attendance] = createResource( | 178 | const [attendance] = createResource( |
| 163 | - () => role() === "student" ? true : null, | 179 | + () => role() === "student" && on("attendance") ? true : null, |
| 164 | - () => getMyAttendance(), | 180 | + () => quiet(getMyAttendance()), |
| 165 | ); | 181 | ); |
| 166 | const [myClasses] = createResource( | 182 | const [myClasses] = createResource( |
| 167 | - () => role() === "student" ? true : null, | 183 | + () => role() === "student" && on("classes") ? true : null, |
| 168 | - () => getMyClasses({ limit: 1 }), | 184 | + () => quiet(getMyClasses({ limit: 1 })), |
| 169 | ); | 185 | ); |
| 170 | // Focus heatmap source. Only a student owns pomodoro sessions — reading | 186 | // Focus heatmap source. Only a student owns pomodoro sessions — reading |
| 171 | // another user's log is the teacher+ /management/pomodoros page's job. | 187 | // another user's log is the teacher+ /management/pomodoros page's job. |
| 172 | const [pomodoro] = createResource( | 188 | const [pomodoro] = createResource( |
| 173 | - () => role() === "student" ? true : null, | 189 | + () => role() === "student" && on("pomodoro") ? true : null, |
| 174 | - () => getPomodoroMe({ limit: 400 }), | 190 | + () => quiet(getPomodoroMe({ limit: 400 })), |
| 175 | ); | 191 | ); |
| 176 | // `/events` is the one list here that really is filtered server-side, by the | 192 | // `/events` is the one list here that really is filtered server-side, by the |
| 177 | // `ends_after` window the deadlines table needs. The heatmap looks backwards | 193 | // `ends_after` window the deadlines table needs. The heatmap looks backwards |
| 178 | // and there is no "before" filter, so past events need their own read. | 194 | // and there is no "before" filter, so past events need their own read. |
| 179 | const [pastEvents] = createResource( | 195 | const [pastEvents] = createResource( |
| 180 | - () => hasMinRole(role(), "teacher") ? true : null, | 196 | + () => hasMinRole(role(), "teacher") && on("events") ? true : null, |
| 181 | () => getEvents({ limit: 100 }).catch(() => null), | 197 | () => getEvents({ limit: 100 }).catch(() => null), |
| 182 | ); | 198 | ); |
| 183 | // Success trend source for teacher+. Exam statistics are grader-only, so this | 199 | // Success trend source for teacher+. Exam statistics are grader-only, so this |
| @@ -240,12 +256,12 @@ function DashboardContent() { | |||
| 240 | if (first && !selectedChildId()) setSelectedChildId(first); | 256 | if (first && !selectedChildId()) setSelectedChildId(first); |
| 241 | }); | 257 | }); |
| 242 | const [childClasses] = createResource( | 258 | const [childClasses] = createResource( |
| 243 | - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), | 259 | + () => (role() === "parent" && on("classes") && selectedChildId() ? selectedChildId() : null), |
| 244 | (id) => getClassesByUserId(id, { limit: 1 }).catch(() => null), | 260 | (id) => getClassesByUserId(id, { limit: 1 }).catch(() => null), |
| 245 | ); | 261 | ); |
| 246 | const homeroomTeacher = () => childClasses()?.items[0]?.teacher ?? null; | 262 | const homeroomTeacher = () => childClasses()?.items[0]?.teacher ?? null; |
| 247 | const [childAttendance] = createResource( | 263 | const [childAttendance] = createResource( |
| 248 | - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), | 264 | + () => (role() === "parent" && on("attendance") && selectedChildId() ? selectedChildId() : null), |
| 249 | (id) => getUserAttendance(id).catch(() => null), | 265 | (id) => getUserAttendance(id).catch(() => null), |
| 250 | ); | 266 | ); |
| 251 | const childAttendanceBreakdown = createMemo(() => { | 267 | const childAttendanceBreakdown = createMemo(() => { |
| @@ -262,7 +278,7 @@ function DashboardContent() { | |||
| 262 | }; | 278 | }; |
| 263 | }); | 279 | }); |
| 264 | const [childStatement] = createResource( | 280 | const [childStatement] = createResource( |
| 265 | - () => (role() === "parent" && selectedChildId() ? selectedChildId() : null), | 281 | + () => (role() === "parent" && on("payments") && selectedChildId() ? selectedChildId() : null), |
| 266 | (id) => getPaymentStatementByUserId(id, { limit: 100 }).catch(() => null), | 282 | (id) => getPaymentStatementByUserId(id, { limit: 100 }).catch(() => null), |
| 267 | ); | 283 | ); |
| 268 | const paymentSummary = createMemo(() => { | 284 | const paymentSummary = createMemo(() => { |
| @@ -294,8 +310,8 @@ function DashboardContent() { | |||
| 294 | () => getUsers({ limit: 30 }), | 310 | () => getUsers({ limit: 30 }), |
| 295 | ); | 311 | ); |
| 296 | const [recentClasses] = createResource( | 312 | const [recentClasses] = createResource( |
| 297 | - () => (isAdminHome() ? true : null), | 313 | + () => (isAdminHome() && on("classes") ? true : null), |
| 298 | - () => getClasses({ limit: 2 }), | 314 | + () => quiet(getClasses({ limit: 2 })), |
| 299 | ); | 315 | ); |
| 300 | const studentQuickLinks = createMemo<QuickLinkRow[]>(() => | 316 | const studentQuickLinks = createMemo<QuickLinkRow[]>(() => |
| 301 | (recentStudents()?.items ?? []) | 317 | (recentStudents()?.items ?? []) |
| @@ -319,7 +335,6 @@ function DashboardContent() { | |||
| 319 | 335 | ||
| 320 | // The school's own entitlements per package: the catalog is deploy-constant, | 336 | // The school's own entitlements per package: the catalog is deploy-constant, |
| 321 | // the enabled set is already in the shell's modules context. | 337 | // the enabled set is already in the shell's modules context. |
| 322 | - const schoolModules = useModules(); | ||
| 323 | const [moduleCatalog] = createResource( | 338 | const [moduleCatalog] = createResource( |
| 324 | () => (isAdminHome() ? true : null), | 339 | () => (isAdminHome() ? true : null), |
| 325 | () => getModulesCatalog().catch(() => null), | 340 | () => getModulesCatalog().catch(() => null), |
| @@ -377,39 +392,40 @@ function DashboardContent() { | |||
| 377 | return total ? Math.round((present / total) * 100) : null; | 392 | return total ? Math.round((present / total) * 100) : null; |
| 378 | }); | 393 | }); |
| 379 | 394 | ||
| 380 | - const stats = createMemo<StatCardData[]>(() => { | 395 | + const allStats = createMemo<StatCardData[]>(() => { |
| 381 | const r = role(); | 396 | const r = role(); |
| 382 | if (r === "student") { | 397 | if (r === "student") { |
| 383 | return [ | 398 | return [ |
| 384 | - { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, | 399 | + { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, |
| 385 | - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, | 400 | + { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, |
| 386 | - { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, | 401 | + { labelKey: "dashboard.stats.average", module: "marks", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, |
| 387 | - { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, | 402 | + { labelKey: "dashboard.stats.attendance", module: "attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, |
| 388 | ]; | 403 | ]; |
| 389 | } | 404 | } |
| 390 | if (r === "teacher") { | 405 | if (r === "teacher") { |
| 391 | return [ | 406 | return [ |
| 392 | - { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, | 407 | + { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, |
| 393 | - { labelKey: "dashboard.stats.students", value: teacherStudentCount() == null ? "—" : String(teacherStudentCount()), Icon: IconUsers }, | 408 | + { labelKey: "dashboard.stats.students", module: "courses", value: teacherStudentCount() == null ? "—" : String(teacherStudentCount()), Icon: IconUsers }, |
| 394 | - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, | 409 | + { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, |
| 395 | - { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework }, | 410 | + { labelKey: "dashboard.stats.homework", module: "homework", value: String(homework()?.total ?? 0), Icon: IconHomework }, |
| 396 | ]; | 411 | ]; |
| 397 | } | 412 | } |
| 398 | if (r === "parent") { | 413 | if (r === "parent") { |
| 399 | return [ | 414 | return [ |
| 400 | { labelKey: "dashboard.stats.children", value: String(children()?.total ?? 0), Icon: IconUsers }, | 415 | { labelKey: "dashboard.stats.children", value: String(children()?.total ?? 0), Icon: IconUsers }, |
| 401 | - { labelKey: "dashboard.stats.appointments", value: String(appointments()?.total ?? 0), Icon: IconCalendarDays }, | 416 | + { labelKey: "dashboard.stats.appointments", module: "appointments", value: String(appointments()?.total ?? 0), Icon: IconCalendarDays }, |
| 402 | - { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, | 417 | + { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, |
| 403 | - { labelKey: "dashboard.stats.childAttendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck }, | 418 | + { labelKey: "dashboard.stats.childAttendance", module: "attendance", value: childAttendanceBreakdown()?.rate == null ? "—" : `${childAttendanceBreakdown()!.rate}%`, Icon: IconClipboardCheck }, |
| 404 | ]; | 419 | ]; |
| 405 | } | 420 | } |
| 406 | return [ | 421 | return [ |
| 407 | - { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, | 422 | + { labelKey: "dashboard.stats.courses", module: "courses", value: String(courseCount()), Icon: IconBook }, |
| 408 | - { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, | 423 | + { labelKey: "dashboard.stats.exams", module: "exams", value: String(exams()?.total ?? 0), Icon: IconExam }, |
| 409 | - { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, | 424 | + { labelKey: "dashboard.stats.events", module: "events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, |
| 410 | - { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, | 425 | + { labelKey: "dashboard.stats.meals", module: "meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, |
| 411 | ]; | 426 | ]; |
| 412 | }); | 427 | }); |
| 428 | + const stats = () => allStats().filter((stat) => !stat.module || on(stat.module)); | ||
| 413 | 429 | ||
| 414 | // Student trend — own marks ordered by their exam's date. Marks whose exam | 430 | // Student trend — own marks ordered by their exam's date. Marks whose exam |
| 415 | // falls outside the fetched exam page carry no date and are left out rather | 431 | // falls outside the fetched exam page carry no date and are left out rather |
| @@ -620,7 +636,7 @@ function DashboardContent() { | |||
| 620 | 636 | ||
| 621 | const error = createMemo(() => { | 637 | const error = createMemo(() => { |
| 622 | 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; | 638 | 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; |
| 623 | - return problem ? formatApiError(problem, locale()) : ""; | 639 | + return problem && !isModuleDisabledError(problem) ? formatApiError(problem, locale()) : ""; |
| 624 | }); | 640 | }); |
| 625 | 641 | ||
| 626 | return ( | 642 | return ( |
| @@ -655,7 +671,7 @@ function DashboardContent() { | |||
| 655 | </div> | 671 | </div> |
| 656 | <h1 class="text-[28px] font-semibold leading-9 tracking-[-0.02em] text-text-strong">{t("dashboard.hero.heading")}</h1> | 672 | <h1 class="text-[28px] font-semibold leading-9 tracking-[-0.02em] text-text-strong">{t("dashboard.hero.heading")}</h1> |
| 657 | <CommandSearchField /> | 673 | <CommandSearchField /> |
| 658 | - <div class="grid w-full grid-cols-1 gap-3 sm:grid-cols-3"> | 674 | + <div class={cn("grid w-full grid-cols-1 gap-3", on("classes") ? "sm:grid-cols-3" : "sm:grid-cols-2")}> |
| 659 | <QuickLinkColumn | 675 | <QuickLinkColumn |
| 660 | title={t("dashboard.quicklinks.students")} | 676 | title={t("dashboard.quicklinks.students")} |
| 661 | illustration="people" | 677 | illustration="people" |
| @@ -663,13 +679,15 @@ function DashboardContent() { | |||
| 663 | empty={t("dashboard.quicklinks.empty")} | 679 | empty={t("dashboard.quicklinks.empty")} |
| 664 | onOpen={(row) => navigate({ to: "/admin/users/$id", params: { id: row.id } })} | 680 | onOpen={(row) => navigate({ to: "/admin/users/$id", params: { id: row.id } })} |
| 665 | /> | 681 | /> |
| 666 | - <QuickLinkColumn | 682 | + <Show when={on("classes")}> |
| 667 | - title={t("dashboard.quicklinks.classes")} | 683 | + <QuickLinkColumn |
| 668 | - illustration="courses" | 684 | + title={t("dashboard.quicklinks.classes")} |
| 669 | - rows={classQuickLinks()} | 685 | + illustration="courses" |
| 670 | - empty={t("dashboard.quicklinks.empty")} | 686 | + rows={classQuickLinks()} |
| 671 | - onOpen={(row) => navigate({ to: "/management/classes/$id", params: { id: row.id } })} | 687 | + empty={t("dashboard.quicklinks.empty")} |
| 672 | - /> | 688 | + onOpen={(row) => navigate({ to: "/management/classes/$id", params: { id: row.id } })} |
| 689 | + /> | ||
| 690 | + </Show> | ||
| 673 | <QuickLinkColumn | 691 | <QuickLinkColumn |
| 674 | title={t("dashboard.quicklinks.modules")} | 692 | title={t("dashboard.quicklinks.modules")} |
| 675 | illustration="modules" | 693 | illustration="modules" |
| @@ -714,26 +732,31 @@ function DashboardContent() { | |||
| 714 | design reserves for that kind of card. */} | 732 | design reserves for that kind of card. */} |
| 715 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-4"> | 733 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-4"> |
| 716 | <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-3 lg:grid-cols-3"> | 734 | <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-3 lg:grid-cols-3"> |
| 717 | - <ChartBar | 735 | + <Show when={on("marks")}> |
| 718 | - title={t("dashboard.progressOverview")} | 736 | + <ChartBar |
| 719 | - subtitle={t("dashboard.courseAverages")} | 737 | + title={t("dashboard.progressOverview")} |
| 720 | - items={courseAverages()} | 738 | + subtitle={t("dashboard.courseAverages")} |
| 721 | - maxScale={100} | 739 | + items={courseAverages()} |
| 722 | - itemsPerPage={5} | 740 | + maxScale={100} |
| 723 | - /> | 741 | + itemsPerPage={5} |
| 724 | - <ChartLine | 742 | + /> |
| 725 | - title={t("dashboard.successTrend")} | 743 | + <ChartLine |
| 726 | - subtitle={t("dashboard.successTrendMine")} | 744 | + title={t("dashboard.successTrend")} |
| 727 | - items={myMarkTrend()} | 745 | + subtitle={t("dashboard.successTrendMine")} |
| 728 | - maxScale={100} | 746 | + items={myMarkTrend()} |
| 729 | - /> | 747 | + maxScale={100} |
| 730 | - <ChartProgressRing | 748 | + /> |
| 731 | - title={t("dashboard.activitySplit")} | 749 | + </Show> |
| 732 | - subtitle={t("dashboard.activitySplitDesc")} | 750 | + <Show when={on("attendance")}> |
| 733 | - segments={attendanceSegments()} | 751 | + <ChartProgressRing |
| 734 | - itemsPerPage={3} | 752 | + title={t("dashboard.activitySplit")} |
| 735 | - /> | 753 | + subtitle={t("dashboard.activitySplitDesc")} |
| 754 | + segments={attendanceSegments()} | ||
| 755 | + itemsPerPage={3} | ||
| 756 | + /> | ||
| 757 | + </Show> | ||
| 736 | </div> | 758 | </div> |
| 759 | + <Show when={on("pomodoro")}> | ||
| 737 | <div class="flex flex-col gap-2 rounded-xl border border-border-line bg-surface-base p-4 lg:col-span-1"> | 760 | <div class="flex flex-col gap-2 rounded-xl border border-border-line bg-surface-base p-4 lg:col-span-1"> |
| 738 | <div class="flex items-center gap-2"> | 761 | <div class="flex items-center gap-2"> |
| 739 | <IconClock class="h-4 w-4 shrink-0 text-text-subtle" /> | 762 | <IconClock class="h-4 w-4 shrink-0 text-text-subtle" /> |
| @@ -757,6 +780,7 @@ function DashboardContent() { | |||
| 757 | </div> | 780 | </div> |
| 758 | <p class="mono text-xs tabular-nums text-text-subtle">{t("dashboard.student.thisWeekTotal", { minutes: String(weeklyFocusTotal()) })}</p> | 781 | <p class="mono text-xs tabular-nums text-text-subtle">{t("dashboard.student.thisWeekTotal", { minutes: String(weeklyFocusTotal()) })}</p> |
| 759 | </div> | 782 | </div> |
| 783 | + </Show> | ||
| 760 | </div> | 784 | </div> |
| 761 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> | 785 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> |
| 762 | <ComingSoonPanel title={t("dashboard.student.todayPlan")} /> | 786 | <ComingSoonPanel title={t("dashboard.student.todayPlan")} /> |
| @@ -774,6 +798,7 @@ function DashboardContent() { | |||
| 774 | item behind that queue — a pending appointment request — | 798 | item behind that queue — a pending appointment request — |
| 775 | gets the rail. */} | 799 | gets the rail. */} |
| 776 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> | 800 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> |
| 801 | + <Show when={on("exams")}> | ||
| 777 | <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-2"> | 802 | <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:col-span-2"> |
| 778 | <ChartLine | 803 | <ChartLine |
| 779 | title={t("dashboard.successTrend")} | 804 | title={t("dashboard.successTrend")} |
| @@ -789,6 +814,8 @@ function DashboardContent() { | |||
| 789 | itemsPerPage={5} | 814 | itemsPerPage={5} |
| 790 | /> | 815 | /> |
| 791 | </div> | 816 | </div> |
| 817 | + </Show> | ||
| 818 | + <Show when={on("appointments")}> | ||
| 792 | <div class="flex flex-col rounded-xl border border-border-line bg-surface-base p-4"> | 819 | <div class="flex flex-col rounded-xl border border-border-line bg-surface-base p-4"> |
| 793 | <div class="flex items-center gap-2 pb-3"> | 820 | <div class="flex items-center gap-2 pb-3"> |
| 794 | <IconCalendarDays class="h-4 w-4 shrink-0 text-text-subtle" /> | 821 | <IconCalendarDays class="h-4 w-4 shrink-0 text-text-subtle" /> |
| @@ -816,6 +843,7 @@ function DashboardContent() { | |||
| 816 | </For> | 843 | </For> |
| 817 | </Show> | 844 | </Show> |
| 818 | </div> | 845 | </div> |
| 846 | + </Show> | ||
| 819 | </div> | 847 | </div> |
| 820 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-2"> | 848 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-2"> |
| 821 | <ComingSoonPanel title={t("dashboard.teacher.schedule")} /> | 849 | <ComingSoonPanel title={t("dashboard.teacher.schedule")} /> |
| @@ -823,7 +851,7 @@ function DashboardContent() { | |||
| 823 | </div> | 851 | </div> |
| 824 | </Show> | 852 | </Show> |
| 825 | 853 | ||
| 826 | - <Show when={role() === "manager" || role() === "admin"}> | 854 | + <Show when={(role() === "manager" || role() === "admin") && on("exams")}> |
| 827 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> | 855 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> |
| 828 | <ChartLine | 856 | <ChartLine |
| 829 | class="lg:col-span-2" | 857 | class="lg:col-span-2" |
| @@ -866,6 +894,7 @@ function DashboardContent() { | |||
| 866 | </div> | 894 | </div> |
| 867 | </Show> | 895 | </Show> |
| 868 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> | 896 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> |
| 897 | + <Show when={on("attendance")}> | ||
| 869 | <div class="flex flex-col gap-3 rounded-xl border border-border-line bg-surface-base p-4 lg:col-span-2"> | 898 | <div class="flex flex-col gap-3 rounded-xl border border-border-line bg-surface-base p-4 lg:col-span-2"> |
| 870 | <div> | 899 | <div> |
| 871 | <p class="text-sm font-semibold text-text-strong">{t("dashboard.parent.attendanceDetail")}</p> | 900 | <p class="text-sm font-semibold text-text-strong">{t("dashboard.parent.attendanceDetail")}</p> |
| @@ -897,6 +926,8 @@ function DashboardContent() { | |||
| 897 | )} | 926 | )} |
| 898 | </Show> | 927 | </Show> |
| 899 | </div> | 928 | </div> |
| 929 | + </Show> | ||
| 930 | + <Show when={on("payments")}> | ||
| 900 | <div class="flex flex-col gap-2 rounded-xl border border-border-line bg-surface-base p-4"> | 931 | <div class="flex flex-col gap-2 rounded-xl border border-border-line bg-surface-base p-4"> |
| 901 | <p class="text-sm font-semibold text-text-strong">{t("dashboard.parent.payment")}</p> | 932 | <p class="text-sm font-semibold text-text-strong">{t("dashboard.parent.payment")}</p> |
| 902 | <p class="text-xs text-text-subtle">{t("dashboard.parent.paymentDesc")}</p> | 933 | <p class="text-xs text-text-subtle">{t("dashboard.parent.paymentDesc")}</p> |
| @@ -924,6 +955,7 @@ function DashboardContent() { | |||
| 924 | )} | 955 | )} |
| 925 | </Show> | 956 | </Show> |
| 926 | </div> | 957 | </div> |
| 958 | + </Show> | ||
| 927 | </div> | 959 | </div> |
| 928 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> | 960 | <div class="grid grid-cols-1 gap-3 lg:grid-cols-3"> |
| 929 | <ComingSoonPanel class="lg:col-span-2" title={t("dashboard.parent.progress")} /> | 961 | <ComingSoonPanel class="lg:col-span-2" title={t("dashboard.parent.progress")} /> |
| @@ -944,6 +976,7 @@ function DashboardContent() { | |||
| 944 | /> | 976 | /> |
| 945 | </section> | 977 | </section> |
| 946 | 978 | ||
| 979 | + <Show when={!heatmapIsFocus() || on("pomodoro")}> | ||
| 947 | <ChartHeatmap | 980 | <ChartHeatmap |
| 948 | title={heatmapIsFocus() ? t("dashboard.focusHeatmap") : t("dashboard.activityHeatmap")} | 981 | title={heatmapIsFocus() ? t("dashboard.focusHeatmap") : t("dashboard.activityHeatmap")} |
| 949 | subtitle={heatmapIsFocus() ? t("dashboard.focusHeatmapDesc") : t("dashboard.activityHeatmapDesc")} | 982 | subtitle={heatmapIsFocus() ? t("dashboard.focusHeatmapDesc") : t("dashboard.activityHeatmapDesc")} |
| @@ -966,6 +999,7 @@ function DashboardContent() { | |||
| 966 | : t("dashboard.heatmapRecordTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) }) | 999 | : t("dashboard.heatmapRecordTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) }) |
| 967 | } | 1000 | } |
| 968 | /> | 1001 | /> |
| 1002 | + </Show> | ||
| 969 | </Suspense> | 1003 | </Suspense> |
| 970 | </div> | 1004 | </div> |
| 971 | ); | 1005 | ); |
src/stores/modules-context.tsxmodified+35 -0
| @@ -3,9 +3,12 @@ import { | |||
| 3 | type ParentProps, | 3 | type ParentProps, |
| 4 | createContext, | 4 | createContext, |
| 5 | createMemo, | 5 | createMemo, |
| 6 | + onCleanup, | ||
| 7 | + onMount, | ||
| 6 | useContext, | 8 | useContext, |
| 7 | } from "solid-js"; | 9 | } from "solid-js"; |
| 8 | import { createResource } from "@/lib/create-resource"; | 10 | import { createResource } from "@/lib/create-resource"; |
| 11 | +import { onModuleDisabled } from "@/api/client"; | ||
| 9 | import { getModules } from "@/api/modules"; | 12 | import { getModules } from "@/api/modules"; |
| 10 | import { useAuth } from "@/stores/auth-context"; | 13 | import { useAuth } from "@/stores/auth-context"; |
| 11 | 14 | ||
| @@ -16,6 +19,12 @@ type ModulesContextValue = { | |||
| 16 | * shows everything (fail open), so a modules outage never blanks the shell. | 19 | * shows everything (fail open), so a modules outage never blanks the shell. |
| 17 | */ | 20 | */ |
| 18 | enabled: Accessor<string[] | null>; | 21 | enabled: Accessor<string[] | null>; |
| 22 | + /** | ||
| 23 | + * True until the first lookup for this account settles. Readers that would | ||
| 24 | + * otherwise fire at a possibly-off module on first paint wait for it; after | ||
| 25 | + * that a failed lookup still fails open. | ||
| 26 | + */ | ||
| 27 | + loading: Accessor<boolean>; | ||
| 19 | /** Fail-open membership test over `enabled`. */ | 28 | /** Fail-open membership test over `enabled`. */ |
| 20 | isEnabled: (module: string) => boolean; | 29 | isEnabled: (module: string) => boolean; |
| 21 | refresh: () => void; | 30 | refresh: () => void; |
| @@ -42,8 +51,34 @@ export function ModulesProvider(props: ParentProps) { | |||
| 42 | { initialValue: null }, | 51 | { initialValue: null }, |
| 43 | ); | 52 | ); |
| 44 | 53 | ||
| 54 | + // The enabled set changes under a live session when a builder flips a | ||
| 55 | + // module. Two cues bring it up to date without a reload: a route answering | ||
| 56 | + // `403 {module}` (switched off), and the tab coming back into view after a | ||
| 57 | + // while (switched on, or off where nothing was asked of it yet). | ||
| 58 | + const REVISIT_AFTER_MS = 60_000; | ||
| 59 | + let lastFetch = Date.now(); | ||
| 60 | + const refreshNow = () => { | ||
| 61 | + if (userId() === null || modules.loading) return; | ||
| 62 | + lastFetch = Date.now(); | ||
| 63 | + void refetch(); | ||
| 64 | + }; | ||
| 65 | + onMount(() => { | ||
| 66 | + const stop = onModuleDisabled((module) => { | ||
| 67 | + if (modules.latest?.includes(module) !== false) refreshNow(); | ||
| 68 | + }); | ||
| 69 | + const onVisible = () => { | ||
| 70 | + if (document.visibilityState === "visible" && Date.now() - lastFetch > REVISIT_AFTER_MS) refreshNow(); | ||
| 71 | + }; | ||
| 72 | + document.addEventListener("visibilitychange", onVisible); | ||
| 73 | + onCleanup(() => { | ||
| 74 | + stop(); | ||
| 75 | + document.removeEventListener("visibilitychange", onVisible); | ||
| 76 | + }); | ||
| 77 | + }); | ||
| 78 | + | ||
| 45 | const value: ModulesContextValue = { | 79 | const value: ModulesContextValue = { |
| 46 | enabled: () => modules(), | 80 | enabled: () => modules(), |
| 81 | + loading: () => userId() !== null && modules.loading && modules.latest === null, | ||
| 47 | isEnabled: (module: string) => { | 82 | isEnabled: (module: string) => { |
| 48 | const enabled = modules(); | 83 | const enabled = modules(); |
| 49 | return enabled === null || enabled.includes(module); | 84 | return enabled === null || enabled.includes(module); |
src/stores/shell-feed-context.test.tsxmodified+2 -0
| @@ -6,6 +6,8 @@ import { ShellFeedProvider, useShellFeed } from "@/stores/shell-feed-context"; | |||
| 6 | // The provider only reads `auth.user()`; drive it from a signal the test owns. | 6 | // The provider only reads `auth.user()`; drive it from a signal the test owns. |
| 7 | const [user, setUser] = createSignal<User | null>(null); | 7 | const [user, setUser] = createSignal<User | null>(null); |
| 8 | vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user }) })); | 8 | vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ user }) })); |
| 9 | +// Every module on: the feed skips switched-off modules, which is not what these cases test. | ||
| 10 | +vi.mock("@/stores/modules-context", () => ({ useModules: () => ({ isEnabled: () => true, enabled: () => null, loading: () => false }) })); | ||
| 9 | 11 | ||
| 10 | const page = <T,>(items: T[]) => ({ items, total: items.length, limit: null, offset: 0 }); | 12 | const page = <T,>(items: T[]) => ({ items, total: items.length, limit: null, offset: 0 }); |
| 11 | 13 | ||
src/stores/shell-feed-context.tsxmodified+14 -3
| @@ -15,6 +15,7 @@ import { getMessages } from "@/api/messages"; | |||
| 15 | import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client"; | 15 | import type { Appointment, Event, Exam, Homework, Message, Page } from "@/api/client"; |
| 16 | import { createLivePoll } from "@/lib/create-live-poll"; | 16 | import { createLivePoll } from "@/lib/create-live-poll"; |
| 17 | import { useAuth } from "@/stores/auth-context"; | 17 | import { useAuth } from "@/stores/auth-context"; |
| 18 | +import { useModules } from "@/stores/modules-context"; | ||
| 18 | 19 | ||
| 19 | // One shared poller for the always-mounted shell (NotificationCenter header + | 20 | // One shared poller for the always-mounted shell (NotificationCenter header + |
| 20 | // header message/notification controls). Both used to `createResource` messages/events/exams | 21 | // header message/notification controls). Both used to `createResource` messages/events/exams |
| @@ -55,15 +56,19 @@ type UserFeed = Omit<ShellFeedContextValue, "nowMs">; | |||
| 55 | // can survive into the next session. Solid keeps a resource's last value when | 56 | // can survive into the next session. Solid keeps a resource's last value when |
| 56 | // its source goes falsy, so gating alone would leak user A's inbox into user | 57 | // its source goes falsy, so gating alone would leak user A's inbox into user |
| 57 | // B's shell until the refetch resolved. | 58 | // B's shell until the refetch resolved. |
| 58 | -function createUserFeed(loggedIn: boolean): UserFeed { | 59 | +function createUserFeed(loggedIn: boolean, modulesLoading: () => boolean, isEnabled: (module: string) => boolean): UserFeed { |
| 59 | // Only fetch for a logged-in user: source is false while logged out, so the | 60 | // Only fetch for a logged-in user: source is false while logged out, so the |
| 60 | // resource keeps its seeded empty value and never hits the network. | 61 | // resource keeps its seeded empty value and never hits the network. |
| 61 | - const source = () => loggedIn; | 62 | + // It also waits for the school's module list, so a first paint never asks a |
| 63 | + // switched-off module (and gets 403) before the list says it is off. | ||
| 64 | + const source = () => loggedIn && !modulesLoading(); | ||
| 62 | 65 | ||
| 63 | const [messagesRes, { refetch: refetchInbox }] = createResource( | 66 | const [messagesRes, { refetch: refetchInbox }] = createResource( |
| 64 | source, | 67 | source, |
| 65 | async () => { | 68 | async () => { |
| 66 | try { | 69 | try { |
| 70 | + // A switched-off module would only answer 403 on every poll. | ||
| 71 | + if (!isEnabled("messages")) return emptyPage<Message>(); | ||
| 67 | return await getMessages("inbox", { limit: 100 }); | 72 | return await getMessages("inbox", { limit: 100 }); |
| 68 | } catch { | 73 | } catch { |
| 69 | return emptyPage<Message>(); | 74 | return emptyPage<Message>(); |
| @@ -80,6 +85,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { | |||
| 80 | source, | 85 | source, |
| 81 | async () => { | 86 | async () => { |
| 82 | try { | 87 | try { |
| 88 | + if (!isEnabled("messages")) return emptyPage<Message>(); | ||
| 83 | return await getMessages("inbox", { read: false, limit: 10 }); | 89 | return await getMessages("inbox", { read: false, limit: 10 }); |
| 84 | } catch { | 90 | } catch { |
| 85 | return emptyPage<Message>(); | 91 | return emptyPage<Message>(); |
| @@ -105,6 +111,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { | |||
| 105 | source, | 111 | source, |
| 106 | async () => { | 112 | async () => { |
| 107 | try { | 113 | try { |
| 114 | + if (!isEnabled("events")) return emptyPage<Event>(); | ||
| 108 | return await getEvents(upcoming()); | 115 | return await getEvents(upcoming()); |
| 109 | } catch { | 116 | } catch { |
| 110 | return emptyPage<Event>(); | 117 | return emptyPage<Event>(); |
| @@ -117,6 +124,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { | |||
| 117 | source, | 124 | source, |
| 118 | async () => { | 125 | async () => { |
| 119 | try { | 126 | try { |
| 127 | + if (!isEnabled("exams")) return emptyPage<Exam>(); | ||
| 120 | return await getExams(upcoming()); | 128 | return await getExams(upcoming()); |
| 121 | } catch { | 129 | } catch { |
| 122 | return emptyPage<Exam>(); | 130 | return emptyPage<Exam>(); |
| @@ -129,6 +137,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { | |||
| 129 | source, | 137 | source, |
| 130 | async () => { | 138 | async () => { |
| 131 | try { | 139 | try { |
| 140 | + if (!isEnabled("appointments")) return emptyPage<Appointment>(); | ||
| 132 | return await getAppointments({ limit: 100 }); | 141 | return await getAppointments({ limit: 100 }); |
| 133 | } catch { | 142 | } catch { |
| 134 | return emptyPage<Appointment>(); | 143 | return emptyPage<Appointment>(); |
| @@ -141,6 +150,7 @@ function createUserFeed(loggedIn: boolean): UserFeed { | |||
| 141 | source, | 150 | source, |
| 142 | async () => { | 151 | async () => { |
| 143 | try { | 152 | try { |
| 153 | + if (!isEnabled("homework")) return emptyPage<Homework>(); | ||
| 144 | return await getHomework(); | 154 | return await getHomework(); |
| 145 | } catch { | 155 | } catch { |
| 146 | return emptyPage<Homework>(); | 156 | return emptyPage<Homework>(); |
| @@ -186,7 +196,8 @@ export function ShellFeedProvider(props: ParentProps) { | |||
| 186 | // the whole feed and builds a fresh one. Children never remount, so the | 196 | // the whole feed and builds a fresh one. Children never remount, so the |
| 187 | // router tree below is untouched. | 197 | // router tree below is untouched. |
| 188 | const userId = createMemo(() => auth.user()?.id ?? null); | 198 | const userId = createMemo(() => auth.user()?.id ?? null); |
| 189 | - const feed = createMemo(() => createUserFeed(userId() !== null)); | 199 | + const modules = useModules(); |
| 200 | + const feed = createMemo(() => createUserFeed(userId() !== null, modules.loading, modules.isEnabled)); | ||
| 190 | 201 | ||
| 191 | // Reactive clock so passed items drop off without a remount. Visibility-aware: | 202 | // Reactive clock so passed items drop off without a remount. Visibility-aware: |
| 192 | // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is | 203 | // no ticks/GETs while the tab is hidden, refetch on tab-back so nothing is |