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 aa79bf5..5d3b50a 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/components/notes/rag-output-document.ts b/src/components/notes/rag-output-document.ts index 4f812df..1d4a3e7 100644 --- a/src/components/notes/rag-output-document.ts +++ b/src/components/notes/rag-output-document.ts @@ -18,6 +18,8 @@ const RENDERED_KEYS: Record = { files: true, failed: true, course_note: true, + passages: true, + passages_truncated: true, }; function asRecord(value: unknown): Record | null { @@ -78,11 +80,61 @@ export type RagOutputDocument = { /** Stored attachment ids whose name the payload does not carry. */ unnamedSources: number; failed: string[]; + /** The indexed chunks the service handed back, in the order it wrote them. */ + passages: RagOutputPassage[]; + /** The service dropped passages above its response budget. */ + passagesTruncated: boolean; + /** The payload's own `chunks` — the total it indexed — when it recorded one. */ + chunksTotal: number | null; /** Payload entries with no dedicated rendering, in payload order. */ fields: Array<{ key: string; value: unknown }>; raw: unknown; }; +/** One indexed chunk as the service returned it — the extraction, readable. */ +export type RagOutputPassage = { + /** The attachment the passage came from, by name; null when unresolvable. */ + sourceName: string | null; + /** The passage came from the note's own text, not from an attachment. */ + fromNote: boolean; + /** The chunk's own text, verbatim. */ + text: string; + pageStart: number | null; + pageEnd: number | null; +}; + +/** The note key the answer stamps its own body chunks with — the payload's own + * `course_note` first, the stored row's link as the fallback. */ +function payloadNoteKey(record: Record | null, output: RagOutput): string { + if (typeof record?.course_note === "string" && record.course_note) return record.course_note; + return typeof output.course_note === "string" ? output.course_note : ""; +} + +/** The passages the service recorded, dropping entries with no readable text. */ +function payloadPassages( + record: Record | null, + names: Map, + noteId: string, +): RagOutputPassage[] { + if (!Array.isArray(record?.passages)) return []; + const pages = (value: unknown) => (typeof value === "number" && Number.isInteger(value) ? value : null); + const passages: RagOutputPassage[] = []; + for (const entry of record.passages) { + const passage = asRecord(entry); + if (typeof passage?.text !== "string" || !passage.text.trim()) continue; + const docId = typeof passage.doc_id === "string" ? passage.doc_id : ""; + passages.push({ + sourceName: (docId ? names.get(docId) : undefined) ?? null, + // The service stamps the note's own chunks with the note key, not a file id. + fromNote: docId !== "" && docId === noteId, + text: passage.text, + pageStart: pages(passage.page_start), + pageEnd: pages(passage.page_end), + }); + } + return passages; +} + /** * Read one stored AI output into everything the drawer shows. The payload is * the service's own object served unread, so every read here is defensive: a @@ -120,6 +172,9 @@ export function readRagOutputDocument(output: RagOutput): RagOutputDocument { sourceNames, unnamedSources, failed, + passages: payloadPassages(record, names, payloadNoteKey(record, output)), + passagesTruncated: record?.passages_truncated === true, + chunksTotal: typeof record?.chunks === "number" && Number.isFinite(record.chunks) ? record.chunks : null, fields: record ? Object.entries(record) .filter(([key]) => !RENDERED_KEYS[key]) @@ -135,6 +190,12 @@ export type RagOutputMarkdownLabels = { sources: string; failed: string; otherFields: string; + /** Heading of the extracted-text section. */ + passages: string; + /** One passage's heading: source name and page range, never a raw id. */ + passageHeader: (passage: RagOutputPassage) => string; + /** Honest note when the service dropped passages; "" when it did not. */ + passagesTruncated: string; }; /** @@ -170,6 +231,13 @@ export function buildRagOutputMarkdown(input: { for (const name of doc.failed) lines.push(`- ${name}`); lines.push(""); } + if (doc.passages.length > 0) { + lines.push(`## ${labels.passages}`, ""); + for (const passage of doc.passages) { + lines.push(`**${labels.passageHeader(passage)}**`, "", passage.text, ""); + } + if (doc.passagesTruncated && labels.passagesTruncated) lines.push(labels.passagesTruncated, ""); + } if (doc.fields.length > 0) { lines.push(`## ${labels.otherFields}`, ""); for (const field of doc.fields) lines.push(`- **${field.key}:** ${fieldValueText(field.value)}`); diff --git a/src/components/notes/rag-output-drawer.test.tsx b/src/components/notes/rag-output-drawer.test.tsx index df60b02..28bfcab 100644 --- a/src/components/notes/rag-output-drawer.test.tsx +++ b/src/components/notes/rag-output-drawer.test.tsx @@ -1,9 +1,14 @@ -import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { RagOutput } from "@/api/client"; import { RagOutputDrawer } from "@/components/notes/rag-output-drawer"; -import { buildRagOutputMarkdown, readRagOutputDocument } from "@/components/notes/rag-output-document"; -import { ragOutputMessage } from "@/components/notes/rag-output-messages"; +import { + buildRagOutputMarkdown, + readRagOutputDocument, + type RagOutputDocument, + type RagOutputMarkdownLabels, +} from "@/components/notes/rag-output-document"; +import { ragOutputMessage, ragOutputPassagePages } from "@/components/notes/rag-output-messages"; import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; import { formatDateTime } from "@/lib/format"; import type { NoteFileSource } from "@/lib/note-source"; @@ -44,24 +49,75 @@ const HEALTHY: RagOutput = { }, }; -const LABELS = { - date: ragOutputMessage("en", "date"), - note: ragOutputMessage("en", "note"), - sources: ragOutputMessage("en", "sources"), - failed: ragOutputMessage("en", "failedTitle"), - otherFields: ragOutputMessage("en", "otherFields"), -}; +const PASSAGE_TEXT_1 = "Hücre zarı seçici geçirgendir; madde alışverişini düzenler.\nZar proteinleri taşımayı üstlenir."; +const PASSAGE_TEXT_2 = "Mitokondri, oksijenli solunumla ATP üretir."; + +/** HEALTHY's payload with extra keys — the shape the service evolved into. */ +function withPassages(extra: Record): RagOutput { + return { ...HEALTHY, payload: { ...(HEALTHY.payload as Record), ...extra } }; +} + +const WITH_PASSAGES = withPassages({ + passages: [ + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, + ], + passages_truncated: false, +}); + +const WITH_TRUNCATED = withPassages({ + passages: [ + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, + ], + passages_truncated: true, +}); + +/** The service stamps the note's own body chunks with the note key. */ +const WITH_NOTE_PASSAGE = withPassages({ + passages: [ + { chunk_id: "01NOTE:01NOTE:c0", doc_id: "note-1", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, + ], +}); + +function markdownLabels(document: RagOutputDocument): RagOutputMarkdownLabels { + return { + date: ragOutputMessage("en", "date"), + note: ragOutputMessage("en", "note"), + sources: ragOutputMessage("en", "sources"), + failed: ragOutputMessage("en", "failedTitle"), + otherFields: ragOutputMessage("en", "otherFields"), + passages: ragOutputMessage("en", "passages"), + passageHeader: (passage) => { + const source = passage.sourceName + ?? (passage.fromNote ? NOTE_TITLE : ragOutputMessage("en", "unnamedSource")); + const pages = ragOutputPassagePages("en", passage.pageStart, passage.pageEnd); + return pages ? `${source} · ${pages}` : source; + }, + passagesTruncated: document.passagesTruncated + ? document.chunksTotal != null + ? ragOutputMessage("en", "passagesTruncated", { shown: document.passages.length, total: document.chunksTotal }) + : ragOutputMessage("en", "passagesTruncatedNoTotal", { shown: document.passages.length }) + : "", + }; +} function expectedMarkdown(output: RagOutput) { + const document = readRagOutputDocument(output); return buildRagOutputMarkdown({ title: NOTE_TITLE, date: formatDateTime(output.generated_at, "en"), noteTitle: NOTE_TITLE, - document: readRagOutputDocument(output), - labels: LABELS, + document, + labels: markdownLabels(document), }); } +/** The drawer's extracted-text section, so raw-record assertions stay scoped. */ +function passagesSection(): HTMLElement { + return screen.getByText("Extracted text").closest("div") as HTMLElement; +} + function stubSource(output: RagOutput): NoteFileSource { return { maxFiles: 10, @@ -112,6 +168,7 @@ describe("RagOutputDrawer", () => { afterEach(() => { cleanup(); + localStorage.removeItem("hezarfen.locale"); vi.clearAllMocks(); }); @@ -189,4 +246,109 @@ describe("RagOutputDrawer", () => { expect(screen.getByText("Unnamed attachment")).toBeTruthy(); expect(screen.queryByText(/file-zzz9/)).toBeNull(); }); + + it("shows the extracted passages with their source files, page ranges and line breaks", async () => { + renderDrawer(WITH_PASSAGES); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect(screen.getByText("hücre-notu.pdf · pp. 3-4")).toBeTruthy(); + expect(screen.getByText("organeller.pdf · p. 5")).toBeTruthy(); + // The section renders the passages — it does not dump their ids. + const section = passagesSection(); + const first = within(section).getByText(/Hücre zarı seçici geçirgendir/); + expect(first.textContent).toBe(PASSAGE_TEXT_1); + expect(first.className).toContain("whitespace-pre-wrap"); + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); + expect(within(section).queryByText(/chunk-/)).toBeNull(); + expect(within(section).queryByText(/doc-/)).toBeNull(); + }); + + it("exports the same passages, in the same order, into the Markdown document", () => { + const markdown = expectedMarkdown(WITH_PASSAGES); + + expect(markdown).toContain("## Extracted text"); + expect(markdown).toContain("**hücre-notu.pdf · pp. 3-4**"); + expect(markdown).toContain("**organeller.pdf · p. 5**"); + const first = markdown.indexOf(PASSAGE_TEXT_1); + const second = markdown.indexOf(PASSAGE_TEXT_2); + expect(first).toBeGreaterThan(-1); + expect(second).toBeGreaterThan(first); + expect(markdown.indexOf("## Extracted text")).toBeLessThan(markdown.indexOf("## Other fields")); + expect(markdown).not.toContain("chunk-1"); + expect(markdown).not.toContain("doc-ccc3"); + expect(markdown).not.toContain("passages_truncated"); + }); + + it("copies the passages exactly as exported, truncation note included", async () => { + renderDrawer(WITH_TRUNCATED); + + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_TRUNCATED)); + }); + + it("renders no extracted-text section for outputs stored before passages existed", async () => { + renderDrawer(HEALTHY); + + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); + expect(screen.queryByText("Extracted text")).toBeNull(); + }); + + it("survives an ill-typed passages value without rendering a section", async () => { + renderDrawer(withPassages({ passages: "bozuk" })); + + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); + expect(screen.queryByText("Extracted text")).toBeNull(); + }); + + it("says honestly how many passages were extracted when the list is capped", async () => { + renderDrawer(WITH_TRUNCATED); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect( + screen.getByText(ragOutputMessage("en", "passagesTruncated", { shown: 2, total: 18 })), + ).toBeTruthy(); + }); + + it("renders the Turkish section title and truncation sentence", async () => { + localStorage.setItem("hezarfen.locale", "tr"); + renderDrawer(WITH_TRUNCATED); + + await waitFor(() => expect(screen.getByText("Çıkarılan metin")).toBeTruthy()); + expect( + screen.getByText(ragOutputMessage("tr", "passagesTruncated", { shown: 2, total: 18 })), + ).toBeTruthy(); + }); + + it("never shows a raw attachment id for a passage whose source cannot be resolved", async () => { + renderDrawer( + withPassages({ + passages: [ + { chunk_id: "chunk-9", doc_id: "doc-zzz9", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, + ], + }), + ); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect(screen.getByText("Unnamed attachment")).toBeTruthy(); + const section = passagesSection(); + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); + expect(within(section).queryByText(/doc-zzz9/)).toBeNull(); + expect(within(section).queryByText(/chunk-9/)).toBeNull(); + }); + + it("labels a note-body passage with the note title, never the note key", async () => { + renderDrawer(WITH_NOTE_PASSAGE); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + const section = passagesSection(); + expect(within(section).getByText(NOTE_TITLE)).toBeTruthy(); + expect(within(section).queryByText(/note-1/)).toBeNull(); + + // The export carries the same label the view shows. + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_NOTE_PASSAGE)); + }); }); diff --git a/src/components/notes/rag-output-drawer.tsx b/src/components/notes/rag-output-drawer.tsx index 6078b94..7805cc7 100644 --- a/src/components/notes/rag-output-drawer.tsx +++ b/src/components/notes/rag-output-drawer.tsx @@ -9,8 +9,14 @@ import { fieldValueText, ragOutputFileName, readRagOutputDocument, + type RagOutputDocument, + type RagOutputPassage, } from "@/components/notes/rag-output-document"; -import { ragOutputMessage, type RagOutputMessageKey } from "@/components/notes/rag-output-messages"; +import { + ragOutputMessage, + ragOutputPassagePages, + type RagOutputMessageKey, +} from "@/components/notes/rag-output-messages"; import { formatDateTime } from "@/lib/format"; import { usePreferences } from "@/stores/preferences-context"; @@ -58,6 +64,20 @@ export function RagOutputDrawer(props: { const doc = () => (props.output ? readRagOutputDocument(props.output) : null); const noteTitle = () => props.noteTitle?.trim() ?? ""; + /** One passage's heading: the source file by name, its page range if any. */ + const passageHeader = (passage: RagOutputPassage) => { + const source = passage.sourceName + ?? (passage.fromNote ? noteTitle() || rt("noteText") : rt("unnamedSource")); + const pages = ragOutputPassagePages(locale(), passage.pageStart, passage.pageEnd); + return pages ? `${source} · ${pages}` : source; + }; + /** The honest note when the service's cap means more passages exist. */ + const passagesNote = (read: RagOutputDocument) => { + if (!read.passagesTruncated) return ""; + return read.chunksTotal != null + ? rt("passagesTruncated", { shown: read.passages.length, total: read.chunksTotal }) + : rt("passagesTruncatedNoTotal", { shown: read.passages.length }); + }; const markdown = () => { const output = props.output; const read = doc(); @@ -73,6 +93,9 @@ export function RagOutputDrawer(props: { sources: rt("sources"), failed: rt("failedTitle"), otherFields: rt("otherFields"), + passages: rt("passages"), + passageHeader, + passagesTruncated: passagesNote(read), }, }); }; @@ -200,6 +223,28 @@ export function RagOutputDrawer(props: { + 0}> +

+

{rt("passages")}

+
    + + {(passage) => ( +
  • +

    {passageHeader(passage)}

    + {/* Scrolls past its cap on screen; print flows it out in full. */} +
    +

    {passage.text}

    +
    +
  • + )} +
    +
+ +

{passagesNote(read())}

+
+
+ + 0}>

diff --git a/src/components/notes/rag-output-messages.ts b/src/components/notes/rag-output-messages.ts index 4ec3f9a..29618be 100644 --- a/src/components/notes/rag-output-messages.ts +++ b/src/components/notes/rag-output-messages.ts @@ -23,6 +23,12 @@ export type RagOutputMessageKey = | "failedLine" | "otherFields" | "chunks" + | "passages" + | "passagePagesSingle" + | "passagePagesRange" + | "passagesTruncated" + | "passagesTruncatedNoTotal" + | "noteText" | "technical" | "copy" | "copied" @@ -43,6 +49,12 @@ const en: Record = { "failedLine": "Not processed: {names}", "otherFields": "Other fields", "chunks": "Text chunks", + "passages": "Extracted text", + "passagePagesSingle": "p. {page}", + "passagePagesRange": "pp. {start}-{end}", + "passagesTruncated": "{total} passages were extracted in total; the first {shown} are listed here.", + "passagesTruncatedNoTotal": "Only the first {shown} extracted passages are listed here.", + "noteText": "Note text", "technical": "Technical details", "copy": "Copy", "copied": "Copied to the clipboard", @@ -64,6 +76,12 @@ const tr: Record = { "failedLine": "İşlenemeyenler: {names}", "otherFields": "Diğer alanlar", "chunks": "Metin parçaları", + "passages": "Çıkarılan metin", + "passagePagesSingle": "s. {page}", + "passagePagesRange": "s. {start}-{end}", + "passagesTruncated": "Toplam {total} metin parçası çıkarıldı; burada ilk {shown} tanesi gösteriliyor.", + "passagesTruncatedNoTotal": "Çıkarılan parçaların yalnızca ilk {shown} tanesi gösteriliyor.", + "noteText": "Not metni", "technical": "Teknik ayrıntı", "copy": "Kopyala", "copied": "Panoya kopyalandı", @@ -79,3 +97,19 @@ export function ragOutputMessage( ): string { return formatMessage((locale === "tr" ? tr : en)[key], vars); } + +/** + * One passage's page range (`s. 3-4`), or an empty string when the service + * recorded no page — the label is then left off entirely. + */ +export function ragOutputPassagePages( + locale: Locale, + pageStart: number | null, + pageEnd: number | null, +): string { + if (pageStart == null) return ""; + if (pageEnd == null || pageEnd <= pageStart) { + return ragOutputMessage(locale, "passagePagesSingle", { page: pageStart }); + } + return ragOutputMessage(locale, "passagePagesRange", { start: pageStart, end: pageEnd }); +} 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