feat(doctor-report): a report can mention a visit, and know why it exists

The VISITS leaf ships in the release that made a visit possible, because a
selectable checkbox that produces nothing is worse than no checkbox. Leaf,
collector and PDF renderer land together, and the leaf carries no LEAF_MODULE
entry — like ALLERGIES beside it — because a visit is core and the whole report
is already gated by doctorReport. The absence is commented at the map so a
later reader does not read it as an oversight.

The rows print the date, the practice with its specialty, the kind, the reason,
the outcome and the conditions the visit was filed against. The two encrypted
columns decrypt at render, fail-soft, and never enter the stored selection. A
condition the person has since deleted is not named: the link row survives a
soft delete, and printing a label they withdrew would put it in front of a
doctor.

No FHIR resource type is added. That deferral is already written at the
Encounter model, and the bundle builder now says so at the point a reader would
look for the missing section: FHIR splits the future from the past across
Appointment and Encounter, which is a serialisation question this release does
not answer.

Two properties are free and worth stating: a stored selection never grows
(unknown ids drop) and a clinician share link's sections are frozen write-once,
so no existing report and no already-shared link gains a section.

The panel also offers a booked visit as the report's reason — one query, one
prefilled window end, one dismissible offer that names its own source and never
applies itself. A window control that moves on its own is what makes an export
panel untrustworthy.
This commit is contained in:
Marc-André Bombeck committed 2026-08-08 14:38:26 +02:00
1 parent c47122ccfe
commit 4d2f706dad
24 files changed
+550 -27

No files matched your search

@@ -172,6 +172,7 @@ const fakeDb = vi.hoisted(() => {
ecgRecording: { findFirst: async () => null },
personalRecord: { findMany: none },
arrivalReaction: { findMany: none },
encounter: { findFirst: async () => null },
};
});
@@ -217,6 +217,73 @@ export function buildClinicalRecordsNotesSection(
.finalY + 8;
}
// Visits inside the window — what happened at a practice, and what came out
// of it. Present only when the VISITS leaf was selected AND the window held a
// visit (the aggregator gates `data.visits`); the leaf carries no module of
// its own, because a visit is core and the whole report is already gated by
// `doctorReport`. Same calm factual register as the illness table above: no
// colour, no status tint. The encrypted reason and outcome decrypt at render
// and never enter the stored selection.
if (data.visits && data.visits.length > 0) {
y = ensureSpace(y, 6 + 18);
doc.setFontSize(14);
doc.setFont("helvetica", "bold");
doc.setTextColor(30, 30, 30);
doc.text(t("doctorReport.visitsTitle"), margin, y);
y += 6;
const visitRows = data.visits.map((visit) => [
fmtDate(visit.occurredAt),
// The practice, with its specialty when there is one; an em dash when
// the visit named neither, which is honest rather than invented.
[visit.practitionerName, visit.practitionerSpecialty]
.filter(Boolean)
.join(" · ") || "—",
t(`encounters.kind.${visit.kind}`),
visit.reason ?? "—",
visit.outcome ?? "—",
visit.conditionLabels.length > 0 ? visit.conditionLabels.join(", ") : "—",
]);
autoTable(doc, {
startY: y,
head: [
[
t("doctorReport.visitsColDate"),
t("doctorReport.visitsColPractice"),
t("doctorReport.visitsColKind"),
t("doctorReport.visitsColReason"),
t("doctorReport.visitsColOutcome"),
t("doctorReport.visitsColConditions"),
],
],
body: visitRows,
theme: "grid",
styles: {
fontSize: 9,
cellPadding: 3,
textColor: [30, 30, 30],
lineColor: [200, 200, 200],
lineWidth: 0.3,
},
headStyles: {
fillColor: [245, 245, 245],
textColor: [30, 30, 30],
fontStyle: "bold",
},
alternateRowStyles: { fillColor: [252, 252, 252] },
margin: {
left: margin,
right: margin,
top: margin,
bottom: tableBottomMargin,
},
});
y =
(doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
}
// v1.27.x — structured allergy / intolerance records. Reference data
// (not time-windowed) the aggregator populates when the `allergies`
// toggle is ON (default) and rows exist. Stored fields only — substance,
+22
View File
@@ -274,6 +274,28 @@ export interface DoctorReportData {
* module is off or no episode overlaps the window; both builders then skip
* the section. Optional so pre-v1.18.1 fixtures still typecheck.
*/
/**
* Visits inside the window — the contacts with the healthcare system this
* period held. Null when the leaf was not selected or none fell inside the
* window; both builders then skip the section. Optional so pre-v1.38
* fixtures still typecheck.
*
* `kind` rides as the enum constant: the renderer names it in the REPORT's
* language, which is the reading clinician's, not whoever generated it.
* `reason` and `outcome` are the decrypted free text and are null on a
* key-rotation gap — an absence rather than a fabricated line.
*/
visits?: Array<{
occurredAt: string;
kind: string;
status: string;
practitionerName: string | null;
practitionerSpecialty: string | null;
reason: string | null;
outcome: string | null;
/** Labels of the conditions this visit was filed against. */
conditionLabels: string[];
}> | null;
illnessEpisodes?: Array<{
/** User-facing condition label (e.g. "Erkältung"). */
label: string;
@@ -216,6 +216,17 @@ function seed() {
resolvedAt: new Date("2026-01-20T00:00:00.000Z"),
},
];
rows.encounter = [
{
occurredAt: new Date("2026-02-05T09:00:00.000Z"),
kind: "SPECIALIST",
status: "DONE",
reasonEncrypted: null,
outcomeEncrypted: null,
practitioner: { name: "Sample practice", specialty: "Cardiology" },
conditionLinks: [],
},
];
rows.allergy = [
{
substance: "Penicillin",
@@ -262,6 +273,7 @@ describe("per-leaf gating sweep", () => {
expect(allPayload.allergies).not.toBeNull();
expect(allPayload.familyHistory).not.toBeNull();
expect(allPayload.illnessEpisodes).not.toBeNull();
expect(allPayload.visits).not.toBeNull();
expect(allPayload.mood).not.toBeNull();
expect(allPayload.cycle).not.toBeNull();
expect(allPayload.anamnesis).not.toBeNull();
@@ -415,6 +427,7 @@ describe("zero read for unchosen leaves", () => {
["ALLERGIES", "allergy"],
["LAB_RESULTS", "labResult"],
["ILLNESS_EPISODES", "illnessEpisode"],
["VISITS", "encounter"],
["ANAMNESIS", "userHealthProfile"],
["ANAMNESIS", "healthProfileFactRevision"],
];
@@ -474,6 +487,7 @@ describe("the empty selection serves nothing", () => {
expect(payload.allergies).toBeNull();
expect(payload.familyHistory).toBeNull();
expect(payload.illnessEpisodes).toBeNull();
expect(payload.visits).toBeNull();
expect(payload.anamnesis).toBeNull();
expect(payload.cycle).toBeNull();
expect(payload.mood).toBeNull();
+72
View File
@@ -122,6 +122,78 @@ export async function loadIllnessEpisodes(
return mapped.length > 0 ? mapped : null;
}
/**
* Visits inside the window, with the conditions each was filed against.
*
* The two free-text columns are `Bytes` ciphertext and decrypt fail-soft, the
* same stance the allergy reaction takes: a key-rotation gap on one row reads
* as a visit with no reason recorded rather than as a failed report. `kind` and
* `status` cross as enum constants — the renderer names them in the REPORT's
* language, which is the reading clinician's.
*
* The condition labels come off the link rows directly rather than through the
* link service: this is a read of the OWNER's own record for the owner's own
* report, with no grant to narrow against and no redaction to apply, and the
* service's per-family visibility predicate has no meaning here.
*/
export async function loadVisits(
userId: string,
start: Date,
end: Date,
): Promise<DoctorReportData["visits"]> {
const rows = await prisma.encounter.findMany({
where: {
userId,
deletedAt: null,
occurredAt: { gte: start, lte: end },
},
orderBy: { occurredAt: "asc" },
select: {
occurredAt: true,
kind: true,
status: true,
reasonEncrypted: true,
outcomeEncrypted: true,
practitioner: { select: { name: true, specialty: true } },
conditionLinks: {
select: { episode: { select: { label: true, deletedAt: true } } },
},
},
});
const decrypt = (
value: Uint8Array | null,
field: "reason" | "outcome",
): string | null => {
if (!value || value.byteLength === 0) return null;
try {
return decryptFromBytes(value);
} catch {
getEvent()?.addWarning(
`doctor-report: visit ${field} decrypt failed for ${userId}`,
);
return null;
}
};
const mapped = rows.map((row) => ({
occurredAt: row.occurredAt.toISOString(),
kind: row.kind,
status: row.status,
practitionerName: row.practitioner?.name ?? null,
practitionerSpecialty: row.practitioner?.specialty ?? null,
reason: decrypt(row.reasonEncrypted, "reason"),
outcome: decrypt(row.outcomeEncrypted, "outcome"),
// A condition the person has since deleted is not named in a clinical
// document: the link row survives the soft delete, and printing a label
// they removed would put a withdrawn diagnosis in front of a doctor.
conditionLabels: row.conditionLinks
.filter((link) => link.episode?.deletedAt === null)
.map((link) => link.episode.label),
}));
return mapped.length > 0 ? mapped : null;
}
/**
* Structured allergy records. Reference data, not time-windowed — a
* penicillin allergy does not expire with the report window.
+6
View File
@@ -64,6 +64,7 @@ import {
loadAnamnesis,
loadFamilyHistory,
loadIllnessEpisodes,
loadVisits,
loadLabResults,
} from "./clinical-records";
@@ -498,6 +499,7 @@ export async function collectDoctorReportData(
cycle,
labResults,
illnessEpisodes,
visits,
allergies,
familyHistory,
anamnesis,
@@ -511,6 +513,9 @@ export async function collectDoctorReportData(
gate.admits("ILLNESS_EPISODES")
? loadIllnessEpisodes(userId, start, end)
: Promise.resolve(null),
gate.admits("VISITS")
? loadVisits(userId, start, end)
: Promise.resolve(null),
gate.admits("ALLERGIES") ? loadAllergies(userId) : Promise.resolve(null),
gate.admits("FAMILY_HISTORY")
? loadFamilyHistory(userId)
@@ -579,6 +584,7 @@ export async function collectDoctorReportData(
cycle,
labResults,
illnessEpisodes,
visits,
allergies,
familyHistory,
anamnesis,
+8
View File
@@ -261,6 +261,14 @@ export function buildFhirDocumentBundle(
// --- Condition + Encounter per illness/condition episode (opt-in) ------
// v1.18.1 — present only when the illness module is enabled AND the window
// No visits section, and the absence is a decision written at the
// `Encounter` model in `prisma/schema.prisma`: FHIR splits the future from
// the past across `Appointment` and `Encounter`, which is a serialisation
// question this release does not answer. `FHIR_REST_RESOURCE_TYPES` stays
// untouched for the same reason — a capability statement naming a type with
// no route module lies. The PDF carries the visits; the Bundle does not, and
// a reader who notices the gap should find this comment rather than a bug.
//
// held an episode (the aggregator gates `data.illnessEpisodes`). Each
// episode emits a patient-reported Condition (generic SNOMED root, label on
// `code.text`) plus a bounding Encounter that references it.
@@ -52,8 +52,8 @@ function resolves(key: string): boolean {
describe("report selection catalogue", () => {
it("carries every measurement type and every structured leaf", () => {
expect(MEASUREMENT_LEAF_IDS).toHaveLength(77);
expect(STRUCTURED_LEAF_IDS).toHaveLength(14);
expect(ALL_LEAF_IDS).toHaveLength(91);
expect(STRUCTURED_LEAF_IDS).toHaveLength(15);
expect(ALL_LEAF_IDS).toHaveLength(92);
});
it("resolves a label for every leaf", () => {
+8 -1
View File
@@ -46,6 +46,7 @@ export type StructuredLeafId =
| "GLP1_THERAPY"
| "ALLERGIES"
| "ILLNESS_EPISODES"
| "VISITS"
| "FAMILY_HISTORY"
| "MOOD"
| "CYCLE"
@@ -199,13 +200,14 @@ export const STRUCTURED_LEAF_GROUP: Record<StructuredLeafId, ReportGroupId> = {
GLP1_THERAPY: "medications",
ALLERGIES: "history",
ILLNESS_EPISODES: "history",
VISITS: "history",
FAMILY_HISTORY: "sensitive",
MOOD: "sensitive",
CYCLE: "sensitive",
ANAMNESIS: "sensitive",
};
/** i18n label keys for the 14 structured leaves. */
/** i18n label keys for the 15 structured leaves. */
export const STRUCTURED_LEAF_LABEL_KEYS: Record<StructuredLeafId, string> = {
PATIENT_IDENTITY: "reportSelection.leafPatientIdentity",
INSURANCE: "reportSelection.leafInsurance",
@@ -217,6 +219,7 @@ export const STRUCTURED_LEAF_LABEL_KEYS: Record<StructuredLeafId, string> = {
GLP1_THERAPY: "reportSelection.leafGlp1Therapy",
ALLERGIES: "reportSelection.leafAllergies",
ILLNESS_EPISODES: "reportSelection.leafIllnessEpisodes",
VISITS: "reportSelection.leafVisits",
FAMILY_HISTORY: "reportSelection.leafFamilyHistory",
MOOD: "reportSelection.leafMood",
CYCLE: "reportSelection.leafCycle",
@@ -306,6 +309,10 @@ export const LEAF_MODULE: Partial<Record<ReportLeafId, ModuleKey>> = {
MEDICATION_ADMINISTRATIONS: "medications",
MEDICATION_COMPLIANCE: "medications",
GLP1_THERAPY: "medications",
// VISITS is deliberately absent, like ALLERGIES beside it. A visit carries
// no module of its own — it is core, like the checkups page it lives on —
// and the whole report is already gated by `doctorReport`. Reading the
// absence as an oversight is the mistake this comment exists to prevent.
};
/** Every measurement leaf id, in enum order. */