diff --git a/src/components/insights/insight-run-report.test.tsx b/src/components/insights/insight-run-report.test.tsx new file mode 100644 index 0000000..2235507 --- /dev/null +++ b/src/components/insights/insight-run-report.test.tsx @@ -0,0 +1,295 @@ +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { InsightRun, PersonRef, StudentInsight } from "@/api/client"; +import { InsightRunsTable } from "@/components/insights/insight-runs-table"; +import { buildRunReportMarkdown, buildRunReportModel } from "@/lib/insight-run-report"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const insightsApi = vi.hoisted(() => ({ getInsightByUserId: vi.fn() })); +const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() })); + +vi.mock("@/api/insights", () => insightsApi); +vi.mock("@/api/users", () => usersApi); +// Kobalte's dropdown chrome is not what this test is about: flatten it to one +// plain button per action so the report path can be driven in jsdom. +vi.mock("@/components/ui/table-row-actions", () => ({ + TableRowActions: (props: { actions: { label: string; onSelect: () => void }[] }) => ( + <> + {props.actions.map((action) => ( + + ))} + + ), +})); + +const DAY_A = "2026-09-18"; +const DAY_B = "2026-09-17"; + +const RUN_A: InsightRun = { + run_day: DAY_A, + started_at: Date.UTC(2026, 8, 18, 9, 37, 59), + finished_at: Date.UTC(2026, 8, 18, 9, 37, 59), + duration_ms: 532, + status: "ok", + students_total: 16, + students_ok: 16, + students_failed: 0, + students_skipped: 0, + rows_written: 16, + budget_exceeded: false, + budget_ms: 60_000, + pending_students: [], + failed_modules: [], +}; + +const RUN_B: InsightRun = { + ...RUN_A, + run_day: DAY_B, + status: "partial", + students_ok: 9, + students_failed: 1, + students_skipped: 6, + rows_written: 9, + pending_students: ["s2"], + failed_modules: ["attendance"], +}; + +const ROSTER: PersonRef[] = [ + { id: "s1", username: "arda.gunes", display_name: "Arda Güneş" }, + { id: "s2", username: "ayca.sahin", display_name: "Ayça Şahin" }, + { id: "s3", username: "burak.polat", display_name: "Burak Polat" }, +]; + +const COMPUTED_AT = Date.UTC(2026, 8, 18, 9, 37, 59); + +const INSIGHT_S1: StudentInsight = { + user_id: "s1", + summary: { + marks: { + classes: ["class-1"], + courses: { + "course-math": { n_marks: 0, average: null }, + "course-physics": { n_marks: 2, average: 71 }, + }, + }, + attendance: { + overall: { n_obs: 4, rate: 0.75, present: 3, absent: 1 }, + limitation: "Devam oranı dönem başından bugüne kümülatiftir.", + }, + study: { recent_28d: { n_stints: 0 }, limitation: "Çalışma oturumlarının ders bağı yoktur." }, + submission: { overall: { n: 5 }, limitation: "Teslim saati bilinmediği için erteleme yorumu yapılmaz." }, + confidence: "exploratory", + computed_at: COMPUTED_AT, + retain_until: COMPUTED_AT + 86_400_000, + }, + attention: [ + { + trigger: "mark_trend", + fact: "Fizik notu son üç sınavda düşüyor.", + course: "Fizik", + window_from: COMPUTED_AT - 30 * 86_400_000, + window_to: COMPUTED_AT, + evidence: { delta: -12 }, + }, + ], + cards: [ + { + id: "c1", + product: "O2", + rule_id: "physics_slip", + rule_version: 1, + audience_role: "teacher", + evidence: { limitation: "İki ölçüm arası fark tek başına eğilim sayılmaz." }, + confidence: "exploratory", + created_at: COMPUTED_AT, + expires_at: COMPUTED_AT + 86_400_000, + }, + ], + segments: [], +}; + +const INSIGHT_S2: StudentInsight = { + user_id: "s2", + summary: { + marks: { classes: [], courses: { "course-math": { n_marks: 0, average: null } } }, + attendance: { overall: { n_obs: 0, rate: null }, limitation: "Devam ucu yalnız sayaç döndürüyor." }, + study: { recent_28d: { n_stints: 0 } }, + submission: { overall: { n: 0 } }, + confidence: "none", + computed_at: COMPUTED_AT, + retain_until: COMPUTED_AT + 86_400_000, + }, + attention: [], + cards: [], + segments: [], +}; + +const INSIGHT_S3: StudentInsight = { user_id: "s3", summary: null, attention: [], cards: [], segments: [] }; + +const panel = () => within(document.querySelector(".side-panel-body") as HTMLElement); + +async function openReport(runDay: string) { + render(() => ( + + + + )); + const row = screen.getByText(runDay).closest("tr") as HTMLElement; + fireEvent.click(within(row).getByRole("button", { name: "Raporu görüntüle" })); + await waitFor(() => expect(screen.getByText(`Çalıştırma günü ${runDay}`)).toBeTruthy()); +} + +describe("InsightRunReport", () => { + beforeEach(() => { + localStorage.setItem("hezarfen.locale", "tr"); + usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 }); + insightsApi.getInsightByUserId.mockImplementation((userId: string) => { + if (userId === "s1") return Promise.resolve(INSIGHT_S1); + if (userId === "s2") return Promise.resolve(INSIGHT_S2); + return Promise.resolve(INSIGHT_S3); + }); + }); + + afterEach(() => { + cleanup(); + localStorage.clear(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it("opens that run's report from the row action", async () => { + await openReport(DAY_B); + + expect(screen.getByText(`Çalıştırma günü ${DAY_B}`)).toBeTruthy(); + // RUN_B's own ledger row, not RUN_A's: its pending student is named in the report. + await waitFor(() => expect(panel().getByText(/1 öğrenci sıradaki çalıştırmaya kaldı: Ayça Şahin/)).toBeTruthy()); + }); + + it("renders the run's counters from the ledger row", async () => { + await openReport(DAY_A); + + await waitFor(() => expect(panel().getByText("İşlenen öğrenci")).toBeTruthy()); + expect(panel().getByText("16/16")).toBeTruthy(); + expect(panel().getByText("Yazılan kayıt")).toBeTruthy(); + expect(panel().getByText("16")).toBeTruthy(); + expect(panel().getByText("532 ms")).toBeTruthy(); + expect(panel().getByText("Sorun yok")).toBeTruthy(); + }); + + it("reads every student's signals through the roster and per-student doors", async () => { + await openReport(DAY_A); + + expect(usersApi.getUserSearch).toHaveBeenCalledWith("", undefined, "student", { limit: 200, offset: 0 }); + await waitFor(() => expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s1")); + expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s2"); + expect(insightsApi.getInsightByUserId).toHaveBeenCalledWith("s3"); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + // The headline numbers come from the answers, not from the fixture's prose. + expect(panel().getByText("71,0 (1/2)")).toBeTruthy(); + expect(panel().getByText("75%")).toBeTruthy(); + expect(panel().getByText("Sinyalleri yüklenen öğrenci: 3/3")).toBeTruthy(); + }); + + it("states veri yok where a module produced nothing instead of a blank panel", async () => { + await openReport(DAY_A); + + await waitFor(() => expect(panel().getByText(/Çalışma: 0\/3 öğrencide veri var/)).toBeTruthy()); + expect(panel().getByText(/Çalışma: 0\/3 öğrencide veri var → veri yok/)).toBeTruthy(); + expect(panel().getByText(/Notlar: 1\/3 öğrencide veri var/)).toBeTruthy(); + expect(panel().getByText("Çalışma oturumlarının ders bağı yoktur.")).toBeTruthy(); + // The student rows carry the same honesty. + expect(panel().getAllByText("veri yok").length).toBeGreaterThan(0); + expect(panel().getByText("Bu öğrenci için henüz analiz hesaplanmamış.")).toBeTruthy(); + }); + + it("opens the student's own analysis drawer from a report row", async () => { + await openReport(DAY_A); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + const row = panel().getByText("Arda Güneş").closest("tr") as HTMLElement; + fireEvent.click(within(row).getByRole("button", { name: "Öğrenci analizini aç" })); + + // The drawer is the shared InsightDetail component, rendering the stored fact. + await waitFor(() => expect(screen.getByText("Fizik notu son üç sınavda düşüyor.")).toBeTruthy()); + expect(screen.getAllByText("Öneriler").length).toBeGreaterThan(0); + }); + + it("copies the same document it shows to the clipboard", async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true }); + await openReport(DAY_A); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Kopyala" })); + + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); + const markdown = writeText.mock.calls[0][0] as string; + expect(markdown).toContain("16/16"); + expect(markdown).toContain("16"); + expect(markdown).toContain("Arda Güneş"); + expect(markdown).toContain("71,0 (1/2)"); + expect(markdown).toContain("Çalışma: 0/3 öğrencide veri var → veri yok"); + expect(markdown).toContain("Bu öğrenci için henüz analiz hesaplanmamış."); + }); + + it("downloads the .md built from the same content", async () => { + const blobs: Blob[] = []; + Object.defineProperty(URL, "createObjectURL", { + configurable: true, + writable: true, + value: (blob: Blob) => { + blobs.push(blob); + return "blob:run-report"; + }, + }); + Object.defineProperty(URL, "revokeObjectURL", { configurable: true, writable: true, value: vi.fn() }); + const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); + await openReport(DAY_A); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "İndir (.md)" })); + + await waitFor(() => expect(click).toHaveBeenCalledTimes(1)); + expect(blobs).toHaveLength(1); + const markdown = await blobs[0].text(); + expect(markdown).toContain("16/16"); + expect(markdown).toContain("Ayça Şahin"); + }); + + it("prints only the report document", async () => { + const print = vi.fn(); + Object.defineProperty(window, "print", { configurable: true, writable: true, value: print }); + await openReport(DAY_A); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + const printRoot = document.querySelector(".insight-report-print-root") as HTMLElement; + expect(printRoot.textContent).toContain("Arda Güneş"); + expect(document.body.classList.contains("insight-report-printing")).toBe(true); + + fireEvent.click(panel().getByRole("button", { name: "Yazdır / PDF" })); + expect(print).toHaveBeenCalledTimes(1); + }); + + it("builds the same Markdown without a DOM", () => { + const model = buildRunReportModel({ + run: RUN_A, + roster: ROSTER, + insights: { s1: INSIGHT_S1, s2: INSIGHT_S2, s3: INSIGHT_S3 }, + errors: {}, + coverageTotal: ROSTER.length, + rosterError: null, + }); + + const markdown = buildRunReportMarkdown(model, "tr"); + + expect(markdown).toContain("16/16"); + expect(markdown).toContain("Yazılan kayıt"); + expect(markdown).toContain("| Arda Güneş |"); + expect(markdown).toContain("71,0 (1/2)"); + expect(markdown).toContain("75%"); + expect(markdown).toContain("Çalışma: 0/3 öğrencide veri var → veri yok"); + expect(markdown).toContain("```json"); + }); +}); diff --git a/src/components/insights/insight-run-report.tsx b/src/components/insights/insight-run-report.tsx new file mode 100644 index 0000000..cea94e8 --- /dev/null +++ b/src/components/insights/insight-run-report.tsx @@ -0,0 +1,459 @@ +import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"; +import { Portal } from "solid-js/web"; +import { getInsightByUserId } from "@/api/insights"; +import { getUserSearch } from "@/api/users"; +import { formatApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client"; +import { InsightDetail } from "@/components/insights/insight-detail"; +import { Button } from "@/components/ui/button"; +import { EmptyInline } from "@/components/ui/empty-inline"; +import { IconCopy, IconDownload, IconFileText } from "@/components/ui/icons"; +import { SidePanel } from "@/components/ui/side-panel"; +import { runReportText, type RunReportKey } from "@/i18n/insights-run-report"; +import { formatDateTime } from "@/lib/format"; +import { + buildRunReportMarkdown, + buildRunReportModel, + formatRunDuration, + moduleLabel, + runReportFileName, + runReportStatusLabel, + studentAttendanceText, + studentMarksText, + studentStatusText, + type RunReportModel, +} from "@/lib/insight-run-report"; +import { personLabel } from "@/lib/person"; +import { createFlash } from "@/lib/flash"; +import { usePreferences } from "@/stores/preferences-context"; + +/** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */ +const ROSTER_PAGE = 200; +/** + * Signals are read one student at a time — the backend serves no school-level + * aggregate — so the report reads a bounded first slice on open and offers the + * rest behind a control that names the count. Never a silent cap. + */ +const AUTO_SIGNAL_LIMIT = 60; +const SIGNAL_CONCURRENCY = 6; +const PRINT_BODY_CLASS = "insight-report-printing"; +const PRINT_ROOT_CLASS = "insight-report-print-root"; + +/** + * Print shows the report and nothing else: the panel is a modal outside + * `#root`, so the app chrome is hidden by body class rather than by targeting + * the app root. Kept as one inline sheet so the report ships without touching + * a global stylesheet. + */ +const PRINT_STYLES = ` +.${PRINT_ROOT_CLASS} { display: none; } +@media print { + /* Hide everything that does not CONTAIN the print document: the app root and + every other portal, including the panel this report is shown in. Hiding + \`body > *:not(.${PRINT_ROOT_CLASS})\` would hide the portal's own wrapper + div (the class sits on its child), which prints a blank page. */ + body.${PRINT_BODY_CLASS} > *:not(:has(.${PRINT_ROOT_CLASS})) { display: none !important; } + .${PRINT_ROOT_CLASS} { display: block !important; padding: 0 10mm; color: #000 !important; background: #fff !important; } + .${PRINT_ROOT_CLASS} * { color: #000 !important; box-shadow: none !important; background: transparent !important; } + .${PRINT_ROOT_CLASS} h1 { font-size: 15pt; } + .${PRINT_ROOT_CLASS} h2 { font-size: 12pt; margin: 6mm 0 2mm; border-bottom: 1px solid #888; } + .${PRINT_ROOT_CLASS} table { width: 100%; border-collapse: collapse; font-size: 9pt; } + .${PRINT_ROOT_CLASS} th, .${PRINT_ROOT_CLASS} td { border: 1px solid #999; padding: 1.5mm; text-align: left; } + .${PRINT_ROOT_CLASS} dl { display: grid; grid-template-columns: 1fr 1fr; gap: 1mm 6mm; } + .${PRINT_ROOT_CLASS} details { display: none; } +} +`; + +/** + * The run's report as a document. One component renders the panel, the print + * sheet and (through the same model) the Markdown, so the export cannot drift + * from what is on screen. `onOpenStudent` is the only interactive affordance + * and it is absent from the print instance. + */ +function ReportDocument(props: { + model: RunReportModel; + /** True while signals are still being read: the school picture is not final. */ + loading?: boolean; + onOpenStudent?: (id: string) => void; +}) { + const prefs = usePreferences(); + const tx = (key: RunReportKey, vars?: Record) => + runReportText(prefs.locale(), key, vars); + const metrics = createMemo(() => { + const run = props.model.run; + return [ + { key: "runDay", label: tx("runDay"), value: run.run_day }, + { key: "status", label: tx("status"), value: runReportStatusLabel(prefs.locale(), run.status) }, + { key: "startedAt", label: tx("startedAt"), value: formatDateTime(run.started_at, prefs.locale()) }, + { key: "finishedAt", label: tx("finishedAt"), value: formatDateTime(run.finished_at, prefs.locale()) }, + { + key: "processed", + label: tx("processed"), + value: `${run.students_ok}/${run.students_total}`, + }, + { key: "skipped", label: tx("skipped"), value: String(run.students_skipped) }, + { key: "failed", label: tx("failed"), value: String(run.students_failed) }, + { key: "rowsWritten", label: tx("rowsWritten"), value: String(run.rows_written) }, + { key: "duration", label: tx("duration"), value: formatRunDuration(run.duration_ms, prefs.locale()) }, + { + key: "budget", + label: tx("budget"), + value: `${run.budget_exceeded ? tx("budgetExceeded") : tx("budgetWithin")} (${formatRunDuration(run.budget_ms, prefs.locale())})`, + }, + ]; + }); + + return ( +
+
+

{tx("title")}

+

{tx("subtitle")}

+
+ +
+

{tx("runSection")}

+
+ + {(metric) => ( +
+
{metric.label}
+
{metric.value}
+
+ )} +
+
+ 0}> +
    + 0}> +
  • + {tx("pendingStudents", { count: props.model.run.pending_students.length })} + {props.model.pending.length > 0 ? `: ${props.model.pending.map((row) => row.name ?? "—").join(", ")}` : ""} +
  • +
    + 0}> +
  • {tx("failedModules", { modules: props.model.run.failed_modules.join(", ") })}
  • +
    +
+
+ +

{tx("noIssues")}

+
+
+ +
+

{tx("schoolSection")}

+ +

+ {tx("coverage", { loaded: props.model.coverage.loaded, total: props.model.coverage.total })} +

+

{tx("coverageNote")}

+
    + + {(module) => ( +
  • + + {tx("moduleCovered", { + label: moduleLabel(prefs.locale(), module.id), + withData: module.with_data, + total: props.model.coverage.loaded, + })} + {module.with_data === 0 ? ` → ${tx("noData")}` : ""} + + + {(limitation) =>

    {limitation()}

    } +
    +
  • + )} +
    +
+ module.with_data === 0)}> +

{tx("modulesEmpty")}

+
+

+ {tx("attention")}: {props.model.totals.attention} · {tx("cards")}:{" "} + {props.model.totals.cards} · {tx("segments")}:{" "} + {props.model.totals.segments} +

+ + {(message) =>

{tx("rosterFailed", { message: message() })}

} +
+ +

{tx("rosterEmpty")}

+
+ + } + > +

{tx("loadingSignals")}

+
+
+ +
+

+ {tx("studentsSection")} ({props.model.coverage.loaded}/{props.model.coverage.total}) +

+
+ + + + + + + + + + + + + + + + + + + {(student) => ( + + + + + + + + + + + + + + )} + + +
{tx("student")}{tx("status")}{tx("confidence")}{tx("attention")}{tx("cards")}{tx("marksAverage")}{tx("attendanceRate")}{tx("computedAt")}{tx("studentAnalysis")}
{student.name}{studentStatusText(prefs.locale(), student)}{student.confidence ?? tx("noData")}{student.attention}{student.cards}{studentMarksText(prefs.locale(), student)}{studentAttendanceText(prefs.locale(), student)}{formatDateTime(student.computed_at, prefs.locale())} + +
+
+ + + +
+ +
+ {tx("technical")} +

{tx("technicalHint")}

+
+          {JSON.stringify(props.model.run, null, 2)}
+        
+
+
+ ); +} + +/** + * The school picture for one run: the ledger row's own counters, the modules' + * coverage across the students read for it, and every student's headline + * signals with a door into their own analysis drawer. + * + * There is no school-level report route: the run counters come from + * `GET /insights/runs`, and everything per-student from + * `GET /insights/students/{id}` — read here, one student at a time, with the + * coverage count always on screen so a partial read never reads as the school. + */ +export function InsightRunReport(props: { run: InsightRun }) { + const prefs = usePreferences(); + const tx = (key: RunReportKey, vars?: Record) => + runReportText(prefs.locale(), key, vars); + const [, flash] = createFlash(); + const [roster, setRoster] = createSignal([]); + const [rosterTotal, setRosterTotal] = createSignal(0); + const [rosterError, setRosterError] = createSignal(null); + const [insights, setInsights] = createSignal>({}); + const [failures, setFailures] = createSignal>({}); + const [loading, setLoading] = createSignal(true); + const [openStudentId, setOpenStudentId] = createSignal(null); + /** Dynamic membership by definition: ids enter and leave as reads settle. */ + const inFlight = new Set(); + + const loadSignals = async (ids: string[]) => { + const wanted = ids.filter( + (id) => !inFlight.has(id) && insights()[id] === undefined && failures()[id] === undefined, + ); + if (wanted.length === 0) return; + setLoading(true); + for (let start = 0; start < wanted.length; start += SIGNAL_CONCURRENCY) { + const batch = wanted.slice(start, start + SIGNAL_CONCURRENCY); + for (const id of batch) inFlight.add(id); + const settled = await Promise.all( + batch.map(async (id) => { + const [outcome] = await Promise.allSettled([getInsightByUserId(id)]); + return { id, outcome }; + }), + ); + const nextInsights = { ...insights() }; + const nextFailures = { ...failures() }; + for (const { id, outcome } of settled) { + inFlight.delete(id); + if (outcome.status === "fulfilled") nextInsights[id] = outcome.value; + else nextFailures[id] = formatApiError(outcome.reason); + } + setInsights(nextInsights); + setFailures(nextFailures); + } + setLoading(false); + }; + + const loadRoster = async (offset: number) => { + setLoading(true); + try { + const page = await getUserSearch("", undefined, "student", { limit: ROSTER_PAGE, offset }); + setRoster((current) => (offset === 0 ? page.items : [...current, ...page.items])); + setRosterTotal(page.total); + await loadSignals(page.items.slice(0, AUTO_SIGNAL_LIMIT).map((person) => person.id)); + } catch (error) { + setRosterError(formatApiError(error)); + } finally { + setLoading(false); + } + }; + + onMount(() => { + document.body.classList.add(PRINT_BODY_CLASS); + onCleanup(() => document.body.classList.remove(PRINT_BODY_CLASS)); + void loadRoster(0); + }); + + const model = createMemo(() => + buildRunReportModel({ + run: props.run, + roster: roster(), + insights: insights(), + errors: failures(), + coverageTotal: rosterTotal() || roster().length, + rosterError: rosterError(), + }), + ); + const markdown = () => buildRunReportMarkdown(model(), prefs.locale()); + const unloaded = () => + roster().filter((person) => insights()[person.id] === undefined && failures()[person.id] === undefined); + const openedStudent = createMemo(() => { + const id = openStudentId(); + return id ? roster().find((person) => person.id === id) ?? null : null; + }); + const openedInsight = createMemo(() => { + const id = openStudentId(); + return id ? insights()[id] ?? null : null; + }); + const openedFailure = createMemo(() => { + const id = openStudentId(); + return id ? failures()[id] ?? null : null; + }); + + const copyReport = async () => { + try { + await navigator.clipboard.writeText(markdown()); + flash(tx("copied")); + } catch { + flash(tx("copyFailed")); + } + }; + + const downloadReport = () => { + const url = URL.createObjectURL(new Blob([markdown()], { type: "text/markdown;charset=utf-8" })); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = runReportFileName(props.run.run_day); + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + URL.revokeObjectURL(url); + flash(tx("downloaded")); + }; + + return ( +
+
+ + + +
+ + 0}> +
+

+ {loading() ? tx("loadingSignals") : tx("coverage", { loaded: model().coverage.loaded, total: model().coverage.total })} +

+ +
+
+ + +

{tx("loadingSignals")}

+
+ + roster().length}> + + + + + + + +
+ +
+
+ + { + if (!open) setOpenStudentId(null); + }} + title={personLabel(openedStudent())} + description={tx("studentAnalysis")} + > + + {(insight) => } + + + {(message) =>

{tx("loadFailed", { message: message() })}

} +
+ + + +
+
+ ); +} diff --git a/src/components/insights/insight-runs-table.tsx b/src/components/insights/insight-runs-table.tsx index adcf28d..8fe7dc3 100644 --- a/src/components/insights/insight-runs-table.tsx +++ b/src/components/insights/insight-runs-table.tsx @@ -1,8 +1,13 @@ -import { createMemo } from "solid-js"; +import { Show, createMemo, createSignal } from "solid-js"; import type { ColumnDef } from "@tanstack/solid-table"; import type { InsightRun } from "@/api/client"; +import { InsightRunReport } from "@/components/insights/insight-run-report"; import { Badge } from "@/components/ui/badge"; import { DataTable } from "@/components/ui/data-table"; +import { IconFileText } from "@/components/ui/icons"; +import { SidePanel } from "@/components/ui/side-panel"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { runReportText, type RunReportKey } from "@/i18n/insights-run-report"; import { cn } from "@/lib/cn"; import { formatDateTime, formatDurationMinutes } from "@/lib/format"; import { usePreferences } from "@/stores/preferences-context"; @@ -18,6 +23,9 @@ function statusVariant(status: string) { export function InsightRunsTable(props: { runs: InsightRun[] }) { const prefs = usePreferences(); const tx = (key: string, vars?: Record) => prefs.t(key as never, vars); + const rtx = (key: RunReportKey, vars?: Record) => + runReportText(prefs.locale(), key, vars); + const [selectedRun, setSelectedRun] = createSignal(null); const statusLabel = (status: string) => ["running", "ok", "partial", "failed", "skipped"].includes(status) ? tx(`insights.status.${status}`) @@ -95,19 +103,58 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { ); }, }, + { + id: "actions", + header: tx("common.actions"), + enableSorting: false, + meta: { + headerClass: "w-[150px] min-w-[150px] max-w-[150px] h-[45px] text-center whitespace-nowrap", + cellClass: "w-[150px] min-w-[150px] max-w-[150px] h-[45px] text-center whitespace-nowrap", + }, + cell: (cell) => ( + , + onSelect: () => setSelectedRun(cell.row.original), + }, + ]} + /> + ), + }, ]); return ( - + <> + setSelectedRun(run)} + /> + + + {(run) => ( + { + if (!open) setSelectedRun(null); + }} + title={rtx("panelDescription", { day: run.run_day })} + > + + + )} + + ); } diff --git a/src/i18n/insights-run-report.ts b/src/i18n/insights-run-report.ts new file mode 100644 index 0000000..95ead55 --- /dev/null +++ b/src/i18n/insights-run-report.ts @@ -0,0 +1,212 @@ +import { formatMessage, type Locale } from "@/i18n/messages"; + +/** + * The school run report's own copy. + * + * It lives here rather than in `src/i18n/messages.ts` on purpose: two lanes + * write insight surfaces in the same batch, and a second writer on the shared + * dictionary is how one lane's keys get dropped by the other's commit. Same + * shape as the shared dictionary (every key, both locales, `{name}` vars), so + * a later tidy-up can fold it in mechanically. + */ +export type RunReportKey = + | "open" + | "title" + | "subtitle" + | "panelDescription" + | "copy" + | "copied" + | "copyFailed" + | "download" + | "downloaded" + | "print" + | "runSection" + | "schoolSection" + | "studentsSection" + | "technical" + | "technicalHint" + | "runDay" + | "startedAt" + | "finishedAt" + | "status" + | "processed" + | "skipped" + | "failed" + | "rowsWritten" + | "duration" + | "budget" + | "budgetExceeded" + | "budgetWithin" + | "issues" + | "noIssues" + | "pendingStudents" + | "failedModules" + | "coverage" + | "coverageNote" + | "loadAll" + | "loadingSignals" + | "loadMoreRoster" + | "rosterEmpty" + | "rosterFailed" + | "student" + | "confidence" + | "attention" + | "cards" + | "segments" + | "marksAverage" + | "marksCourses" + | "attendanceRate" + | "computedAt" + | "noData" + | "noSummary" + | "noModules" + | "loadFailed" + | "notLoaded" + | "openStudent" + | "studentAnalysis" + | "moduleMarks" + | "moduleAttendance" + | "moduleStudy" + | "moduleSubmission" + | "moduleCovered" + | "modulesEmpty" + | "documentTitle"; + +const tr: Record = { + open: "Raporu görüntüle", + title: "Okul analiz raporu", + subtitle: "Bu çalıştırmanın ürettiği sonuçlar", + panelDescription: "Çalıştırma günü {day}", + copy: "Kopyala", + copied: "Rapor panoya kopyalandı.", + copyFailed: "Rapor panoya kopyalanamadı.", + download: "İndir (.md)", + downloaded: "Rapor indirildi.", + print: "Yazdır / PDF", + runSection: "Çalıştırma özeti", + schoolSection: "Okul geneli", + studentsSection: "Öğrenci dökümü", + technical: "Teknik ayrıntı", + technicalHint: "Ham alanlar; insan görünümünde gizli tutulur.", + runDay: "Çalıştırma günü", + startedAt: "Başlangıç", + finishedAt: "Bitiş", + status: "Durum", + processed: "İşlenen öğrenci", + skipped: "Atlanan", + failed: "Hatalı", + rowsWritten: "Yazılan kayıt", + duration: "Süre", + budget: "Süre bütçesi", + budgetExceeded: "Bütçe doldu; sıradaki öğrenciler sonraki çalıştırmaya kaldı.", + budgetWithin: "Bütçe içinde tamamlandı.", + issues: "Sorunlar", + noIssues: "Sorun yok", + pendingStudents: "{count} öğrenci sıradaki çalıştırmaya kaldı", + failedModules: "Veri üretmeyen modüller: {modules}", + coverage: "Sinyalleri yüklenen öğrenci: {loaded}/{total}", + coverageNote: "Okul geneli sayılar yalnızca sinyalleri yüklenmiş öğrencileri kapsar.", + loadAll: "Kalan {count} öğrenciyi yükle", + loadingSignals: "Öğrenci sinyalleri yükleniyor…", + loadMoreRoster: "Öğrenci listesinin devamını yükle", + rosterEmpty: "Bu okulda listelenecek öğrenci yok; kapsanacak kimse bulunamadı.", + rosterFailed: "Öğrenci listesi okunamadı: {message}", + student: "Öğrenci", + confidence: "Güven", + attention: "Uyarı", + cards: "Öneri", + segments: "Soru grubu", + marksAverage: "Not ortalaması", + marksCourses: "Not girilen ders", + attendanceRate: "Devam oranı", + computedAt: "Hesaplandığı an", + noData: "veri yok", + noSummary: "Bu öğrenci için henüz analiz hesaplanmamış.", + noModules: "Analiz hesaplandı ama dört modülün hiçbiri veri üretmedi.", + loadFailed: "Analiz okunamadı: {message}", + notLoaded: "Yüklenmedi", + openStudent: "Öğrenci analizini aç", + studentAnalysis: "Öğrenci analizi", + moduleMarks: "Notlar", + moduleAttendance: "Yoklama", + moduleStudy: "Çalışma", + moduleSubmission: "Teslim", + moduleCovered: "{label}: {withData}/{total} öğrencide veri var", + modulesEmpty: "Hiçbir modül veri üretmedi; bu öğrenciler için hesaplanacak kaynak yok.", + documentTitle: "Okul analiz raporu — {day}", +}; + +const en: Record = { + open: "View report", + title: "School analysis report", + subtitle: "What this run produced", + panelDescription: "Run day {day}", + copy: "Copy", + copied: "Report copied to the clipboard.", + copyFailed: "Could not copy the report.", + download: "Download (.md)", + downloaded: "Report downloaded.", + print: "Print / PDF", + runSection: "Run summary", + schoolSection: "School overview", + studentsSection: "Student breakdown", + technical: "Technical detail", + technicalHint: "Raw fields, kept out of the human view.", + runDay: "Run day", + startedAt: "Started", + finishedAt: "Finished", + status: "Status", + processed: "Students processed", + skipped: "Skipped", + failed: "Failed", + rowsWritten: "Rows written", + duration: "Duration", + budget: "Time budget", + budgetExceeded: "The budget ran out; the remaining students wait for the next run.", + budgetWithin: "Finished within budget.", + issues: "Issues", + noIssues: "No issues", + pendingStudents: "{count} students left for the next run", + failedModules: "Modules that produced nothing: {modules}", + coverage: "Students with signals loaded: {loaded}/{total}", + coverageNote: "School overview numbers cover only the students whose signals are loaded.", + loadAll: "Load the remaining {count} students", + loadingSignals: "Loading student signals…", + loadMoreRoster: "Load more of the student list", + rosterEmpty: "This school has no students to list, so nobody could be covered.", + rosterFailed: "Could not read the student list: {message}", + student: "Student", + confidence: "Confidence", + attention: "Attention", + cards: "Recommendation", + segments: "Question group", + marksAverage: "Marks average", + marksCourses: "Courses with marks", + attendanceRate: "Attendance rate", + computedAt: "Computed at", + noData: "no data", + noSummary: "No analysis has been computed for this student yet.", + noModules: "The analysis ran but none of the four modules produced anything.", + loadFailed: "Could not read the analysis: {message}", + notLoaded: "Not loaded", + openStudent: "Open student analysis", + studentAnalysis: "Student analysis", + moduleMarks: "Marks", + moduleAttendance: "Attendance", + moduleStudy: "Study", + moduleSubmission: "Submission", + moduleCovered: "{label}: {withData}/{total} students have data", + modulesEmpty: "No module produced anything; there is nothing to compute from for these students.", + documentTitle: "School analysis report — {day}", +}; + +export const RUN_REPORT_MESSAGES: Record> = { en, tr }; + +export function runReportText( + locale: Locale, + key: RunReportKey, + vars?: Record, +): string { + const text = RUN_REPORT_MESSAGES[locale][key] ?? RUN_REPORT_MESSAGES.en[key] ?? key; + return formatMessage(text, vars); +} diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 823cd37..9bfcb7a 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -965,6 +965,8 @@ export type MessageKey = | "insights.duration" | "insights.issues" | "insights.issueCount" + | "insights.pendingStudents" + | "insights.failedModules" | "insights.noIssues" | "insights.budgetExceeded" | "insights.emptyRuns" @@ -3089,6 +3091,8 @@ const en: Dict = { "insights.duration": "Duration", "insights.issues": "Issues", "insights.issueCount": "{count} issue(s)", + "insights.pendingStudents": "{count} student(s) pending", + "insights.failedModules": "Modules that failed: {modules}", "insights.noIssues": "No issue", "insights.budgetExceeded": "Time budget exceeded", "insights.emptyRuns": "No analysis run yet.", @@ -5215,6 +5219,8 @@ const tr: Dict = { "insights.duration": "Süre", "insights.issues": "Sorunlar", "insights.issueCount": "{count} sorun", + "insights.pendingStudents": "{count} öğrenci sırada", + "insights.failedModules": "Veri üretmeyen modüller: {modules}", "insights.noIssues": "Sorun yok", "insights.budgetExceeded": "Süre bütçesi aşıldı", "insights.emptyRuns": "Henüz analiz çalıştırması yok.", diff --git a/src/lib/insight-run-report.ts b/src/lib/insight-run-report.ts new file mode 100644 index 0000000..8db257c --- /dev/null +++ b/src/lib/insight-run-report.ts @@ -0,0 +1,412 @@ +import type { InsightRun, PersonRef, StudentInsight } from "@/api/client"; +import { runReportText } from "@/i18n/insights-run-report"; +import type { Locale } from "@/i18n/messages"; +import { formatDateTime } from "@/lib/format"; + +/** + * The school run report's model and its Markdown rendering. + * + * The report has no aggregate door: the backend serves a run's counters + * (`GET /insights/runs`) and one student at a time (`GET /insights/students/{id}`), + * and nothing in between. So the school picture is composed here, from the + * students whose signals have been read, and every number the model carries is + * stated together with how many students it was computed over — a partial read + * must never read as "the school has none". + * + * The Markdown is the report: the panel renders this model, and the clipboard, + * the `.md` download and the print document are all built from the same model, + * so what is exported is exactly what is shown. + */ + +export type ModuleId = "marks" | "attendance" | "study" | "submission"; + +export type ModuleCoverage = { + id: ModuleId; + /** Students whose module holds a measurement (not merely a computed shell). */ + with_data: number; + /** Students whose summary carries the module at all. */ + computed: number; + /** The module's own limitation sentence, when it ships one. */ + limitation: string | null; +}; + +export type StudentSignal = { + id: string; + name: string; + /** + * `ok` — a summary was read. `no_summary` — the door answered and nothing has + * been computed for this student. `not_loaded` — this report has not read + * them yet. `error` — the read itself failed. + */ + state: "ok" | "no_summary" | "not_loaded" | "error"; + error: string | null; + confidence: string | null; + computed_at: number | null; + attention: number; + cards: number; + segments: number; + marks: { courses_with_marks: number; courses_total: number; average: number | null }; + attendance: { rate: number | null; observed: number }; + study: { stints: number }; + submission: { counted: number }; +}; + +export type RunReportModel = { + run: InsightRun; + students: StudentSignal[]; + /** How many students the school picture was computed over. */ + coverage: { loaded: number; total: number }; + modules: ModuleCoverage[]; + totals: { attention: number; cards: number; segments: number }; + pending: { id: string; name: string | null }[]; + roster_error: string | null; +}; + +// ---- reading ZEKA's module payloads --------------------------------------- +// +// The module members are `unknown` by contract and the service may grow them, +// so every read is by name behind a shape check: a missing field means "this +// module measured nothing", never a throw and never a zero invented from a +// different field. + +/** The shape gate every module read goes through; `null` for anything else. */ +function recordOf(value: unknown): Record | null { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : null; +} + +/** A finite number, or `null` — counts and rates alike are read through this. */ +function finiteNumber(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +export function readMarks(marks: unknown): StudentSignal["marks"] { + const courses = recordOf(recordOf(marks)?.courses) ?? {}; + const rows = Object.values(courses); + let withMarks = 0; + let sum = 0; + let counted = 0; + for (const row of rows) { + const course = recordOf(row); + if (!course) continue; + if ((finiteNumber(course.n_marks) ?? 0) > 0) withMarks += 1; + const average = finiteNumber(course.average); + if (average != null) { + sum += average; + counted += 1; + } + } + return { + courses_with_marks: withMarks, + courses_total: rows.length, + average: counted > 0 ? sum / counted : null, + }; +} + +export function readAttendance(attendance: unknown): StudentSignal["attendance"] & { limitation: string | null } { + const module = recordOf(attendance); + const overall = recordOf(module?.overall); + const limitation = module?.limitation; + return { + rate: finiteNumber(overall?.rate), + observed: finiteNumber(overall?.n_obs) ?? 0, + limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null, + }; +} + +export function readStudy(study: unknown): StudentSignal["study"] & { limitation: string | null } { + const module = recordOf(study); + const recent = recordOf(module?.recent_28d); + const limitation = module?.limitation; + return { + stints: finiteNumber(recent?.n_stints) ?? 0, + limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null, + }; +} + +export function readSubmission(submission: unknown): StudentSignal["submission"] & { limitation: string | null } { + const module = recordOf(submission); + const overall = recordOf(module?.overall); + const limitation = module?.limitation; + return { + counted: finiteNumber(overall?.n) ?? 0, + limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null, + }; +} + +const EMPTY_SIGNAL: Omit = { + confidence: null, + computed_at: null, + attention: 0, + cards: 0, + segments: 0, + marks: { courses_with_marks: 0, courses_total: 0, average: null }, + attendance: { rate: null, observed: 0 }, + study: { stints: 0 }, + submission: { counted: 0 }, +}; + +/** One student's readable signal line, from whatever the door answered. */ +export function toStudentSignal( + person: { id: string; name: string }, + insight: StudentInsight | null | undefined, + error: string | null, +): StudentSignal { + const identity = { id: person.id, name: person.name }; + if (error) return { ...identity, ...EMPTY_SIGNAL, state: "error", error }; + if (!insight) return { ...identity, ...EMPTY_SIGNAL, state: "not_loaded", error: null }; + const summary = insight.summary ?? null; + if (!summary) { + return { + ...identity, + ...EMPTY_SIGNAL, + state: "no_summary", + error: null, + attention: insight.attention.length, + cards: insight.cards.length, + segments: insight.segments.length, + }; + } + return { + ...identity, + state: "ok", + error: null, + confidence: summary.confidence, + computed_at: summary.computed_at, + attention: insight.attention.length, + cards: insight.cards.length, + segments: insight.segments.length, + marks: readMarks(summary.marks), + attendance: readAttendance(summary.attendance), + study: readStudy(summary.study), + submission: readSubmission(summary.submission), + }; +} + +/** Whether a module holds a measurement for one student. */ +export function moduleHasData(signal: StudentSignal, id: ModuleId): boolean { + if (signal.state !== "ok") return false; + if (id === "marks") return signal.marks.courses_with_marks > 0; + if (id === "attendance") return signal.attendance.observed > 0; + if (id === "study") return signal.study.stints > 0; + return signal.submission.counted > 0; +} + +export function buildRunReportModel(args: { + run: InsightRun; + roster: PersonRef[]; + insights: Record; + errors: Record; + coverageTotal: number; + rosterError: string | null; +}): RunReportModel { + const students = args.roster.map((person) => + toStudentSignal( + { id: person.id, name: person.display_name || person.username || person.id }, + args.insights[person.id] ?? null, + args.errors[person.id] ?? null, + ), + ); + const nameById: Record = {}; + for (const person of args.roster) { + nameById[person.id] = person.display_name || person.username; + } + const loaded = students.filter((student) => student.state === "ok" || student.state === "no_summary"); + const limitations: Record = { + marks: null, + attendance: null, + study: null, + submission: null, + }; + for (const student of loaded) { + const summary = args.insights[student.id]?.summary; + if (!summary) continue; + const found: [ModuleId, string | null][] = [ + ["attendance", readAttendance(summary.attendance).limitation], + ["study", readStudy(summary.study).limitation], + ["submission", readSubmission(summary.submission).limitation], + ]; + for (const [id, value] of found) { + if (value && !limitations[id]) limitations[id] = value; + } + } + const modules: ModuleCoverage[] = (["marks", "attendance", "study", "submission"] as ModuleId[]).map((id) => ({ + id, + with_data: loaded.filter((student) => moduleHasData(student, id)).length, + computed: loaded.filter((student) => args.insights[student.id]?.summary?.[id] != null).length, + limitation: limitations[id], + })); + return { + run: args.run, + students, + coverage: { loaded: loaded.length, total: args.coverageTotal }, + modules, + totals: { + attention: loaded.reduce((sum, student) => sum + student.attention, 0), + cards: loaded.reduce((sum, student) => sum + student.cards, 0), + segments: loaded.reduce((sum, student) => sum + student.segments, 0), + }, + pending: args.run.pending_students.map((id) => ({ id, name: nameById[id] ?? null })), + roster_error: args.rosterError, + }; +} + +// ---- rendering ------------------------------------------------------------- + +/** Run durations are sub-second in practice, so minutes-only would read "0 dk". */ +export function formatRunDuration(ms: number | null | undefined, locale: Locale): string { + if (ms == null) return "—"; + const tr = locale === "tr"; + if (ms < 1000) return `${Math.round(ms)} ms`; + if (ms < 60_000) return tr ? `${(ms / 1000).toFixed(1)} sn` : `${(ms / 1000).toFixed(1)} s`; + const minutes = ms / 60_000; + if (minutes < 60) return tr ? `${minutes.toFixed(1)} dk` : `${minutes.toFixed(1)} min`; + return tr ? `${(minutes / 60).toFixed(1)} sa` : `${(minutes / 60).toFixed(1)} h`; +} + +export function moduleLabel(locale: Locale, id: ModuleId): string { + if (id === "marks") return runReportText(locale, "moduleMarks"); + if (id === "attendance") return runReportText(locale, "moduleAttendance"); + if (id === "study") return runReportText(locale, "moduleStudy"); + return runReportText(locale, "moduleSubmission"); +} + +const STATUS_LABELS: Record> = { + tr: { running: "Sürüyor", ok: "Tamamlandı", partial: "Kısmi", failed: "Başarısız", skipped: "Atlandı" }, + en: { running: "Running", ok: "Completed", partial: "Partial", failed: "Failed", skipped: "Skipped" }, +}; + +export function runReportStatusLabel(locale: Locale, status: string): string { + return STATUS_LABELS[locale][status] ?? status; +} + +export function runReportFileName(runDay: string): string { + return `okul-analiz-raporu-${runDay}.md`; +} + +/** `0,716` in Turkish, `0.716` in English — the same number either way. */ +export function runReportDecimal(value: number, locale: Locale): string { + return value.toFixed(1).replace(".", locale === "tr" ? "," : "."); +} + +/** `85%`, or `veri yok` when the module measured nothing. */ +export function runReportPercent(value: number | null, locale: Locale): string { + return value == null ? runReportText(locale, "noData") : `${Math.round(value * 100)}%`; +} + +export function studentStatusText(locale: Locale, student: StudentSignal): string { + if (student.state === "ok") return runReportStatusLabel(locale, "ok"); + if (student.state === "no_summary") return runReportText(locale, "noSummary"); + if (student.state === "error") return student.error ?? runReportText(locale, "noData"); + return runReportText(locale, "notLoaded"); +} + +/** + * `Yüklenmedi` while nothing has been read, `veri yok` only once a read has + * said so — the two are different claims, and the panel and the export must + * make the same one. + */ +export function studentMarksText(locale: Locale, student: StudentSignal): string { + if (student.state === "not_loaded") return runReportText(locale, "notLoaded"); + if (student.state !== "ok") return runReportText(locale, "noData"); + const average = student.marks.average == null ? "—" : runReportDecimal(student.marks.average, locale); + return `${average} (${student.marks.courses_with_marks}/${student.marks.courses_total})`; +} + +export function studentAttendanceText(locale: Locale, student: StudentSignal): string { + if (student.state === "not_loaded") return runReportText(locale, "notLoaded"); + if (student.state !== "ok" || student.attendance.observed === 0) return runReportText(locale, "noData"); + return runReportPercent(student.attendance.rate, locale); +} + +/** + * The report as Markdown — what `Kopyala`, the `.md` download and the print + * document all carry. Every section of the panel is here, `veri yok` lines + * included: an export that silently dropped the empty modules would be a + * prettier lie than the screen. + */ +export function buildRunReportMarkdown(model: RunReportModel, locale: Locale): string { + const t = (key: Parameters[1], vars?: Record) => + runReportText(locale, key, vars); + const { run, coverage } = model; + const lines: string[] = []; + lines.push(`# ${t("documentTitle", { day: run.run_day })}`); + lines.push(""); + lines.push(`## ${t("runSection")}`); + lines.push(`- ${t("runDay")}: ${run.run_day}`); + lines.push(`- ${t("status")}: ${runReportStatusLabel(locale, run.status)}`); + lines.push(`- ${t("startedAt")}: ${formatDateTime(run.started_at, locale)}`); + lines.push(`- ${t("finishedAt")}: ${formatDateTime(run.finished_at, locale)}`); + lines.push( + `- ${t("processed")}: ${run.students_ok}/${run.students_total} (${t("skipped").toLowerCase()} ${run.students_skipped}, ${t("failed").toLowerCase()} ${run.students_failed})`, + ); + lines.push(`- ${t("rowsWritten")}: ${run.rows_written}`); + lines.push(`- ${t("duration")}: ${formatRunDuration(run.duration_ms, locale)}`); + lines.push( + `- ${t("budget")}: ${run.budget_exceeded ? t("budgetExceeded") : t("budgetWithin")} (${formatRunDuration(run.budget_ms, locale)})`, + ); + const issueCount = run.pending_students.length + run.failed_modules.length + (run.budget_exceeded ? 1 : 0); + lines.push(`- ${t("issues")}: ${issueCount === 0 ? t("noIssues") : String(issueCount)}`); + if (run.pending_students.length > 0) { + lines.push(`- ${t("pendingStudents", { count: run.pending_students.length })}`); + } + if (run.failed_modules.length > 0) { + lines.push(`- ${t("failedModules", { modules: run.failed_modules.join(", ") })}`); + } + lines.push(""); + lines.push(`## ${t("schoolSection")}`); + if (model.roster_error) lines.push(`- ${t("rosterFailed", { message: model.roster_error })}`); + lines.push(`- ${t("coverage", { loaded: coverage.loaded, total: coverage.total })}`); + if (coverage.loaded === 0) lines.push(`- ${t("rosterEmpty")}`); + for (const module of model.modules) { + const label = moduleLabel(locale, module.id); + const covered = t("moduleCovered", { label, withData: module.with_data, total: coverage.loaded }); + lines.push(`- ${covered}${module.with_data === 0 ? ` → ${t("noData")}` : ""}`); + if (module.limitation) lines.push(` - ${module.limitation}`); + } + if (coverage.loaded > 0 && model.modules.every((module) => module.with_data === 0)) { + lines.push(`- ${t("modulesEmpty")}`); + } + lines.push( + `- ${t("attention")}: ${model.totals.attention} · ${t("cards")}: ${model.totals.cards} · ${t("segments")}: ${model.totals.segments}`, + ); + lines.push(`- ${t("coverageNote")}`); + lines.push(""); + lines.push(`## ${t("studentsSection")} (${coverage.loaded}/${coverage.total})`); + const header = [ + t("student"), + t("status"), + t("confidence"), + t("attention"), + t("cards"), + t("marksAverage"), + t("attendanceRate"), + t("computedAt"), + ]; + lines.push(`| ${header.join(" | ")} |`); + lines.push(`| ${header.map(() => "---").join(" | ")} |`); + for (const student of model.students) { + const cells = [ + student.name, + studentStatusText(locale, student), + student.confidence ?? t("noData"), + String(student.attention), + String(student.cards), + studentMarksText(locale, student), + studentAttendanceText(locale, student), + formatDateTime(student.computed_at, locale), + ]; + lines.push(`| ${cells.map((cell) => cell.replace(/\|/g, "\\|")).join(" | ")} |`); + } + if (model.students.length === 0) lines.push(`| ${t("rosterEmpty")} | | | | | | | |`); + lines.push(""); + lines.push(`## ${t("technical")}`); + lines.push(t("technicalHint")); + lines.push(""); + lines.push("```json"); + lines.push(JSON.stringify(run, null, 2)); + lines.push("```"); + lines.push(""); + return lines.join("\n"); +}