forge
Explore
Log in

Don't you dare go Hollow

✨ add module and note intelligence workflows

Browse files at this commit

d2570ac8ffcc8f88590fad56a4a9f3fac3e31e2fBurak BoduroğluParent: 6f30785
  • feat
    • ✨ add module and note intelligence workflows
Show full message
feat: ✨ add module and note intelligence workflows

- add module catalog APIs and shared module context

- add course-note RAG retrieval and output deletion flows

- add term archive controls and blueprint status integration

- refine responsive navigation, settings, and note panels

- extend API and navigation test coverage
src/api/__tests__/classes/classes.test.tsmodified+11 -0
@@ -19,6 +19,7 @@ import {
19 patchClassBlueprintByGrade,19 patchClassBlueprintByGrade,
20 deleteClassBlueprintByGrade,20 deleteClassBlueprintByGrade,
21 postClassBlueprintApply,21 postClassBlueprintApply,
22+ getClassBlueprintStatus,
22 } from "../../classes";23 } from "../../classes";
23 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";24 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
24 25
@@ -185,4 +186,14 @@ describe("classes API", () => {
185 expect(init?.method).toBe("POST");186 expect(init?.method).toBe("POST");
186 expect(init?.body).toBeUndefined();187 expect(init?.body).toBeUndefined();
187 });188 });
189+
190+ it("getClassBlueprintStatus GETs /classes/blueprints/:grade/status", async () => {
191+ const mockStatus = { grade: "9/A", courses: ["co1"], matched: 3, sections: [] };
192+ mockFetchSuccess(mockStatus);
193+ const result = await getClassBlueprintStatus("9/A");
194+ expect(result).toEqual(mockStatus);
195+ const [url, init] = lastFetchCall();
196+ expect(url).toBe("/api/classes/blueprints/9%2FA/status");
197+ expect(init?.method).toBe("GET");
198+ });
188 });199 });
src/api/__tests__/course-notes/course-notes.test.tsmodified+24 -1
@@ -9,8 +9,9 @@ import { postCourseNoteFile } from "../../course-notes";
9 import { deleteCourseNoteFileById } from "../../course-notes";9 import { deleteCourseNoteFileById } from "../../course-notes";
10 import { getCourseNoteFileUrl } from "../../course-notes";10 import { getCourseNoteFileUrl } from "../../course-notes";
11 import { getCourseNoteFileBlob } from "../../course-notes";11 import { getCourseNoteFileBlob } from "../../course-notes";
12+import { getCourseNoteRag } from "../../course-notes";
13+import { deleteCourseNoteRagOutput } from "../../course-notes";
12 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";14 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
13-
14 describe("course notes API", () => {15 describe("course notes API", () => {
15 afterEach(() => {16 afterEach(() => {
16 vi.restoreAllMocks();17 vi.restoreAllMocks();
@@ -141,4 +142,26 @@ describe("course notes API", () => {
141 expect(url).toBe("/api/course-notes/cn1/files/f1");142 expect(url).toBe("/api/course-notes/cn1/files/f1");
142 expect(init?.credentials).toBe("same-origin");143 expect(init?.credentials).toBe("same-origin");
143 });144 });
145+
146+ it("getCourseNoteRag calls /course-notes/:id/rag with pagination", async () => {
147+ const mockPage = { items: [{ id: "r1", course_note: "cn1" }], total: 1 };
148+ mockFetchSuccess(mockPage);
149+
150+ const result = await getCourseNoteRag("cn1", { limit: 10 });
151+ expect(result).toEqual({ ...mockPage, limit: null, offset: 0 });
152+
153+ const [url, init] = lastFetchCall();
154+ expect(url).toBe("/api/course-notes/cn1/rag?limit=10");
155+ expect(init?.method).toBe("GET");
156+ });
157+
158+ it("deleteCourseNoteRagOutput calls /course-notes/:id/rag/:outputId", async () => {
159+ mockFetch204();
160+
161+ await deleteCourseNoteRagOutput("cn1", "r1");
162+
163+ const [url, init] = lastFetchCall();
164+ expect(url).toBe("/api/course-notes/cn1/rag/r1");
165+ expect(init?.method).toBe("DELETE");
166+ });
144 });167 });
src/api/__tests__/modules/modules.test.tsadded+37 -0
@@ -0,0 +1,37 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import { getModules } from "../../modules";
3+import { getModulesCatalog } from "../../modules";
4+import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";
5+
6+describe("modules API", () => {
7+ afterEach(() => {
8+ vi.restoreAllMocks();
9+ });
10+
11+ it("getModules calls /modules", async () => {
12+ const mockModules = { enabled: ["courses", "meals"] };
13+ mockFetchSuccess(mockModules);
14+
15+ const result = await getModules();
16+ expect(result).toEqual(mockModules);
17+
18+ const [url, init] = lastFetchCall();
19+ expect(url).toBe("/api/modules");
20+ expect(init?.method).toBe("GET");
21+ });
22+
23+ it("getModulesCatalog calls /modules/catalog", async () => {
24+ const mockCatalog = {
25+ modules: [{ module: "exams", package: "academics", requires: ["courses"] }],
26+ packages: [{ package: "academics", modules: ["exams"] }],
27+ };
28+ mockFetchSuccess(mockCatalog);
29+
30+ const result = await getModulesCatalog();
31+ expect(result).toEqual(mockCatalog);
32+
33+ const [url, init] = lastFetchCall();
34+ expect(url).toBe("/api/modules/catalog");
35+ expect(init?.method).toBe("GET");
36+ });
37+});
src/api/__tests__/terms/terms.test.tsmodified+26 -1
@@ -4,8 +4,9 @@ import { getTermById } from "../../terms";
4 import { postTerm } from "../../terms";4 import { postTerm } from "../../terms";
5 import { patchTermById } from "../../terms";5 import { patchTermById } from "../../terms";
6 import { deleteTermById } from "../../terms";6 import { deleteTermById } from "../../terms";
7+import { postTermArchive } from "../../terms";
8+import { postTermUnarchive } from "../../terms";
7 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";9 import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
8-
9 describe("terms API", () => {10 describe("terms API", () => {
10 afterEach(() => {11 afterEach(() => {
11 vi.restoreAllMocks();12 vi.restoreAllMocks();
@@ -72,4 +73,28 @@ describe("terms API", () => {
72 expect(url).toBe("/api/terms/t1");73 expect(url).toBe("/api/terms/t1");
73 expect(init?.method).toBe("DELETE");74 expect(init?.method).toBe("DELETE");
74 });75 });
76+
77+ it("postTermArchive calls /terms/:id/archive", async () => {
78+ const mockTerm = { id: "t1", archived_at: 1756896000000 };
79+ mockFetchSuccess(mockTerm);
80+
81+ const result = await postTermArchive("t1");
82+ expect(result).toEqual(mockTerm);
83+
84+ const [url, init] = lastFetchCall();
85+ expect(url).toBe("/api/terms/t1/archive");
86+ expect(init?.method).toBe("POST");
87+ });
88+
89+ it("postTermUnarchive calls /terms/:id/unarchive", async () => {
90+ const mockTerm = { id: "t1", archived_at: null };
91+ mockFetchSuccess(mockTerm);
92+
93+ const result = await postTermUnarchive("t1");
94+ expect(result).toEqual(mockTerm);
95+
96+ const [url, init] = lastFetchCall();
97+ expect(url).toBe("/api/terms/t1/unarchive");
98+ expect(init?.method).toBe("POST");
99+ });
75 });100 });
src/api/classes/getClassBlueprintStatus.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { BlueprintStatus } from "../client";
3+
4+export function getClassBlueprintStatus(grade: string, signal?: AbortSignal): Promise<BlueprintStatus> {
5+ return client<BlueprintStatus>(`/classes/blueprints/${encodeURIComponent(grade)}/status`, { signal });
6+}
src/api/classes/index.tsmodified+1 -0
@@ -17,3 +17,4 @@ export * from "./getClassBlueprintByGrade";
17 export * from "./patchClassBlueprintByGrade";17 export * from "./patchClassBlueprintByGrade";
18 export * from "./deleteClassBlueprintByGrade";18 export * from "./deleteClassBlueprintByGrade";
19 export * from "./postClassBlueprintApply";19 export * from "./postClassBlueprintApply";
20+export * from "./getClassBlueprintStatus";
src/api/client/client.tsmodified+12 -0
@@ -166,6 +166,18 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
166 en: "Question bank templates still use this subject. Re-tag or delete them first.",166 en: "Question bank templates still use this subject. Re-tag or delete them first.",
167 tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.",167 tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.",
168 },168 },
169+ "the term is archived — past years are read-only": {
170+ en: "This term is archived. Past years are read-only.",
171+ tr: "Bu dönem arşivli. Geçmiş dönemler salt okunur.",
172+ },
173+ "this course's term is archived — past years are read-only": {
174+ en: "This course's term is archived. Past years are read-only.",
175+ tr: "Bu dersin dönemi arşivli. Geçmiş dönemler salt okunur.",
176+ },
177+ "module disabled": {
178+ en: "This feature is not enabled for your school.",
179+ tr: "Bu özellik okulunuz için etkin değil.",
180+ },
169 "course not found": {181 "course not found": {
170 en: "Course not found.",182 en: "Course not found.",
171 tr: "Ders bulunamadı.",183 tr: "Ders bulunamadı.",
src/api/client/types.tsmodified+55 -0
@@ -113,6 +113,19 @@ export type CourseNote = {
113 content: string;113 content: string;
114 };114 };
115 115
116+/** One AI service output stored against a course note. `payload` is the
117+ * service's own shape — stored and served unread, rendered as JSON. */
118+export type RagOutput = {
119+ id: string;
120+ course_note: string;
121+ course: string;
122+ /** The note's file attachments the output was built from. */
123+ sources: string[];
124+ payload: unknown;
125+ /** When the backend stored it, epoch milliseconds. */
126+ generated_at: number;
127+};
128+
116 export type NoteFile = {129 export type NoteFile = {
117 id: string;130 id: string;
118 name: string;131 name: string;
@@ -120,6 +133,29 @@ export type NoteFile = {
120 size: number;133 size: number;
121 };134 };
122 135
136+/** The caller's school entitlements: every switched-on module, sorted by name. */
137+export type EnabledModules = {
138+ enabled: string[];
139+};
140+
141+export type ModuleCatalogEntry = {
142+ module: string;
143+ package: string;
144+ /** Modules that must be enabled alongside this one. */
145+ requires: string[];
146+};
147+
148+export type ModuleCatalogPackage = {
149+ package: string;
150+ modules: string[];
151+};
152+
153+/** The deployment's whole module catalog — identical for every school. */
154+export type ModuleCatalog = {
155+ modules: ModuleCatalogEntry[];
156+ packages: ModuleCatalogPackage[];
157+};
158+
123 export type EventAudience =159 export type EventAudience =
124 | { kind: "school" }160 | { kind: "school" }
125 | { kind: "role"; role: Role }161 | { kind: "role"; role: Role }
@@ -219,6 +255,8 @@ export type Term = {
219 name: string;255 name: string;
220 starts_at: number;256 starts_at: number;
221 ends_at: number;257 ends_at: number;
258+ /** Archived at, UTC unix-millis; null while the term is open. */
259+ archived_at: number | null;
222 };260 };
223 261
224 export type Enrollment = {262 export type Enrollment = {
@@ -285,6 +323,23 @@ export type BlueprintResult = { blueprint: ClassBlueprint; skipped: BlueprintSki
285 323
286 export type BlueprintApplyResult = { skipped: BlueprintSkip[] };324 export type BlueprintApplyResult = { skipped: BlueprintSkip[] };
287 325
326+/** One section measured against its grade's blueprint. */
327+export type BlueprintSectionStatus = {
328+ class: string;
329+ class_name: string;
330+ /** Template courses the section does not carry; empty when in sync. */
331+ missing: string[];
332+};
333+
334+/** Every section at a grade with the template courses it is missing. */
335+export type BlueprintStatus = {
336+ grade: string;
337+ /** The template every section below is measured against. */
338+ courses: string[];
339+ matched: number;
340+ sections: BlueprintSectionStatus[];
341+};
342+
288 export type CourseSession = {343 export type CourseSession = {
289 id: string;344 id: string;
290 course: string;345 course: string;
src/api/course-notes/deleteCourseNoteRagOutput.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "../client";
2+
3+export function deleteCourseNoteRagOutput(noteId: string, outputId: string): Promise<void> {
4+ return client<void>(`/course-notes/${noteId}/rag/${outputId}`, { method: "DELETE" });
5+}
src/api/course-notes/getCourseNoteRag.tsadded+12 -0
@@ -0,0 +1,12 @@
1+import { client } from "../client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "../client";
3+import type { RagOutput } from "../client";
4+
5+export async function getCourseNoteRag(
6+ noteId: string,
7+ params?: PageParams,
8+ signal?: AbortSignal,
9+): Promise<Page<RagOutput>> {
10+ const data = await client<unknown>(`/course-notes/${noteId}/rag${pageQuery(params)}`, { signal });
11+ return normalizePage<RagOutput>(data);
12+}
src/api/course-notes/index.tsmodified+2 -0
@@ -8,3 +8,5 @@ export * from "./postCourseNoteFile";
8 export * from "./deleteCourseNoteFileById";8 export * from "./deleteCourseNoteFileById";
9 export * from "./getCourseNoteFileUrl";9 export * from "./getCourseNoteFileUrl";
10 export * from "./getCourseNoteFileBlob";10 export * from "./getCourseNoteFileBlob";
11+export * from "./getCourseNoteRag";
12+export * from "./deleteCourseNoteRagOutput";
src/api/modules/getModules.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { EnabledModules } from "../client";
3+
4+export function getModules(signal?: AbortSignal): Promise<EnabledModules> {
5+ return client<EnabledModules>("/modules", { signal });
6+}
src/api/modules/getModulesCatalog.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { ModuleCatalog } from "../client";
3+
4+export function getModulesCatalog(signal?: AbortSignal): Promise<ModuleCatalog> {
5+ return client<ModuleCatalog>("/modules/catalog", { signal });
6+}
src/api/modules/index.tsadded+2 -0
@@ -0,0 +1,2 @@
1+export * from "./getModules";
2+export * from "./getModulesCatalog";
src/api/terms/index.tsmodified+2 -0
@@ -3,3 +3,5 @@ export * from "./getTermById";
3 export * from "./postTerm";3 export * from "./postTerm";
4 export * from "./patchTermById";4 export * from "./patchTermById";
5 export * from "./deleteTermById";5 export * from "./deleteTermById";
6+export * from "./postTermArchive";
7+export * from "./postTermUnarchive";
src/api/terms/postTermArchive.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { Term } from "../client";
3+
4+export function postTermArchive(id: string): Promise<Term> {
5+ return client<Term>(`/terms/${id}/archive`, { method: "POST" });
6+}
src/api/terms/postTermUnarchive.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { Term } from "../client";
3+
4+export function postTermUnarchive(id: string): Promise<Term> {
5+ return client<Term>(`/terms/${id}/unarchive`, { method: "POST" });
6+}
src/components/classes/blueprints-tab.tsxmodified+53 -3
@@ -1,16 +1,17 @@
1 import { Show, createMemo, createResource, createSignal } from "solid-js";1 import { Show, createMemo, createResource, createSignal } from "solid-js";
2 import type { ColumnDef } from "@tanstack/solid-table";2 import type { ColumnDef } from "@tanstack/solid-table";
3-import { deleteClassBlueprintByGrade, getClassBlueprints } from "@/api/classes";3+import { deleteClassBlueprintByGrade, getClassBlueprints, getClassBlueprintStatus } from "@/api/classes";
4 import { getCourses } from "@/api/courses";4 import { getCourses } from "@/api/courses";
5 import { getLimits } from "@/api/limits";5 import { getLimits } from "@/api/limits";
6-import { formatApiError, type BlueprintSkip, type ClassBlueprint } from "@/api/client";6+import { formatApiError, type BlueprintSectionStatus, type BlueprintSkip, type BlueprintStatus, type ClassBlueprint } from "@/api/client";
7 import { BlueprintPanel } from "@/components/classes/blueprint-panel";7 import { BlueprintPanel } from "@/components/classes/blueprint-panel";
8 import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report";8 import { BlueprintSkippedReport } from "@/components/classes/blueprint-skipped-report";
9 import { Alert } from "@/components/ui/alert";9 import { Alert } from "@/components/ui/alert";
10 import { Button } from "@/components/ui/button";10 import { Button } from "@/components/ui/button";
11 import { ConfirmDialog } from "@/components/ui/confirm-dialog";11 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
12 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";12 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
13-import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";13+import { IconClipboardCheck, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
14+import { SidePanel } from "@/components/ui/side-panel";
14 import { TableRowActions } from "@/components/ui/table-row-actions";15 import { TableRowActions } from "@/components/ui/table-row-actions";
15 import { createFlash } from "@/lib/flash";16 import { createFlash } from "@/lib/flash";
16 import { personLabel } from "@/lib/person";17 import { personLabel } from "@/lib/person";
@@ -30,6 +31,7 @@ export function BlueprintsTab(props: {
30 const [deleting, setDeleting] = createSignal<ClassBlueprint | null>(null);31 const [deleting, setDeleting] = createSignal<ClassBlueprint | null>(null);
31 const [skipped, setSkipped] = createSignal<BlueprintSkip[]>([]);32 const [skipped, setSkipped] = createSignal<BlueprintSkip[]>([]);
32 const [reportOpen, setReportOpen] = createSignal(false);33 const [reportOpen, setReportOpen] = createSignal(false);
34+ const [status, setStatus] = createSignal<BlueprintStatus | null>(null);
33 35
34 const enabled = () => (props.active() && props.canManage() ? true : null);36 const enabled = () => (props.active() && props.canManage() ? true : null);
35 const [list, { refetch }] = createResource(enabled, async () =>37 const [list, { refetch }] = createResource(enabled, async () =>
@@ -90,6 +92,11 @@ export function BlueprintsTab(props: {
90 destructive: true,92 destructive: true,
91 onSelect: () => setDeleting(cell.row.original),93 onSelect: () => setDeleting(cell.row.original),
92 },94 },
95+ {
96+ label: t("classBlueprints.status"),
97+ icon: <IconClipboardCheck class="h-4 w-4" />,
98+ onSelect: () => void checkStatus(cell.row.original.grade),
99+ },
93 ]}100 ]}
94 />101 />
95 ),102 ),
@@ -120,6 +127,29 @@ export function BlueprintsTab(props: {
120 setError(formatApiError(err));127 setError(formatApiError(err));
121 }128 }
122 };129 };
130+ const checkStatus = async (grade: string) => {
131+ setError("");
132+ try {
133+ setStatus(await getClassBlueprintStatus(grade));
134+ } catch (err) {
135+ setError(formatApiError(err));
136+ }
137+ };
138+
139+ const statusColumns = createMemo<ColumnDef<BlueprintSectionStatus>[]>(() => [
140+ {
141+ id: "section",
142+ accessorFn: (row) => row.class_name || row.class,
143+ header: t("classBlueprints.statusSection"),
144+ meta: { cellClass: "font-medium" },
145+ },
146+ {
147+ id: "missing",
148+ accessorFn: (row) => row.missing.map(courseTitle).join(", ") || "—",
149+ header: t("classBlueprints.statusMissing"),
150+ meta: { cellClass: "text-muted-foreground" },
151+ },
152+ ]);
123 153
124 return (154 return (
125 <div class="space-y-4">155 <div class="space-y-4">
@@ -186,6 +216,26 @@ export function BlueprintsTab(props: {
186 courseTitle={courseTitle}216 courseTitle={courseTitle}
187 />217 />
188 218
219+ <SidePanel
220+ open={status() != null}
221+ onOpenChange={(open) => !open && setStatus(null)}
222+ title={t("classBlueprints.statusTitle", { grade: status()?.grade ?? "" })}
223+ size="wide"
224+ >
225+ <Show when={status()}>
226+ {(current) => (
227+ <Show
228+ when={current().sections.some((section) => section.missing.length > 0)}
229+ fallback={<p class="text-sm text-muted-foreground">{t("classBlueprints.statusEmpty")}</p>}
230+ >
231+ <DataTable
232+ columns={statusColumns()}
233+ data={current().sections.filter((section) => section.missing.length > 0)}
234+ />
235+ </Show>
236+ )}
237+ </Show>
238+ </SidePanel>
189 <ConfirmDialog239 <ConfirmDialog
190 open={deleting() !== null}240 open={deleting() !== null}
191 onOpenChange={(open) => !open && setDeleting(null)}241 onOpenChange={(open) => !open && setDeleting(null)}
src/components/layout/app-shell.tsxmodified+14 -10
@@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button";
15 import { IconChevronLeft, IconPanelLeft, IconSearch, IconSparkles } from "@/components/ui/icons";15 import { IconChevronLeft, IconPanelLeft, IconSearch, IconSparkles } from "@/components/ui/icons";
16 import { Toaster } from "@/components/ui/toast";16 import { Toaster } from "@/components/ui/toast";
17 import { useAuth } from "@/stores/auth-context";17 import { useAuth } from "@/stores/auth-context";
18+import { useModules } from "@/stores/modules-context";
18 import { ShellFeedProvider } from "@/stores/shell-feed-context";19 import { ShellFeedProvider } from "@/stores/shell-feed-context";
19 import { usePreferences, useT } from "@/stores/preferences-context";20 import { usePreferences, useT } from "@/stores/preferences-context";
20 import { cn } from "@/lib/cn";21 import { cn } from "@/lib/cn";
@@ -26,6 +27,7 @@ export function AppShell(props: ParentProps) {
26 const auth = useAuth();27 const auth = useAuth();
27 const prefs = usePreferences();28 const prefs = usePreferences();
28 const t = useT();29 const t = useT();
30+ const modules = useModules();
29 const navigate = useNavigate();31 const navigate = useNavigate();
30 const [mobileOpen, setMobileOpen] = createSignal(false);32 const [mobileOpen, setMobileOpen] = createSignal(false);
31 const [celebiOpen, setCelebiOpen] = createSignal(false);33 const [celebiOpen, setCelebiOpen] = createSignal(false);
@@ -143,16 +145,18 @@ export function AppShell(props: ParentProps) {
143 <div class="flex shrink-0 items-center justify-end gap-2">145 <div class="flex shrink-0 items-center justify-end gap-2">
144 <ShellMessagesButton />146 <ShellMessagesButton />
145 <NotificationCenter />147 <NotificationCenter />
146- <button148+ <Show when={modules.isEnabled("chatbot")}>
147- type="button"149+ <button
148- class="topbar-ai-control hidden h-9 shrink-0 items-center justify-center gap-2 rounded-md px-3 text-xs font-semibold outline-hidden focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98] sm:flex"150+ type="button"
149- aria-label={t("ai.askCelebi")}151+ class="topbar-ai-control hidden h-9 shrink-0 items-center justify-center gap-2 rounded-md px-3 text-xs font-semibold outline-hidden focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98] sm:flex"
150- title={t("ai.askCelebi")}152+ aria-label={t("ai.askCelebi")}
151- onClick={() => setCelebiOpen(true)}153+ title={t("ai.askCelebi")}
152- >154+ onClick={() => setCelebiOpen(true)}
153- <IconSparkles class="h-4 w-4" />155+ >
154- <span>{t("ai.askCelebi")}</span>156+ <IconSparkles class="h-4 w-4" />
155- </button>157+ <span>{t("ai.askCelebi")}</span>
158+ </button>
159+ </Show>
156 </div>160 </div>
157 </header>161 </header>
158 </Show>162 </Show>
src/components/layout/command-palette.tsxmodified+3 -1
@@ -20,6 +20,7 @@ import {
20 import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items";20 import { HOME_ITEM, visibleNavGroups } from "@/components/layout/nav-items";
21 import { hasMinRole } from "@/lib/roles";21 import { hasMinRole } from "@/lib/roles";
22 import { useAuth } from "@/stores/auth-context";22 import { useAuth } from "@/stores/auth-context";
23+import { useModules } from "@/stores/modules-context";
23 import { usePreferences, useT } from "@/stores/preferences-context";24 import { usePreferences, useT } from "@/stores/preferences-context";
24 import { cn } from "@/lib/cn";25 import { cn } from "@/lib/cn";
25 26
@@ -50,6 +51,7 @@ export function CommandPalette(props: CommandPaletteProps) {
50 const prefs = usePreferences();51 const prefs = usePreferences();
51 const t = useT();52 const t = useT();
52 const navigate = useNavigate();53 const navigate = useNavigate();
54+ const modules = useModules();
53 55
54 const [query, setQuery] = createSignal("");56 const [query, setQuery] = createSignal("");
55 const [selectedIndex, setSelectedIndex] = createSignal(0);57 const [selectedIndex, setSelectedIndex] = createSignal(0);
@@ -200,7 +202,7 @@ export function CommandPalette(props: CommandPaletteProps) {
200 onSelect: () => void navigate({ to: HOME_ITEM.to }),202 onSelect: () => void navigate({ to: HOME_ITEM.to }),
201 });203 });
202 204
203- for (const group of visibleNavGroups(userRole)) {205+ for (const group of visibleNavGroups(userRole, modules.enabled())) {
204 const groupName = t(group.labelKey);206 const groupName = t(group.labelKey);
205 for (const item of group.items) {207 for (const item of group.items) {
206 list.push({208 list.push({
src/components/layout/mobile-nav-sheet.tsxmodified+3 -1
@@ -5,6 +5,7 @@ import { SidebarAccount } from "@/components/layout/sidebar-account";
5 import { IconX } from "@/components/ui/icons";5 import { IconX } from "@/components/ui/icons";
6 import { cn } from "@/lib/cn";6 import { cn } from "@/lib/cn";
7 import { useAuth } from "@/stores/auth-context";7 import { useAuth } from "@/stores/auth-context";
8+import { useModules } from "@/stores/modules-context";
8 import { useShellFeed } from "@/stores/shell-feed-context";9 import { useShellFeed } from "@/stores/shell-feed-context";
9 import { useT } from "@/stores/preferences-context";10 import { useT } from "@/stores/preferences-context";
10 11
@@ -30,11 +31,12 @@ export function MobileNavSheet(props: {
30 const auth = useAuth();31 const auth = useAuth();
31 const t = useT();32 const t = useT();
32 const feed = useShellFeed();33 const feed = useShellFeed();
34+ const modules = useModules();
33 const pathname = useRouterState({ select: (state) => state.location.pathname });35 const pathname = useRouterState({ select: (state) => state.location.pathname });
34 36
35 // The primary destinations are already one tap away in the tab bar, so the37 // The primary destinations are already one tap away in the tab bar, so the
36 // sheet lists everything else.38 // sheet lists everything else.
37- const groups = () => sidebarNavGroups(auth.user()?.role);39+ const groups = () => sidebarNavGroups(auth.user()?.role, modules.enabled());
38 const current = () => routeNavItem(pathname(), auth.user()?.role);40 const current = () => routeNavItem(pathname(), auth.user()?.role);
39 const badgeFor = (item: NavItem) => (item.id === "messages" ? feed.unreadMessages().total : 0);41 const badgeFor = (item: NavItem) => (item.id === "messages" ? feed.unreadMessages().total : 0);
40 42
src/components/layout/mobile-tab-bar.tsxmodified+3 -1
@@ -4,13 +4,15 @@ import { IconMenu } from "@/components/ui/icons";
4 import { primaryNavItems, primaryPathActive } from "@/components/layout/nav-items";4 import { primaryNavItems, primaryPathActive } from "@/components/layout/nav-items";
5 import { cn } from "@/lib/cn";5 import { cn } from "@/lib/cn";
6 import { useAuth } from "@/stores/auth-context";6 import { useAuth } from "@/stores/auth-context";
7+import { useModules } from "@/stores/modules-context";
7 import { useT } from "@/stores/preferences-context";8 import { useT } from "@/stores/preferences-context";
8 9
9 export function MobileTabBar(props: { onMenu: () => void }) {10 export function MobileTabBar(props: { onMenu: () => void }) {
10 const auth = useAuth();11 const auth = useAuth();
11 const t = useT();12 const t = useT();
13+ const modules = useModules();
12 const pathname = useRouterState({ select: (state) => state.location.pathname });14 const pathname = useRouterState({ select: (state) => state.location.pathname });
13- const items = () => primaryNavItems(auth.user()?.role);15+ const items = () => primaryNavItems(auth.user()?.role, modules.enabled());
14 16
15 return (17 return (
16 <nav18 <nav
src/components/layout/nav-items.test.tsmodified+20 -1
@@ -1,4 +1,4 @@
1-import { pathActive, primaryNavItems, primaryPathActive, routeLabelKey, routeNavItem, sidebarNavGroups, visibleNavItems } from "@/components/layout/nav-items";1+import { moduleVisible, pathActive, primaryNavItems, primaryPathActive, routeLabelKey, routeNavItem, sidebarNavGroups, visibleNavItems } from "@/components/layout/nav-items";
2 2
3 test.each([3 test.each([
4 ["student", ["/", "/courses", "/calendar", "/marks"]],4 ["student", ["/", "/courses", "/calendar", "/marks"]],
@@ -97,3 +97,22 @@ test("a page keeps its name for a viewer who may not open it", () => {
97 expect(routeLabelKey("/students", "admin")).toBe("nav.children");97 expect(routeLabelKey("/students", "admin")).toBe("nav.children");
98 expect(routeLabelKey("/students", "parent")).toBe("nav.children");98 expect(routeLabelKey("/students", "parent")).toBe("nav.children");
99 });99 });
100+
101+test("module gate fails open while the entitlement lookup is unknown", () => {
102+ expect(primaryNavItems("student", null).map((item) => item.to)).toEqual(primaryNavItems("student").map((item) => item.to));
103+ expect(primaryNavItems("student", undefined).map((item) => item.to)).toEqual(primaryNavItems("student").map((item) => item.to));
104+});
105+
106+test("module gate hides nests the school did not buy", () => {
107+ const enabled = ["courses", "notes"];
108+ const primary = primaryNavItems("student", enabled).map((item) => item.to);
109+ expect(primary).toContain("/courses");
110+ expect(primary).not.toContain("/marks");
111+ const sidebar = sidebarNavGroups("teacher", enabled).flatMap((group) => group.items.map((item) => item.to));
112+ expect(sidebar).not.toContain("/meals");
113+ expect(sidebar).not.toContain("/messages");
114+});
115+
116+test("ungated entries never drop on module filtering", () => {
117+ expect(moduleVisible({ id: "x", to: "/calendar", labelKey: "nav.calendar", Icon: (() => null) as never }, [])).toBe(true);
118+});
src/components/layout/nav-items.tsmodified+48 -28
@@ -38,6 +38,8 @@ export type NavItem = {
38 maxRole?: Role;38 maxRole?: Role;
39 exactRole?: Role;39 exactRole?: Role;
40 exact?: boolean;40 exact?: boolean;
41+ /** Backend module nest behind this entry; hidden when the school did not buy it. */
42+ module?: string;
41 };43 };
42 44
43 export type NavGroup = {45 export type NavGroup = {
@@ -60,6 +62,7 @@ const CLASSES_ITEM: NavItem = {
60 to: "/courses",62 to: "/courses",
61 labelKey: "nav.classes",63 labelKey: "nav.classes",
62 Icon: IconBook,64 Icon: IconBook,
65+ module: "courses",
63 };66 };
64 67
65 const CALENDAR_ITEM: NavItem = {68 const CALENDAR_ITEM: NavItem = {
@@ -83,6 +86,7 @@ const PROGRESS_ITEM: NavItem = {
83 labelKey: "nav.marks",86 labelKey: "nav.marks",
84 Icon: IconChart,87 Icon: IconChart,
85 exactRole: "student",88 exactRole: "student",
89+ module: "marks",
86 };90 };
87 91
88 const MEALS_ITEM: NavItem = {92 const MEALS_ITEM: NavItem = {
@@ -90,6 +94,7 @@ const MEALS_ITEM: NavItem = {
90 to: "/meals",94 to: "/meals",
91 labelKey: "nav.meals",95 labelKey: "nav.meals",
92 Icon: IconUtensils,96 Icon: IconUtensils,
97+ module: "meals",
93 };98 };
94 99
95 const PRIMARY_BY_ROLE: Record<Role, NavItem[]> = {100 const PRIMARY_BY_ROLE: Record<Role, NavItem[]> = {
@@ -109,10 +114,10 @@ const NAV_GROUPS: NavGroup[] = [
109 Icon: IconSchool,114 Icon: IconSchool,
110 items: [115 items: [
111 CLASSES_ITEM,116 CLASSES_ITEM,
112- { id: "homework", to: "/homework", labelKey: "nav.homework", Icon: IconHomework },117+ { id: "homework", to: "/homework", labelKey: "nav.homework", Icon: IconHomework, module: "homework" },
113- { id: "exams", to: "/exams", labelKey: "nav.exams", Icon: IconExam },118+ { id: "exams", to: "/exams", labelKey: "nav.exams", Icon: IconExam, module: "exams" },
114- { id: "question-bank", to: "/question-bank", labelKey: "nav.questionBank", Icon: IconArchive, minRole: "teacher" },119+ { id: "question-bank", to: "/question-bank", labelKey: "nav.questionBank", Icon: IconArchive, minRole: "teacher", module: "bank_questions" },
115- { id: "marks", to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student" },120+ { id: "marks", to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student", module: "marks" },
116 ],121 ],
117 },122 },
118 {123 {
@@ -120,9 +125,9 @@ const NAV_GROUPS: NavGroup[] = [
120 labelKey: "nav.group.planning",125 labelKey: "nav.group.planning",
121 Icon: IconCalendarDays,126 Icon: IconCalendarDays,
122 items: [127 items: [
123- { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendar },128+ { id: "events", to: "/events", labelKey: "nav.events", Icon: IconCalendar, module: "events" },
124 CALENDAR_ITEM,129 CALENDAR_ITEM,
125- { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock },130+ { id: "appointments", to: "/appointments", labelKey: "nav.appointments", Icon: IconClock, module: "appointments" },
126 ],131 ],
127 },132 },
128 {133 {
@@ -130,10 +135,10 @@ const NAV_GROUPS: NavGroup[] = [
130 labelKey: "nav.group.workspace",135 labelKey: "nav.group.workspace",
131 Icon: IconNote,136 Icon: IconNote,
132 items: [137 items: [
133- { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote },138+ { id: "notes", to: "/notes", labelKey: "nav.notes", Icon: IconNote, module: "notes" },
134- { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, minRole: "student" },139+ { id: "whiteboards", to: "/whiteboards", labelKey: "nav.whiteboards", Icon: IconEdit, minRole: "student", module: "boards" },
135- { id: "pomodoro", to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student" },140+ { id: "pomodoro", to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student", module: "pomodoro" },
136- { id: "work", to: "/work", labelKey: "nav.work", Icon: IconBriefcase, minRole: "teacher", maxRole: "manager" },141+ { id: "work", to: "/work", labelKey: "nav.work", Icon: IconBriefcase, minRole: "teacher", maxRole: "manager", module: "work" },
137 ],142 ],
138 },143 },
139 {144 {
@@ -142,10 +147,10 @@ const NAV_GROUPS: NavGroup[] = [
142 Icon: IconReportAnalytics,147 Icon: IconReportAnalytics,
143 items: [148 items: [
144 CHILDREN_ITEM,149 CHILDREN_ITEM,
145- { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconUsers, minRole: "teacher" },150+ { id: "class-groups", to: "/management/classes", labelKey: "nav.classGroups", Icon: IconUsers, minRole: "teacher", module: "classes" },
146- { id: "student-marks", to: "/management/student-marks", labelKey: "nav.studentMarks", Icon: IconChart, minRole: "teacher" },151+ { id: "student-marks", to: "/management/student-marks", labelKey: "nav.studentMarks", Icon: IconChart, minRole: "teacher", module: "marks" },
147- { id: "student-attendance", to: "/management/student-attendance", labelKey: "nav.studentAttendance", Icon: IconClipboardCheck, minRole: "teacher" },152+ { id: "student-attendance", to: "/management/student-attendance", labelKey: "nav.studentAttendance", Icon: IconClipboardCheck, minRole: "teacher", module: "attendance" },
148- { id: "student-pomodoro", to: "/management/pomodoros", labelKey: "nav.studentPomodoro", Icon: IconClock, minRole: "teacher" },153+ { id: "student-pomodoro", to: "/management/pomodoros", labelKey: "nav.studentPomodoro", Icon: IconClock, minRole: "teacher", module: "pomodoro" },
149 ],154 ],
150 },155 },
151 {156 {
@@ -154,7 +159,7 @@ const NAV_GROUPS: NavGroup[] = [
154 Icon: IconGuide,159 Icon: IconGuide,
155 items: [160 items: [
156 MEALS_ITEM,161 MEALS_ITEM,
157- { id: "payment-statement", to: "/payments", labelKey: "nav.paymentStatement", Icon: IconChart, maxRole: "student" },162+ { id: "payment-statement", to: "/payments", labelKey: "nav.paymentStatement", Icon: IconChart, maxRole: "student", module: "payments" },
158 ],163 ],
159 },164 },
160 {165 {
@@ -162,8 +167,8 @@ const NAV_GROUPS: NavGroup[] = [
162 labelKey: "nav.group.community",167 labelKey: "nav.group.community",
163 Icon: IconGlobe,168 Icon: IconGlobe,
164 items: [169 items: [
165- { id: "messages", to: "/messages", labelKey: "nav.messages", Icon: IconMessage },170+ { id: "messages", to: "/messages", labelKey: "nav.messages", Icon: IconMessage, module: "messages" },
166- { id: "questions", to: "/questions", labelKey: "nav.questions", Icon: IconHelpCircle },171+ { id: "questions", to: "/questions", labelKey: "nav.questions", Icon: IconHelpCircle, module: "questions" },
167 ],172 ],
168 },173 },
169 {174 {
@@ -171,10 +176,10 @@ const NAV_GROUPS: NavGroup[] = [
171 labelKey: "nav.group.school",176 labelKey: "nav.group.school",
172 Icon: IconGrid,177 Icon: IconGrid,
173 items: [178 items: [
174- { id: "staff-work", to: "/management/staff-work", labelKey: "nav.staffWork", Icon: IconBriefcase, minRole: "manager" },179+ { id: "staff-work", to: "/management/staff-work", labelKey: "nav.staffWork", Icon: IconBriefcase, minRole: "manager", module: "work" },
175 { id: "settings", to: "/management/settings", labelKey: "nav.settings", Icon: IconSettings, minRole: "manager" },180 { id: "settings", to: "/management/settings", labelKey: "nav.settings", Icon: IconSettings, minRole: "manager" },
176 { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendarDays, minRole: "manager" },181 { id: "terms", to: "/management/terms", labelKey: "nav.terms", Icon: IconCalendarDays, minRole: "manager" },
177- { id: "payments", to: "/management/payments", labelKey: "nav.payments", Icon: IconReportAnalytics, minRole: "manager" },182+ { id: "payments", to: "/management/payments", labelKey: "nav.payments", Icon: IconReportAnalytics, minRole: "manager", module: "payments" },
178 { id: "users", to: "/admin/users", labelKey: "nav.users", Icon: IconUserCog, minRole: "admin" },183 { id: "users", to: "/admin/users", labelKey: "nav.users", Icon: IconUserCog, minRole: "admin" },
179 ],184 ],
180 },185 },
@@ -187,25 +192,40 @@ function itemVisible(item: NavItem, role: Role | undefined) {
187 return role !== "parent" || ["/", "/calendar", "/appointments", "/meals", "/messages"].includes(item.to);192 return role !== "parent" || ["/", "/calendar", "/appointments", "/meals", "/messages"].includes(item.to);
188 }193 }
189 194
190-export function primaryNavItems(role: Role | undefined): NavItem[] {195+/**
191- return role ? PRIMARY_BY_ROLE[role] : [];196+ * The school's entitlement gate. Null/undefined means "unknown" (still
197+ * loading, logged out, or the lookup failed) and shows everything — a modules
198+ * outage must never blank the shell; the backend still 403s the nest itself.
199+ */
200+export function moduleVisible(item: NavItem, enabled: readonly string[] | null | undefined): boolean {
201+ if (enabled == null) return true;
202+ if (item.module == null) return true;
203+ return enabled.includes(item.module);
204+}
205+
206+export function primaryNavItems(role: Role | undefined, enabled?: readonly string[] | null): NavItem[] {
207+ if (!role) return [];
208+ return PRIMARY_BY_ROLE[role].filter((item) => moduleVisible(item, enabled));
192 }209 }
193 210
194-export function visibleNavGroups(role: Role | undefined): NavGroup[] {211+export function visibleNavGroups(role: Role | undefined, enabled?: readonly string[] | null): NavGroup[] {
195 return NAV_GROUPS212 return NAV_GROUPS
196- .map((group) => ({ ...group, items: group.items.filter((item) => itemVisible(item, role)) }))213+ .map((group) => ({
214+ ...group,
215+ items: group.items.filter((item) => itemVisible(item, role) && moduleVisible(item, enabled)),
216+ }))
197 .filter((group) => group.items.length > 0);217 .filter((group) => group.items.length > 0);
198 }218 }
199 219
200-export function sidebarNavGroups(role: Role | undefined): NavGroup[] {220+export function sidebarNavGroups(role: Role | undefined, enabled?: readonly string[] | null): NavGroup[] {
201- const primaryPaths = new Set(primaryNavItems(role).map((item) => item.to));221+ const primaryPaths = new Set(primaryNavItems(role, enabled).map((item) => item.to));
202- return visibleNavGroups(role)222+ return visibleNavGroups(role, enabled)
203 .map((group) => ({ ...group, items: group.items.filter((item) => !primaryPaths.has(item.to)) }))223 .map((group) => ({ ...group, items: group.items.filter((item) => !primaryPaths.has(item.to)) }))
204 .filter((group) => group.items.length > 0);224 .filter((group) => group.items.length > 0);
205 }225 }
206 226
207-export function visibleNavItems(role: Role | undefined): NavItem[] {227+export function visibleNavItems(role: Role | undefined, enabled?: readonly string[] | null): NavItem[] {
208- const items = [HOME_ITEM, ...visibleNavGroups(role).flatMap((group) => group.items)];228+ const items = [HOME_ITEM, ...visibleNavGroups(role, enabled).flatMap((group) => group.items)];
209 return items.filter((item, index) => items.findIndex((candidate) => candidate.to === item.to) === index);229 return items.filter((item, index) => items.findIndex((candidate) => candidate.to === item.to) === index);
210 }230 }
211 231
src/components/layout/side-nav.tsxmodified+4 -2
@@ -5,6 +5,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSepara
5 import { IconChevronRight } from "@/components/ui/icons";5 import { IconChevronRight } from "@/components/ui/icons";
6 import { cn } from "@/lib/cn";6 import { cn } from "@/lib/cn";
7 import { useAuth } from "@/stores/auth-context";7 import { useAuth } from "@/stores/auth-context";
8+import { useModules } from "@/stores/modules-context";
8 import { useShellFeed } from "@/stores/shell-feed-context";9 import { useShellFeed } from "@/stores/shell-feed-context";
9 import { useT } from "@/stores/preferences-context";10 import { useT } from "@/stores/preferences-context";
10 11
@@ -12,11 +13,12 @@ export function SideNav(props: { onNavigate?: () => void; collapsed?: boolean })
12 const auth = useAuth();13 const auth = useAuth();
13 const t = useT();14 const t = useT();
14 const feed = useShellFeed();15 const feed = useShellFeed();
16+ const modules = useModules();
15 const navigate = useNavigate();17 const navigate = useNavigate();
16 const pathname = useRouterState({ select: (state) => state.location.pathname });18 const pathname = useRouterState({ select: (state) => state.location.pathname });
17 19
18- const primary = () => primaryNavItems(auth.user()?.role);20+ const primary = () => primaryNavItems(auth.user()?.role, modules.enabled());
19- const groups = () => sidebarNavGroups(auth.user()?.role);21+ const groups = () => sidebarNavGroups(auth.user()?.role, modules.enabled());
20 const current = () => routeNavItem(pathname(), auth.user()?.role);22 const current = () => routeNavItem(pathname(), auth.user()?.role);
21 const unread = () => feed.unreadMessages().total;23 const unread = () => feed.unreadMessages().total;
22 const badgeFor = (item: NavItem) => (item.id === "messages" ? unread() : 0);24 const badgeFor = (item: NavItem) => (item.id === "messages" ? unread() : 0);
src/components/notes/note-reader-panel.tsxmodified+4 -0
@@ -2,6 +2,7 @@ import { Show } from "solid-js";
2 import type { Note } from "@/api/client";2 import type { Note } from "@/api/client";
3 import type { NoteFileSource } from "@/lib/note-source";3 import type { NoteFileSource } from "@/lib/note-source";
4 import { NoteFilesPanel } from "@/components/notes/note-files-panel";4 import { NoteFilesPanel } from "@/components/notes/note-files-panel";
5+import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel";
5 import { SidePanel } from "@/components/ui/side-panel";6 import { SidePanel } from "@/components/ui/side-panel";
6 import { useT } from "@/stores/preferences-context";7 import { useT } from "@/stores/preferences-context";
7 8
@@ -37,6 +38,9 @@ export function NoteReaderPanel(props: {
37 </div>38 </div>
38 </article>39 </article>
39 <NoteFilesPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} />40 <NoteFilesPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} />
41+ <Show when={props.source.listRagOutputs}>
42+ <RagOutputsPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} />
43+ </Show>
40 </div>44 </div>
41 )}45 )}
42 </Show>46 </Show>
src/components/notes/rag-outputs-panel.tsxadded+106 -0
@@ -0,0 +1,106 @@
1+import { For, Show, Suspense, createResource, createSignal } from "solid-js";
2+import { formatApiError } from "@/api/client";
3+import type { RagOutput } from "@/api/client";
4+import type { NoteFileSource } from "@/lib/note-source";
5+import { Alert } from "@/components/ui/alert";
6+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
7+import { PageSpinner } from "@/components/ui/page-spinner";
8+import { TableRowActions } from "@/components/ui/table-row-actions";
9+import { createFlash } from "@/lib/flash";
10+import { formatDateTime } from "@/lib/format";
11+import { usePreferences, useT } from "@/stores/preferences-context";
12+import { IconTrash } from "@/components/ui/icons";
13+
14+const RAG_PAGE_SIZE = 10;
15+
16+export function RagOutputsPanel(props: {
17+ noteId: string;
18+ active: boolean;
19+ source: NoteFileSource;
20+ /** Delete control is teacher-only; readers see the list. Defaults to true. */
21+ canManage?: boolean;
22+}) {
23+ const t = useT();
24+ const { locale } = usePreferences();
25+ const [error, setError] = createSignal("");
26+ const [flash, setFlash] = createFlash();
27+ const [deleteTarget, setDeleteTarget] = createSignal<RagOutput | null>(null);
28+
29+ const [list, { refetch }] = createResource(
30+ () => (props.active && props.source.listRagOutputs ? props.noteId : null),
31+ async (noteId) => props.source.listRagOutputs!(noteId, { limit: RAG_PAGE_SIZE }),
32+ );
33+
34+ const outputs = () => list()?.items ?? [];
35+
36+ const remove = async () => {
37+ const target = deleteTarget();
38+ if (!target || !props.source.deleteRagOutput) return;
39+ setError("");
40+ try {
41+ await props.source.deleteRagOutput(props.noteId, target.id);
42+ await refetch();
43+ setFlash(t("common.deleted"));
44+ } catch (err) {
45+ setError(formatApiError(err));
46+ } finally {
47+ setDeleteTarget(null);
48+ }
49+ };
50+
51+ return (
52+ <section class="space-y-3 rounded-lg border border-border/80 bg-card p-4 shadow-xs dark:border-white/8">
53+ <h3 class="text-sm font-semibold">{t("courseNotes.ragTitle")}</h3>
54+ <Show when={flash()}>
55+ <Alert variant="success">{flash()}</Alert>
56+ </Show>
57+ <Show when={error()}>
58+ <Alert variant="destructive">{error()}</Alert>
59+ </Show>
60+ <Suspense fallback={<PageSpinner />}>
61+ <Show when={list.error}>
62+ <Alert variant="destructive">{formatApiError(list.error)}</Alert>
63+ </Show>
64+ <Show when={outputs().length > 0} fallback={<p class="text-sm text-muted-foreground">{t("courseNotes.ragEmpty")}</p>}>
65+ <ul class="space-y-3">
66+ <For each={outputs()}>
67+ {(output) => (
68+ <li class="space-y-1.5 rounded-lg border border-border/60 p-3">
69+ <div class="flex items-center gap-2">
70+ <span class="mono text-xs text-muted-foreground">
71+ {formatDateTime(output.generated_at, locale())}
72+ </span>
73+ <span class="ml-auto">
74+ <Show when={props.canManage !== false && props.source.deleteRagOutput}>
75+ <TableRowActions
76+ label={t("common.actions")}
77+ actions={[
78+ {
79+ label: t("common.delete"),
80+ icon: <IconTrash class="h-4 w-4" />,
81+ destructive: true,
82+ onSelect: () => setDeleteTarget(output),
83+ },
84+ ]}
85+ />
86+ </Show>
87+ </span>
88+ </div>
89+ <pre class="overflow-x-auto whitespace-pre-wrap text-xs leading-5">{JSON.stringify(output.payload, null, 2)}</pre>
90+ </li>
91+ )}
92+ </For>
93+ </ul>
94+ </Show>
95+ </Suspense>
96+ <ConfirmDialog
97+ open={deleteTarget() != null}
98+ onOpenChange={(open) => !open && setDeleteTarget(null)}
99+ title={t("confirm.deleteTitle")}
100+ variant="destructive"
101+ summary={deleteTarget() ? formatDateTime(deleteTarget()?.generated_at ?? 0, locale()) : ""}
102+ onConfirm={() => void remove()}
103+ />
104+ </section>
105+ );
106+}
src/i18n/messages.tsmodified+36 -0
@@ -84,6 +84,11 @@ export type MessageKey =
84 | "classBlueprints.saved"84 | "classBlueprints.saved"
85 | "classBlueprints.delete"85 | "classBlueprints.delete"
86 | "classBlueprints.deleteConfirm"86 | "classBlueprints.deleteConfirm"
87+ | "classBlueprints.status"
88+ | "classBlueprints.statusTitle"
89+ | "classBlueprints.statusEmpty"
90+ | "classBlueprints.statusSection"
91+ | "classBlueprints.statusMissing"
87 | "classBlueprints.deleted"92 | "classBlueprints.deleted"
88 | "classBlueprints.apply"93 | "classBlueprints.apply"
89 | "classBlueprints.applyHint"94 | "classBlueprints.applyHint"
@@ -540,6 +545,8 @@ export type MessageKey =
540 | "courseNotes.add"545 | "courseNotes.add"
541 | "courseNotes.empty"546 | "courseNotes.empty"
542 | "courseNotes.emptyManageHint"547 | "courseNotes.emptyManageHint"
548+ | "courseNotes.ragTitle"
549+ | "courseNotes.ragEmpty"
543 | "notes.title"550 | "notes.title"
544 | "notes.subtitle"551 | "notes.subtitle"
545 | "notes.new"552 | "notes.new"
@@ -1159,6 +1166,8 @@ export type MessageKey =
1159 | "settings.mealSlotNameInvalid"1166 | "settings.mealSlotNameInvalid"
1160 | "settings.aiPolicy"1167 | "settings.aiPolicy"
1161 | "settings.aiPolicyHelp"1168 | "settings.aiPolicyHelp"
1169+ | "settings.modules"
1170+ | "settings.modulesHelp"
1162 | "settings.chatHistory"1171 | "settings.chatHistory"
1163 | "settings.chatThreads"1172 | "settings.chatThreads"
1164 | "settings.chatMessage"1173 | "settings.chatMessage"
@@ -1365,6 +1374,9 @@ export type MessageKey =
1365 | "terms.term"1374 | "terms.term"
1366 | "terms.unassigned"1375 | "terms.unassigned"
1367 | "terms.dateRequired"1376 | "terms.dateRequired"
1377+ | "terms.archive"
1378+ | "terms.unarchive"
1379+ | "terms.archived"
1368 | "sessions.title"1380 | "sessions.title"
1369 | "sessions.item"1381 | "sessions.item"
1370 | "sessions.subtitle"1382 | "sessions.subtitle"
@@ -1619,6 +1631,11 @@ const en: Dict = {
1619 "classBlueprints.deleteConfirm":1631 "classBlueprints.deleteConfirm":
1620 "Delete the blueprint for grade {grade}? The courses it attached are detached from every class at this grade. Hand-attached courses stay.",1632 "Delete the blueprint for grade {grade}? The courses it attached are detached from every class at this grade. Hand-attached courses stay.",
1621 "classBlueprints.deleted": "Blueprint deleted.",1633 "classBlueprints.deleted": "Blueprint deleted.",
1634+ "classBlueprints.status": "Check sync",
1635+ "classBlueprints.statusTitle": "Sync status for grade {grade}",
1636+ "classBlueprints.statusEmpty": "Every section at this grade carries the full template.",
1637+ "classBlueprints.statusSection": "Section",
1638+ "classBlueprints.statusMissing": "Missing courses",
1622 "classBlueprints.apply": "Apply blueprint",1639 "classBlueprints.apply": "Apply blueprint",
1623 "classBlueprints.applyHint": "Attaches this grade's blueprint courses to this class.",1640 "classBlueprints.applyHint": "Attaches this grade's blueprint courses to this class.",
1624 "classBlueprints.applyNoGrade": "Assign a grade to this class first.",1641 "classBlueprints.applyNoGrade": "Assign a grade to this class first.",
@@ -2077,6 +2094,8 @@ const en: Dict = {
2077 "courseNotes.add": "Add note",2094 "courseNotes.add": "Add note",
2078 "courseNotes.empty": "No notes on this course yet.",2095 "courseNotes.empty": "No notes on this course yet.",
2079 "courseNotes.emptyManageHint": "Write a note the whole class can read, and attach files to it.",2096 "courseNotes.emptyManageHint": "Write a note the whole class can read, and attach files to it.",
2097+ "courseNotes.ragTitle": "AI outputs",
2098+ "courseNotes.ragEmpty": "No AI outputs on this note yet.",
2080 "notes.title": "Notebook",2099 "notes.title": "Notebook",
2081 "notes.subtitle": "Your private notebook for class ideas and reminders.",2100 "notes.subtitle": "Your private notebook for class ideas and reminders.",
2082 "notes.new": "New note",2101 "notes.new": "New note",
@@ -2786,6 +2805,8 @@ const en: Dict = {
2786 "settings.mealSlotNameInvalid": "A meal slot name can't contain / \\ ? # or %.",2805 "settings.mealSlotNameInvalid": "A meal slot name can't contain / \\ ? # or %.",
2787 "settings.aiPolicy": "AI policy",2806 "settings.aiPolicy": "AI policy",
2788 "settings.aiPolicyHelp": "Limits for conversation context, threads, and message length.",2807 "settings.aiPolicyHelp": "Limits for conversation context, threads, and message length.",
2808+ "settings.modules": "Modules",
2809+ "settings.modulesHelp": "Features your school has switched on, grouped by package. Switched-off features stay hidden in navigation.",
2789 "settings.chatHistory": "History turns",2810 "settings.chatHistory": "History turns",
2790 "settings.chatThreads": "Maximum threads",2811 "settings.chatThreads": "Maximum threads",
2791 "settings.chatMessage": "Message length",2812 "settings.chatMessage": "Message length",
@@ -2992,6 +3013,9 @@ const en: Dict = {
2992 "terms.term": "Term",3013 "terms.term": "Term",
2993 "terms.unassigned": "Unassigned",3014 "terms.unassigned": "Unassigned",
2994 "terms.dateRequired": "Start and end dates are required.",3015 "terms.dateRequired": "Start and end dates are required.",
3016+ "terms.archive": "Archive term",
3017+ "terms.unarchive": "Reopen term",
3018+ "terms.archived": "Archived",
2995 "sessions.title": "Lesson sessions",3019 "sessions.title": "Lesson sessions",
2996 "sessions.item": "Session",3020 "sessions.item": "Session",
2997 "sessions.subtitle": "Schedule lesson sessions and record roll call for each class.",3021 "sessions.subtitle": "Schedule lesson sessions and record roll call for each class.",
@@ -3162,6 +3186,11 @@ const tr: Dict = {
3162 "classBlueprints.deleteConfirm":3186 "classBlueprints.deleteConfirm":
3163 "{grade} seviyesinin şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.",3187 "{grade} seviyesinin şablonu silinsin mi? Şablonun eklediği dersler bu seviyedeki her şubeden çıkarılır. Elle eklenen dersler kalır.",
3164 "classBlueprints.deleted": "Şablon silindi.",3188 "classBlueprints.deleted": "Şablon silindi.",
3189+ "classBlueprints.status": "Eşitleme kontrolü",
3190+ "classBlueprints.statusTitle": "{grade} seviyesi eşitleme durumu",
3191+ "classBlueprints.statusEmpty": "Bu seviyedeki her şube şablonun tamamını taşıyor.",
3192+ "classBlueprints.statusSection": "Şube",
3193+ "classBlueprints.statusMissing": "Eksik dersler",
3165 "classBlueprints.apply": "Şablonu uygula",3194 "classBlueprints.apply": "Şablonu uygula",
3166 "classBlueprints.applyHint": "Bu seviyenin şablon derslerini bu şubeye ekler.",3195 "classBlueprints.applyHint": "Bu seviyenin şablon derslerini bu şubeye ekler.",
3167 "classBlueprints.applyNoGrade": "Önce bu şubeye bir seviye ata.",3196 "classBlueprints.applyNoGrade": "Önce bu şubeye bir seviye ata.",
@@ -3620,6 +3649,8 @@ const tr: Dict = {
3620 "courseNotes.add": "Not ekle",3649 "courseNotes.add": "Not ekle",
3621 "courseNotes.empty": "Bu derse ait henüz not yok.",3650 "courseNotes.empty": "Bu derse ait henüz not yok.",
3622 "courseNotes.emptyManageHint": "Tüm sınıfın okuyabileceği bir not yazın, dosya da ekleyebilirsiniz.",3651 "courseNotes.emptyManageHint": "Tüm sınıfın okuyabileceği bir not yazın, dosya da ekleyebilirsiniz.",
3652+ "courseNotes.ragTitle": "YZ çıktıları",
3653+ "courseNotes.ragEmpty": "Bu notta henüz YZ çıktısı yok.",
3623 "notes.title": "Defter",3654 "notes.title": "Defter",
3624 "notes.subtitle": "Ders fikirleriniz ve hatırlatmalarınız için özel defteriniz.",3655 "notes.subtitle": "Ders fikirleriniz ve hatırlatmalarınız için özel defteriniz.",
3625 "notes.new": "Yeni not",3656 "notes.new": "Yeni not",
@@ -4329,6 +4360,8 @@ const tr: Dict = {
4329 "settings.mealSlotNameInvalid": "Öğün adı / \\ ? # veya % içeremez.",4360 "settings.mealSlotNameInvalid": "Öğün adı / \\ ? # veya % içeremez.",
4330 "settings.aiPolicy": "Yapay zekâ politikası",4361 "settings.aiPolicy": "Yapay zekâ politikası",
4331 "settings.aiPolicyHelp": "Konuşma bağlamı, konu sayısı ve mesaj uzunluğu sınırları.",4362 "settings.aiPolicyHelp": "Konuşma bağlamı, konu sayısı ve mesaj uzunluğu sınırları.",
4363+ "settings.modules": "Modüller",
4364+ "settings.modulesHelp": "Okulunuzda açık olan özellikler, pakete göre gruplu. Kapalı özellikler gezgin menüde gizlenir.",
4332 "settings.chatHistory": "Geçmiş turu",4365 "settings.chatHistory": "Geçmiş turu",
4333 "settings.chatThreads": "En fazla konu",4366 "settings.chatThreads": "En fazla konu",
4334 "settings.chatMessage": "Mesaj uzunluğu",4367 "settings.chatMessage": "Mesaj uzunluğu",
@@ -4535,6 +4568,9 @@ const tr: Dict = {
4535 "terms.term": "Dönem",4568 "terms.term": "Dönem",
4536 "terms.unassigned": "Atanmamış",4569 "terms.unassigned": "Atanmamış",
4537 "terms.dateRequired": "Başlangıç ve bitiş tarihi gerekli.",4570 "terms.dateRequired": "Başlangıç ve bitiş tarihi gerekli.",
4571+ "terms.archive": "Dönemi arşivle",
4572+ "terms.unarchive": "Dönemi yeniden aç",
4573+ "terms.archived": "Arşivli",
4538 "sessions.title": "Ders oturumları",4574 "sessions.title": "Ders oturumları",
4539 "sessions.item": "Oturum",4575 "sessions.item": "Oturum",
4540 "sessions.subtitle": "Ders oturumlarını planlayın ve her ders için yoklama alın.",4576 "sessions.subtitle": "Ders oturumlarını planlayın ve her ders için yoklama alın.",
src/lib/note-source.tsmodified+7 -2
@@ -1,5 +1,5 @@
1-import type { NoteFile, Page, PageParams } from "@/api/client";1+import type { NoteFile, Page, PageParams, RagOutput } from "@/api/client";
2-import { deleteCourseNoteFileById, getCourseNoteFileBlob, getCourseNoteFileUrl, getCourseNoteFiles, postCourseNoteFile } from "@/api/course-notes";2+import { deleteCourseNoteFileById, deleteCourseNoteRagOutput, getCourseNoteFileBlob, getCourseNoteFileUrl, getCourseNoteFiles, getCourseNoteRag, postCourseNoteFile } from "@/api/course-notes";
3 import { deleteNoteFileById, getNoteFileBlob, getNoteFileUrl, getNoteFiles, postNoteFile } from "@/api/notes";3 import { deleteNoteFileById, getNoteFileBlob, getNoteFileUrl, getNoteFiles, postNoteFile } from "@/api/notes";
4 4
5 /**5 /**
@@ -16,6 +16,9 @@ export type NoteFileSource = {
16 deleteFile: (noteId: string, fileId: string) => Promise<void>;16 deleteFile: (noteId: string, fileId: string) => Promise<void>;
17 fileUrl: (noteId: string, fileId: string) => string;17 fileUrl: (noteId: string, fileId: string) => string;
18 fileBlob: (noteId: string, fileId: string, signal?: AbortSignal) => Promise<Blob>;18 fileBlob: (noteId: string, fileId: string, signal?: AbortSignal) => Promise<Blob>;
19+ /** AI outputs hanging off the note — only course notes have them. */
20+ listRagOutputs?: (noteId: string, params?: PageParams, signal?: AbortSignal) => Promise<Page<RagOutput>>;
21+ deleteRagOutput?: (noteId: string, outputId: string) => Promise<void>;
19 };22 };
20 23
21 export const personalNoteFiles: NoteFileSource = {24 export const personalNoteFiles: NoteFileSource = {
@@ -34,4 +37,6 @@ export const courseNoteFiles: NoteFileSource = {
34 deleteFile: deleteCourseNoteFileById,37 deleteFile: deleteCourseNoteFileById,
35 fileUrl: getCourseNoteFileUrl,38 fileUrl: getCourseNoteFileUrl,
36 fileBlob: getCourseNoteFileBlob,39 fileBlob: getCourseNoteFileBlob,
40+ listRagOutputs: getCourseNoteRag,
41+ deleteRagOutput: deleteCourseNoteRagOutput,
37 };42 };
src/pages/settings-page.tsxmodified+39 -1
@@ -1,7 +1,8 @@
1-import { Index, Show, Suspense, createEffect, createResource, createSignal } from "solid-js";1+import { For, Index, Show, Suspense, createEffect, createResource, createSignal } from "solid-js";
2 import { getSettings } from "@/api/settings";2 import { getSettings } from "@/api/settings";
3 import { patchSettings } from "@/api/settings";3 import { patchSettings } from "@/api/settings";
4 import { getLimits } from "@/api/limits";4 import { getLimits } from "@/api/limits";
5+import { getModules, getModulesCatalog } from "@/api/modules";
5 import type { ExamKindSetting, GradeBand, MealSlot, SchoolSettings } from "@/api/client";6 import type { ExamKindSetting, GradeBand, MealSlot, SchoolSettings } from "@/api/client";
6 import { formatApiError } from "@/api/client";7 import { formatApiError } from "@/api/client";
7 import { RouteGuard } from "@/components/layout/route-guard";8 import { RouteGuard } from "@/components/layout/route-guard";
@@ -49,6 +50,10 @@ export default function SettingsPage() {
49 function SettingsContent() {50 function SettingsContent() {
50 const t = useT();51 const t = useT();
51 const [settings, { refetch, mutate }] = createResource(() => getSettings());52 const [settings, { refetch, mutate }] = createResource(() => getSettings());
53+ const [modulesInfo, { refetch: refetchModules }] = createResource(async () => {
54+ const [mine, catalog] = await Promise.all([getModules(), getModulesCatalog()]);
55+ return { mine, catalog };
56+ });
52 const [examKinds, setExamKinds] = createSignal<ExamKindSetting[]>([]);57 const [examKinds, setExamKinds] = createSignal<ExamKindSetting[]>([]);
53 const [attendanceStatuses, setAttendanceStatuses] = createSignal<string[]>([]);58 const [attendanceStatuses, setAttendanceStatuses] = createSignal<string[]>([]);
54 const [gradeBands, setGradeBands] = createSignal<GradeBand[]>([]);59 const [gradeBands, setGradeBands] = createSignal<GradeBand[]>([]);
@@ -588,6 +593,39 @@ function SettingsContent() {
588 </div>593 </div>
589 </div>594 </div>
590 </section>595 </section>
596+ <section class="data-shell space-y-4 p-4">
597+ <div>
598+ <h2 class="text-base font-semibold">{t("settings.modules")}</h2>
599+ <p class="mt-1 text-sm text-muted-foreground">{t("settings.modulesHelp")}</p>
600+ </div>
601+ <Suspense fallback={<PageSpinner />}>
602+ <Show when={modulesInfo.error}>
603+ <ErrorAlert message={formatApiError(modulesInfo.error)} onRetry={() => void refetchModules()} />
604+ </Show>
605+ <Show when={modulesInfo()}>
606+ {(info) => (
607+ <div class="space-y-3">
608+ <For each={info().catalog.packages}>
609+ {(pkg) => (
610+ <div class="space-y-1.5">
611+ <h3 class="text-sm font-medium capitalize">{pkg.package}</h3>
612+ <div class="flex flex-wrap gap-1.5">
613+ <For each={pkg.modules}>
614+ {(name) => (
615+ <Badge variant={info().mine.enabled.includes(name) ? "secondary" : "outline"} class="rounded-full">
616+ {name}
617+ </Badge>
618+ )}
619+ </For>
620+ </div>
621+ </div>
622+ )}
623+ </For>
624+ </div>
625+ )}
626+ </Show>
627+ </Suspense>
628+ </section>
591 </Show>629 </Show>
592 </TabsContent>630 </TabsContent>
593 </Suspense>631 </Suspense>
src/pages/terms-page.tsxmodified+38 -1
@@ -4,18 +4,21 @@ import { deleteTermById } from "@/api/terms";
4 import { getTerms } from "@/api/terms";4 import { getTerms } from "@/api/terms";
5 import { patchTermById } from "@/api/terms";5 import { patchTermById } from "@/api/terms";
6 import { postTerm } from "@/api/terms";6 import { postTerm } from "@/api/terms";
7+import { postTermArchive } from "@/api/terms";
8+import { postTermUnarchive } from "@/api/terms";
7 import { formatApiError } from "@/api/client";9 import { formatApiError } from "@/api/client";
8 import type { Term } from "@/api/client";10 import type { Term } from "@/api/client";
9 import { RouteGuard } from "@/components/layout/route-guard";11 import { RouteGuard } from "@/components/layout/route-guard";
10 import { PageHeader } from "@/components/layout/page-header";12 import { PageHeader } from "@/components/layout/page-header";
11 import { Alert } from "@/components/ui/alert";13 import { Alert } from "@/components/ui/alert";
14+import { Badge } from "@/components/ui/badge";
12 import { Button } from "@/components/ui/button";15 import { Button } from "@/components/ui/button";
13 import { ConfirmDialog } from "@/components/ui/confirm-dialog";16 import { ConfirmDialog } from "@/components/ui/confirm-dialog";
14 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";17 import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
15 import { EmptyState } from "@/components/ui/empty-state";18 import { EmptyState } from "@/components/ui/empty-state";
16 import { DatePicker } from "@/components/ui/date-picker";19 import { DatePicker } from "@/components/ui/date-picker";
17 import { ErrorAlert } from "@/components/ui/error-alert";20 import { ErrorAlert } from "@/components/ui/error-alert";
18-import { IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";21+import { IconArchive, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
19 import { Input } from "@/components/ui/input";22 import { Input } from "@/components/ui/input";
20 import { Label } from "@/components/ui/label";23 import { Label } from "@/components/ui/label";
21 import { SidePanel } from "@/components/ui/side-panel";24 import { SidePanel } from "@/components/ui/side-panel";
@@ -82,6 +85,15 @@ function TermsContent() {
82 header: t("events.ends"),85 header: t("events.ends"),
83 cell: (cell) => <span class="mono text-sm">{formatDateTime(cell.row.original.ends_at, locale())}</span>,86 cell: (cell) => <span class="mono text-sm">{formatDateTime(cell.row.original.ends_at, locale())}</span>,
84 },87 },
88+ {
89+ accessorKey: "archived_at",
90+ header: t("terms.archived"),
91+ cell: (cell) => (
92+ <Show when={cell.row.original.archived_at != null} fallback={<span class="text-muted-foreground">—</span>}>
93+ <Badge variant="secondary" class="rounded-full">{t("terms.archived")}</Badge>
94+ </Show>
95+ ),
96+ },
85 {97 {
86 id: "actions",98 id: "actions",
87 header: t("common.actions"),99 header: t("common.actions"),
@@ -95,6 +107,17 @@ function TermsContent() {
95 icon: <IconEdit class="h-4 w-4" />,107 icon: <IconEdit class="h-4 w-4" />,
96 onSelect: () => startEdit(cell.row.original),108 onSelect: () => startEdit(cell.row.original),
97 },109 },
110+ cell.row.original.archived_at == null
111+ ? {
112+ label: t("terms.archive"),
113+ icon: <IconArchive class="h-4 w-4" />,
114+ onSelect: () => void toggleArchive(cell.row.original, true),
115+ }
116+ : {
117+ label: t("terms.unarchive"),
118+ icon: <IconArchive class="h-4 w-4" />,
119+ onSelect: () => void toggleArchive(cell.row.original, false),
120+ },
98 {121 {
99 label: t("common.delete"),122 label: t("common.delete"),
100 icon: <IconTrash class="h-4 w-4" />,123 icon: <IconTrash class="h-4 w-4" />,
@@ -128,6 +151,20 @@ function TermsContent() {
128 setError("");151 setError("");
129 setPanelOpen(true);152 setPanelOpen(true);
130 };153 };
154+ const toggleArchive = async (term: Term, archive: boolean) => {
155+ setError("");
156+ try {
157+ if (archive) {
158+ await postTermArchive(term.id);
159+ } else {
160+ await postTermUnarchive(term.id);
161+ }
162+ await refetch();
163+ setFlash(t("common.saved"));
164+ } catch (err) {
165+ setError(formatApiError(err));
166+ }
167+ };
131 168
132 const save = async (e: SubmitEvent) => {169 const save = async (e: SubmitEvent) => {
133 e.preventDefault();170 e.preventDefault();
src/routes/router.tsxmodified+6 -3
@@ -9,6 +9,7 @@ import { Suspense, createRenderEffect, createRoot, lazy, type Component } from "
9 import { AppShell } from "@/components/layout/app-shell";9 import { AppShell } from "@/components/layout/app-shell";
10 import { PageSpinner } from "@/components/ui/page-spinner";10 import { PageSpinner } from "@/components/ui/page-spinner";
11 import { AuthProvider } from "@/stores/auth-context";11 import { AuthProvider } from "@/stores/auth-context";
12+import { ModulesProvider } from "@/stores/modules-context";
12 import { PreferencesProvider } from "@/stores/preferences-context";13 import { PreferencesProvider } from "@/stores/preferences-context";
13 14
14 function lazyRoute(loader: () => Promise<{ default: Component }>): Component {15 function lazyRoute(loader: () => Promise<{ default: Component }>): Component {
@@ -70,9 +71,11 @@ function RootComponent() {
70 return (71 return (
71 <PreferencesProvider>72 <PreferencesProvider>
72 <AuthProvider>73 <AuthProvider>
73- <AppShell>74+ <ModulesProvider>
74- <Outlet />75+ <AppShell>
75- </AppShell>76+ <Outlet />
77+ </AppShell>
78+ </ModulesProvider>
76 </AuthProvider>79 </AuthProvider>
77 </PreferencesProvider>80 </PreferencesProvider>
78 );81 );
src/stores/modules-context.tsxadded+61 -0
@@ -0,0 +1,61 @@
1+import {
2+ type Accessor,
3+ type ParentProps,
4+ createContext,
5+ createMemo,
6+ createResource,
7+ useContext,
8+} from "solid-js";
9+import { getModules } from "@/api/modules";
10+import { useAuth } from "@/stores/auth-context";
11+
12+type ModulesContextValue = {
13+ /**
14+ * The school's switched-on modules, sorted by name. Null while logged out,
15+ * still loading, or failed — every consumer treats null as "unknown" and
16+ * shows everything (fail open), so a modules outage never blanks the shell.
17+ */
18+ enabled: Accessor<string[] | null>;
19+ /** Fail-open membership test over `enabled`. */
20+ isEnabled: (module: string) => boolean;
21+ refresh: () => void;
22+};
23+
24+const ModulesContext = createContext<ModulesContextValue>();
25+
26+export function ModulesProvider(props: ParentProps) {
27+ const auth = useAuth();
28+ // Keyed on the account id: switching account refetches. While logged out
29+ // the source is null and the resource keeps its seeded null — the shell
30+ // shows no nav without a role anyway, so nothing stale can render.
31+ const userId = createMemo(() => auth.user()?.id ?? null);
32+ const [modules, { refetch }] = createResource(
33+ userId,
34+ async (id) => {
35+ if (id === null) return null;
36+ try {
37+ return (await getModules()).enabled;
38+ } catch {
39+ return null;
40+ }
41+ },
42+ { initialValue: null },
43+ );
44+
45+ const value: ModulesContextValue = {
46+ enabled: () => modules(),
47+ isEnabled: (module: string) => {
48+ const enabled = modules();
49+ return enabled === null || enabled.includes(module);
50+ },
51+ refresh: () => void refetch(),
52+ };
53+
54+ return <ModulesContext.Provider value={value}>{props.children}</ModulesContext.Provider>;
55+}
56+
57+export function useModules(): ModulesContextValue {
58+ const context = useContext(ModulesContext);
59+ if (!context) throw new Error("useModules must be used inside ModulesProvider");
60+ return context;
61+}