merge: bring in the RAG passages export and the school report document
Browse files at this commit13 changed files +688 -21
- src/api/__tests__/insights/insights.test.ts +44 -1
- src/api/insights/getInsightRunReport.ts +12 -0
- src/api/insights/index.ts +3 -0
- src/api/insights/insightRunReportUrl.ts +16 -0
- src/api/insights/postInsightRunReport.ts +26 -0
- src/components/insights/insight-run-report.test.tsx +168 -4
- src/components/insights/insight-run-report.tsx +77 -3
- src/components/notes/rag-output-document.ts +68 -0
- src/components/notes/rag-output-drawer.test.tsx +174 -12
- src/components/notes/rag-output-drawer.tsx +46 -1
- src/components/notes/rag-output-messages.ts +34 -0
- src/i18n/insights-run-report.ts +15 -0
- src/lib/insight-run-report.ts +5 -0
src/api/__tests__/insights/insights.test.tsmodified+44 -1
| @@ -1,13 +1,16 @@ | ||
| 1 | 1 | import { afterEach, describe, expect, it, vi } from "vitest"; |
| 2 | 2 | import { |
| 3 | 3 | getInsightByUserId, |
| 4 | + getInsightRunReport, | |
| 4 | 5 | getInsightRuns, |
| 5 | 6 | getInsightsPending, |
| 6 | 7 | getMyInsight, |
| 8 | + insightRunReportUrl, | |
| 7 | 9 | postInsightComputeByUserId, |
| 10 | + postInsightRunReport, | |
| 8 | 11 | postInsightsRefresh, |
| 9 | 12 | } from "../../insights"; |
| 10 | -import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; | |
| 13 | +import { lastFetchCall, mockFetchBlob, mockFetchError, mockFetchSuccess } from "../helpers/mock-fetch"; | |
| 11 | 14 | |
| 12 | 15 | describe("insights API", () => { |
| 13 | 16 | afterEach(() => { |
| @@ -115,4 +118,44 @@ describe("insights API", () => { | ||
| 115 | 118 | const [, init] = lastFetchCall(); |
| 116 | 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 | 4 | export * from "./getInsightRuns"; |
| 5 | 5 | export * from "./postInsightsRefresh"; |
| 6 | 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 | 1 | import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; |
| 2 | 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 | 5 | import { InsightRunsTable } from "@/components/insights/insight-runs-table"; |
| 5 | 6 | import { buildRunReportMarkdown, buildRunReportModel } from "@/lib/insight-run-report"; |
| 6 | 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 | 14 | const usersApi = vi.hoisted(() => ({ getUserSearch: vi.fn() })); |
| 10 | - | |
| 11 | -vi.mock("@/api/insights", () => insightsApi); | |
| 15 | +/** Who the drawer thinks is reading: generation is offered to manager+ only. */ | |
| 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 | 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 | 28 | // Kobalte's dropdown chrome is not what this test is about: flatten it to one |
| 14 | 29 | // plain button per action so the report path can be driven in jsdom. |
| 15 | 30 | vi.mock("@/components/ui/table-row-actions", () => ({ |
| @@ -147,6 +162,7 @@ async function openReport(runDay: string) { | ||
| 147 | 162 | |
| 148 | 163 | describe("InsightRunReport", () => { |
| 149 | 164 | beforeEach(() => { |
| 165 | + viewer.role = "manager"; | |
| 150 | 166 | localStorage.setItem("hezarfen.locale", "tr"); |
| 151 | 167 | usersApi.getUserSearch.mockResolvedValue({ items: ROSTER, total: ROSTER.length, limit: 200, offset: 0 }); |
| 152 | 168 | insightsApi.getInsightByUserId.mockImplementation((userId: string) => { |
| @@ -335,4 +351,152 @@ describe("InsightRunReport", () => { | ||
| 335 | 351 | expect(markdown).toContain("Keşifsel"); |
| 336 | 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 | 1 | import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"; |
| 2 | 2 | import { Portal } from "solid-js/web"; |
| 3 | -import { getInsightByUserId } from "@/api/insights"; | |
| 3 | +import { getInsightByUserId, getInsightRunReport, insightRunReportUrl, postInsightRunReport } from "@/api/insights"; | |
| 4 | 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 | 6 | import { InsightDetail } from "@/components/insights/insight-detail"; |
| 7 | 7 | import { Button } from "@/components/ui/button"; |
| 8 | 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 | 11 | import { SidePanel } from "@/components/ui/side-panel"; |
| 11 | 12 | import { runReportText, type RunReportKey } from "@/i18n/insights-run-report"; |
| 12 | 13 | import { formatDateTime } from "@/lib/format"; |
| @@ -19,6 +20,7 @@ import { | ||
| 19 | 20 | moduleLabel, |
| 20 | 21 | pendingStudentsLine, |
| 21 | 22 | runReportFileName, |
| 23 | + runReportHtmlFileName, | |
| 22 | 24 | runReportStatusLabel, |
| 23 | 25 | studentAttendanceText, |
| 24 | 26 | studentMarksText, |
| @@ -27,6 +29,8 @@ import { | ||
| 27 | 29 | } from "@/lib/insight-run-report"; |
| 28 | 30 | import { personLabel } from "@/lib/person"; |
| 29 | 31 | import { createFlash } from "@/lib/flash"; |
| 32 | +import { hasMinRole } from "@/lib/roles"; | |
| 33 | +import { useAuth } from "@/stores/auth-context"; | |
| 30 | 34 | import { usePreferences } from "@/stores/preferences-context"; |
| 31 | 35 | |
| 32 | 36 | /** The roster door pages at 200; `loadMoreRoster` walks the pages on request. */ |
| @@ -278,7 +282,12 @@ export function InsightRunReport(props: { run: InsightRun }) { | ||
| 278 | 282 | const prefs = usePreferences(); |
| 279 | 283 | const tx = (key: RunReportKey, vars?: Record<string, string | number>) => |
| 280 | 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 | 288 | const [, flash] = createFlash(); |
| 289 | + const [generatingReport, setGeneratingReport] = createSignal(false); | |
| 290 | + const [reportError, setReportError] = createSignal<string | null>(null); | |
| 282 | 291 | const [roster, setRoster] = createSignal<PersonRef[]>([]); |
| 283 | 292 | const [rosterTotal, setRosterTotal] = createSignal(0); |
| 284 | 293 | const [rosterError, setRosterError] = createSignal<string | null>(null); |
| @@ -384,6 +393,54 @@ export function InsightRunReport(props: { run: InsightRun }) { | ||
| 384 | 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 | 444 | return ( |
| 388 | 445 | <div class="space-y-5"> |
| 389 | 446 | <div class="flex flex-wrap items-center justify-end gap-2"> |
| @@ -399,8 +456,25 @@ export function InsightRunReport(props: { run: InsightRun }) { | ||
| 399 | 456 | <IconFileText class="h-4 w-4" /> |
| 400 | 457 | {tx("print")} |
| 401 | 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 | 472 | </div> |
| 403 | 473 | |
| 474 | + <Show when={reportError()}> | |
| 475 | + {(message) => <ErrorAlert message={message()} />} | |
| 476 | + </Show> | |
| 477 | + | |
| 404 | 478 | <Show when={unloaded().length > 0}> |
| 405 | 479 | <div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border-line px-3 py-2"> |
| 406 | 480 | <p class="text-xs text-muted-foreground"> |
src/components/notes/rag-output-document.tsmodified+68 -0
| @@ -18,6 +18,8 @@ const RENDERED_KEYS: Record<string, true> = { | ||
| 18 | 18 | files: true, |
| 19 | 19 | failed: true, |
| 20 | 20 | course_note: true, |
| 21 | + passages: true, | |
| 22 | + passages_truncated: true, | |
| 21 | 23 | }; |
| 22 | 24 | |
| 23 | 25 | function asRecord(value: unknown): Record<string, unknown> | null { |
| @@ -78,11 +80,61 @@ export type RagOutputDocument = { | ||
| 78 | 80 | /** Stored attachment ids whose name the payload does not carry. */ |
| 79 | 81 | unnamedSources: number; |
| 80 | 82 | failed: string[]; |
| 83 | + /** The indexed chunks the service handed back, in the order it wrote them. */ | |
| 84 | + passages: RagOutputPassage[]; | |
| 85 | + /** The service dropped passages above its response budget. */ | |
| 86 | + passagesTruncated: boolean; | |
| 87 | + /** The payload's own `chunks` — the total it indexed — when it recorded one. */ | |
| 88 | + chunksTotal: number | null; | |
| 81 | 89 | /** Payload entries with no dedicated rendering, in payload order. */ |
| 82 | 90 | fields: Array<{ key: string; value: unknown }>; |
| 83 | 91 | raw: unknown; |
| 84 | 92 | }; |
| 85 | 93 | |
| 94 | +/** One indexed chunk as the service returned it — the extraction, readable. */ | |
| 95 | +export type RagOutputPassage = { | |
| 96 | + /** The attachment the passage came from, by name; null when unresolvable. */ | |
| 97 | + sourceName: string | null; | |
| 98 | + /** The passage came from the note's own text, not from an attachment. */ | |
| 99 | + fromNote: boolean; | |
| 100 | + /** The chunk's own text, verbatim. */ | |
| 101 | + text: string; | |
| 102 | + pageStart: number | null; | |
| 103 | + pageEnd: number | null; | |
| 104 | +}; | |
| 105 | + | |
| 106 | +/** The note key the answer stamps its own body chunks with — the payload's own | |
| 107 | + * `course_note` first, the stored row's link as the fallback. */ | |
| 108 | +function payloadNoteKey(record: Record<string, unknown> | null, output: RagOutput): string { | |
| 109 | + if (typeof record?.course_note === "string" && record.course_note) return record.course_note; | |
| 110 | + return typeof output.course_note === "string" ? output.course_note : ""; | |
| 111 | +} | |
| 112 | + | |
| 113 | +/** The passages the service recorded, dropping entries with no readable text. */ | |
| 114 | +function payloadPassages( | |
| 115 | + record: Record<string, unknown> | null, | |
| 116 | + names: Map<string, string>, | |
| 117 | + noteId: string, | |
| 118 | +): RagOutputPassage[] { | |
| 119 | + if (!Array.isArray(record?.passages)) return []; | |
| 120 | + const pages = (value: unknown) => (typeof value === "number" && Number.isInteger(value) ? value : null); | |
| 121 | + const passages: RagOutputPassage[] = []; | |
| 122 | + for (const entry of record.passages) { | |
| 123 | + const passage = asRecord(entry); | |
| 124 | + if (typeof passage?.text !== "string" || !passage.text.trim()) continue; | |
| 125 | + const docId = typeof passage.doc_id === "string" ? passage.doc_id : ""; | |
| 126 | + passages.push({ | |
| 127 | + sourceName: (docId ? names.get(docId) : undefined) ?? null, | |
| 128 | + // The service stamps the note's own chunks with the note key, not a file id. | |
| 129 | + fromNote: docId !== "" && docId === noteId, | |
| 130 | + text: passage.text, | |
| 131 | + pageStart: pages(passage.page_start), | |
| 132 | + pageEnd: pages(passage.page_end), | |
| 133 | + }); | |
| 134 | + } | |
| 135 | + return passages; | |
| 136 | +} | |
| 137 | + | |
| 86 | 138 | /** |
| 87 | 139 | * Read one stored AI output into everything the drawer shows. The payload is |
| 88 | 140 | * the service's own object served unread, so every read here is defensive: a |
| @@ -120,6 +172,9 @@ export function readRagOutputDocument(output: RagOutput): RagOutputDocument { | ||
| 120 | 172 | sourceNames, |
| 121 | 173 | unnamedSources, |
| 122 | 174 | failed, |
| 175 | + passages: payloadPassages(record, names, payloadNoteKey(record, output)), | |
| 176 | + passagesTruncated: record?.passages_truncated === true, | |
| 177 | + chunksTotal: typeof record?.chunks === "number" && Number.isFinite(record.chunks) ? record.chunks : null, | |
| 123 | 178 | fields: record |
| 124 | 179 | ? Object.entries(record) |
| 125 | 180 | .filter(([key]) => !RENDERED_KEYS[key]) |
| @@ -135,6 +190,12 @@ export type RagOutputMarkdownLabels = { | ||
| 135 | 190 | sources: string; |
| 136 | 191 | failed: string; |
| 137 | 192 | otherFields: string; |
| 193 | + /** Heading of the extracted-text section. */ | |
| 194 | + passages: string; | |
| 195 | + /** One passage's heading: source name and page range, never a raw id. */ | |
| 196 | + passageHeader: (passage: RagOutputPassage) => string; | |
| 197 | + /** Honest note when the service dropped passages; "" when it did not. */ | |
| 198 | + passagesTruncated: string; | |
| 138 | 199 | }; |
| 139 | 200 | |
| 140 | 201 | /** |
| @@ -170,6 +231,13 @@ export function buildRagOutputMarkdown(input: { | ||
| 170 | 231 | for (const name of doc.failed) lines.push(`- ${name}`); |
| 171 | 232 | lines.push(""); |
| 172 | 233 | } |
| 234 | + if (doc.passages.length > 0) { | |
| 235 | + lines.push(`## ${labels.passages}`, ""); | |
| 236 | + for (const passage of doc.passages) { | |
| 237 | + lines.push(`**${labels.passageHeader(passage)}**`, "", passage.text, ""); | |
| 238 | + } | |
| 239 | + if (doc.passagesTruncated && labels.passagesTruncated) lines.push(labels.passagesTruncated, ""); | |
| 240 | + } | |
| 173 | 241 | if (doc.fields.length > 0) { |
| 174 | 242 | lines.push(`## ${labels.otherFields}`, ""); |
| 175 | 243 | for (const field of doc.fields) lines.push(`- **${field.key}:** ${fieldValueText(field.value)}`); |
src/components/notes/rag-output-drawer.test.tsxmodified+174 -12
| @@ -1,9 +1,14 @@ | ||
| 1 | -import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; | |
| 1 | +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; | |
| 2 | 2 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 3 | 3 | import type { RagOutput } from "@/api/client"; |
| 4 | 4 | import { RagOutputDrawer } from "@/components/notes/rag-output-drawer"; |
| 5 | -import { buildRagOutputMarkdown, readRagOutputDocument } from "@/components/notes/rag-output-document"; | |
| 6 | -import { ragOutputMessage } from "@/components/notes/rag-output-messages"; | |
| 5 | +import { | |
| 6 | + buildRagOutputMarkdown, | |
| 7 | + readRagOutputDocument, | |
| 8 | + type RagOutputDocument, | |
| 9 | + type RagOutputMarkdownLabels, | |
| 10 | +} from "@/components/notes/rag-output-document"; | |
| 11 | +import { ragOutputMessage, ragOutputPassagePages } from "@/components/notes/rag-output-messages"; | |
| 7 | 12 | import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; |
| 8 | 13 | import { formatDateTime } from "@/lib/format"; |
| 9 | 14 | import type { NoteFileSource } from "@/lib/note-source"; |
| @@ -44,24 +49,75 @@ const HEALTHY: RagOutput = { | ||
| 44 | 49 | }, |
| 45 | 50 | }; |
| 46 | 51 | |
| 47 | -const LABELS = { | |
| 48 | - date: ragOutputMessage("en", "date"), | |
| 49 | - note: ragOutputMessage("en", "note"), | |
| 50 | - sources: ragOutputMessage("en", "sources"), | |
| 51 | - failed: ragOutputMessage("en", "failedTitle"), | |
| 52 | - otherFields: ragOutputMessage("en", "otherFields"), | |
| 53 | -}; | |
| 52 | +const PASSAGE_TEXT_1 = "Hücre zarı seçici geçirgendir; madde alışverişini düzenler.\nZar proteinleri taşımayı üstlenir."; | |
| 53 | +const PASSAGE_TEXT_2 = "Mitokondri, oksijenli solunumla ATP üretir."; | |
| 54 | + | |
| 55 | +/** HEALTHY's payload with extra keys — the shape the service evolved into. */ | |
| 56 | +function withPassages(extra: Record<string, unknown>): RagOutput { | |
| 57 | + return { ...HEALTHY, payload: { ...(HEALTHY.payload as Record<string, unknown>), ...extra } }; | |
| 58 | +} | |
| 59 | + | |
| 60 | +const WITH_PASSAGES = withPassages({ | |
| 61 | + passages: [ | |
| 62 | + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, | |
| 63 | + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, | |
| 64 | + ], | |
| 65 | + passages_truncated: false, | |
| 66 | +}); | |
| 67 | + | |
| 68 | +const WITH_TRUNCATED = withPassages({ | |
| 69 | + passages: [ | |
| 70 | + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, | |
| 71 | + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, | |
| 72 | + ], | |
| 73 | + passages_truncated: true, | |
| 74 | +}); | |
| 75 | + | |
| 76 | +/** The service stamps the note's own body chunks with the note key. */ | |
| 77 | +const WITH_NOTE_PASSAGE = withPassages({ | |
| 78 | + passages: [ | |
| 79 | + { chunk_id: "01NOTE:01NOTE:c0", doc_id: "note-1", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, | |
| 80 | + ], | |
| 81 | +}); | |
| 82 | + | |
| 83 | +function markdownLabels(document: RagOutputDocument): RagOutputMarkdownLabels { | |
| 84 | + return { | |
| 85 | + date: ragOutputMessage("en", "date"), | |
| 86 | + note: ragOutputMessage("en", "note"), | |
| 87 | + sources: ragOutputMessage("en", "sources"), | |
| 88 | + failed: ragOutputMessage("en", "failedTitle"), | |
| 89 | + otherFields: ragOutputMessage("en", "otherFields"), | |
| 90 | + passages: ragOutputMessage("en", "passages"), | |
| 91 | + passageHeader: (passage) => { | |
| 92 | + const source = passage.sourceName | |
| 93 | + ?? (passage.fromNote ? NOTE_TITLE : ragOutputMessage("en", "unnamedSource")); | |
| 94 | + const pages = ragOutputPassagePages("en", passage.pageStart, passage.pageEnd); | |
| 95 | + return pages ? `${source} · ${pages}` : source; | |
| 96 | + }, | |
| 97 | + passagesTruncated: document.passagesTruncated | |
| 98 | + ? document.chunksTotal != null | |
| 99 | + ? ragOutputMessage("en", "passagesTruncated", { shown: document.passages.length, total: document.chunksTotal }) | |
| 100 | + : ragOutputMessage("en", "passagesTruncatedNoTotal", { shown: document.passages.length }) | |
| 101 | + : "", | |
| 102 | + }; | |
| 103 | +} | |
| 54 | 104 | |
| 55 | 105 | function expectedMarkdown(output: RagOutput) { |
| 106 | + const document = readRagOutputDocument(output); | |
| 56 | 107 | return buildRagOutputMarkdown({ |
| 57 | 108 | title: NOTE_TITLE, |
| 58 | 109 | date: formatDateTime(output.generated_at, "en"), |
| 59 | 110 | noteTitle: NOTE_TITLE, |
| 60 | - document: readRagOutputDocument(output), | |
| 61 | - labels: LABELS, | |
| 111 | + document, | |
| 112 | + labels: markdownLabels(document), | |
| 62 | 113 | }); |
| 63 | 114 | } |
| 64 | 115 | |
| 116 | +/** The drawer's extracted-text section, so raw-record assertions stay scoped. */ | |
| 117 | +function passagesSection(): HTMLElement { | |
| 118 | + return screen.getByText("Extracted text").closest("div") as HTMLElement; | |
| 119 | +} | |
| 120 | + | |
| 65 | 121 | function stubSource(output: RagOutput): NoteFileSource { |
| 66 | 122 | return { |
| 67 | 123 | maxFiles: 10, |
| @@ -112,6 +168,7 @@ describe("RagOutputDrawer", () => { | ||
| 112 | 168 | |
| 113 | 169 | afterEach(() => { |
| 114 | 170 | cleanup(); |
| 171 | + localStorage.removeItem("hezarfen.locale"); | |
| 115 | 172 | vi.clearAllMocks(); |
| 116 | 173 | }); |
| 117 | 174 | |
| @@ -189,4 +246,109 @@ describe("RagOutputDrawer", () => { | ||
| 189 | 246 | expect(screen.getByText("Unnamed attachment")).toBeTruthy(); |
| 190 | 247 | expect(screen.queryByText(/file-zzz9/)).toBeNull(); |
| 191 | 248 | }); |
| 249 | + | |
| 250 | + it("shows the extracted passages with their source files, page ranges and line breaks", async () => { | |
| 251 | + renderDrawer(WITH_PASSAGES); | |
| 252 | + | |
| 253 | + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); | |
| 254 | + expect(screen.getByText("hücre-notu.pdf · pp. 3-4")).toBeTruthy(); | |
| 255 | + expect(screen.getByText("organeller.pdf · p. 5")).toBeTruthy(); | |
| 256 | + // The section renders the passages — it does not dump their ids. | |
| 257 | + const section = passagesSection(); | |
| 258 | + const first = within(section).getByText(/Hücre zarı seçici geçirgendir/); | |
| 259 | + expect(first.textContent).toBe(PASSAGE_TEXT_1); | |
| 260 | + expect(first.className).toContain("whitespace-pre-wrap"); | |
| 261 | + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); | |
| 262 | + expect(within(section).queryByText(/chunk-/)).toBeNull(); | |
| 263 | + expect(within(section).queryByText(/doc-/)).toBeNull(); | |
| 264 | + }); | |
| 265 | + | |
| 266 | + it("exports the same passages, in the same order, into the Markdown document", () => { | |
| 267 | + const markdown = expectedMarkdown(WITH_PASSAGES); | |
| 268 | + | |
| 269 | + expect(markdown).toContain("## Extracted text"); | |
| 270 | + expect(markdown).toContain("**hücre-notu.pdf · pp. 3-4**"); | |
| 271 | + expect(markdown).toContain("**organeller.pdf · p. 5**"); | |
| 272 | + const first = markdown.indexOf(PASSAGE_TEXT_1); | |
| 273 | + const second = markdown.indexOf(PASSAGE_TEXT_2); | |
| 274 | + expect(first).toBeGreaterThan(-1); | |
| 275 | + expect(second).toBeGreaterThan(first); | |
| 276 | + expect(markdown.indexOf("## Extracted text")).toBeLessThan(markdown.indexOf("## Other fields")); | |
| 277 | + expect(markdown).not.toContain("chunk-1"); | |
| 278 | + expect(markdown).not.toContain("doc-ccc3"); | |
| 279 | + expect(markdown).not.toContain("passages_truncated"); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("copies the passages exactly as exported, truncation note included", async () => { | |
| 283 | + renderDrawer(WITH_TRUNCATED); | |
| 284 | + | |
| 285 | + fireEvent.click(screen.getByRole("button", { name: "Copy" })); | |
| 286 | + | |
| 287 | + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); | |
| 288 | + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_TRUNCATED)); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + it("renders no extracted-text section for outputs stored before passages existed", async () => { | |
| 292 | + renderDrawer(HEALTHY); | |
| 293 | + | |
| 294 | + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); | |
| 295 | + expect(screen.queryByText("Extracted text")).toBeNull(); | |
| 296 | + }); | |
| 297 | + | |
| 298 | + it("survives an ill-typed passages value without rendering a section", async () => { | |
| 299 | + renderDrawer(withPassages({ passages: "bozuk" })); | |
| 300 | + | |
| 301 | + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); | |
| 302 | + expect(screen.queryByText("Extracted text")).toBeNull(); | |
| 303 | + }); | |
| 304 | + | |
| 305 | + it("says honestly how many passages were extracted when the list is capped", async () => { | |
| 306 | + renderDrawer(WITH_TRUNCATED); | |
| 307 | + | |
| 308 | + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); | |
| 309 | + expect( | |
| 310 | + screen.getByText(ragOutputMessage("en", "passagesTruncated", { shown: 2, total: 18 })), | |
| 311 | + ).toBeTruthy(); | |
| 312 | + }); | |
| 313 | + | |
| 314 | + it("renders the Turkish section title and truncation sentence", async () => { | |
| 315 | + localStorage.setItem("hezarfen.locale", "tr"); | |
| 316 | + renderDrawer(WITH_TRUNCATED); | |
| 317 | + | |
| 318 | + await waitFor(() => expect(screen.getByText("Çıkarılan metin")).toBeTruthy()); | |
| 319 | + expect( | |
| 320 | + screen.getByText(ragOutputMessage("tr", "passagesTruncated", { shown: 2, total: 18 })), | |
| 321 | + ).toBeTruthy(); | |
| 322 | + }); | |
| 323 | + | |
| 324 | + it("never shows a raw attachment id for a passage whose source cannot be resolved", async () => { | |
| 325 | + renderDrawer( | |
| 326 | + withPassages({ | |
| 327 | + passages: [ | |
| 328 | + { chunk_id: "chunk-9", doc_id: "doc-zzz9", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, | |
| 329 | + ], | |
| 330 | + }), | |
| 331 | + ); | |
| 332 | + | |
| 333 | + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); | |
| 334 | + expect(screen.getByText("Unnamed attachment")).toBeTruthy(); | |
| 335 | + const section = passagesSection(); | |
| 336 | + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); | |
| 337 | + expect(within(section).queryByText(/doc-zzz9/)).toBeNull(); | |
| 338 | + expect(within(section).queryByText(/chunk-9/)).toBeNull(); | |
| 339 | + }); | |
| 340 | + | |
| 341 | + it("labels a note-body passage with the note title, never the note key", async () => { | |
| 342 | + renderDrawer(WITH_NOTE_PASSAGE); | |
| 343 | + | |
| 344 | + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); | |
| 345 | + const section = passagesSection(); | |
| 346 | + expect(within(section).getByText(NOTE_TITLE)).toBeTruthy(); | |
| 347 | + expect(within(section).queryByText(/note-1/)).toBeNull(); | |
| 348 | + | |
| 349 | + // The export carries the same label the view shows. | |
| 350 | + fireEvent.click(screen.getByRole("button", { name: "Copy" })); | |
| 351 | + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); | |
| 352 | + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_NOTE_PASSAGE)); | |
| 353 | + }); | |
| 192 | 354 | }); |
src/components/notes/rag-output-drawer.tsxmodified+46 -1
| @@ -9,8 +9,14 @@ import { | ||
| 9 | 9 | fieldValueText, |
| 10 | 10 | ragOutputFileName, |
| 11 | 11 | readRagOutputDocument, |
| 12 | + type RagOutputDocument, | |
| 13 | + type RagOutputPassage, | |
| 12 | 14 | } from "@/components/notes/rag-output-document"; |
| 13 | -import { ragOutputMessage, type RagOutputMessageKey } from "@/components/notes/rag-output-messages"; | |
| 15 | +import { | |
| 16 | + ragOutputMessage, | |
| 17 | + ragOutputPassagePages, | |
| 18 | + type RagOutputMessageKey, | |
| 19 | +} from "@/components/notes/rag-output-messages"; | |
| 14 | 20 | import { formatDateTime } from "@/lib/format"; |
| 15 | 21 | import { usePreferences } from "@/stores/preferences-context"; |
| 16 | 22 | |
| @@ -58,6 +64,20 @@ export function RagOutputDrawer(props: { | ||
| 58 | 64 | |
| 59 | 65 | const doc = () => (props.output ? readRagOutputDocument(props.output) : null); |
| 60 | 66 | const noteTitle = () => props.noteTitle?.trim() ?? ""; |
| 67 | + /** One passage's heading: the source file by name, its page range if any. */ | |
| 68 | + const passageHeader = (passage: RagOutputPassage) => { | |
| 69 | + const source = passage.sourceName | |
| 70 | + ?? (passage.fromNote ? noteTitle() || rt("noteText") : rt("unnamedSource")); | |
| 71 | + const pages = ragOutputPassagePages(locale(), passage.pageStart, passage.pageEnd); | |
| 72 | + return pages ? `${source} · ${pages}` : source; | |
| 73 | + }; | |
| 74 | + /** The honest note when the service's cap means more passages exist. */ | |
| 75 | + const passagesNote = (read: RagOutputDocument) => { | |
| 76 | + if (!read.passagesTruncated) return ""; | |
| 77 | + return read.chunksTotal != null | |
| 78 | + ? rt("passagesTruncated", { shown: read.passages.length, total: read.chunksTotal }) | |
| 79 | + : rt("passagesTruncatedNoTotal", { shown: read.passages.length }); | |
| 80 | + }; | |
| 61 | 81 | const markdown = () => { |
| 62 | 82 | const output = props.output; |
| 63 | 83 | const read = doc(); |
| @@ -73,6 +93,9 @@ export function RagOutputDrawer(props: { | ||
| 73 | 93 | sources: rt("sources"), |
| 74 | 94 | failed: rt("failedTitle"), |
| 75 | 95 | otherFields: rt("otherFields"), |
| 96 | + passages: rt("passages"), | |
| 97 | + passageHeader, | |
| 98 | + passagesTruncated: passagesNote(read), | |
| 76 | 99 | }, |
| 77 | 100 | }); |
| 78 | 101 | }; |
| @@ -200,6 +223,28 @@ export function RagOutputDrawer(props: { | ||
| 200 | 223 | </Show> |
| 201 | 224 | </Show> |
| 202 | 225 | |
| 226 | + <Show when={read().passages.length > 0}> | |
| 227 | + <div class="space-y-2"> | |
| 228 | + <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{rt("passages")}</p> | |
| 229 | + <ul class="space-y-3"> | |
| 230 | + <For each={read().passages}> | |
| 231 | + {(passage) => ( | |
| 232 | + <li class="rounded-lg border border-border/60 p-3"> | |
| 233 | + <p class="text-xs text-muted-foreground">{passageHeader(passage)}</p> | |
| 234 | + {/* Scrolls past its cap on screen; print flows it out in full. */} | |
| 235 | + <div class="mt-1.5 max-h-60 overflow-y-auto print:max-h-none"> | |
| 236 | + <p class="whitespace-pre-wrap break-words text-sm leading-6">{passage.text}</p> | |
| 237 | + </div> | |
| 238 | + </li> | |
| 239 | + )} | |
| 240 | + </For> | |
| 241 | + </ul> | |
| 242 | + <Show when={passagesNote(read())}> | |
| 243 | + <p class="text-xs text-muted-foreground">{passagesNote(read())}</p> | |
| 244 | + </Show> | |
| 245 | + </div> | |
| 246 | + </Show> | |
| 247 | + | |
| 203 | 248 | <Show when={read().fields.length > 0}> |
| 204 | 249 | <div class="space-y-1.5"> |
| 205 | 250 | <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"> |
src/components/notes/rag-output-messages.tsmodified+34 -0
| @@ -23,6 +23,12 @@ export type RagOutputMessageKey = | ||
| 23 | 23 | | "failedLine" |
| 24 | 24 | | "otherFields" |
| 25 | 25 | | "chunks" |
| 26 | + | "passages" | |
| 27 | + | "passagePagesSingle" | |
| 28 | + | "passagePagesRange" | |
| 29 | + | "passagesTruncated" | |
| 30 | + | "passagesTruncatedNoTotal" | |
| 31 | + | "noteText" | |
| 26 | 32 | | "technical" |
| 27 | 33 | | "copy" |
| 28 | 34 | | "copied" |
| @@ -43,6 +49,12 @@ const en: Record<RagOutputMessageKey, string> = { | ||
| 43 | 49 | "failedLine": "Not processed: {names}", |
| 44 | 50 | "otherFields": "Other fields", |
| 45 | 51 | "chunks": "Text chunks", |
| 52 | + "passages": "Extracted text", | |
| 53 | + "passagePagesSingle": "p. {page}", | |
| 54 | + "passagePagesRange": "pp. {start}-{end}", | |
| 55 | + "passagesTruncated": "{total} passages were extracted in total; the first {shown} are listed here.", | |
| 56 | + "passagesTruncatedNoTotal": "Only the first {shown} extracted passages are listed here.", | |
| 57 | + "noteText": "Note text", | |
| 46 | 58 | "technical": "Technical details", |
| 47 | 59 | "copy": "Copy", |
| 48 | 60 | "copied": "Copied to the clipboard", |
| @@ -64,6 +76,12 @@ const tr: Record<RagOutputMessageKey, string> = { | ||
| 64 | 76 | "failedLine": "İşlenemeyenler: {names}", |
| 65 | 77 | "otherFields": "Diğer alanlar", |
| 66 | 78 | "chunks": "Metin parçaları", |
| 79 | + "passages": "Çıkarılan metin", | |
| 80 | + "passagePagesSingle": "s. {page}", | |
| 81 | + "passagePagesRange": "s. {start}-{end}", | |
| 82 | + "passagesTruncated": "Toplam {total} metin parçası çıkarıldı; burada ilk {shown} tanesi gösteriliyor.", | |
| 83 | + "passagesTruncatedNoTotal": "Çıkarılan parçaların yalnızca ilk {shown} tanesi gösteriliyor.", | |
| 84 | + "noteText": "Not metni", | |
| 67 | 85 | "technical": "Teknik ayrıntı", |
| 68 | 86 | "copy": "Kopyala", |
| 69 | 87 | "copied": "Panoya kopyalandı", |
| @@ -79,3 +97,19 @@ export function ragOutputMessage( | ||
| 79 | 97 | ): string { |
| 80 | 98 | return formatMessage((locale === "tr" ? tr : en)[key], vars); |
| 81 | 99 | } |
| 100 | + | |
| 101 | +/** | |
| 102 | + * One passage's page range (`s. 3-4`), or an empty string when the service | |
| 103 | + * recorded no page — the label is then left off entirely. | |
| 104 | + */ | |
| 105 | +export function ragOutputPassagePages( | |
| 106 | + locale: Locale, | |
| 107 | + pageStart: number | null, | |
| 108 | + pageEnd: number | null, | |
| 109 | +): string { | |
| 110 | + if (pageStart == null) return ""; | |
| 111 | + if (pageEnd == null || pageEnd <= pageStart) { | |
| 112 | + return ragOutputMessage(locale, "passagePagesSingle", { page: pageStart }); | |
| 113 | + } | |
| 114 | + return ragOutputMessage(locale, "passagePagesRange", { start: pageStart, end: pageEnd }); | |
| 115 | +} |
src/i18n/insights-run-report.tsmodified+15 -0
| @@ -19,6 +19,11 @@ export type RunReportKey = | ||
| 19 | 19 | | "copyFailed" |
| 20 | 20 | | "download" |
| 21 | 21 | | "downloaded" |
| 22 | + | "schoolReport" | |
| 23 | + | "schoolReportGenerating" | |
| 24 | + | "schoolReportUnavailable" | |
| 25 | + | "schoolReportUnreadable" | |
| 26 | + | "schoolReportTooLarge" | |
| 22 | 27 | | "print" |
| 23 | 28 | | "runSection" |
| 24 | 29 | | "schoolSection" |
| @@ -82,6 +87,11 @@ const tr: Record<RunReportKey, string> = { | ||
| 82 | 87 | copyFailed: "Rapor panoya kopyalanamadı.", |
| 83 | 88 | download: "İndir (.md)", |
| 84 | 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 | 95 | print: "Yazdır / PDF", |
| 86 | 96 | runSection: "Çalıştırma özeti", |
| 87 | 97 | schoolSection: "Okul geneli", |
| @@ -146,6 +156,11 @@ const en: Record<RunReportKey, string> = { | ||
| 146 | 156 | copyFailed: "Could not copy the report.", |
| 147 | 157 | download: "Download (.md)", |
| 148 | 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 | 164 | print: "Print / PDF", |
| 150 | 165 | runSection: "Run summary", |
| 151 | 166 | schoolSection: "School overview", |
src/lib/insight-run-report.tsmodified+5 -0
| @@ -328,6 +328,11 @@ export function runReportFileName(runDay: string): string { | ||
| 328 | 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 | 337 | * The run's pending students, by name, in the ledger's own order — the panel |
| 333 | 338 | * and the export both render this one line, so the count, the names and the |