diff --git a/src/api/__tests__/insights/insights.test.ts b/src/api/__tests__/insights/insights.test.ts index a190286..8a9609f 100644 --- a/src/api/__tests__/insights/insights.test.ts +++ b/src/api/__tests__/insights/insights.test.ts @@ -1,13 +1,16 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { getInsightByUserId, + getInsightRunReport, getInsightRuns, getInsightsPending, getMyInsight, + insightRunReportUrl, postInsightComputeByUserId, + postInsightRunReport, postInsightsRefresh, } from "../../insights"; -import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; +import { lastFetchCall, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch"; describe("insights API", () => { afterEach(() => { @@ -115,4 +118,44 @@ describe("insights API", () => { const [, init] = lastFetchCall(); expect(init?.body).toBe(JSON.stringify({})); }); + + it("postInsightRunReport POSTs the run day's own /report door", async () => { + mockFetchSuccess({ + run_day: "2026-09-18", + byte_size: 4096, + truncated: false, + notes: [], + generated_at: 1_758_000_000_000, + }); + + const receipt = await postInsightRunReport("2026-09-18"); + expect(receipt.byte_size).toBe(4096); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/insights/runs/2026-09-18/report"); + expect(init?.method).toBe("POST"); + }); + + it("insightRunReportUrl encodes the run day and getInsightRunReport reads those bytes back", async () => { + expect(insightRunReportUrl("a/b")).toBe("/api/insights/runs/a%2Fb/report"); + const blob = new Blob(["okul"], { type: "text/html;charset=utf-8" }); + mockFetchBlob(blob); + + const bytes = await getInsightRunReport("2026-09-18"); + + expect(await bytes.text()).toBe("okul"); + const [url, init] = lastFetchCall(); + // `blobClient` adds the `/api` the URL builder already carries for hrefs. + expect(url).toBe("/api/insights/runs/2026-09-18/report"); + expect(init?.method ?? "GET").toBe("GET"); + }); + + it("getInsightRunReport surfaces a 409 report_missing as an ApiError", async () => { + mockFetchError(409, { error: "no school report is stored for this run day", code: "report_missing" }); + + await expect(getInsightRunReport("2026-09-18")).rejects.toMatchObject({ + status: 409, + message: "no school report is stored for this run day", + }); + }); }); diff --git a/src/api/insights/getInsightRunReport.ts b/src/api/insights/getInsightRunReport.ts new file mode 100644 index 0000000..50fe7d4 --- /dev/null +++ b/src/api/insights/getInsightRunReport.ts @@ -0,0 +1,12 @@ +import { blobClient } from "../client"; +import { insightRunReportPath } from "./insightRunReportUrl"; + +/** + * The stored document's bytes. Read back after a generation that answered + * `200`: a day whose report was never written — or was lost since — answers + * `409 report_missing`, which must not be handed over as a download. + * Manager+ only, like the generation that wrote it. + */ +export function getInsightRunReport(runDay: string, signal?: AbortSignal): Promise { + return blobClient(insightRunReportPath(runDay), signal); +} diff --git a/src/api/insights/index.ts b/src/api/insights/index.ts index 8110faf..ead3b07 100644 --- a/src/api/insights/index.ts +++ b/src/api/insights/index.ts @@ -4,3 +4,6 @@ export * from "./postInsightComputeByUserId"; export * from "./getInsightRuns"; export * from "./postInsightsRefresh"; export * from "./getInsightsPending"; +export * from "./insightRunReportUrl"; +export * from "./postInsightRunReport"; +export * from "./getInsightRunReport"; diff --git a/src/api/insights/insightRunReportUrl.ts b/src/api/insights/insightRunReportUrl.ts new file mode 100644 index 0000000..eb3075a --- /dev/null +++ b/src/api/insights/insightRunReportUrl.ts @@ -0,0 +1,16 @@ +/** + * One run day's school report door, spelled once: the two requests go through + * `client`/`blobClient`, which add `/api` themselves, while the download link + * has to carry the prefix — so the prefixed form is built from the same path. + * + * `runDay` is the ledger row's own `run_day` (`YYYY-MM-DD`). A day nothing was + * generated for answers `409 report_missing`; a caller below manager is refused. + */ +export function insightRunReportPath(runDay: string): string { + return `/insights/runs/${encodeURIComponent(runDay)}/report`; +} + +/** The same door as a same-origin URL — hand it to an ``: the session cookie rides along. */ +export function insightRunReportUrl(runDay: string): string { + return `/api${insightRunReportPath(runDay)}`; +} diff --git a/src/api/insights/postInsightRunReport.ts b/src/api/insights/postInsightRunReport.ts new file mode 100644 index 0000000..0e54a28 --- /dev/null +++ b/src/api/insights/postInsightRunReport.ts @@ -0,0 +1,26 @@ +import { client } from "../client"; +import { insightRunReportPath } from "./insightRunReportUrl"; + +/** + * The receipt for the school report the service just wrote: the day it covers, + * its size in bytes, whether the service had to truncate it, the service's own + * notes, and when it was stored (ms epoch, the same clock as the run ledger). + */ +export type GeneratedInsightRunReport = { + run_day: string; + byte_size: number; + truncated: boolean; + notes: string[]; + generated_at: number; +}; + +/** + * Generate the school-level report document for one run day. Manager+ only, + * and synchronous: the service writes it before this answers. `503` when no AI + * service offers the report right now; `409` (`report_refused`) when the + * service refused — nothing is stored then, so `getInsightRunReport` would + * find nothing. + */ +export function postInsightRunReport(runDay: string): Promise { + return client(insightRunReportPath(runDay), { method: "POST" }); +} diff --git a/src/components/insights/insight-run-report.test.tsx b/src/components/insights/insight-run-report.test.tsx index 2ef206a..d38f5d3 100644 --- a/src/components/insights/insight-run-report.test.tsx +++ b/src/components/insights/insight-run-report.test.tsx @@ -1,15 +1,30 @@ 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 { ApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client"; +import type * as insightsApiModule from "@/api/insights"; 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 insightsApi = vi.hoisted(() => ({ + getInsightByUserId: vi.fn(), + postInsightRunReport: vi.fn(), + getInsightRunReport: vi.fn(), +})); const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() })); - -vi.mock("@/api/insights", () => insightsApi); +/** Who the drawer thinks is reading: generation is offered to manager+ only. */ +const viewer = vi.hoisted(() => ({ role: "manager" as "manager" | "teacher" })); + +// The URL builder stays real (the drawer and the download use it); only the +// two doors and the per-student read are stood in for. +vi.mock("@/api/insights", async () => ({ + ...(await vi.importActual("@/api/insights")), + ...insightsApi, +})); vi.mock("@/api/users", () => usersApi); +vi.mock("@/stores/auth-context", () => ({ + useAuth: () => ({ user: () => ({ id: "m-1", role: viewer.role }), loading: () => false }), +})); // 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", () => ({ @@ -147,6 +162,7 @@ async function openReport(runDay: string) { describe("InsightRunReport", () => { beforeEach(() => { + viewer.role = "manager"; localStorage.setItem("hezarfen.locale", "tr"); usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 }); insightsApi.getInsightByUserId.mockImplementation((userId: string) => { @@ -335,4 +351,152 @@ describe("InsightRunReport", () => { expect(markdown).toContain("Keşifsel"); expect(markdown).toContain("```json"); }); + + it("asks the service for the rendered run day's report and reads it back before offering it", async () => { + const receipt = { + run_day: DAY_B, + byte_size: 4096, + truncated: false, + notes: [], + generated_at: COMPUTED_AT, + }; + const pending = Promise.withResolvers(); + insightsApi.postInsightRunReport.mockImplementation(() => pending.promise); + insightsApi.getInsightRunReport.mockResolvedValue(new Blob([""], { type: "text/html" })); + // The hand-over itself is the other test's subject; here it must not navigate. + vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + // The door is this run row's own day, and it is asked before the read. + expect(insightsApi.postInsightRunReport).toHaveBeenCalledWith(DAY_B); + expect(insightsApi.getInsightRunReport).not.toHaveBeenCalled(); + const busy = panel().getByRole("button", { name: "Rapor oluşturuluyor…" }) as HTMLButtonElement; + expect(busy.disabled).toBe(true); + + pending.resolve(receipt); + + // Read-back first: the bytes are what prove there is a document to hand over. + await waitFor(() => expect(insightsApi.getInsightRunReport).toHaveBeenCalledWith(DAY_B)); + await waitFor(() => + expect(panel().getByRole("button", { name: "Okul raporu (HTML)" })).toBeTruthy(), + ); + expect((panel().getByRole("button", { name: "Okul raporu (HTML)" }) as HTMLButtonElement).disabled).toBe( + false, + ); + }); + + it("hands the stored document over as an anchor on its own door, under its own file name", async () => { + const clicked: { href: string | null; download: string | null }[] = []; + const click = vi + .spyOn(HTMLAnchorElement.prototype, "click") + .mockImplementation(function (this: HTMLAnchorElement) { + clicked.push({ href: this.getAttribute("href"), download: this.getAttribute("download") }); + }); + insightsApi.postInsightRunReport.mockResolvedValue({ + run_day: DAY_B, + byte_size: 4096, + truncated: false, + notes: [], + generated_at: COMPUTED_AT, + }); + insightsApi.getInsightRunReport.mockResolvedValue(new Blob([""], { type: "text/html" })); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + await waitFor(() => expect(click).toHaveBeenCalledTimes(1)); + expect(clicked[0]).toEqual({ + href: `/api/insights/runs/${DAY_B}/report`, + download: `okul-analiz-raporu-${DAY_B}.html`, + }); + }); + + it("says the report service is unavailable on a 503 and puts the control back", async () => { + insightsApi.postInsightRunReport.mockRejectedValue( + new ApiError(503, "no AI service is connected right now"), + ); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + await waitFor(() => + expect( + panel().getByText("Okul raporu servisi şu an kullanılamıyor. Sonra tekrar dene."), + ).toBeTruthy(), + ); + expect((panel().getByRole("button", { name: "Okul raporu (HTML)" }) as HTMLButtonElement).disabled).toBe( + false, + ); + expect(insightsApi.getInsightRunReport).not.toHaveBeenCalled(); + }); + + it("says the document is too large without telling the reader to pick a smaller file", async () => { + insightsApi.postInsightRunReport.mockRejectedValue(new ApiError(413, "document_too_large")); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + await waitFor(() => + expect(panel().getByText("Rapor belgesi sunucunun boyut sınırını aştı.")).toBeTruthy(), + ); + expect(panel().queryByText(/Daha küçük bir dosya seç/)).toBeNull(); + }); + + it("shows the server's own sentence when the service refuses the generation", async () => { + insightsApi.postInsightRunReport.mockRejectedValue( + new ApiError(409, "the school report was refused: no marks were stored for this run day"), + ); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + await waitFor(() => + expect( + panel().getByText("the school report was refused: no marks were stored for this run day"), + ).toBeTruthy(), + ); + }); + + it("says the document could not be read back when the generation answered but stored nothing", async () => { + insightsApi.postInsightRunReport.mockResolvedValue({ + run_day: DAY_B, + byte_size: 0, + truncated: false, + notes: [], + generated_at: COMPUTED_AT, + }); + insightsApi.getInsightRunReport.mockRejectedValue( + new ApiError(409, "no school report is stored for this run day"), + ); + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + fireEvent.click(panel().getByRole("button", { name: "Okul raporu (HTML)" })); + + await waitFor(() => + expect(panel().getByText("Rapor oluşturuldu ama belge okunamadı. Tekrar dene.")).toBeTruthy(), + ); + // The server's own 409 text is not what the reader gets: nothing was refused. + expect(panel().queryByText("no school report is stored for this run day")).toBeNull(); + }); + + it("offers no generation control to a reader the door would refuse", async () => { + viewer.role = "teacher"; + await openReport(DAY_B); + await waitFor(() => expect(panel().getByText("71,0 (1/2)")).toBeTruthy()); + + expect(panel().queryByRole("button", { name: "Okul raporu (HTML)" })).toBeNull(); + // The three controls that only read what is already on screen stay. + expect(panel().getByRole("button", { name: "Kopyala" })).toBeTruthy(); + expect(panel().getByRole("button", { name: "İndir (.md)" })).toBeTruthy(); + expect(panel().getByRole("button", { name: "Yazdır / PDF" })).toBeTruthy(); + expect(insightsApi.postInsightRunReport).not.toHaveBeenCalled(); + }); }); diff --git a/src/components/insights/insight-run-report.tsx b/src/components/insights/insight-run-report.tsx index dd2e6be..99d7da1 100644 --- a/src/components/insights/insight-run-report.tsx +++ b/src/components/insights/insight-run-report.tsx @@ -1,12 +1,13 @@ import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"; import { Portal } from "solid-js/web"; -import { getInsightByUserId } from "@/api/insights"; +import { getInsightByUserId, getInsightRunReport, insightRunReportUrl, postInsightRunReport } from "@/api/insights"; import { getUserSearch } from "@/api/users"; -import { formatApiError, type InsightRun, type PersonRef, type StudentInsight } from "@/api/client"; +import { ApiError, 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 { ErrorAlert } from "@/components/ui/error-alert"; +import { IconCopy, IconDownload, IconFileText, IconReportAnalytics } 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"; @@ -19,6 +20,7 @@ import { moduleLabel, pendingStudentsLine, runReportFileName, + runReportHtmlFileName, runReportStatusLabel, studentAttendanceText, studentMarksText, @@ -27,6 +29,8 @@ import { } from "@/lib/insight-run-report"; import { personLabel } from "@/lib/person"; import { createFlash } from "@/lib/flash"; +import { hasMinRole } from "@/lib/roles"; +import { useAuth } from "@/stores/auth-context"; import { usePreferences } from "@/stores/preferences-context"; /** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */ @@ -278,7 +282,12 @@ export function InsightRunReport(props: { run: InsightRun }) { const prefs = usePreferences(); const tx = (key: RunReportKey, vars?: Record) => runReportText(prefs.locale(), key, vars); + const auth = useAuth(); + /** Generation is manager+ — the door refuses anyone below it, so the control is not offered. */ + const canGenerateReport = () => hasMinRole(auth.user()?.role, "manager"); const [, flash] = createFlash(); + const [generatingReport, setGeneratingReport] = createSignal(false); + const [reportError, setReportError] = createSignal(null); const [roster, setRoster] = createSignal([]); const [rosterTotal, setRosterTotal] = createSignal(0); const [rosterError, setRosterError] = createSignal(null); @@ -384,6 +393,54 @@ export function InsightRunReport(props: { run: InsightRun }) { flash(tx("downloaded")); }; + /** + * The sentence a failed generation shows. A coded refusal (`409`) carries + * the server's own sentence about why it refused, so that one is shown + * as-is; everything else goes through the house renderer. The single `409` + * this control can meet *after* its own `200` — `report_missing` — says the + * document could not be read back instead: the service did not refuse + * anything, its document is simply not there. + */ + const reportFailureText = (err: unknown, readingBack: boolean): string => { + if (err instanceof ApiError && err.status === 409) { + return readingBack ? tx("schoolReportUnreadable") : err.message; + } + if (err instanceof ApiError && err.status === 503) return tx("schoolReportUnavailable"); + // The house 413 copy is about uploads ("choose a smaller file") — wrong + // instruction here: nothing was chosen, the service's own document is big. + if (err instanceof ApiError && err.status === 413) return tx("schoolReportTooLarge"); + return formatApiError(err); + }; + + /** + * Ask the service for this run day's school-level document, then hand it + * over. The read-back in between is what keeps a `200` honest: without it a + * generation that stored nothing would still open a download that answers + * `409`. The anchor points at the door itself — same-origin, so the session + * cookie rides along — rather than at bytes this tab fetched. + */ + const generateSchoolReport = async () => { + const runDay = props.run.run_day; + setGeneratingReport(true); + setReportError(null); + let readingBack = false; + try { + await postInsightRunReport(runDay); + readingBack = true; + await getInsightRunReport(runDay); + const anchor = document.createElement("a"); + anchor.href = insightRunReportUrl(runDay); + anchor.download = runReportHtmlFileName(runDay); + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + } catch (err) { + setReportError(reportFailureText(err, readingBack)); + } finally { + setGeneratingReport(false); + } + }; + return (
@@ -399,8 +456,25 @@ export function InsightRunReport(props: { run: InsightRun }) { {tx("print")} + + +
+ + {(message) => } + + 0}>

diff --git a/src/i18n/insights-run-report.ts b/src/i18n/insights-run-report.ts index 95ead55..dde9bfe 100644 --- a/src/i18n/insights-run-report.ts +++ b/src/i18n/insights-run-report.ts @@ -19,6 +19,11 @@ export type RunReportKey = | "copyFailed" | "download" | "downloaded" + | "schoolReport" + | "schoolReportGenerating" + | "schoolReportUnavailable" + | "schoolReportUnreadable" + | "schoolReportTooLarge" | "print" | "runSection" | "schoolSection" @@ -82,6 +87,11 @@ const tr: Record = { copyFailed: "Rapor panoya kopyalanamadı.", download: "İndir (.md)", downloaded: "Rapor indirildi.", + schoolReport: "Okul raporu (HTML)", + schoolReportGenerating: "Rapor oluşturuluyor…", + schoolReportUnavailable: "Okul raporu servisi şu an kullanılamıyor. Sonra tekrar dene.", + schoolReportUnreadable: "Rapor oluşturuldu ama belge okunamadı. Tekrar dene.", + schoolReportTooLarge: "Rapor belgesi sunucunun boyut sınırını aştı.", print: "Yazdır / PDF", runSection: "Çalıştırma özeti", schoolSection: "Okul geneli", @@ -146,6 +156,11 @@ const en: Record = { copyFailed: "Could not copy the report.", download: "Download (.md)", downloaded: "Report downloaded.", + schoolReport: "School report (HTML)", + schoolReportGenerating: "Generating report…", + schoolReportUnavailable: "The school report service is not available right now. Try again later.", + schoolReportUnreadable: "The report was generated but the document could not be read back. Try again.", + schoolReportTooLarge: "The report document is larger than the server's size limit.", print: "Print / PDF", runSection: "Run summary", schoolSection: "School overview", diff --git a/src/lib/insight-run-report.ts b/src/lib/insight-run-report.ts index daa891c..1b62048 100644 --- a/src/lib/insight-run-report.ts +++ b/src/lib/insight-run-report.ts @@ -328,6 +328,11 @@ export function runReportFileName(runDay: string): string { return `okul-analiz-raporu-${runDay}.md`; } +/** The AI service's own document, under the same base name as the .md export. */ +export function runReportHtmlFileName(runDay: string): string { + return `okul-analiz-raporu-${runDay}.html`; +} + /** * The run's pending students, by name, in the ledger's own order — the panel * and the export both render this one line, so the count, the names and the