forge
Explore
Log in

Don't you dare go Hollow

merge: the run-level school report with exports

Browse files at this commit

666a37ee158035f701fa231acc5aa7cdf7d598e0Ahmet Kaan GümüşParent: fa83bf59895664
src/components/insights/insight-run-report.test.tsxadded+295 -0
@@ -0,0 +1,295 @@
1+import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";
2+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+import type { InsightRun, PersonRef, StudentInsight } from "@/api/client";
4+import { InsightRunsTable } from "@/components/insights/insight-runs-table";
5+import { buildRunReportMarkdown, buildRunReportModel } from "@/lib/insight-run-report";
6+import { PreferencesProvider } from "@/stores/preferences-context";
7+
8+const insightsApi = vi.hoisted(() => ({ getInsightByUserId: vi.fn() }));
9+const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() }));
10+
11+vi.mock("@/api/insights", () => insightsApi);
12+vi.mock("@/api/users", () => usersApi);
13+// Kobalte's dropdown chrome is not what this test is about: flatten it to one
14+// plain button per action so the report path can be driven in jsdom.
15+vi.mock("@/components/ui/table-row-actions", () => ({
16+ TableRowActions: (props: { actions: { label: string; onSelect: () => void }[] }) => (
17+ <>
18+ {props.actions.map((action) => (
19+ <button type="button" onClick={() => action.onSelect()}>
20+ {action.label}
21+ </button>
22+ ))}
23+ </>
24+ ),
25+}));
26+
27+const DAY_A = "2026-09-18";
28+const DAY_B = "2026-09-17";
29+
30+const RUN_A: InsightRun = {
31+ run_day: DAY_A,
32+ started_at: Date.UTC(2026, 8, 18, 9, 37, 59),
33+ finished_at: Date.UTC(2026, 8, 18, 9, 37, 59),
34+ duration_ms: 532,
35+ status: "ok",
36+ students_total: 16,
37+ students_ok: 16,
38+ students_failed: 0,
39+ students_skipped: 0,
40+ rows_written: 16,
41+ budget_exceeded: false,
42+ budget_ms: 60_000,
43+ pending_students: [],
44+ failed_modules: [],
45+};
46+
47+const RUN_B: InsightRun = {
48+ ...RUN_A,
49+ run_day: DAY_B,
50+ status: "partial",
51+ students_ok: 9,
52+ students_failed: 1,
53+ students_skipped: 6,
54+ rows_written: 9,
55+ pending_students: ["s2"],
56+ failed_modules: ["attendance"],
57+};
58+
59+const ROSTER: PersonRef[] = [
60+ { id: "s1", username: "arda.gunes", display_name: "Arda Güneş" },
61+ { id: "s2", username: "ayca.sahin", display_name: "Ayça Şahin" },
62+ { id: "s3", username: "burak.polat", display_name: "Burak Polat" },
63+];
64+
65+const COMPUTED_AT = Date.UTC(2026, 8, 18, 9, 37, 59);
66+
67+const INSIGHT_S1: StudentInsight = {
68+ user_id: "s1",
69+ summary: {
70+ marks: {
71+ classes: ["class-1"],
72+ courses: {
73+ "course-math": { n_marks: 0, average: null },
74+ "course-physics": { n_marks: 2, average: 71 },
75+ },
76+ },
77+ attendance: {
78+ overall: { n_obs: 4, rate: 0.75, present: 3, absent: 1 },
79+ limitation: "Devam oranı dönem başından bugüne kümülatiftir.",
80+ },
81+ study: { recent_28d: { n_stints: 0 }, limitation: "Çalışma oturumlarının ders bağı yoktur." },
82+ submission: { overall: { n: 5 }, limitation: "Teslim saati bilinmediği için erteleme yorumu yapılmaz." },
83+ confidence: "exploratory",
84+ computed_at: COMPUTED_AT,
85+ retain_until: COMPUTED_AT + 86_400_000,
86+ },
87+ attention: [
88+ {
89+ trigger: "mark_trend",
90+ fact: "Fizik notu son üç sınavda düşüyor.",
91+ course: "Fizik",
92+ window_from: COMPUTED_AT - 30 * 86_400_000,
93+ window_to: COMPUTED_AT,
94+ evidence: { delta: -12 },
95+ },
96+ ],
97+ cards: [
98+ {
99+ id: "c1",
100+ product: "O2",
101+ rule_id: "physics_slip",
102+ rule_version: 1,
103+ audience_role: "teacher",
104+ evidence: { limitation: "İki ölçüm arası fark tek başına eğilim sayılmaz." },
105+ confidence: "exploratory",
106+ created_at: COMPUTED_AT,
107+ expires_at: COMPUTED_AT + 86_400_000,
108+ },
109+ ],
110+ segments: [],
111+};
112+
113+const INSIGHT_S2: StudentInsight = {
114+ user_id: "s2",
115+ summary: {
116+ marks: { classes: [], courses: { "course-math": { n_marks: 0, average: null } } },
117+ attendance: { overall: { n_obs: 0, rate: null }, limitation: "Devam ucu yalnız sayaç döndürüyor." },
118+ study: { recent_28d: { n_stints: 0 } },
119+ submission: { overall: { n: 0 } },
120+ confidence: "none",
121+ computed_at: COMPUTED_AT,
122+ retain_until: COMPUTED_AT + 86_400_000,
123+ },
124+ attention: [],
125+ cards: [],
126+ segments: [],
127+};
128+
129+const INSIGHT_S3: StudentInsight = { user_id: "s3", summary: null, attention: [], cards: [], segments: [] };
130+
131+const panel = () => within(document.querySelector(".side-panel-body") as HTMLElement);
132+
133+async function openReport(runDay: string) {
134+ render(() => (
135+ <PreferencesProvider>
136+ <InsightRunsTable runs={[RUN_A, RUN_B]} />
137+ </PreferencesProvider>
138+ ));
139+ const row = screen.getByText(runDay).closest("tr") as HTMLElement;
140+ fireEvent.click(within(row).getByRole("button", { name: "Raporu görüntüle" }));
141+ await waitFor(() => expect(screen.getByText(`Çalıştırma günü ${runDay}`)).toBeTruthy());
142+}
143+
144+describe("InsightRunReport", () => {
145+ beforeEach(() => {
146+ localStorage.setItem("hezarfen.locale", "tr");
147+ usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 });
148+ insightsApi.getInsightByUserId.mockImplementation((userId: string) => {
149+ if (userId === "s1") return Promise.resolve(INSIGHT_S1);
150+ if (userId === "s2") return Promise.resolve(INSIGHT_S2);
151+ return Promise.resolve(INSIGHT_S3);
152+ });
153+ });
154+
155+ afterEach(() => {
156+ cleanup();
157+ localStorage.clear();
158+ vi.restoreAllMocks();
159+ vi.clearAllMocks();
160+ });
161+
162+ it("opens that run's report from the row action", async () => {
163+ await openReport(DAY_B);
164+
165+ expect(screen.getByText(`Çalıştırma günü ${DAY_B}`)).toBeTruthy();
166+ // RUN_B's own ledger row, not RUN_A's: its pending student is named in the report.
167+ await waitFor(() => expect(panel().getByText(/1 öğrenci sıradaki çalıştırmaya kaldı: Ayça Şahin/)).toBeTruthy());
168+ });
169+
170+ it("renders the run's counters from the ledger row", async () => {
171+ await openReport(DAY_A);
172+
173+ await waitFor(() => expect(panel().getByText("İşlenen öğrenci")).toBeTruthy());
174+ expect(panel().getByText("16/16")).toBeTruthy();
175+ expect(panel().getByText("Yazılan kayıt")).toBeTruthy();
176+ expect(panel().getByText("16")).toBeTruthy();
177+ expect(panel().getByText("532 ms")).toBeTruthy();
178+ expect(panel().getByText("Sorun yok")).toBeTruthy();
179+ });
180+
181+ it("reads every student's signals through the roster and per-student doors", async () => {
182+ await openReport(DAY_A);
183+
184+ expect(usersApi.getUserSearch).toHaveBeenCalledWith("", undefined, "student", { limit: 200, offset: 0 });
185+ await waitFor(() => expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s1"));
186+ expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s2");
187+ expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s3");
188+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
189+ // The headline numbers come from the answers, not from the fixture's prose.
190+ expect(panel().getByText("71,0 (1/2)")).toBeTruthy();
191+ expect(panel().getByText("75%")).toBeTruthy();
192+ expect(panel().getByText("Sinyalleri yüklenen öğrenci: 3/3")).toBeTruthy();
193+ });
194+
195+ it("states veri yok where a module produced nothing instead of a blank panel", async () => {
196+ await openReport(DAY_A);
197+
198+ await waitFor(() => expect(panel().getByText(/Çalışma: 0\/3 öğrencide veri var/)).toBeTruthy());
199+ expect(panel().getByText(/Çalışma: 0\/3 öğrencide veri var → veri yok/)).toBeTruthy();
200+ expect(panel().getByText(/Notlar: 1\/3 öğrencide veri var/)).toBeTruthy();
201+ expect(panel().getByText("Çalışma oturumlarının ders bağı yoktur.")).toBeTruthy();
202+ // The student rows carry the same honesty.
203+ expect(panel().getAllByText("veri yok").length).toBeGreaterThan(0);
204+ expect(panel().getByText("Bu öğrenci için henüz analiz hesaplanmamış.")).toBeTruthy();
205+ });
206+
207+ it("opens the student's own analysis drawer from a report row", async () => {
208+ await openReport(DAY_A);
209+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
210+
211+ const row = panel().getByText("Arda Güneş").closest("tr") as HTMLElement;
212+ fireEvent.click(within(row).getByRole("button", { name: "Öğrenci analizini aç" }));
213+
214+ // The drawer is the shared InsightDetail component, rendering the stored fact.
215+ await waitFor(() => expect(screen.getByText("Fizik notu son üç sınavda düşüyor.")).toBeTruthy());
216+ expect(screen.getAllByText("Öneriler").length).toBeGreaterThan(0);
217+ });
218+
219+ it("copies the same document it shows to the clipboard", async () => {
220+ const writeText = vi.fn().mockResolvedValue(undefined);
221+ Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true });
222+ await openReport(DAY_A);
223+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
224+
225+ fireEvent.click(panel().getByRole("button", { name: "Kopyala" }));
226+
227+ await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
228+ const markdown = writeText.mock.calls[0][0] as string;
229+ expect(markdown).toContain("16/16");
230+ expect(markdown).toContain("16");
231+ expect(markdown).toContain("Arda Güneş");
232+ expect(markdown).toContain("71,0 (1/2)");
233+ expect(markdown).toContain("Çalışma: 0/3 öğrencide veri var → veri yok");
234+ expect(markdown).toContain("Bu öğrenci için henüz analiz hesaplanmamış.");
235+ });
236+
237+ it("downloads the .md built from the same content", async () => {
238+ const blobs: Blob[] = [];
239+ Object.defineProperty(URL, "createObjectURL", {
240+ configurable: true,
241+ writable: true,
242+ value: (blob: Blob) => {
243+ blobs.push(blob);
244+ return "blob:run-report";
245+ },
246+ });
247+ Object.defineProperty(URL, "revokeObjectURL", { configurable: true, writable: true, value: vi.fn() });
248+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
249+ await openReport(DAY_A);
250+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
251+
252+ fireEvent.click(panel().getByRole("button", { name: "İndir (.md)" }));
253+
254+ await waitFor(() => expect(click).toHaveBeenCalledTimes(1));
255+ expect(blobs).toHaveLength(1);
256+ const markdown = await blobs[0].text();
257+ expect(markdown).toContain("16/16");
258+ expect(markdown).toContain("Ayça Şahin");
259+ });
260+
261+ it("prints only the report document", async () => {
262+ const print = vi.fn();
263+ Object.defineProperty(window, "print", { configurable: true, writable: true, value: print });
264+ await openReport(DAY_A);
265+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
266+
267+ const printRoot = document.querySelector(".insight-report-print-root") as HTMLElement;
268+ expect(printRoot.textContent).toContain("Arda Güneş");
269+ expect(document.body.classList.contains("insight-report-printing")).toBe(true);
270+
271+ fireEvent.click(panel().getByRole("button", { name: "Yazdır / PDF" }));
272+ expect(print).toHaveBeenCalledTimes(1);
273+ });
274+
275+ it("builds the same Markdown without a DOM", () => {
276+ const model = buildRunReportModel({
277+ run: RUN_A,
278+ roster: ROSTER,
279+ insights: { s1: INSIGHT_S1, s2: INSIGHT_S2, s3: INSIGHT_S3 },
280+ errors: {},
281+ coverageTotal: ROSTER.length,
282+ rosterError: null,
283+ });
284+
285+ const markdown = buildRunReportMarkdown(model, "tr");
286+
287+ expect(markdown).toContain("16/16");
288+ expect(markdown).toContain("Yazılan kayıt");
289+ expect(markdown).toContain("| Arda Güneş |");
290+ expect(markdown).toContain("71,0 (1/2)");
291+ expect(markdown).toContain("75%");
292+ expect(markdown).toContain("Çalışma: 0/3 öğrencide veri var → veri yok");
293+ expect(markdown).toContain("```json");
294+ });
295+});
src/components/insights/insight-run-report.tsxadded+459 -0
@@ -0,0 +1,459 @@
1+import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";
2+import { Portal } from "solid-js/web";
3+import { getInsightByUserId } from "@/api/insights";
4+import { getUserSearch } from "@/api/users";
5+import { formatApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client";
6+import { InsightDetail } from "@/components/insights/insight-detail";
7+import { Button } from "@/components/ui/button";
8+import { EmptyInline } from "@/components/ui/empty-inline";
9+import { IconCopy, IconDownload, IconFileText } from "@/components/ui/icons";
10+import { SidePanel } from "@/components/ui/side-panel";
11+import { runReportText, type RunReportKey } from "@/i18n/insights-run-report";
12+import { formatDateTime } from "@/lib/format";
13+import {
14+ buildRunReportMarkdown,
15+ buildRunReportModel,
16+ formatRunDuration,
17+ moduleLabel,
18+ runReportFileName,
19+ runReportStatusLabel,
20+ studentAttendanceText,
21+ studentMarksText,
22+ studentStatusText,
23+ type RunReportModel,
24+} from "@/lib/insight-run-report";
25+import { personLabel } from "@/lib/person";
26+import { createFlash } from "@/lib/flash";
27+import { usePreferences } from "@/stores/preferences-context";
28+
29+/** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */
30+const ROSTER_PAGE = 200;
31+/**
32+ * Signals are read one student at a time — the backend serves no school-level
33+ * aggregate — so the report reads a bounded first slice on open and offers the
34+ * rest behind a control that names the count. Never a silent cap.
35+ */
36+const AUTO_SIGNAL_LIMIT = 60;
37+const SIGNAL_CONCURRENCY = 6;
38+const PRINT_BODY_CLASS = "insight-report-printing";
39+const PRINT_ROOT_CLASS = "insight-report-print-root";
40+
41+/**
42+ * Print shows the report and nothing else: the panel is a modal outside
43+ * `#root`, so the app chrome is hidden by body class rather than by targeting
44+ * the app root. Kept as one inline sheet so the report ships without touching
45+ * a global stylesheet.
46+ */
47+const PRINT_STYLES = `
48+.${PRINT_ROOT_CLASS} { display: none; }
49+@media print {
50+ /* Hide everything that does not CONTAIN the print document: the app root and
51+ every other portal, including the panel this report is shown in. Hiding
52+ \`body > *:not(.${PRINT_ROOT_CLASS})\` would hide the portal's own wrapper
53+ div (the class sits on its child), which prints a blank page. */
54+ body.${PRINT_BODY_CLASS} > *:not(:has(.${PRINT_ROOT_CLASS})) { display: none !important; }
55+ .${PRINT_ROOT_CLASS} { display: block !important; padding: 0 10mm; color: #000 !important; background: #fff !important; }
56+ .${PRINT_ROOT_CLASS} * { color: #000 !important; box-shadow: none !important; background: transparent !important; }
57+ .${PRINT_ROOT_CLASS} h1 { font-size: 15pt; }
58+ .${PRINT_ROOT_CLASS} h2 { font-size: 12pt; margin: 6mm 0 2mm; border-bottom: 1px solid #888; }
59+ .${PRINT_ROOT_CLASS} table { width: 100%; border-collapse: collapse; font-size: 9pt; }
60+ .${PRINT_ROOT_CLASS} th, .${PRINT_ROOT_CLASS} td { border: 1px solid #999; padding: 1.5mm; text-align: left; }
61+ .${PRINT_ROOT_CLASS} dl { display: grid; grid-template-columns: 1fr 1fr; gap: 1mm 6mm; }
62+ .${PRINT_ROOT_CLASS} details { display: none; }
63+}
64+`;
65+
66+/**
67+ * The run's report as a document. One component renders the panel, the print
68+ * sheet and (through the same model) the Markdown, so the export cannot drift
69+ * from what is on screen. `onOpenStudent` is the only interactive affordance
70+ * and it is absent from the print instance.
71+ */
72+function ReportDocument(props: {
73+ model: RunReportModel;
74+ /** True while signals are still being read: the school picture is not final. */
75+ loading?: boolean;
76+ onOpenStudent?: (id: string) => void;
77+}) {
78+ const prefs = usePreferences();
79+ const tx = (key: RunReportKey, vars?: Record<string, string | number>) =>
80+ runReportText(prefs.locale(), key, vars);
81+ const metrics = createMemo(() => {
82+ const run = props.model.run;
83+ return [
84+ { key: "runDay", label: tx("runDay"), value: run.run_day },
85+ { key: "status", label: tx("status"), value: runReportStatusLabel(prefs.locale(), run.status) },
86+ { key: "startedAt", label: tx("startedAt"), value: formatDateTime(run.started_at, prefs.locale()) },
87+ { key: "finishedAt", label: tx("finishedAt"), value: formatDateTime(run.finished_at, prefs.locale()) },
88+ {
89+ key: "processed",
90+ label: tx("processed"),
91+ value: `${run.students_ok}/${run.students_total}`,
92+ },
93+ { key: "skipped", label: tx("skipped"), value: String(run.students_skipped) },
94+ { key: "failed", label: tx("failed"), value: String(run.students_failed) },
95+ { key: "rowsWritten", label: tx("rowsWritten"), value: String(run.rows_written) },
96+ { key: "duration", label: tx("duration"), value: formatRunDuration(run.duration_ms, prefs.locale()) },
97+ {
98+ key: "budget",
99+ label: tx("budget"),
100+ value: `${run.budget_exceeded ? tx("budgetExceeded") : tx("budgetWithin")} (${formatRunDuration(run.budget_ms, prefs.locale())})`,
101+ },
102+ ];
103+ });
104+
105+ return (
106+ <div class="space-y-5">
107+ <header class="space-y-1">
108+ <h2 class="text-base font-semibold text-text-strong">{tx("title")}</h2>
109+ <p class="text-sm text-muted-foreground">{tx("subtitle")}</p>
110+ </header>
111+
112+ <section class="space-y-3">
113+ <h3 class="text-sm font-semibold text-text-strong">{tx("runSection")}</h3>
114+ <dl class="grid gap-2 sm:grid-cols-2">
115+ <For each={metrics()}>
116+ {(metric) => (
117+ <div class="detail-metric-card">
118+ <dt class="text-xs text-muted-foreground">{metric.label}</dt>
119+ <dd class="mono mt-1 text-sm font-medium">{metric.value}</dd>
120+ </div>
121+ )}
122+ </For>
123+ </dl>
124+ <Show when={props.model.run.pending_students.length + props.model.run.failed_modules.length > 0}>
125+ <ul class="space-y-1 text-xs text-warning">
126+ <Show when={props.model.run.pending_students.length > 0}>
127+ <li>
128+ {tx("pendingStudents", { count: props.model.run.pending_students.length })}
129+ {props.model.pending.length > 0 ? `: ${props.model.pending.map((row) => row.name ?? "—").join(", ")}` : ""}
130+ </li>
131+ </Show>
132+ <Show when={props.model.run.failed_modules.length > 0}>
133+ <li>{tx("failedModules", { modules: props.model.run.failed_modules.join(", ") })}</li>
134+ </Show>
135+ </ul>
136+ </Show>
137+ <Show when={props.model.run.pending_students.length + props.model.run.failed_modules.length === 0}>
138+ <p class="text-xs text-muted-foreground">{tx("noIssues")}</p>
139+ </Show>
140+ </section>
141+
142+ <section class="space-y-3 border-t border-border-hairline pt-5">
143+ <h3 class="text-sm font-semibold text-text-strong">{tx("schoolSection")}</h3>
144+ <Show
145+ when={props.loading}
146+ fallback={
147+ <>
148+ <p class="text-sm">
149+ {tx("coverage", { loaded: props.model.coverage.loaded, total: props.model.coverage.total })}
150+ </p>
151+ <p class="text-xs text-muted-foreground">{tx("coverageNote")}</p>
152+ <ul class="space-y-1.5 text-sm">
153+ <For each={props.model.modules}>
154+ {(module) => (
155+ <li>
156+ <span class={module.with_data === 0 ? "text-warning" : undefined}>
157+ {tx("moduleCovered", {
158+ label: moduleLabel(prefs.locale(), module.id),
159+ withData: module.with_data,
160+ total: props.model.coverage.loaded,
161+ })}
162+ {module.with_data === 0 ? ` → ${tx("noData")}` : ""}
163+ </span>
164+ <Show when={module.limitation}>
165+ {(limitation) => <p class="mt-0.5 text-xs text-muted-foreground">{limitation()}</p>}
166+ </Show>
167+ </li>
168+ )}
169+ </For>
170+ </ul>
171+ <Show when={props.model.modules.every((module) => module.with_data === 0)}>
172+ <p class="text-xs text-muted-foreground">{tx("modulesEmpty")}</p>
173+ </Show>
174+ <p class="text-sm">
175+ {tx("attention")}: <span class="mono tabular-nums">{props.model.totals.attention}</span> · {tx("cards")}:{" "}
176+ <span class="mono tabular-nums">{props.model.totals.cards}</span> · {tx("segments")}:{" "}
177+ <span class="mono tabular-nums">{props.model.totals.segments}</span>
178+ </p>
179+ <Show when={props.model.roster_error}>
180+ {(message) => <p class="text-xs text-destructive">{tx("rosterFailed", { message: message() })}</p>}
181+ </Show>
182+ <Show when={props.model.coverage.loaded === 0 && !props.model.roster_error}>
183+ <p class="text-xs text-muted-foreground">{tx("rosterEmpty")}</p>
184+ </Show>
185+ </>
186+ }
187+ >
188+ <p class="text-sm text-muted-foreground">{tx("loadingSignals")}</p>
189+ </Show>
190+ </section>
191+
192+ <section class="space-y-3 border-t border-border-hairline pt-5">
193+ <h3 class="text-sm font-semibold text-text-strong">
194+ {tx("studentsSection")} ({props.model.coverage.loaded}/{props.model.coverage.total})
195+ </h3>
196+ <div class="overflow-x-auto">
197+ <table class="w-full text-sm">
198+ <thead class="text-left text-xs text-muted-foreground">
199+ <tr>
200+ <th class="py-2 pr-3">{tx("student")}</th>
201+ <th class="py-2 pr-3">{tx("status")}</th>
202+ <th class="py-2 pr-3">{tx("confidence")}</th>
203+ <th class="py-2 pr-3 text-right">{tx("attention")}</th>
204+ <th class="py-2 pr-3 text-right">{tx("cards")}</th>
205+ <th class="py-2 pr-3">{tx("marksAverage")}</th>
206+ <th class="py-2 pr-3">{tx("attendanceRate")}</th>
207+ <th class="py-2 pr-3">{tx("computedAt")}</th>
208+ <Show when={props.onOpenStudent}>
209+ <th class="py-2">{tx("studentAnalysis")}</th>
210+ </Show>
211+ </tr>
212+ </thead>
213+ <tbody>
214+ <For each={props.model.students}>
215+ {(student) => (
216+ <tr class="border-t border-border-hairline">
217+ <td class="py-2 pr-3 font-medium text-text-strong">{student.name}</td>
218+ <td class="py-2 pr-3 text-muted-foreground">{studentStatusText(prefs.locale(), student)}</td>
219+ <td class="py-2 pr-3 text-muted-foreground">{student.confidence ?? tx("noData")}</td>
220+ <td class="mono py-2 pr-3 text-right tabular-nums">{student.attention}</td>
221+ <td class="mono py-2 pr-3 text-right tabular-nums">{student.cards}</td>
222+ <td class="mono py-2 pr-3 tabular-nums">{studentMarksText(prefs.locale(), student)}</td>
223+ <td class="mono py-2 pr-3 tabular-nums">{studentAttendanceText(prefs.locale(), student)}</td>
224+ <td class="py-2 pr-3 text-muted-foreground">{formatDateTime(student.computed_at, prefs.locale())}</td>
225+ <Show when={props.onOpenStudent}>
226+ <td class="py-2">
227+ <Button
228+ variant="outline"
229+ size="sm"
230+ class="rounded-lg"
231+ onClick={() => props.onOpenStudent?.(student.id)}
232+ >
233+ {tx("openStudent")}
234+ </Button>
235+ </td>
236+ </Show>
237+ </tr>
238+ )}
239+ </For>
240+ </tbody>
241+ </table>
242+ </div>
243+ <Show when={props.model.students.length === 0}>
244+ <EmptyInline illustration="people" size="md" title={tx("rosterEmpty")} />
245+ </Show>
246+ </section>
247+
248+ <details class="border-t border-border-hairline pt-5">
249+ <summary class="cursor-pointer text-sm font-semibold text-text-strong">{tx("technical")}</summary>
250+ <p class="mt-1 text-xs text-muted-foreground">{tx("technicalHint")}</p>
251+ <pre class="mono mt-2 overflow-x-auto rounded-lg bg-surface-overlay p-3 text-[11px]">
252+ {JSON.stringify(props.model.run, null, 2)}
253+ </pre>
254+ </details>
255+ </div>
256+ );
257+}
258+
259+/**
260+ * The school picture for one run: the ledger row's own counters, the modules'
261+ * coverage across the students read for it, and every student's headline
262+ * signals with a door into their own analysis drawer.
263+ *
264+ * There is no school-level report route: the run counters come from
265+ * `GET /insights/runs`, and everything per-student from
266+ * `GET /insights/students/{id}` — read here, one student at a time, with the
267+ * coverage count always on screen so a partial read never reads as the school.
268+ */
269+export function InsightRunReport(props: { run: InsightRun }) {
270+ const prefs = usePreferences();
271+ const tx = (key: RunReportKey, vars?: Record<string, string | number>) =>
272+ runReportText(prefs.locale(), key, vars);
273+ const [, flash] = createFlash();
274+ const [roster, setRoster] = createSignal<PersonRef[]>([]);
275+ const [rosterTotal, setRosterTotal] = createSignal(0);
276+ const [rosterError, setRosterError] = createSignal<string | null>(null);
277+ const [insights, setInsights] = createSignal<Record<string, StudentInsight>>({});
278+ const [failures, setFailures] = createSignal<Record<string, string>>({});
279+ const [loading, setLoading] = createSignal(true);
280+ const [openStudentId, setOpenStudentId] = createSignal<string | null>(null);
281+ /** Dynamic membership by definition: ids enter and leave as reads settle. */
282+ const inFlight = new Set<string>();
283+
284+ const loadSignals = async (ids: string[]) => {
285+ const wanted = ids.filter(
286+ (id) => !inFlight.has(id) && insights()[id] === undefined && failures()[id] === undefined,
287+ );
288+ if (wanted.length === 0) return;
289+ setLoading(true);
290+ for (let start = 0; start < wanted.length; start += SIGNAL_CONCURRENCY) {
291+ const batch = wanted.slice(start, start + SIGNAL_CONCURRENCY);
292+ for (const id of batch) inFlight.add(id);
293+ const settled = await Promise.all(
294+ batch.map(async (id) => {
295+ const [outcome] = await Promise.allSettled([getInsightByUserId(id)]);
296+ return { id, outcome };
297+ }),
298+ );
299+ const nextInsights = { ...insights() };
300+ const nextFailures = { ...failures() };
301+ for (const { id, outcome } of settled) {
302+ inFlight.delete(id);
303+ if (outcome.status === "fulfilled") nextInsights[id] = outcome.value;
304+ else nextFailures[id] = formatApiError(outcome.reason);
305+ }
306+ setInsights(nextInsights);
307+ setFailures(nextFailures);
308+ }
309+ setLoading(false);
310+ };
311+
312+ const loadRoster = async (offset: number) => {
313+ setLoading(true);
314+ try {
315+ const page = await getUserSearch("", undefined, "student", { limit: ROSTER_PAGE, offset });
316+ setRoster((current) => (offset === 0 ? page.items : [...current, ...page.items]));
317+ setRosterTotal(page.total);
318+ await loadSignals(page.items.slice(0, AUTO_SIGNAL_LIMIT).map((person) => person.id));
319+ } catch (error) {
320+ setRosterError(formatApiError(error));
321+ } finally {
322+ setLoading(false);
323+ }
324+ };
325+
326+ onMount(() => {
327+ document.body.classList.add(PRINT_BODY_CLASS);
328+ onCleanup(() => document.body.classList.remove(PRINT_BODY_CLASS));
329+ void loadRoster(0);
330+ });
331+
332+ const model = createMemo(() =>
333+ buildRunReportModel({
334+ run: props.run,
335+ roster: roster(),
336+ insights: insights(),
337+ errors: failures(),
338+ coverageTotal: rosterTotal() || roster().length,
339+ rosterError: rosterError(),
340+ }),
341+ );
342+ const markdown = () => buildRunReportMarkdown(model(), prefs.locale());
343+ const unloaded = () =>
344+ roster().filter((person) => insights()[person.id] === undefined && failures()[person.id] === undefined);
345+ const openedStudent = createMemo(() => {
346+ const id = openStudentId();
347+ return id ? roster().find((person) => person.id === id) ?? null : null;
348+ });
349+ const openedInsight = createMemo(() => {
350+ const id = openStudentId();
351+ return id ? insights()[id] ?? null : null;
352+ });
353+ const openedFailure = createMemo(() => {
354+ const id = openStudentId();
355+ return id ? failures()[id] ?? null : null;
356+ });
357+
358+ const copyReport = async () => {
359+ try {
360+ await navigator.clipboard.writeText(markdown());
361+ flash(tx("copied"));
362+ } catch {
363+ flash(tx("copyFailed"));
364+ }
365+ };
366+
367+ const downloadReport = () => {
368+ const url = URL.createObjectURL(new Blob([markdown()], { type: "text/markdown;charset=utf-8" }));
369+ const anchor = document.createElement("a");
370+ anchor.href = url;
371+ anchor.download = runReportFileName(props.run.run_day);
372+ document.body.appendChild(anchor);
373+ anchor.click();
374+ anchor.remove();
375+ URL.revokeObjectURL(url);
376+ flash(tx("downloaded"));
377+ };
378+
379+ return (
380+ <div class="space-y-5">
381+ <div class="flex flex-wrap items-center justify-end gap-2">
382+ <Button variant="outline" size="sm" class="rounded-lg" disabled={loading()} onClick={() => void copyReport()}>
383+ <IconCopy class="h-4 w-4" />
384+ {tx("copy")}
385+ </Button>
386+ <Button variant="outline" size="sm" class="rounded-lg" disabled={loading()} onClick={downloadReport}>
387+ <IconDownload class="h-4 w-4" />
388+ {tx("download")}
389+ </Button>
390+ <Button variant="outline" size="sm" class="rounded-lg" disabled={loading()} onClick={() => window.print()}>
391+ <IconFileText class="h-4 w-4" />
392+ {tx("print")}
393+ </Button>
394+ </div>
395+
396+ <Show when={unloaded().length > 0}>
397+ <div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border-line px-3 py-2">
398+ <p class="text-xs text-muted-foreground">
399+ {loading() ? tx("loadingSignals") : tx("coverage", { loaded: model().coverage.loaded, total: model().coverage.total })}
400+ </p>
401+ <Button
402+ variant="outline"
403+ size="sm"
404+ class="rounded-lg"
405+ disabled={loading()}
406+ onClick={() => void loadSignals(unloaded().map((person) => person.id))}
407+ >
408+ {tx("loadAll", { count: unloaded().length })}
409+ </Button>
410+ </div>
411+ </Show>
412+
413+ <Show when={loading() && unloaded().length === 0 && model().coverage.loaded === 0}>
414+ <p class="text-sm text-muted-foreground">{tx("loadingSignals")}</p>
415+ </Show>
416+
417+ <Show when={rosterTotal() > roster().length}>
418+ <Button
419+ variant="outline"
420+ size="sm"
421+ class="rounded-lg"
422+ disabled={loading()}
423+ onClick={() => void loadRoster(roster().length)}
424+ >
425+ {tx("loadMoreRoster")}
426+ </Button>
427+ </Show>
428+
429+ <ReportDocument model={model()} loading={loading()} onOpenStudent={setOpenStudentId} />
430+
431+ <Portal mount={document.body}>
432+ <style>{PRINT_STYLES}</style>
433+ <div class={PRINT_ROOT_CLASS}>
434+ <ReportDocument model={model()} loading={loading()} />
435+ </div>
436+ </Portal>
437+
438+ <SidePanel
439+ size="wide"
440+ open={openStudentId() != null}
441+ onOpenChange={(open) => {
442+ if (!open) setOpenStudentId(null);
443+ }}
444+ title={personLabel(openedStudent())}
445+ description={tx("studentAnalysis")}
446+ >
447+ <Show keyed when={openedInsight()}>
448+ {(insight) => <InsightDetail insight={insight} />}
449+ </Show>
450+ <Show when={openedFailure()}>
451+ {(message) => <p class="text-sm text-muted-foreground">{tx("loadFailed", { message: message() })}</p>}
452+ </Show>
453+ <Show when={openStudentId() != null && !openedInsight() && !openedFailure()}>
454+ <EmptyInline illustration="charts" size="md" title={tx("noSummary")} hint={tx("noModules")} />
455+ </Show>
456+ </SidePanel>
457+ </div>
458+ );
459+}
src/components/insights/insight-runs-table.tsxmodified+59 -12
@@ -1,8 +1,13 @@
1-import { createMemo } from "solid-js";1+import { Show, createMemo, createSignal } from "solid-js";
2 import type { ColumnDef } from "@tanstack/solid-table";2 import type { ColumnDef } from "@tanstack/solid-table";
3 import type { InsightRun } from "@/api/client";3 import type { InsightRun } from "@/api/client";
4+import { InsightRunReport } from "@/components/insights/insight-run-report";
4 import { Badge } from "@/components/ui/badge";5 import { Badge } from "@/components/ui/badge";
5 import { DataTable } from "@/components/ui/data-table";6 import { DataTable } from "@/components/ui/data-table";
7+import { IconFileText } from "@/components/ui/icons";
8+import { SidePanel } from "@/components/ui/side-panel";
9+import { TableRowActions } from "@/components/ui/table-row-actions";
10+import { runReportText, type RunReportKey } from "@/i18n/insights-run-report";
6 import { cn } from "@/lib/cn";11 import { cn } from "@/lib/cn";
7 import { formatDateTime, formatDurationMinutes } from "@/lib/format";12 import { formatDateTime, formatDurationMinutes } from "@/lib/format";
8 import { usePreferences } from "@/stores/preferences-context";13 import { usePreferences } from "@/stores/preferences-context";
@@ -18,6 +23,9 @@ function statusVariant(status: string) {
18 export function InsightRunsTable(props: { runs: InsightRun[] }) {23 export function InsightRunsTable(props: { runs: InsightRun[] }) {
19 const prefs = usePreferences();24 const prefs = usePreferences();
20 const tx = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars);25 const tx = (key: string, vars?: Record<string, string | number>) => prefs.t(key as never, vars);
26+ const rtx = (key: RunReportKey, vars?: Record<string, string | number>) =>
27+ runReportText(prefs.locale(), key, vars);
28+ const [selectedRun, setSelectedRun] = createSignal<InsightRun | null>(null);
21 const statusLabel = (status: string) =>29 const statusLabel = (status: string) =>
22 ["running", "ok", "partial", "failed", "skipped"].includes(status)30 ["running", "ok", "partial", "failed", "skipped"].includes(status)
23 ? tx(`insights.status.${status}`)31 ? tx(`insights.status.${status}`)
@@ -95,19 +103,58 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) {
95 );103 );
96 },104 },
97 },105 },
106+ {
107+ id: "actions",
108+ header: tx("common.actions"),
109+ enableSorting: false,
110+ meta: {
111+ headerClass: "w-[150px] min-w-[150px] max-w-[150px] h-[45px] text-center whitespace-nowrap",
112+ cellClass: "w-[150px] min-w-[150px] max-w-[150px] h-[45px] text-center whitespace-nowrap",
113+ },
114+ cell: (cell) => (
115+ <TableRowActions
116+ label={tx("common.actions")}
117+ actions={[
118+ {
119+ label: rtx("open"),
120+ icon: <IconFileText class="h-4 w-4" />,
121+ onSelect: () => setSelectedRun(cell.row.original),
122+ },
123+ ]}
124+ />
125+ ),
126+ },
98 ]);127 ]);
99 128
100 return (129 return (
101- <DataTable130+ <>
102- title={tx("insights.runs")}131+ <DataTable
103- description={tx("insights.runsSubtitle")}132+ title={tx("insights.runs")}
104- columns={columns()}133+ description={tx("insights.runsSubtitle")}
105- data={props.runs}134+ columns={columns()}
106- empty={tx("insights.emptyRuns")}135+ data={props.runs}
107- tableClass="min-w-[820px]"136+ empty={tx("insights.emptyRuns")}
108- enablePagination137+ tableClass="min-w-[980px]"
109- pageSize={10}138+ enablePagination
110- storageKey="insight-runs"139+ pageSize={10}
111- />140+ storageKey="insight-runs"
141+ onRowClick={(run) => setSelectedRun(run)}
142+ />
143+
144+ <Show keyed when={selectedRun()}>
145+ {(run) => (
146+ <SidePanel
147+ size="xl"
148+ open
149+ onOpenChange={(open) => {
150+ if (!open) setSelectedRun(null);
151+ }}
152+ title={rtx("panelDescription", { day: run.run_day })}
153+ >
154+ <InsightRunReport run={run} />
155+ </SidePanel>
156+ )}
157+ </Show>
158+ </>
112 );159 );
113 }160 }
src/i18n/insights-run-report.tsadded+212 -0
@@ -0,0 +1,212 @@
1+import { formatMessage, type Locale } from "@/i18n/messages";
2+
3+/**
4+ * The school run report's own copy.
5+ *
6+ * It lives here rather than in `src/i18n/messages.ts` on purpose: two lanes
7+ * write insight surfaces in the same batch, and a second writer on the shared
8+ * dictionary is how one lane's keys get dropped by the other's commit. Same
9+ * shape as the shared dictionary (every key, both locales, `{name}` vars), so
10+ * a later tidy-up can fold it in mechanically.
11+ */
12+export type RunReportKey =
13+ | "open"
14+ | "title"
15+ | "subtitle"
16+ | "panelDescription"
17+ | "copy"
18+ | "copied"
19+ | "copyFailed"
20+ | "download"
21+ | "downloaded"
22+ | "print"
23+ | "runSection"
24+ | "schoolSection"
25+ | "studentsSection"
26+ | "technical"
27+ | "technicalHint"
28+ | "runDay"
29+ | "startedAt"
30+ | "finishedAt"
31+ | "status"
32+ | "processed"
33+ | "skipped"
34+ | "failed"
35+ | "rowsWritten"
36+ | "duration"
37+ | "budget"
38+ | "budgetExceeded"
39+ | "budgetWithin"
40+ | "issues"
41+ | "noIssues"
42+ | "pendingStudents"
43+ | "failedModules"
44+ | "coverage"
45+ | "coverageNote"
46+ | "loadAll"
47+ | "loadingSignals"
48+ | "loadMoreRoster"
49+ | "rosterEmpty"
50+ | "rosterFailed"
51+ | "student"
52+ | "confidence"
53+ | "attention"
54+ | "cards"
55+ | "segments"
56+ | "marksAverage"
57+ | "marksCourses"
58+ | "attendanceRate"
59+ | "computedAt"
60+ | "noData"
61+ | "noSummary"
62+ | "noModules"
63+ | "loadFailed"
64+ | "notLoaded"
65+ | "openStudent"
66+ | "studentAnalysis"
67+ | "moduleMarks"
68+ | "moduleAttendance"
69+ | "moduleStudy"
70+ | "moduleSubmission"
71+ | "moduleCovered"
72+ | "modulesEmpty"
73+ | "documentTitle";
74+
75+const tr: Record<RunReportKey, string> = {
76+ open: "Raporu görüntüle",
77+ title: "Okul analiz raporu",
78+ subtitle: "Bu çalıştırmanın ürettiği sonuçlar",
79+ panelDescription: "Çalıştırma günü {day}",
80+ copy: "Kopyala",
81+ copied: "Rapor panoya kopyalandı.",
82+ copyFailed: "Rapor panoya kopyalanamadı.",
83+ download: "İndir (.md)",
84+ downloaded: "Rapor indirildi.",
85+ print: "Yazdır / PDF",
86+ runSection: "Çalıştırma özeti",
87+ schoolSection: "Okul geneli",
88+ studentsSection: "Öğrenci dökümü",
89+ technical: "Teknik ayrıntı",
90+ technicalHint: "Ham alanlar; insan görünümünde gizli tutulur.",
91+ runDay: "Çalıştırma günü",
92+ startedAt: "Başlangıç",
93+ finishedAt: "Bitiş",
94+ status: "Durum",
95+ processed: "İşlenen öğrenci",
96+ skipped: "Atlanan",
97+ failed: "Hatalı",
98+ rowsWritten: "Yazılan kayıt",
99+ duration: "Süre",
100+ budget: "Süre bütçesi",
101+ budgetExceeded: "Bütçe doldu; sıradaki öğrenciler sonraki çalıştırmaya kaldı.",
102+ budgetWithin: "Bütçe içinde tamamlandı.",
103+ issues: "Sorunlar",
104+ noIssues: "Sorun yok",
105+ pendingStudents: "{count} öğrenci sıradaki çalıştırmaya kaldı",
106+ failedModules: "Veri üretmeyen modüller: {modules}",
107+ coverage: "Sinyalleri yüklenen öğrenci: {loaded}/{total}",
108+ coverageNote: "Okul geneli sayılar yalnızca sinyalleri yüklenmiş öğrencileri kapsar.",
109+ loadAll: "Kalan {count} öğrenciyi yükle",
110+ loadingSignals: "Öğrenci sinyalleri yükleniyor…",
111+ loadMoreRoster: "Öğrenci listesinin devamını yükle",
112+ rosterEmpty: "Bu okulda listelenecek öğrenci yok; kapsanacak kimse bulunamadı.",
113+ rosterFailed: "Öğrenci listesi okunamadı: {message}",
114+ student: "Öğrenci",
115+ confidence: "Güven",
116+ attention: "Uyarı",
117+ cards: "Öneri",
118+ segments: "Soru grubu",
119+ marksAverage: "Not ortalaması",
120+ marksCourses: "Not girilen ders",
121+ attendanceRate: "Devam oranı",
122+ computedAt: "Hesaplandığı an",
123+ noData: "veri yok",
124+ noSummary: "Bu öğrenci için henüz analiz hesaplanmamış.",
125+ noModules: "Analiz hesaplandı ama dört modülün hiçbiri veri üretmedi.",
126+ loadFailed: "Analiz okunamadı: {message}",
127+ notLoaded: "Yüklenmedi",
128+ openStudent: "Öğrenci analizini aç",
129+ studentAnalysis: "Öğrenci analizi",
130+ moduleMarks: "Notlar",
131+ moduleAttendance: "Yoklama",
132+ moduleStudy: "Çalışma",
133+ moduleSubmission: "Teslim",
134+ moduleCovered: "{label}: {withData}/{total} öğrencide veri var",
135+ modulesEmpty: "Hiçbir modül veri üretmedi; bu öğrenciler için hesaplanacak kaynak yok.",
136+ documentTitle: "Okul analiz raporu — {day}",
137+};
138+
139+const en: Record<RunReportKey, string> = {
140+ open: "View report",
141+ title: "School analysis report",
142+ subtitle: "What this run produced",
143+ panelDescription: "Run day {day}",
144+ copy: "Copy",
145+ copied: "Report copied to the clipboard.",
146+ copyFailed: "Could not copy the report.",
147+ download: "Download (.md)",
148+ downloaded: "Report downloaded.",
149+ print: "Print / PDF",
150+ runSection: "Run summary",
151+ schoolSection: "School overview",
152+ studentsSection: "Student breakdown",
153+ technical: "Technical detail",
154+ technicalHint: "Raw fields, kept out of the human view.",
155+ runDay: "Run day",
156+ startedAt: "Started",
157+ finishedAt: "Finished",
158+ status: "Status",
159+ processed: "Students processed",
160+ skipped: "Skipped",
161+ failed: "Failed",
162+ rowsWritten: "Rows written",
163+ duration: "Duration",
164+ budget: "Time budget",
165+ budgetExceeded: "The budget ran out; the remaining students wait for the next run.",
166+ budgetWithin: "Finished within budget.",
167+ issues: "Issues",
168+ noIssues: "No issues",
169+ pendingStudents: "{count} students left for the next run",
170+ failedModules: "Modules that produced nothing: {modules}",
171+ coverage: "Students with signals loaded: {loaded}/{total}",
172+ coverageNote: "School overview numbers cover only the students whose signals are loaded.",
173+ loadAll: "Load the remaining {count} students",
174+ loadingSignals: "Loading student signals…",
175+ loadMoreRoster: "Load more of the student list",
176+ rosterEmpty: "This school has no students to list, so nobody could be covered.",
177+ rosterFailed: "Could not read the student list: {message}",
178+ student: "Student",
179+ confidence: "Confidence",
180+ attention: "Attention",
181+ cards: "Recommendation",
182+ segments: "Question group",
183+ marksAverage: "Marks average",
184+ marksCourses: "Courses with marks",
185+ attendanceRate: "Attendance rate",
186+ computedAt: "Computed at",
187+ noData: "no data",
188+ noSummary: "No analysis has been computed for this student yet.",
189+ noModules: "The analysis ran but none of the four modules produced anything.",
190+ loadFailed: "Could not read the analysis: {message}",
191+ notLoaded: "Not loaded",
192+ openStudent: "Open student analysis",
193+ studentAnalysis: "Student analysis",
194+ moduleMarks: "Marks",
195+ moduleAttendance: "Attendance",
196+ moduleStudy: "Study",
197+ moduleSubmission: "Submission",
198+ moduleCovered: "{label}: {withData}/{total} students have data",
199+ modulesEmpty: "No module produced anything; there is nothing to compute from for these students.",
200+ documentTitle: "School analysis report — {day}",
201+};
202+
203+export const RUN_REPORT_MESSAGES: Record<Locale, Record<RunReportKey, string>> = { en, tr };
204+
205+export function runReportText(
206+ locale: Locale,
207+ key: RunReportKey,
208+ vars?: Record<string, string | number>,
209+): string {
210+ const text = RUN_REPORT_MESSAGES[locale][key] ?? RUN_REPORT_MESSAGES.en[key] ?? key;
211+ return formatMessage(text, vars);
212+}
src/i18n/messages.tsmodified+6 -0
@@ -965,6 +965,8 @@ export type MessageKey =
965 | "insights.duration"965 | "insights.duration"
966 | "insights.issues"966 | "insights.issues"
967 | "insights.issueCount"967 | "insights.issueCount"
968+ | "insights.pendingStudents"
969+ | "insights.failedModules"
968 | "insights.noIssues"970 | "insights.noIssues"
969 | "insights.budgetExceeded"971 | "insights.budgetExceeded"
970 | "insights.emptyRuns"972 | "insights.emptyRuns"
@@ -3089,6 +3091,8 @@ const en: Dict = {
3089 "insights.duration": "Duration",3091 "insights.duration": "Duration",
3090 "insights.issues": "Issues",3092 "insights.issues": "Issues",
3091 "insights.issueCount": "{count} issue(s)",3093 "insights.issueCount": "{count} issue(s)",
3094+ "insights.pendingStudents": "{count} student(s) pending",
3095+ "insights.failedModules": "Modules that failed: {modules}",
3092 "insights.noIssues": "No issue",3096 "insights.noIssues": "No issue",
3093 "insights.budgetExceeded": "Time budget exceeded",3097 "insights.budgetExceeded": "Time budget exceeded",
3094 "insights.emptyRuns": "No analysis run yet.",3098 "insights.emptyRuns": "No analysis run yet.",
@@ -5215,6 +5219,8 @@ const tr: Dict = {
5215 "insights.duration": "Süre",5219 "insights.duration": "Süre",
5216 "insights.issues": "Sorunlar",5220 "insights.issues": "Sorunlar",
5217 "insights.issueCount": "{count} sorun",5221 "insights.issueCount": "{count} sorun",
5222+ "insights.pendingStudents": "{count} öğrenci sırada",
5223+ "insights.failedModules": "Veri üretmeyen modüller: {modules}",
5218 "insights.noIssues": "Sorun yok",5224 "insights.noIssues": "Sorun yok",
5219 "insights.budgetExceeded": "Süre bütçesi aşıldı",5225 "insights.budgetExceeded": "Süre bütçesi aşıldı",
5220 "insights.emptyRuns": "Henüz analiz çalıştırması yok.",5226 "insights.emptyRuns": "Henüz analiz çalıştırması yok.",
src/lib/insight-run-report.tsadded+412 -0
@@ -0,0 +1,412 @@
1+import type { InsightRun, PersonRef, StudentInsight } from "@/api/client";
2+import { runReportText } from "@/i18n/insights-run-report";
3+import type { Locale } from "@/i18n/messages";
4+import { formatDateTime } from "@/lib/format";
5+
6+/**
7+ * The school run report's model and its Markdown rendering.
8+ *
9+ * The report has no aggregate door: the backend serves a run's counters
10+ * (`GET /insights/runs`) and one student at a time (`GET /insights/students/{id}`),
11+ * and nothing in between. So the school picture is composed here, from the
12+ * students whose signals have been read, and every number the model carries is
13+ * stated together with how many students it was computed over — a partial read
14+ * must never read as "the school has none".
15+ *
16+ * The Markdown is the report: the panel renders this model, and the clipboard,
17+ * the `.md` download and the print document are all built from the same model,
18+ * so what is exported is exactly what is shown.
19+ */
20+
21+export type ModuleId = "marks" | "attendance" | "study" | "submission";
22+
23+export type ModuleCoverage = {
24+ id: ModuleId;
25+ /** Students whose module holds a measurement (not merely a computed shell). */
26+ with_data: number;
27+ /** Students whose summary carries the module at all. */
28+ computed: number;
29+ /** The module's own limitation sentence, when it ships one. */
30+ limitation: string | null;
31+};
32+
33+export type StudentSignal = {
34+ id: string;
35+ name: string;
36+ /**
37+ * `ok` — a summary was read. `no_summary` — the door answered and nothing has
38+ * been computed for this student. `not_loaded` — this report has not read
39+ * them yet. `error` — the read itself failed.
40+ */
41+ state: "ok" | "no_summary" | "not_loaded" | "error";
42+ error: string | null;
43+ confidence: string | null;
44+ computed_at: number | null;
45+ attention: number;
46+ cards: number;
47+ segments: number;
48+ marks: { courses_with_marks: number; courses_total: number; average: number | null };
49+ attendance: { rate: number | null; observed: number };
50+ study: { stints: number };
51+ submission: { counted: number };
52+};
53+
54+export type RunReportModel = {
55+ run: InsightRun;
56+ students: StudentSignal[];
57+ /** How many students the school picture was computed over. */
58+ coverage: { loaded: number; total: number };
59+ modules: ModuleCoverage[];
60+ totals: { attention: number; cards: number; segments: number };
61+ pending: { id: string; name: string | null }[];
62+ roster_error: string | null;
63+};
64+
65+// ---- reading ZEKA's module payloads ---------------------------------------
66+//
67+// The module members are `unknown` by contract and the service may grow them,
68+// so every read is by name behind a shape check: a missing field means "this
69+// module measured nothing", never a throw and never a zero invented from a
70+// different field.
71+
72+/** The shape gate every module read goes through; `null` for anything else. */
73+function recordOf(value: unknown): Record<string, unknown> | null {
74+ return typeof value === "object" && value !== null && !Array.isArray(value)
75+ ? (value as Record<string, unknown>)
76+ : null;
77+}
78+
79+/** A finite number, or `null` — counts and rates alike are read through this. */
80+function finiteNumber(value: unknown): number | null {
81+ return typeof value === "number" && Number.isFinite(value) ? value : null;
82+}
83+
84+export function readMarks(marks: unknown): StudentSignal["marks"] {
85+ const courses = recordOf(recordOf(marks)?.courses) ?? {};
86+ const rows = Object.values(courses);
87+ let withMarks = 0;
88+ let sum = 0;
89+ let counted = 0;
90+ for (const row of rows) {
91+ const course = recordOf(row);
92+ if (!course) continue;
93+ if ((finiteNumber(course.n_marks) ?? 0) > 0) withMarks += 1;
94+ const average = finiteNumber(course.average);
95+ if (average != null) {
96+ sum += average;
97+ counted += 1;
98+ }
99+ }
100+ return {
101+ courses_with_marks: withMarks,
102+ courses_total: rows.length,
103+ average: counted > 0 ? sum / counted : null,
104+ };
105+}
106+
107+export function readAttendance(attendance: unknown): StudentSignal["attendance"] & { limitation: string | null } {
108+ const module = recordOf(attendance);
109+ const overall = recordOf(module?.overall);
110+ const limitation = module?.limitation;
111+ return {
112+ rate: finiteNumber(overall?.rate),
113+ observed: finiteNumber(overall?.n_obs) ?? 0,
114+ limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
115+ };
116+}
117+
118+export function readStudy(study: unknown): StudentSignal["study"] & { limitation: string | null } {
119+ const module = recordOf(study);
120+ const recent = recordOf(module?.recent_28d);
121+ const limitation = module?.limitation;
122+ return {
123+ stints: finiteNumber(recent?.n_stints) ?? 0,
124+ limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
125+ };
126+}
127+
128+export function readSubmission(submission: unknown): StudentSignal["submission"] & { limitation: string | null } {
129+ const module = recordOf(submission);
130+ const overall = recordOf(module?.overall);
131+ const limitation = module?.limitation;
132+ return {
133+ counted: finiteNumber(overall?.n) ?? 0,
134+ limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
135+ };
136+}
137+
138+const EMPTY_SIGNAL: Omit<StudentSignal, "id" | "name" | "state" | "error"> = {
139+ confidence: null,
140+ computed_at: null,
141+ attention: 0,
142+ cards: 0,
143+ segments: 0,
144+ marks: { courses_with_marks: 0, courses_total: 0, average: null },
145+ attendance: { rate: null, observed: 0 },
146+ study: { stints: 0 },
147+ submission: { counted: 0 },
148+};
149+
150+/** One student's readable signal line, from whatever the door answered. */
151+export function toStudentSignal(
152+ person: { id: string; name: string },
153+ insight: StudentInsight | null | undefined,
154+ error: string | null,
155+): StudentSignal {
156+ const identity = { id: person.id, name: person.name };
157+ if (error) return { ...identity, ...EMPTY_SIGNAL, state: "error", error };
158+ if (!insight) return { ...identity, ...EMPTY_SIGNAL, state: "not_loaded", error: null };
159+ const summary = insight.summary ?? null;
160+ if (!summary) {
161+ return {
162+ ...identity,
163+ ...EMPTY_SIGNAL,
164+ state: "no_summary",
165+ error: null,
166+ attention: insight.attention.length,
167+ cards: insight.cards.length,
168+ segments: insight.segments.length,
169+ };
170+ }
171+ return {
172+ ...identity,
173+ state: "ok",
174+ error: null,
175+ confidence: summary.confidence,
176+ computed_at: summary.computed_at,
177+ attention: insight.attention.length,
178+ cards: insight.cards.length,
179+ segments: insight.segments.length,
180+ marks: readMarks(summary.marks),
181+ attendance: readAttendance(summary.attendance),
182+ study: readStudy(summary.study),
183+ submission: readSubmission(summary.submission),
184+ };
185+}
186+
187+/** Whether a module holds a measurement for one student. */
188+export function moduleHasData(signal: StudentSignal, id: ModuleId): boolean {
189+ if (signal.state !== "ok") return false;
190+ if (id === "marks") return signal.marks.courses_with_marks > 0;
191+ if (id === "attendance") return signal.attendance.observed > 0;
192+ if (id === "study") return signal.study.stints > 0;
193+ return signal.submission.counted > 0;
194+}
195+
196+export function buildRunReportModel(args: {
197+ run: InsightRun;
198+ roster: PersonRef[];
199+ insights: Record<string, StudentInsight>;
200+ errors: Record<string, string>;
201+ coverageTotal: number;
202+ rosterError: string | null;
203+}): RunReportModel {
204+ const students = args.roster.map((person) =>
205+ toStudentSignal(
206+ { id: person.id, name: person.display_name || person.username || person.id },
207+ args.insights[person.id] ?? null,
208+ args.errors[person.id] ?? null,
209+ ),
210+ );
211+ const nameById: Record<string, string> = {};
212+ for (const person of args.roster) {
213+ nameById[person.id] = person.display_name || person.username;
214+ }
215+ const loaded = students.filter((student) => student.state === "ok" || student.state === "no_summary");
216+ const limitations: Record<ModuleId, string | null> = {
217+ marks: null,
218+ attendance: null,
219+ study: null,
220+ submission: null,
221+ };
222+ for (const student of loaded) {
223+ const summary = args.insights[student.id]?.summary;
224+ if (!summary) continue;
225+ const found: [ModuleId, string | null][] = [
226+ ["attendance", readAttendance(summary.attendance).limitation],
227+ ["study", readStudy(summary.study).limitation],
228+ ["submission", readSubmission(summary.submission).limitation],
229+ ];
230+ for (const [id, value] of found) {
231+ if (value && !limitations[id]) limitations[id] = value;
232+ }
233+ }
234+ const modules: ModuleCoverage[] = (["marks", "attendance", "study", "submission"] as ModuleId[]).map((id) => ({
235+ id,
236+ with_data: loaded.filter((student) => moduleHasData(student, id)).length,
237+ computed: loaded.filter((student) => args.insights[student.id]?.summary?.[id] != null).length,
238+ limitation: limitations[id],
239+ }));
240+ return {
241+ run: args.run,
242+ students,
243+ coverage: { loaded: loaded.length, total: args.coverageTotal },
244+ modules,
245+ totals: {
246+ attention: loaded.reduce((sum, student) => sum + student.attention, 0),
247+ cards: loaded.reduce((sum, student) => sum + student.cards, 0),
248+ segments: loaded.reduce((sum, student) => sum + student.segments, 0),
249+ },
250+ pending: args.run.pending_students.map((id) => ({ id, name: nameById[id] ?? null })),
251+ roster_error: args.rosterError,
252+ };
253+}
254+
255+// ---- rendering -------------------------------------------------------------
256+
257+/** Run durations are sub-second in practice, so minutes-only would read "0 dk". */
258+export function formatRunDuration(ms: number | null | undefined, locale: Locale): string {
259+ if (ms == null) return "—";
260+ const tr = locale === "tr";
261+ if (ms < 1000) return `${Math.round(ms)} ms`;
262+ if (ms < 60_000) return tr ? `${(ms / 1000).toFixed(1)} sn` : `${(ms / 1000).toFixed(1)} s`;
263+ const minutes = ms / 60_000;
264+ if (minutes < 60) return tr ? `${minutes.toFixed(1)} dk` : `${minutes.toFixed(1)} min`;
265+ return tr ? `${(minutes / 60).toFixed(1)} sa` : `${(minutes / 60).toFixed(1)} h`;
266+}
267+
268+export function moduleLabel(locale: Locale, id: ModuleId): string {
269+ if (id === "marks") return runReportText(locale, "moduleMarks");
270+ if (id === "attendance") return runReportText(locale, "moduleAttendance");
271+ if (id === "study") return runReportText(locale, "moduleStudy");
272+ return runReportText(locale, "moduleSubmission");
273+}
274+
275+const STATUS_LABELS: Record<string, Record<string, string>> = {
276+ tr: { running: "Sürüyor", ok: "Tamamlandı", partial: "Kısmi", failed: "Başarısız", skipped: "Atlandı" },
277+ en: { running: "Running", ok: "Completed", partial: "Partial", failed: "Failed", skipped: "Skipped" },
278+};
279+
280+export function runReportStatusLabel(locale: Locale, status: string): string {
281+ return STATUS_LABELS[locale][status] ?? status;
282+}
283+
284+export function runReportFileName(runDay: string): string {
285+ return `okul-analiz-raporu-${runDay}.md`;
286+}
287+
288+/** `0,716` in Turkish, `0.716` in English — the same number either way. */
289+export function runReportDecimal(value: number, locale: Locale): string {
290+ return value.toFixed(1).replace(".", locale === "tr" ? "," : ".");
291+}
292+
293+/** `85%`, or `veri yok` when the module measured nothing. */
294+export function runReportPercent(value: number | null, locale: Locale): string {
295+ return value == null ? runReportText(locale, "noData") : `${Math.round(value * 100)}%`;
296+}
297+
298+export function studentStatusText(locale: Locale, student: StudentSignal): string {
299+ if (student.state === "ok") return runReportStatusLabel(locale, "ok");
300+ if (student.state === "no_summary") return runReportText(locale, "noSummary");
301+ if (student.state === "error") return student.error ?? runReportText(locale, "noData");
302+ return runReportText(locale, "notLoaded");
303+}
304+
305+/**
306+ * `Yüklenmedi` while nothing has been read, `veri yok` only once a read has
307+ * said so — the two are different claims, and the panel and the export must
308+ * make the same one.
309+ */
310+export function studentMarksText(locale: Locale, student: StudentSignal): string {
311+ if (student.state === "not_loaded") return runReportText(locale, "notLoaded");
312+ if (student.state !== "ok") return runReportText(locale, "noData");
313+ const average = student.marks.average == null ? "—" : runReportDecimal(student.marks.average, locale);
314+ return `${average} (${student.marks.courses_with_marks}/${student.marks.courses_total})`;
315+}
316+
317+export function studentAttendanceText(locale: Locale, student: StudentSignal): string {
318+ if (student.state === "not_loaded") return runReportText(locale, "notLoaded");
319+ if (student.state !== "ok" || student.attendance.observed === 0) return runReportText(locale, "noData");
320+ return runReportPercent(student.attendance.rate, locale);
321+}
322+
323+/**
324+ * The report as Markdown — what `Kopyala`, the `.md` download and the print
325+ * document all carry. Every section of the panel is here, `veri yok` lines
326+ * included: an export that silently dropped the empty modules would be a
327+ * prettier lie than the screen.
328+ */
329+export function buildRunReportMarkdown(model: RunReportModel, locale: Locale): string {
330+ const t = (key: Parameters<typeof runReportText>[1], vars?: Record<string, string | number>) =>
331+ runReportText(locale, key, vars);
332+ const { run, coverage } = model;
333+ const lines: string[] = [];
334+ lines.push(`# ${t("documentTitle", { day: run.run_day })}`);
335+ lines.push("");
336+ lines.push(`## ${t("runSection")}`);
337+ lines.push(`- ${t("runDay")}: ${run.run_day}`);
338+ lines.push(`- ${t("status")}: ${runReportStatusLabel(locale, run.status)}`);
339+ lines.push(`- ${t("startedAt")}: ${formatDateTime(run.started_at, locale)}`);
340+ lines.push(`- ${t("finishedAt")}: ${formatDateTime(run.finished_at, locale)}`);
341+ lines.push(
342+ `- ${t("processed")}: ${run.students_ok}/${run.students_total} (${t("skipped").toLowerCase()} ${run.students_skipped}, ${t("failed").toLowerCase()} ${run.students_failed})`,
343+ );
344+ lines.push(`- ${t("rowsWritten")}: ${run.rows_written}`);
345+ lines.push(`- ${t("duration")}: ${formatRunDuration(run.duration_ms, locale)}`);
346+ lines.push(
347+ `- ${t("budget")}: ${run.budget_exceeded ? t("budgetExceeded") : t("budgetWithin")} (${formatRunDuration(run.budget_ms, locale)})`,
348+ );
349+ const issueCount = run.pending_students.length + run.failed_modules.length + (run.budget_exceeded ? 1 : 0);
350+ lines.push(`- ${t("issues")}: ${issueCount === 0 ? t("noIssues") : String(issueCount)}`);
351+ if (run.pending_students.length > 0) {
352+ lines.push(`- ${t("pendingStudents", { count: run.pending_students.length })}`);
353+ }
354+ if (run.failed_modules.length > 0) {
355+ lines.push(`- ${t("failedModules", { modules: run.failed_modules.join(", ") })}`);
356+ }
357+ lines.push("");
358+ lines.push(`## ${t("schoolSection")}`);
359+ if (model.roster_error) lines.push(`- ${t("rosterFailed", { message: model.roster_error })}`);
360+ lines.push(`- ${t("coverage", { loaded: coverage.loaded, total: coverage.total })}`);
361+ if (coverage.loaded === 0) lines.push(`- ${t("rosterEmpty")}`);
362+ for (const module of model.modules) {
363+ const label = moduleLabel(locale, module.id);
364+ const covered = t("moduleCovered", { label, withData: module.with_data, total: coverage.loaded });
365+ lines.push(`- ${covered}${module.with_data === 0 ? ` → ${t("noData")}` : ""}`);
366+ if (module.limitation) lines.push(` - ${module.limitation}`);
367+ }
368+ if (coverage.loaded > 0 && model.modules.every((module) => module.with_data === 0)) {
369+ lines.push(`- ${t("modulesEmpty")}`);
370+ }
371+ lines.push(
372+ `- ${t("attention")}: ${model.totals.attention} · ${t("cards")}: ${model.totals.cards} · ${t("segments")}: ${model.totals.segments}`,
373+ );
374+ lines.push(`- ${t("coverageNote")}`);
375+ lines.push("");
376+ lines.push(`## ${t("studentsSection")} (${coverage.loaded}/${coverage.total})`);
377+ const header = [
378+ t("student"),
379+ t("status"),
380+ t("confidence"),
381+ t("attention"),
382+ t("cards"),
383+ t("marksAverage"),
384+ t("attendanceRate"),
385+ t("computedAt"),
386+ ];
387+ lines.push(`| ${header.join(" | ")} |`);
388+ lines.push(`| ${header.map(() => "---").join(" | ")} |`);
389+ for (const student of model.students) {
390+ const cells = [
391+ student.name,
392+ studentStatusText(locale, student),
393+ student.confidence ?? t("noData"),
394+ String(student.attention),
395+ String(student.cards),
396+ studentMarksText(locale, student),
397+ studentAttendanceText(locale, student),
398+ formatDateTime(student.computed_at, locale),
399+ ];
400+ lines.push(`| ${cells.map((cell) => cell.replace(/\|/g, "\\|")).join(" | ")} |`);
401+ }
402+ if (model.students.length === 0) lines.push(`| ${t("rosterEmpty")} | | | | | | | |`);
403+ lines.push("");
404+ lines.push(`## ${t("technical")}`);
405+ lines.push(t("technicalHint"));
406+ lines.push("");
407+ lines.push("```json");
408+ lines.push(JSON.stringify(run, null, 2));
409+ lines.push("```");
410+ lines.push("");
411+ return lines.join("\n");
412+}