feat(doctor-report): mark screener totals answered in an unvalidated translation

The report data counts, per screener score type, how many of the
window's results were answered in a translation that has not been
validated (`screenerUnvalidatedTranslations`, read only when a screener
total is in the report). The PDF marks such a row with an asterisk and
says under the vitals table how many of how many read as orientation;
the clinician share view says the same under the row.

To keep the aggregator and the PDF section from growing, the wellness
summary and the per-context glucose rows move into helpers; the size
ratchets only fall.
This commit is contained in:
Marc-André Bombeck committed 2026-10-23 08:14:32 +02:00
1 parent 02cc0631fa
commit 14273051db
22 files changed
+369 -85

No files matched your search

@@ -11,6 +11,7 @@ import { MEASUREMENT_TYPE_LABEL_KEYS } from "../measurements/type-label-keys";
import type { DoctorReportData } from "../doctor-report-data";
import { computeGlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
import { getServerTranslator } from "../i18n/server-translator";
import { reportMeasurementLabelKey } from "../report-selection/catalogue";
async function extractText(bytes: Uint8Array): Promise<string> {
const parser = new PDFParse({ data: bytes });
@@ -251,6 +252,47 @@ describe("renderDoctorReportPdfBytes", () => {
expect(text).not.toContain("mg/dL");
});
it("marks a screener total answered in an unvalidated translation and says how many", async () => {
const data = makeData({
stats: {
...makeData().stats,
SCI_SCORE: { avg: 18, min: 14, max: 22, count: 3, latest: 20 },
PHQ9_SCORE: { avg: 6, min: 4, max: 8, count: 2, latest: 4 },
},
screenerUnvalidatedTranslations: { SCI_SCORE: 2 },
});
const { t } = getServerTranslator("en");
const bytes = renderDoctorReportPdfBytes(data, {
timeFormat: "AUTO",
dateFormat: "AUTO",
t,
locale: "en",
now: FIXED_NOW,
});
const text = (await extractText(bytes)).replace(/\s+/g, " ");
const sci = t(reportMeasurementLabelKey("SCI_SCORE"));
expect(text).toContain(`${sci} *`);
expect(text).toContain("2 of 3 results were answered in a translation");
// The PHQ-9 row, all answered in validated wording, carries no mark.
const phq = t(reportMeasurementLabelKey("PHQ9_SCORE"));
expect(text).not.toContain(`${phq} *`);
});
it("prints no translation note when every total was answered in validated wording", async () => {
const bytes = renderDoctorReportPdfBytes(
makeData({ screenerUnvalidatedTranslations: null }),
{
timeFormat: "AUTO",
dateFormat: "AUTO",
t: getServerTranslator("en").t,
locale: "en",
now: FIXED_NOW,
},
);
const text = (await extractText(bytes)).replace(/\s+/g, " ");
expect(text).not.toContain("not been scientifically validated");
});
it("omits the sleep vitals row when there are no sleep stats", async () => {
const bytes = renderDoctorReportPdfBytes(makeData(), {
timeFormat: "AUTO",
+48 -6
View File
@@ -25,12 +25,14 @@ import {
lastNonSkippedTakenAt,
tallyComplianceFromLedger,
} from "@/lib/analytics/compliance";
import type {
CanonicalCollapseRow,
DoctorReportCompliance,
DoctorReportComplianceIntake,
DoctorReportComplianceMedication,
DoctorReportRange,
import {
WELLNESS_SCORE_REPORT_TYPES,
type CanonicalCollapseRow,
type DoctorReportCompliance,
type DoctorReportComplianceIntake,
type DoctorReportComplianceMedication,
type DoctorReportRange,
type DoctorReportStats,
} from "./doctor-report-types";
/**
@@ -188,6 +190,46 @@ export function summariseCanonicalRecovery(
};
}
/**
* The wellness summary of a report: one row per wellness score leaf the
* report admits and holds readings for, from the same stats the measurement
* table prints, so the two cannot disagree. RECOVERY_SCORE carries both the
* native row and the computed proxy for one day; it resolves to the canonical
* row so the PDF reads the SAME value the tile shows. Null when no row is
* left.
*/
export function summariseWellnessScores(input: {
admits: (type: (typeof WELLNESS_SCORE_REPORT_TYPES)[number]) => boolean;
stats: Readonly<Record<string, DoctorReportStats>>;
byType: Readonly<Record<string, ReadonlyArray<{ measuredAt: string }>>>;
measurements: readonly RecoveryMeasurementRow[];
timezone: string;
}): WellnessScoreSummary[] | null {
const { admits, stats, byType, measurements, timezone } = input;
const summaries = WELLNESS_SCORE_REPORT_TYPES.flatMap((type) => {
if (!admits(type)) return [];
if (type === "RECOVERY_SCORE") {
const summary = summariseCanonicalRecovery(measurements, timezone);
return summary ? [summary] : [];
}
const s = stats[type];
const rows = byType[type];
if (!s || !rows || rows.length === 0) return [];
return [
{
type,
latest: Math.round(s.latest),
avg: Math.round(s.avg),
min: Math.round(s.min),
max: Math.round(s.max),
count: s.count,
latestAt: rows[rows.length - 1].measuredAt,
},
];
});
return summaries.length > 0 ? summaries : null;
}
/**
* Validate and normalise the requested reporting window.
* Accepts an unknown value (typically `body.days`); falls back to 90.
@@ -184,6 +184,80 @@ function groupSubHeadRow(label: string): VitalTableRow {
];
}
/**
* Per-context glucose rows. Values are stored canonically in mg/dL and print
* in the owner's unit, in the precision their readings carry.
*/
function glucoseContextTableRows(
context: DoctorReportPdfRenderContext,
glucoseUnit: ReturnType<typeof resolveGlucoseUnit>,
): string[][] {
const { data, t, num } = context;
const rows: string[][] = [];
for (const ctx of GLUCOSE_CONTEXTS) {
const s = data.glucoseStats?.[ctx];
if (!s) continue;
const digits = reportStatFractionDigits("BLOOD_GLUCOSE", s, glucoseUnit);
const show = (v: number) => num(convertGlucose(v, glucoseUnit), digits);
rows.push([
t(GLUCOSE_LABEL_KEYS[ctx]),
`${show(s.latest)} ${glucoseUnit}`.trim(),
`${show(s.avg)} ${glucoseUnit}`.trim(),
show(s.min),
show(s.max),
String(s.count),
]);
}
return rows;
}
/**
* A row's label. A screener total answered in a translation that has not
* been validated carries a mark, which the line under the table explains.
*/
function vitalRowLabel(
context: DoctorReportPdfRenderContext,
type: string,
): string {
const label = context.t(reportMeasurementLabelKey(type as MeasurementType));
return context.data.screenerUnvalidatedTranslations?.[type]
? `${label} *`
: label;
}
/** One line under the table per marked screener: how many, of how many. */
function drawScreenerTranslationNotes(
context: DoctorReportPdfRenderContext,
startY: number,
): number {
const { doc, data, t, margin, pageWidth, ensureSpace } = context;
const notes = Object.entries(data.screenerUnvalidatedTranslations ?? {})
.filter(([type, count]) => count > 0 && data.stats[type])
.map(([type, count]) =>
t("doctorReport.screenerUnvalidated", {
label: t(reportMeasurementLabelKey(type as MeasurementType)),
count,
total: data.stats[type].count,
}),
);
if (notes.length === 0) return startY;
let y = startY;
doc.setFontSize(8);
doc.setFont("helvetica", "italic");
doc.setTextColor(110, 110, 110);
for (const note of notes) {
for (const line of doc.splitTextToSize(
`* ${note}`,
pageWidth - 2 * margin,
)) {
y = ensureSpace(y, 4);
doc.text(line, margin, y);
y += 4;
}
}
return y + 4;
}
export function buildMeasurementsChartsSection(
context: DoctorReportPdfRenderContext,
state: DoctorReportPdfCursorState,
@@ -219,25 +293,9 @@ export function buildMeasurementsChartsSection(
// leaf that was withheld or has no reading — the table cannot over-serve.
const vitalRows: VitalTableRow[] = [];
// Per-context glucose rows. Values stored canonically in mg/dL — convert to
// the user's display unit. They belong under the glucose group heading with
// the raw series, not appended after the whole table.
// Per-context glucose rows, in the owner's unit, under the glucose heading.
const glucoseUnit = resolveGlucoseUnit(data.glucoseUnit ?? null);
const glucoseContextRows: string[][] = [];
for (const ctx of GLUCOSE_CONTEXTS) {
const s = data.glucoseStats?.[ctx];
if (!s) continue;
const digits = reportStatFractionDigits("BLOOD_GLUCOSE", s, glucoseUnit);
const show = (v: number) => num(convertGlucose(v, glucoseUnit), digits);
glucoseContextRows.push([
t(GLUCOSE_LABEL_KEYS[ctx]),
`${show(s.latest)} ${glucoseUnit}`.trim(),
`${show(s.avg)} ${glucoseUnit}`.trim(),
show(s.min),
show(s.max),
String(s.count),
]);
}
const glucoseContextRows = glucoseContextTableRows(context, glucoseUnit);
for (const group of vitalGroups) {
const groupRows: string[][] = [];
@@ -253,7 +311,7 @@ export function buildMeasurementsChartsSection(
const show = (v: number) =>
num(reportStatValue(type, v, glucoseUnit), digits);
groupRows.push([
t(reportMeasurementLabelKey(type as MeasurementType)),
vitalRowLabel(context, type),
`${show(s.latest)} ${unit}`.trim(),
`${show(s.avg)} ${unit}`.trim(),
show(s.min),
@@ -307,6 +365,8 @@ export function buildMeasurementsChartsSection(
.finalY + 8;
}
y = drawScreenerTranslationNotes(context, y);
// v1.18.0 — clinical glucose panel (TIR / GMI / eA1C / mean / CV%). The
// server already computes this (`data.glucoseClinical`) by the one
// literature-locked engine the insights panel + coach consume, and zeroes it
+7
View File
@@ -236,6 +236,13 @@ export interface DoctorReportData {
* user has no computed scores in the window (the renderer + FHIR builder
* then skip the section). Optional so pre-v1.10 fixtures still typecheck.
*/
/**
* Per screener score type (`PHQ9_SCORE`, `SCI_SCORE`, …), how many
* of the window's results were answered in a translation that has not been
* validated. The renderers note them beside the type's row, so a clinician
* reads those totals as orientation. Null (or absent) when there are none.
*/
screenerUnvalidatedTranslations?: Record<string, number> | null;
wellnessScores?: Array<{
/** The score MeasurementType (RECOVERY_SCORE / STRESS_SCORE / STRAIN_SCORE). */
type: string;
+18 -28
View File
@@ -42,7 +42,6 @@ import {
import { MEASUREMENT_LEAF_IDS } from "@/lib/report-selection/catalogue";
import type { ReportSelection } from "@/lib/report-selection/selection";
import {
WELLNESS_SCORE_REPORT_TYPES,
type CollectDoctorReportOptions,
type DoctorReportData,
type DoctorReportMood,
@@ -54,7 +53,7 @@ import {
collapseMeasurementsToCanonical,
minMaxOf,
sanitisePracticeName,
summariseCanonicalRecovery,
summariseWellnessScores,
} from "@/lib/doctor-report-helpers";
import {
excludedMeasurementTypes,
@@ -81,6 +80,7 @@ import {
} from "./clinical-records";
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
import { readingsMean } from "@/lib/measurements/day-mean";
import { loadScreenerUnvalidatedTranslations } from "./screener-translations";
const DENSE_REPORT_RAW_WINDOW_DAYS = 90;
@@ -620,33 +620,22 @@ export async function collectDoctorReportData(
})
: null;
// The wellness summary is filtered to the same score leaves the stats carry,
// so it cannot disagree with them. RECOVERY_SCORE carries both the native row
// and the computed proxy for one day; resolve to the canonical row so the PDF
// reads the SAME value the tile shows.
const wellnessScoreSummaries = WELLNESS_SCORE_REPORT_TYPES.flatMap((type) => {
if (!gate.admits(type)) return [];
if (type === "RECOVERY_SCORE") {
const summary = summariseCanonicalRecovery(measurements, reportTz);
return summary ? [summary] : [];
}
const s = stats[type];
const rows = byType[type];
if (!s || !rows || rows.length === 0) return [];
return [
{
type,
latest: Math.round(s.latest),
avg: Math.round(s.avg),
min: Math.round(s.min),
max: Math.round(s.max),
count: s.count,
latestAt: rows[rows.length - 1].measuredAt,
},
];
// The wellness summary reads the same score leaves the stats carry.
const wellnessScores = summariseWellnessScores({
admits: (type) => gate.admits(type),
stats,
byType,
measurements,
timezone: reportTz,
});
const wellnessScores =
wellnessScoreSummaries.length > 0 ? wellnessScoreSummaries : null;
// Screener totals answered in an unvalidated translation, per score type.
const screenerUnvalidatedTranslations =
await loadScreenerUnvalidatedTranslations(
userId,
filteredStats,
start,
end,
);
// Each remaining structured block: read only when its leaf was chosen.
const [
@@ -787,6 +776,7 @@ export async function collectDoctorReportData(
mood,
glp1,
wellnessScores,
screenerUnvalidatedTranslations,
cycle,
labResults,
illnessEpisodes,
@@ -0,0 +1,50 @@
/**
* Which screener totals in a report were answered in a translation that has
* not been validated.
*
* A questionnaire in a language without a validated version is shown in a
* translation written for HealthLog, and its result reads as orientation.
* The report's renderers mark those totals beside the score type's row, so a
* clinician reads them the same way. Counted per score type the report
* carries, over the report window; the table is not asked at all when no
* screener total is in the report.
*/
import { prisma } from "@/lib/db";
import {
INSTRUMENT_MEASUREMENT_TYPE,
INSTRUMENT_ORDER,
} from "@/lib/mental-health/instruments";
/**
* Per score type (`SCI_SCORE`, …), the number of the window's administrations
* answered in an unvalidated translation. Null when there are none, which is
* every report of a reader whose language has validated versions.
*/
export async function loadScreenerUnvalidatedTranslations(
userId: string,
stats: Readonly<Record<string, unknown>>,
start: Date,
end: Date,
): Promise<Record<string, number> | null> {
const instruments = INSTRUMENT_ORDER.filter(
(id) => stats[INSTRUMENT_MEASUREMENT_TYPE[id]] !== undefined,
);
if (instruments.length === 0) return null;
const groups = await prisma.mentalHealthAssessment.groupBy({
by: ["instrument"],
where: {
userId,
deletedAt: null,
wording: "unvalidated_translation",
instrument: { in: [...instruments] },
takenAt: { gte: start, lte: end },
},
_count: { _all: true },
});
const counts: Record<string, number> = {};
for (const id of instruments) {
const count = groups.find((g) => g.instrument === id)?._count._all ?? 0;
if (count > 0) counts[INSTRUMENT_MEASUREMENT_TYPE[id]] = count;
}
return Object.keys(counts).length > 0 ? counts : null;
}