forge
Explore
Log in

Don't you dare go Hollow

📄 generate the school report document from the run drawer

Browse files at this commit

ea53ad27732920bc64a21998fb9374c2b74abd00Ahmet Kaan GümüşParent: e6e9aad
  • feat
    • 📄 generate the school report document from the run drawer
Show full message
feat: 📄 generate the school report document from the run drawer

The run report drawer could copy, export Markdown and print what the page
had already read, but the school-level document the AI service writes had
no control. `Okul raporu (HTML)` now POSTs the run day's own
`/insights/runs/{run_day}/report` door, reads the stored document back and
then hands it over as a same-origin `<a download>` — so a generation that
answered `200` but stored nothing surfaces as "belge okunamadı" instead of
an empty download.

- `src/api/insights/`: `insightRunReportUrl`/`insightRunReportPath`,
  `postInsightRunReport` and `getInsightRunReport`, following the podcast
  audio-door shape; the path is spelled once for both doors.
- Failure copy: `503` says the report service is unavailable, a coded `409`
  shows the server's own sentence, a read-back `409 report_missing` says the
  document could not be read back — never an invented diagnosis.
- The control exists for manager+ only, the role the door accepts.
- Tests: the door URLs at the API layer, and in the drawer the exact POST
  target, the in-flight disabled state, the anchor's href/download name, and
  each of the three failure classes.
src/api/__tests__/insights/insights.test.tsmodified+44 -1
@@ -1,13 +1,16 @@
1 import { afterEach, describe, expect, it, vi } from "vitest";1 import { afterEach, describe, expect, it, vi } from "vitest";
2 import {2 import {
3 getInsightByUserId,3 getInsightByUserId,
4+ getInsightRunReport,
4 getInsightRuns,5 getInsightRuns,
5 getInsightsPending,6 getInsightsPending,
6 getMyInsight,7 getMyInsight,
8+ insightRunReportUrl,
7 postInsightComputeByUserId,9 postInsightComputeByUserId,
10+ postInsightRunReport,
8 postInsightsRefresh,11 postInsightsRefresh,
9 } from "../../insights";12 } from "../../insights";
10-import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";13+import { lastFetchCall, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch";
11 14
12 describe("insights API", () => {15 describe("insights API", () => {
13 afterEach(() => {16 afterEach(() => {
@@ -115,4 +118,44 @@ describe("insights API", () => {
115 const [, init] = lastFetchCall();118 const [, init] = lastFetchCall();
116 expect(init?.body).toBe(JSON.stringify({}));119 expect(init?.body).toBe(JSON.stringify({}));
117 });120 });
121+
122+ it("postInsightRunReport POSTs the run day's own /report door", async () => {
123+ mockFetchSuccess({
124+ run_day: "2026-09-18",
125+ byte_size: 4096,
126+ truncated: false,
127+ notes: [],
128+ generated_at: 1_758_000_000_000,
129+ });
130+
131+ const receipt = await postInsightRunReport("2026-09-18");
132+ expect(receipt.byte_size).toBe(4096);
133+
134+ const [url, init] = lastFetchCall();
135+ expect(url).toBe("/api/insights/runs/2026-09-18/report");
136+ expect(init?.method).toBe("POST");
137+ });
138+
139+ it("insightRunReportUrl encodes the run day and getInsightRunReport reads those bytes back", async () => {
140+ expect(insightRunReportUrl("a/b")).toBe("/api/insights/runs/a%2Fb/report");
141+ const blob = new Blob(["<html>okul</html>"], { type: "text/html;charset=utf-8" });
142+ mockFetchBlob(blob);
143+
144+ const bytes = await getInsightRunReport("2026-09-18");
145+
146+ expect(await bytes.text()).toBe("<html>okul</html>");
147+ const [url, init] = lastFetchCall();
148+ // `blobClient` adds the `/api` the URL builder already carries for hrefs.
149+ expect(url).toBe("/api/insights/runs/2026-09-18/report");
150+ expect(init?.method ?? "GET").toBe("GET");
151+ });
152+
153+ it("getInsightRunReport surfaces a 409 report_missing as an ApiError", async () => {
154+ mockFetchError(409, { error: "no school report is stored for this run day", code: "report_missing" });
155+
156+ await expect(getInsightRunReport("2026-09-18")).rejects.toMatchObject({
157+ status: 409,
158+ message: "no school report is stored for this run day",
159+ });
160+ });
118 });161 });
src/api/insights/getInsightRunReport.tsadded+12 -0
@@ -0,0 +1,12 @@
1+import { blobClient } from "../client";
2+import { insightRunReportPath } from "./insightRunReportUrl";
3+
4+/**
5+ * The stored document's bytes. Read back after a generation that answered
6+ * `200`: a day whose report was never written — or was lost since — answers
7+ * `409 report_missing`, which must not be handed over as a download.
8+ * Manager+ only, like the generation that wrote it.
9+ */
10+export function getInsightRunReport(runDay: string, signal?: AbortSignal): Promise<Blob> {
11+ return blobClient(insightRunReportPath(runDay), signal);
12+}
src/api/insights/index.tsmodified+3 -0
@@ -4,3 +4,6 @@ export * from "./postInsightComputeByUserId";
4 export * from "./getInsightRuns";4 export * from "./getInsightRuns";
5 export * from "./postInsightsRefresh";5 export * from "./postInsightsRefresh";
6 export * from "./getInsightsPending";6 export * from "./getInsightsPending";
7+export * from "./insightRunReportUrl";
8+export * from "./postInsightRunReport";
9+export * from "./getInsightRunReport";
src/api/insights/insightRunReportUrl.tsadded+16 -0
@@ -0,0 +1,16 @@
1+/**
2+ * One run day's school report door, spelled once: the two requests go through
3+ * `client`/`blobClient`, which add `/api` themselves, while the download link
4+ * has to carry the prefix — so the prefixed form is built from the same path.
5+ *
6+ * `runDay` is the ledger row's own `run_day` (`YYYY-MM-DD`). A day nothing was
7+ * generated for answers `409 report_missing`; a caller below manager is refused.
8+ */
9+export function insightRunReportPath(runDay: string): string {
10+ return `/insights/runs/${encodeURIComponent(runDay)}/report`;
11+}
12+
13+/** The same door as a same-origin URL — hand it to an `<a href>`: the session cookie rides along. */
14+export function insightRunReportUrl(runDay: string): string {
15+ return `/api${insightRunReportPath(runDay)}`;
16+}
src/api/insights/postInsightRunReport.tsadded+26 -0
@@ -0,0 +1,26 @@
1+import { client } from "../client";
2+import { insightRunReportPath } from "./insightRunReportUrl";
3+
4+/**
5+ * The receipt for the school report the service just wrote: the day it covers,
6+ * its size in bytes, whether the service had to truncate it, the service's own
7+ * notes, and when it was stored (ms epoch, the same clock as the run ledger).
8+ */
9+export type GeneratedInsightRunReport = {
10+ run_day: string;
11+ byte_size: number;
12+ truncated: boolean;
13+ notes: string[];
14+ generated_at: number;
15+};
16+
17+/**
18+ * Generate the school-level report document for one run day. Manager+ only,
19+ * and synchronous: the service writes it before this answers. `503` when no AI
20+ * service offers the report right now; `409` (`report_refused`) when the
21+ * service refused — nothing is stored then, so `getInsightRunReport` would
22+ * find nothing.
23+ */
24+export function postInsightRunReport(runDay: string): Promise<GeneratedInsightRunReport> {
25+ return client<GeneratedInsightRunReport>(insightRunReportPath(runDay), { method: "POST" });
26+}
src/components/insights/insight-run-report.test.tsxmodified+168 -4
@@ -1,15 +1,30 @@
1 import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";1 import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";
2 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";2 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3-import type { InsightRun, PersonRef, StudentInsight } from "@/api/client";3+import { ApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client";
4+import type * as insightsApiModule from "@/api/insights";
4 import { InsightRunsTable } from "@/components/insights/insight-runs-table";5 import { InsightRunsTable } from "@/components/insights/insight-runs-table";
5 import { buildRunReportMarkdown, buildRunReportModel } from "@/lib/insight-run-report";6 import { buildRunReportMarkdown, buildRunReportModel } from "@/lib/insight-run-report";
6 import { PreferencesProvider } from "@/stores/preferences-context";7 import { PreferencesProvider } from "@/stores/preferences-context";
7 8
8-const insightsApi = vi.hoisted(() => ({ getInsightByUserId: vi.fn() }));9+const insightsApi = vi.hoisted(() => ({
10+ getInsightByUserId: vi.fn(),
11+ postInsightRunReport: vi.fn(),
12+ getInsightRunReport: vi.fn(),
13+}));
9 const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() }));14 const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() }));
10-15+/** Who the drawer thinks is reading: generation is offered to manager+ only. */
11-vi.mock("@/api/insights", () => insightsApi);16+const viewer = vi.hoisted(() => ({ role: "manager" as "manager" | "teacher" }));
17+
18+// The URL builder stays real (the drawer and the download use it); only the
19+// two doors and the per-student read are stood in for.
20+vi.mock("@/api/insights", async () => ({
21+ ...(await vi.importActual<typeof insightsApiModule>("@/api/insights")),
22+ ...insightsApi,
23+}));
12 vi.mock("@/api/users", () => usersApi);24 vi.mock("@/api/users", () => usersApi);
25+vi.mock("@/stores/auth-context", () => ({
26+ useAuth: () => ({ user: () => ({ id: "m-1", role: viewer.role }), loading: () => false }),
27+}));
13 // Kobalte's dropdown chrome is not what this test is about: flatten it to one28 // 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.29 // plain button per action so the report path can be driven in jsdom.
15 vi.mock("@/components/ui/table-row-actions", () => ({30 vi.mock("@/components/ui/table-row-actions", () => ({
@@ -147,6 +162,7 @@ async function openReport(runDay: string) {
147 162
148 describe("InsightRunReport", () => {163 describe("InsightRunReport", () => {
149 beforeEach(() => {164 beforeEach(() => {
165+ viewer.role = "manager";
150 localStorage.setItem("hezarfen.locale", "tr");166 localStorage.setItem("hezarfen.locale", "tr");
151 usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 });167 usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 });
152 insightsApi.getInsightByUserId.mockImplementation((userId: string) => {168 insightsApi.getInsightByUserId.mockImplementation((userId: string) => {
@@ -335,4 +351,152 @@ describe("InsightRunReport", () => {
335 expect(markdown).toContain("Keşifsel");351 expect(markdown).toContain("Keşifsel");
336 expect(markdown).toContain("```json");352 expect(markdown).toContain("```json");
337 });353 });
354+
355+ it("asks the service for the rendered run day's report and reads it back before offering it", async () => {
356+ const receipt = {
357+ run_day: DAY_B,
358+ byte_size: 4096,
359+ truncated: false,
360+ notes: [],
361+ generated_at: COMPUTED_AT,
362+ };
363+ const pending = Promise.withResolvers<typeof receipt>();
364+ insightsApi.postInsightRunReport.mockImplementation(() => pending.promise);
365+ insightsApi.getInsightRunReport.mockResolvedValue(new Blob(["<html/>"], { type: "text/html" }));
366+ // The hand-over itself is the other test's subject; here it must not navigate.
367+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
368+ await openReport(DAY_B);
369+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
370+
371+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
372+
373+ // The door is this run row's own day, and it is asked before the read.
374+ expect(insightsApi.postInsightRunReport).toHaveBeenCalledWith(DAY_B);
375+ expect(insightsApi.getInsightRunReport).not.toHaveBeenCalled();
376+ const busy = panel().getByRole("button", { name: "Rapor oluşturuluyor…" }) as HTMLButtonElement;
377+ expect(busy.disabled).toBe(true);
378+
379+ pending.resolve(receipt);
380+
381+ // Read-back first: the bytes are what prove there is a document to hand over.
382+ await waitFor(() => expect(insightsApi.getInsightRunReport).toHaveBeenCalledWith(DAY_B));
383+ await waitFor(() =>
384+ expect(panel().getByRole("button", { name: "Okul raporu (HTML)" })).toBeTruthy(),
385+ );
386+ expect((panel().getByRole("button", { name: "Okul raporu (HTML)" }) as HTMLButtonElement).disabled).toBe(
387+ false,
388+ );
389+ });
390+
391+ it("hands the stored document over as an anchor on its own door, under its own file name", async () => {
392+ const clicked: { href: string | null; download: string | null }[] = [];
393+ const click = vi
394+ .spyOn(HTMLAnchorElement.prototype, "click")
395+ .mockImplementation(function (this: HTMLAnchorElement) {
396+ clicked.push({ href: this.getAttribute("href"), download: this.getAttribute("download") });
397+ });
398+ insightsApi.postInsightRunReport.mockResolvedValue({
399+ run_day: DAY_B,
400+ byte_size: 4096,
401+ truncated: false,
402+ notes: [],
403+ generated_at: COMPUTED_AT,
404+ });
405+ insightsApi.getInsightRunReport.mockResolvedValue(new Blob(["<html/>"], { type: "text/html" }));
406+ await openReport(DAY_B);
407+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
408+
409+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
410+
411+ await waitFor(() => expect(click).toHaveBeenCalledTimes(1));
412+ expect(clicked[0]).toEqual({
413+ href: `/api/insights/runs/${DAY_B}/report`,
414+ download: `okul-analiz-raporu-${DAY_B}.html`,
415+ });
416+ });
417+
418+ it("says the report service is unavailable on a 503 and puts the control back", async () => {
419+ insightsApi.postInsightRunReport.mockRejectedValue(
420+ new ApiError(503, "no AI service is connected right now"),
421+ );
422+ await openReport(DAY_B);
423+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
424+
425+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
426+
427+ await waitFor(() =>
428+ expect(
429+ panel().getByText("Okul raporu servisi şu an kullanılamıyor. Sonra tekrar dene."),
430+ ).toBeTruthy(),
431+ );
432+ expect((panel().getByRole("button", { name: "Okul raporu (HTML)" }) as HTMLButtonElement).disabled).toBe(
433+ false,
434+ );
435+ expect(insightsApi.getInsightRunReport).not.toHaveBeenCalled();
436+ });
437+
438+ it("says the document is too large without telling the reader to pick a smaller file", async () => {
439+ insightsApi.postInsightRunReport.mockRejectedValue(new ApiError(413, "document_too_large"));
440+ await openReport(DAY_B);
441+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
442+
443+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
444+
445+ await waitFor(() =>
446+ expect(panel().getByText("Rapor belgesi sunucunun boyut sınırını aştı.")).toBeTruthy(),
447+ );
448+ expect(panel().queryByText(/Daha küçük bir dosya seç/)).toBeNull();
449+ });
450+
451+ it("shows the server's own sentence when the service refuses the generation", async () => {
452+ insightsApi.postInsightRunReport.mockRejectedValue(
453+ new ApiError(409, "the school report was refused: no marks were stored for this run day"),
454+ );
455+ await openReport(DAY_B);
456+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
457+
458+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
459+
460+ await waitFor(() =>
461+ expect(
462+ panel().getByText("the school report was refused: no marks were stored for this run day"),
463+ ).toBeTruthy(),
464+ );
465+ });
466+
467+ it("says the document could not be read back when the generation answered but stored nothing", async () => {
468+ insightsApi.postInsightRunReport.mockResolvedValue({
469+ run_day: DAY_B,
470+ byte_size: 0,
471+ truncated: false,
472+ notes: [],
473+ generated_at: COMPUTED_AT,
474+ });
475+ insightsApi.getInsightRunReport.mockRejectedValue(
476+ new ApiError(409, "no school report is stored for this run day"),
477+ );
478+ await openReport(DAY_B);
479+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
480+
481+ fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" }));
482+
483+ await waitFor(() =>
484+ expect(panel().getByText("Rapor oluşturuldu ama belge okunamadı. Tekrar dene.")).toBeTruthy(),
485+ );
486+ // The server's own 409 text is not what the reader gets: nothing was refused.
487+ expect(panel().queryByText("no school report is stored for this run day")).toBeNull();
488+ });
489+
490+ it("offers no generation control to a reader the door would refuse", async () => {
491+ viewer.role = "teacher";
492+ await openReport(DAY_B);
493+ await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy());
494+
495+ expect(panel().queryByRole("button", { name: "Okul raporu (HTML)" })).toBeNull();
496+ // The three controls that only read what is already on screen stay.
497+ expect(panel().getByRole("button", { name: "Kopyala" })).toBeTruthy();
498+ expect(panel().getByRole("button", { name: "İndir (.md)" })).toBeTruthy();
499+ expect(panel().getByRole("button", { name: "Yazdır / PDF" })).toBeTruthy();
500+ expect(insightsApi.postInsightRunReport).not.toHaveBeenCalled();
501+ });
338 });502 });
src/components/insights/insight-run-report.tsxmodified+77 -3
@@ -1,12 +1,13 @@
1 import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";1 import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";
2 import { Portal } from "solid-js/web";2 import { Portal } from "solid-js/web";
3-import { getInsightByUserId } from "@/api/insights";3+import { getInsightByUserId, getInsightRunReport, insightRunReportUrl, postInsightRunReport } from "@/api/insights";
4 import { getUserSearch } from "@/api/users";4 import { getUserSearch } from "@/api/users";
5-import { formatApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client";5+import { ApiError, formatApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client";
6 import { InsightDetail } from "@/components/insights/insight-detail";6 import { InsightDetail } from "@/components/insights/insight-detail";
7 import { Button } from "@/components/ui/button";7 import { Button } from "@/components/ui/button";
8 import { EmptyInline } from "@/components/ui/empty-inline";8 import { EmptyInline } from "@/components/ui/empty-inline";
9-import { IconCopy, IconDownload, IconFileText } from "@/components/ui/icons";9+import { ErrorAlert } from "@/components/ui/error-alert";
10+import { IconCopy, IconDownload, IconFileText, IconReportAnalytics } from "@/components/ui/icons";
10 import { SidePanel } from "@/components/ui/side-panel";11 import { SidePanel } from "@/components/ui/side-panel";
11 import { runReportText, type RunReportKey } from "@/i18n/insights-run-report";12 import { runReportText, type RunReportKey } from "@/i18n/insights-run-report";
12 import { formatDateTime } from "@/lib/format";13 import { formatDateTime } from "@/lib/format";
@@ -19,6 +20,7 @@ import {
19 moduleLabel,20 moduleLabel,
20 pendingStudentsLine,21 pendingStudentsLine,
21 runReportFileName,22 runReportFileName,
23+ runReportHtmlFileName,
22 runReportStatusLabel,24 runReportStatusLabel,
23 studentAttendanceText,25 studentAttendanceText,
24 studentMarksText,26 studentMarksText,
@@ -27,6 +29,8 @@ import {
27 } from "@/lib/insight-run-report";29 } from "@/lib/insight-run-report";
28 import { personLabel } from "@/lib/person";30 import { personLabel } from "@/lib/person";
29 import { createFlash } from "@/lib/flash";31 import { createFlash } from "@/lib/flash";
32+import { hasMinRole } from "@/lib/roles";
33+import { useAuth } from "@/stores/auth-context";
30 import { usePreferences } from "@/stores/preferences-context";34 import { usePreferences } from "@/stores/preferences-context";
31 35
32 /** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */36 /** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */
@@ -278,7 +282,12 @@ export function InsightRunReport(props: { run: InsightRun }) {
278 const prefs = usePreferences();282 const prefs = usePreferences();
279 const tx = (key: RunReportKey, vars?: Record<string, string | number>) =>283 const tx = (key: RunReportKey, vars?: Record<string, string | number>) =>
280 runReportText(prefs.locale(), key, vars);284 runReportText(prefs.locale(), key, vars);
285+ const auth = useAuth();
286+ /** Generation is manager+ — the door refuses anyone below it, so the control is not offered. */
287+ const canGenerateReport = () => hasMinRole(auth.user()?.role, "manager");
281 const [, flash] = createFlash();288 const [, flash] = createFlash();
289+ const [generatingReport, setGeneratingReport] = createSignal(false);
290+ const [reportError, setReportError] = createSignal<string | null>(null);
282 const [roster, setRoster] = createSignal<PersonRef[]>([]);291 const [roster, setRoster] = createSignal<PersonRef[]>([]);
283 const [rosterTotal, setRosterTotal] = createSignal(0);292 const [rosterTotal, setRosterTotal] = createSignal(0);
284 const [rosterError, setRosterError] = createSignal<string | null>(null);293 const [rosterError, setRosterError] = createSignal<string | null>(null);
@@ -384,6 +393,54 @@ export function InsightRunReport(props: { run: InsightRun }) {
384 flash(tx("downloaded"));393 flash(tx("downloaded"));
385 };394 };
386 395
396+ /**
397+ * The sentence a failed generation shows. A coded refusal (`409`) carries
398+ * the server's own sentence about why it refused, so that one is shown
399+ * as-is; everything else goes through the house renderer. The single `409`
400+ * this control can meet *after* its own `200` — `report_missing` — says the
401+ * document could not be read back instead: the service did not refuse
402+ * anything, its document is simply not there.
403+ */
404+ const reportFailureText = (err: unknown, readingBack: boolean): string => {
405+ if (err instanceof ApiError && err.status === 409) {
406+ return readingBack ? tx("schoolReportUnreadable") : err.message;
407+ }
408+ if (err instanceof ApiError && err.status === 503) return tx("schoolReportUnavailable");
409+ // The house 413 copy is about uploads ("choose a smaller file") — wrong
410+ // instruction here: nothing was chosen, the service's own document is big.
411+ if (err instanceof ApiError && err.status === 413) return tx("schoolReportTooLarge");
412+ return formatApiError(err);
413+ };
414+
415+ /**
416+ * Ask the service for this run day's school-level document, then hand it
417+ * over. The read-back in between is what keeps a `200` honest: without it a
418+ * generation that stored nothing would still open a download that answers
419+ * `409`. The anchor points at the door itself — same-origin, so the session
420+ * cookie rides along — rather than at bytes this tab fetched.
421+ */
422+ const generateSchoolReport = async () => {
423+ const runDay = props.run.run_day;
424+ setGeneratingReport(true);
425+ setReportError(null);
426+ let readingBack = false;
427+ try {
428+ await postInsightRunReport(runDay);
429+ readingBack = true;
430+ await getInsightRunReport(runDay);
431+ const anchor = document.createElement("a");
432+ anchor.href = insightRunReportUrl(runDay);
433+ anchor.download = runReportHtmlFileName(runDay);
434+ document.body.appendChild(anchor);
435+ anchor.click();
436+ anchor.remove();
437+ } catch (err) {
438+ setReportError(reportFailureText(err, readingBack));
439+ } finally {
440+ setGeneratingReport(false);
441+ }
442+ };
443+
387 return (444 return (
388 <div class="space-y-5">445 <div class="space-y-5">
389 <div class="flex flex-wrap items-center justify-end gap-2">446 <div class="flex flex-wrap items-center justify-end gap-2">
@@ -399,8 +456,25 @@ export function InsightRunReport(props: { run: InsightRun }) {
399 <IconFileText class="h-4 w-4" />456 <IconFileText class="h-4 w-4" />
400 {tx("print")}457 {tx("print")}
401 </Button>458 </Button>
459+ <Show when={canGenerateReport()}>
460+ <Button
461+ variant="outline"
462+ size="sm"
463+ class="rounded-lg"
464+ disabled={generatingReport()}
465+ aria-busy={generatingReport()}
466+ onClick={() => void generateSchoolReport()}
467+ >
468+ <IconReportAnalytics class="h-4 w-4" />
469+ {generatingReport() ? tx("schoolReportGenerating") : tx("schoolReport")}
470+ </Button>
471+ </Show>
402 </div>472 </div>
403 473
474+ <Show when={reportError()}>
475+ {(message) => <ErrorAlert message={message()} />}
476+ </Show>
477+
404 <Show when={unloaded().length > 0}>478 <Show when={unloaded().length > 0}>
405 <div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border-line px-3 py-2">479 <div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border-line px-3 py-2">
406 <p class="text-xs text-muted-foreground">480 <p class="text-xs text-muted-foreground">
src/i18n/insights-run-report.tsmodified+15 -0
@@ -19,6 +19,11 @@ export type RunReportKey =
19 | "copyFailed"19 | "copyFailed"
20 | "download"20 | "download"
21 | "downloaded"21 | "downloaded"
22+ | "schoolReport"
23+ | "schoolReportGenerating"
24+ | "schoolReportUnavailable"
25+ | "schoolReportUnreadable"
26+ | "schoolReportTooLarge"
22 | "print"27 | "print"
23 | "runSection"28 | "runSection"
24 | "schoolSection"29 | "schoolSection"
@@ -82,6 +87,11 @@ const tr: Record<RunReportKey, string> = {
82 copyFailed: "Rapor panoya kopyalanamadı.",87 copyFailed: "Rapor panoya kopyalanamadı.",
83 download: "İndir (.md)",88 download: "İndir (.md)",
84 downloaded: "Rapor indirildi.",89 downloaded: "Rapor indirildi.",
90+ schoolReport: "Okul raporu (HTML)",
91+ schoolReportGenerating: "Rapor oluşturuluyor…",
92+ schoolReportUnavailable: "Okul raporu servisi şu an kullanılamıyor. Sonra tekrar dene.",
93+ schoolReportUnreadable: "Rapor oluşturuldu ama belge okunamadı. Tekrar dene.",
94+ schoolReportTooLarge: "Rapor belgesi sunucunun boyut sınırını aştı.",
85 print: "Yazdır / PDF",95 print: "Yazdır / PDF",
86 runSection: "Çalıştırma özeti",96 runSection: "Çalıştırma özeti",
87 schoolSection: "Okul geneli",97 schoolSection: "Okul geneli",
@@ -146,6 +156,11 @@ const en: Record<RunReportKey, string> = {
146 copyFailed: "Could not copy the report.",156 copyFailed: "Could not copy the report.",
147 download: "Download (.md)",157 download: "Download (.md)",
148 downloaded: "Report downloaded.",158 downloaded: "Report downloaded.",
159+ schoolReport: "School report (HTML)",
160+ schoolReportGenerating: "Generating report…",
161+ schoolReportUnavailable: "The school report service is not available right now. Try again later.",
162+ schoolReportUnreadable: "The report was generated but the document could not be read back. Try again.",
163+ schoolReportTooLarge: "The report document is larger than the server's size limit.",
149 print: "Print / PDF",164 print: "Print / PDF",
150 runSection: "Run summary",165 runSection: "Run summary",
151 schoolSection: "School overview",166 schoolSection: "School overview",
src/lib/insight-run-report.tsmodified+5 -0
@@ -328,6 +328,11 @@ export function runReportFileName(runDay: string): string {
328 return `okul-analiz-raporu-${runDay}.md`;328 return `okul-analiz-raporu-${runDay}.md`;
329 }329 }
330 330
331+/** The AI service's own document, under the same base name as the .md export. */
332+export function runReportHtmlFileName(runDay: string): string {
333+ return `okul-analiz-raporu-${runDay}.html`;
334+}
335+
331 /**336 /**
332 * The run's pending students, by name, in the ledger's own order — the panel337 * The run's pending students, by name, in the ledger's own order — the panel
333 * and the export both render this one line, so the count, the names and the338 * and the export both render this one line, so the count, the names and the