forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

insight-run-report.ts472 lines, 18.7 KiBHistoryRawDownload
1import type { InsightRun, PersonRef, StudentInsight } from "@/api/client";
2import { runReportText } from "@/i18n/insights-run-report";
3import { messageFor, type Locale, type MessageKey } from "@/i18n/messages";
4import { formatDateTime } from "@/lib/format";
5
6/**
7 * The school run report's model and its Markdown rendering.
8 *
9 * The report has no aggregate door: the backend serves a run's counters
10 * (`GET /insights/runs`) and one student at a time (`GET /insights/students/{id}`),
11 * and nothing in between. So the school picture is composed here, from the
12 * students whose signals have been read, and every number the model carries is
13 * stated together with how many students it was computed over — a partial read
14 * must never read as "the school has none".
15 *
16 * The Markdown is the report: the panel renders this model, and the clipboard,
17 * the `.md` download and the print document are all built from the same model,
18 * so what is exported is exactly what is shown.
19 */
20
21export type ModuleId = "marks" | "attendance" | "study" | "submission";
22
23export type ModuleCoverage = {
24 id: ModuleId;
25 /** Students whose module holds a measurement (not merely a computed shell). */
26 with_data: number;
27 /** Students whose summary carries the module at all. */
28 computed: number;
29 /** The module's own limitation sentence, when it ships one. */
30 limitation: string | null;
31};
32
33export type StudentSignal = {
34 id: string;
35 name: string;
36 /**
37 * `ok` — a summary was read. `no_summary` — the door answered and nothing has
38 * been computed for this student. `not_loaded` — this report has not read
39 * them yet. `error` — the read itself failed.
40 */
41 state: "ok" | "no_summary" | "not_loaded" | "error";
42 error: string | null;
43 confidence: string | null;
44 computed_at: number | null;
45 attention: number;
46 cards: number;
47 segments: number;
48 marks: { courses_with_marks: number; courses_total: number; average: number | null };
49 attendance: { rate: number | null; observed: number };
50 study: { stints: number };
51 submission: { counted: number };
52};
53
54export type RunReportModel = {
55 run: InsightRun;
56 students: StudentSignal[];
57 /** How many students the school picture was computed over. */
58 coverage: { loaded: number; total: number };
59 modules: ModuleCoverage[];
60 totals: { attention: number; cards: number; segments: number };
61 pending: { id: string; name: string | null }[];
62 roster_error: string | null;
63};
64
65// ---- reading ZEKA's module payloads ---------------------------------------
66//
67// The module members are `unknown` by contract and the service may grow them,
68// so every read is by name behind a shape check: a missing field means "this
69// module measured nothing", never a throw and never a zero invented from a
70// different field.
71
72/** The shape gate every module read goes through; `null` for anything else. */
73function recordOf(value: unknown): Record<string, unknown> | null {
74 return typeof value === "object" && value !== null && !Array.isArray(value)
75 ? (value as Record<string, unknown>)
76 : null;
77}
78
79/** A finite number, or `null` — counts and rates alike are read through this. */
80function finiteNumber(value: unknown): number | null {
81 return typeof value === "number" && Number.isFinite(value) ? value : null;
82}
83
84export function readMarks(marks: unknown): StudentSignal["marks"] {
85 const courses = recordOf(recordOf(marks)?.courses) ?? {};
86 const rows = Object.values(courses);
87 let withMarks = 0;
88 let sum = 0;
89 let counted = 0;
90 for (const row of rows) {
91 const course = recordOf(row);
92 if (!course) continue;
93 if ((finiteNumber(course.n_marks) ?? 0) > 0) withMarks += 1;
94 const average = finiteNumber(course.average);
95 if (average != null) {
96 sum += average;
97 counted += 1;
98 }
99 }
100 return {
101 courses_with_marks: withMarks,
102 courses_total: rows.length,
103 average: counted > 0 ? sum / counted : null,
104 };
105}
106
107export function readAttendance(attendance: unknown): StudentSignal["attendance"] & { limitation: string | null } {
108 const module = recordOf(attendance);
109 const overall = recordOf(module?.overall);
110 const limitation = module?.limitation;
111 return {
112 rate: finiteNumber(overall?.rate),
113 observed: finiteNumber(overall?.n_obs) ?? 0,
114 limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
115 };
116}
117
118export function readStudy(study: unknown): StudentSignal["study"] & { limitation: string | null } {
119 const module = recordOf(study);
120 const recent = recordOf(module?.recent_28d);
121 const limitation = module?.limitation;
122 return {
123 stints: finiteNumber(recent?.n_stints) ?? 0,
124 limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
125 };
126}
127
128export function readSubmission(submission: unknown): StudentSignal["submission"] & { limitation: string | null } {
129 const module = recordOf(submission);
130 const overall = recordOf(module?.overall);
131 const limitation = module?.limitation;
132 return {
133 counted: finiteNumber(overall?.n) ?? 0,
134 limitation: typeof limitation === "string" && limitation.trim().length > 0 ? limitation : null,
135 };
136}
137
138const EMPTY_SIGNAL: Omit<StudentSignal, "id" | "name" | "state" | "error"> = {
139 confidence: null,
140 computed_at: null,
141 attention: 0,
142 cards: 0,
143 segments: 0,
144 marks: { courses_with_marks: 0, courses_total: 0, average: null },
145 attendance: { rate: null, observed: 0 },
146 study: { stints: 0 },
147 submission: { counted: 0 },
148};
149
150/** One student's readable signal line, from whatever the door answered. */
151export function toStudentSignal(
152 person: { id: string; name: string },
153 insight: StudentInsight | null | undefined,
154 error: string | null,
155): StudentSignal {
156 const identity = { id: person.id, name: person.name };
157 if (error) return { ...identity, ...EMPTY_SIGNAL, state: "error", error };
158 if (!insight) return { ...identity, ...EMPTY_SIGNAL, state: "not_loaded", error: null };
159 const summary = insight.summary ?? null;
160 if (!summary) {
161 return {
162 ...identity,
163 ...EMPTY_SIGNAL,
164 state: "no_summary",
165 error: null,
166 attention: insight.attention.length,
167 cards: insight.cards.length,
168 segments: insight.segments.length,
169 };
170 }
171 return {
172 ...identity,
173 state: "ok",
174 error: null,
175 confidence: summary.confidence,
176 computed_at: summary.computed_at,
177 attention: insight.attention.length,
178 cards: insight.cards.length,
179 segments: insight.segments.length,
180 marks: readMarks(summary.marks),
181 attendance: readAttendance(summary.attendance),
182 study: readStudy(summary.study),
183 submission: readSubmission(summary.submission),
184 };
185}
186
187/** Whether a module holds a measurement for one student. */
188export function moduleHasData(signal: StudentSignal, id: ModuleId): boolean {
189 if (signal.state !== "ok") return false;
190 if (id === "marks") return signal.marks.courses_with_marks > 0;
191 if (id === "attendance") return signal.attendance.observed > 0;
192 if (id === "study") return signal.study.stints > 0;
193 return signal.submission.counted > 0;
194}
195
196export function buildRunReportModel(args: {
197 run: InsightRun;
198 roster: PersonRef[];
199 insights: Record<string, StudentInsight>;
200 errors: Record<string, string>;
201 coverageTotal: number;
202 rosterError: string | null;
203}): RunReportModel {
204 const students = args.roster.map((person) =>
205 toStudentSignal(
206 { id: person.id, name: person.display_name || person.username || person.id },
207 args.insights[person.id] ?? null,
208 args.errors[person.id] ?? null,
209 ),
210 );
211 const nameById: Record<string, string> = {};
212 for (const person of args.roster) {
213 nameById[person.id] = person.display_name || person.username;
214 }
215 const loaded = students.filter((student) => student.state === "ok" || student.state === "no_summary");
216 const limitations: Record<ModuleId, string | null> = {
217 marks: null,
218 attendance: null,
219 study: null,
220 submission: null,
221 };
222 for (const student of loaded) {
223 const summary = args.insights[student.id]?.summary;
224 if (!summary) continue;
225 const found: [ModuleId, string | null][] = [
226 ["attendance", readAttendance(summary.attendance).limitation],
227 ["study", readStudy(summary.study).limitation],
228 ["submission", readSubmission(summary.submission).limitation],
229 ];
230 for (const [id, value] of found) {
231 if (value && !limitations[id]) limitations[id] = value;
232 }
233 }
234 const modules: ModuleCoverage[] = (["marks", "attendance", "study", "submission"] as ModuleId[]).map((id) => ({
235 id,
236 with_data: loaded.filter((student) => moduleHasData(student, id)).length,
237 computed: loaded.filter((student) => args.insights[student.id]?.summary?.[id] != null).length,
238 limitation: limitations[id],
239 }));
240 return {
241 run: args.run,
242 students,
243 coverage: { loaded: loaded.length, total: args.coverageTotal },
244 modules,
245 totals: {
246 attention: loaded.reduce((sum, student) => sum + student.attention, 0),
247 cards: loaded.reduce((sum, student) => sum + student.cards, 0),
248 segments: loaded.reduce((sum, student) => sum + student.segments, 0),
249 },
250 pending: args.run.pending_students.map((id) => ({ id, name: nameById[id] ?? null })),
251 roster_error: args.rosterError,
252 };
253}
254
255// ---- rendering -------------------------------------------------------------
256
257/** Run durations are sub-second in practice, so minutes-only would read "0 dk". */
258export function formatRunDuration(ms: number | null | undefined, locale: Locale): string {
259 if (ms == null) return "—";
260 const tr = locale === "tr";
261 if (ms < 1000) return `${Math.round(ms)} ms`;
262 if (ms < 60_000) return tr ? `${(ms / 1000).toFixed(1)} sn` : `${(ms / 1000).toFixed(1)} s`;
263 const minutes = ms / 60_000;
264 if (minutes < 60) return tr ? `${minutes.toFixed(1)} dk` : `${minutes.toFixed(1)} min`;
265 return tr ? `${(minutes / 60).toFixed(1)} sa` : `${(minutes / 60).toFixed(1)} h`;
266}
267
268export function moduleLabel(locale: Locale, id: ModuleId): string {
269 if (id === "marks") return runReportText(locale, "moduleMarks");
270 if (id === "attendance") return runReportText(locale, "moduleAttendance");
271 if (id === "study") return runReportText(locale, "moduleStudy");
272 return runReportText(locale, "moduleSubmission");
273}
274
275const STATUS_KEYS: Record<string, MessageKey> = {
276 running: "insights.status.running",
277 ok: "insights.status.ok",
278 partial: "insights.status.partial",
279 failed: "insights.status.failed",
280 skipped: "insights.status.skipped",
281};
282
283/**
284 * A run status, from the app's dictionary — the same keys the run table's own
285 * badge uses, so the ledger and the report can never disagree about what
286 * `partial` says. A status this build does not know stays raw rather than being
287 * guessed at.
288 */
289export function runReportStatusLabel(locale: Locale, status: string): string {
290 const key = STATUS_KEYS[status];
291 if (!key) return status;
292 return messageFor(locale, key) ?? status;
293}
294
295const CONFIDENCE_KEYS: Record<string, MessageKey> = {
296 none: "insights.confidence.none",
297 exploratory: "insights.confidence.exploratory",
298 stable: "insights.confidence.stable",
299};
300
301/**
302 * ZEKA's confidence tiers, in the reader's language. They come from the app's
303 * own dictionary so the drawer and the report cannot disagree; a tier the
304 * dictionary does not know stays raw rather than being guessed at.
305 */
306export function confidenceText(locale: Locale, confidence: string): string {
307 const key = CONFIDENCE_KEYS[confidence];
308 if (!key) return confidence;
309 return messageFor(locale, key) ?? confidence;
310}
311
312/**
313 * A failed pipeline stage. The values are zeka's own stage names
314 * (`discover_students` / `fetch` / `compute` / `store`); an unrecognised one is
315 * shown as the technical stage it is, and the raw list stays in the report's
316 * technical disclosure.
317 */
318const FAILED_STAGE_LABELS: Record<string, Record<string, string>> = {
319 tr: { discover_students: "Öğrenci listesi", fetch: "Veri toplama", compute: "Hesaplama", store: "Kayıt" },
320 en: { discover_students: "Student list", fetch: "Data fetch", compute: "Computation", store: "Storage" },
321};
322
323export function failedStageText(locale: Locale, stage: string): string {
324 return FAILED_STAGE_LABELS[locale][stage] ?? stage;
325}
326
327export function runReportFileName(runDay: string): string {
328 return `okul-analiz-raporu-${runDay}.md`;
329}
330
331/** The AI service's own document, under the same base name as the .md export. */
332export function runReportHtmlFileName(runDay: string): string {
333 return `okul-analiz-raporu-${runDay}.html`;
334}
335
336/**
337 * The run's pending students, by name, in the ledger's own order — the panel
338 * and the export both render this one line, so the count, the names and the
339 * `—` for a student the roster cannot resolve can never drift apart.
340 */
341export function pendingStudentsLine(locale: Locale, model: RunReportModel): string | null {
342 if (model.run.pending_students.length === 0) return null;
343 const named = model.pending.map((row) => row.name ?? "—").join(", ");
344 return `${runReportText(locale, "pendingStudents", { count: model.run.pending_students.length })}: ${named}`;
345}
346
347/** `0,716` in Turkish, `0.716` in English — the same number either way. */
348export function runReportDecimal(value: number, locale: Locale): string {
349 return value.toFixed(1).replace(".", locale === "tr" ? "," : ".");
350}
351
352/** `85%`, or `veri yok` when the module measured nothing. */
353export function runReportPercent(value: number | null, locale: Locale): string {
354 return value == null ? runReportText(locale, "noData") : `${Math.round(value * 100)}%`;
355}
356
357export function studentStatusText(locale: Locale, student: StudentSignal): string {
358 if (student.state === "ok") return runReportStatusLabel(locale, "ok");
359 if (student.state === "no_summary") return runReportText(locale, "noSummary");
360 if (student.state === "error") return student.error ?? runReportText(locale, "noData");
361 return runReportText(locale, "notLoaded");
362}
363
364/**
365 * `Yüklenmedi` while nothing has been read, `veri yok` only once a read has
366 * said so — the two are different claims, and the panel and the export must
367 * make the same one.
368 */
369export function studentMarksText(locale: Locale, student: StudentSignal): string {
370 if (student.state === "not_loaded") return runReportText(locale, "notLoaded");
371 if (student.state !== "ok") return runReportText(locale, "noData");
372 const average = student.marks.average == null ? "—" : runReportDecimal(student.marks.average, locale);
373 return `${average} (${student.marks.courses_with_marks}/${student.marks.courses_total})`;
374}
375
376export function studentAttendanceText(locale: Locale, student: StudentSignal): string {
377 if (student.state === "not_loaded") return runReportText(locale, "notLoaded");
378 if (student.state !== "ok" || student.attendance.observed === 0) return runReportText(locale, "noData");
379 return runReportPercent(student.attendance.rate, locale);
380}
381
382/**
383 * The report as Markdown — what `Kopyala`, the `.md` download and the print
384 * document all carry. Every section of the panel is here, `veri yok` lines
385 * included: an export that silently dropped the empty modules would be a
386 * prettier lie than the screen.
387 */
388export function buildRunReportMarkdown(model: RunReportModel, locale: Locale): string {
389 const t = (key: Parameters<typeof runReportText>[1], vars?: Record<string, string | number>) =>
390 runReportText(locale, key, vars);
391 const { run, coverage } = model;
392 const lines: string[] = [];
393 lines.push(`# ${t("documentTitle", { day: run.run_day })}`);
394 lines.push("");
395 lines.push(`## ${t("runSection")}`);
396 lines.push(`- ${t("runDay")}: ${run.run_day}`);
397 lines.push(`- ${t("status")}: ${runReportStatusLabel(locale, run.status)}`);
398 lines.push(`- ${t("startedAt")}: ${formatDateTime(run.started_at, locale)}`);
399 lines.push(`- ${t("finishedAt")}: ${formatDateTime(run.finished_at, locale)}`);
400 lines.push(
401 `- ${t("processed")}: ${run.students_ok}/${run.students_total} (${t("skipped").toLowerCase()} ${run.students_skipped}, ${t("failed").toLowerCase()} ${run.students_failed})`,
402 );
403 lines.push(`- ${t("rowsWritten")}: ${run.rows_written}`);
404 lines.push(`- ${t("duration")}: ${formatRunDuration(run.duration_ms, locale)}`);
405 lines.push(
406 `- ${t("budget")}: ${run.budget_exceeded ? t("budgetExceeded") : t("budgetWithin")} (${formatRunDuration(run.budget_ms, locale)})`,
407 );
408 const issueCount = run.pending_students.length + run.failed_modules.length + (run.budget_exceeded ? 1 : 0);
409 lines.push(`- ${t("issues")}: ${issueCount === 0 ? t("noIssues") : String(issueCount)}`);
410 const pendingLine = pendingStudentsLine(locale, model);
411 if (pendingLine) lines.push(`- ${pendingLine}`);
412 if (run.failed_modules.length > 0) {
413 lines.push(
414 `- ${t("failedModules", { modules: run.failed_modules.map((stage) => failedStageText(locale, stage)).join(", ") })}`,
415 );
416 }
417 lines.push("");
418 lines.push(`## ${t("schoolSection")}`);
419 if (model.roster_error) lines.push(`- ${t("rosterFailed", { message: model.roster_error })}`);
420 lines.push(`- ${t("coverage", { loaded: coverage.loaded, total: coverage.total })}`);
421 if (coverage.loaded === 0) lines.push(`- ${t("rosterEmpty")}`);
422 for (const module of model.modules) {
423 const label = moduleLabel(locale, module.id);
424 const covered = t("moduleCovered", { label, withData: module.with_data, total: coverage.loaded });
425 lines.push(`- ${covered}${module.with_data === 0 ? ` → ${t("noData")}` : ""}`);
426 if (module.limitation) lines.push(` - ${module.limitation}`);
427 }
428 if (coverage.loaded > 0 && model.modules.every((module) => module.with_data === 0)) {
429 lines.push(`- ${t("modulesEmpty")}`);
430 }
431 lines.push(
432 `- ${t("attention")}: ${model.totals.attention} · ${t("cards")}: ${model.totals.cards} · ${t("segments")}: ${model.totals.segments}`,
433 );
434 lines.push(`- ${t("coverageNote")}`);
435 lines.push("");
436 lines.push(`## ${t("studentsSection")} (${coverage.loaded}/${coverage.total})`);
437 const header = [
438 t("student"),
439 t("status"),
440 t("confidence"),
441 t("attention"),
442 t("cards"),
443 t("marksAverage"),
444 t("attendanceRate"),
445 t("computedAt"),
446 ];
447 lines.push(`| ${header.join(" | ")} |`);
448 lines.push(`| ${header.map(() => "---").join(" | ")} |`);
449 for (const student of model.students) {
450 const cells = [
451 student.name,
452 studentStatusText(locale, student),
453 student.confidence == null ? t("noData") : confidenceText(locale, student.confidence),
454 String(student.attention),
455 String(student.cards),
456 studentMarksText(locale, student),
457 studentAttendanceText(locale, student),
458 formatDateTime(student.computed_at, locale),
459 ];
460 lines.push(`| ${cells.map((cell) => cell.replace(/\|/g, "\\|")).join(" | ")} |`);
461 }
462 if (model.students.length === 0) lines.push(`| ${t("rosterEmpty")} | | | | | | | |`);
463 lines.push("");
464 lines.push(`## ${t("technical")}`);
465 lines.push(t("technicalHint"));
466 lines.push("");
467 lines.push("```json");
468 lines.push(JSON.stringify(run, null, 2));
469 lines.push("```");
470 lines.push("");
471 return lines.join("\n");
472}