Merge branch 'feat/procedure-history' into release/v1.39.1

This commit is contained in:
Marc-André Bombeck committed 2026-09-25 08:23:34 +02:00
commit c327ae81d5
59 files changed
+2959 -79

No files matched your search

@@ -641,6 +641,82 @@ describe("doctor-report illness section", () => {
});
});
// v1.39.1 — the surgical history. Lifetime reference data like the
// immunization record: every procedure that happened, with its date, what was
// done (the visit's reason), where, and what came of it. Present only when the
// SURGICAL_HISTORY leaf was admitted and at least one procedure exists.
//
// Mutation checks (each run, each seen red):
// - drop the section's `if` block from the renderer → "prints the surgical
// history table" goes red;
// - print `bodySite` without the side → "names the side beside the site"
// goes red.
describe("doctor-report surgical history section", () => {
const PROCEDURES: NonNullable<DoctorReportData["surgicalHistory"]> = [
{
occurredAt: "2011-03-14T09:00:00.000Z",
procedure: "Meniscus repair",
bodySite: "Knee",
laterality: "LEFT",
outcome: "Full recovery after physiotherapy",
practitionerName: "Sample clinic",
},
{
occurredAt: "2019-07-02T09:00:00.000Z",
procedure: null,
bodySite: null,
laterality: null,
outcome: null,
practitionerName: null,
},
];
it("prints the surgical history table with procedure, site and outcome", async () => {
const bytes = renderDoctorReportPdfBytes(
makeData({ surgicalHistory: PROCEDURES }),
{
timeFormat: "AUTO",
dateFormat: "AUTO",
t: getServerTranslator("en").t,
locale: "en",
now: FIXED_NOW,
},
);
const text = await extractText(bytes);
expect(text).toContain("Surgical history");
expect(text).toContain("Meniscus repair");
expect(text).toContain("Full recovery after physiotherapy");
});
it("names the side beside the site", async () => {
const bytes = renderDoctorReportPdfBytes(
makeData({ surgicalHistory: PROCEDURES }),
{
timeFormat: "AUTO",
dateFormat: "AUTO",
t: getServerTranslator("de").t,
locale: "de",
now: FIXED_NOW,
},
);
const text = await extractText(bytes);
expect(text).toContain("Operationen und Eingriffe");
expect(text).toMatch(/Knee · Links/);
});
it("omits the section when there is no procedure", async () => {
const bytes = renderDoctorReportPdfBytes(makeData(), {
timeFormat: "AUTO",
dateFormat: "AUTO",
t: getServerTranslator("en").t,
locale: "en",
now: FIXED_NOW,
});
const text = await extractText(bytes);
expect(text).not.toContain("Surgical history");
});
});
// ── emergency first page ── the Notfalldaten sheet owns page one, but only
// when the aggregator populated `data.emergency` (the EMERGENCY leaf admitted
// AND the profile holds something). A null payload — which is exactly what the
@@ -102,6 +102,42 @@ describe("buildVisitsSnapshotBlock", () => {
expect(recentArg.orderBy).toEqual({ occurredAt: "desc" });
});
// v1.39.1 — a procedure's body site rides the entry so "the knee operation
// in March" reads as one fact, and stays off every other entry so the block
// does not grow for visits that never carry one.
//
// Mutation check: always emit `bodySite` → the absent-key assertion goes red.
it("names the body site and side of a procedure, and only when one is set", async () => {
prismaMock.encounter.findFirst.mockResolvedValue({
occurredAt: new Date(NOW.getTime() - 30 * DAY),
kind: "PROCEDURE",
reasonEncrypted: Buffer.from("arthroscopy", "utf8"),
outcomeEncrypted: null,
bodySiteEncrypted: Buffer.from("knee", "utf8"),
laterality: "LEFT",
practitioner: null,
});
prismaMock.encounter.findMany.mockResolvedValue([
{
occurredAt: new Date(NOW.getTime() + 3 * DAY),
kind: "ROUTINE",
reasonEncrypted: null,
outcomeEncrypted: null,
bodySiteEncrypted: null,
laterality: null,
practitioner: null,
},
]);
const block = await buildVisitsSnapshotBlock("user_1", NOW);
expect(block!.mostRecent).toMatchObject({
kind: "PROCEDURE",
bodySite: "knee",
laterality: "LEFT",
});
expect(block!.upcoming[0]).not.toHaveProperty("bodySite");
expect(block!.upcoming[0]).not.toHaveProperty("laterality");
});
it("fail-softs a decrypt error to null rather than throwing the whole block", async () => {
vi.mocked(decryptFromBytes).mockImplementation(() => {
throw new Error("bad key id");
+14
View File
@@ -55,6 +55,14 @@ export interface CoachVisitEntry {
reason: string | null;
/** What came out of it, decrypted + sanitised; null (always) for an upcoming visit. */
outcome: string | null;
/**
* Where on the body, decrypted + sanitised (v1.39.1). Present only when the
* visit names a site, so the block does not grow for the visits that never
* carry one.
*/
bodySite?: string;
/** The side of `bodySite`, when one is stated. */
laterality?: string;
}
export interface CoachVisitsBlock {
@@ -70,6 +78,8 @@ interface EncounterRow {
kind: string;
reasonEncrypted: Uint8Array | null;
outcomeEncrypted: Uint8Array | null;
bodySiteEncrypted?: Uint8Array | null;
laterality?: string | null;
practitioner: { name: string; specialty: string | null } | null;
}
@@ -87,6 +97,7 @@ function decryptText(value: Uint8Array | null): string | null {
}
function toEntry(row: EncounterRow): CoachVisitEntry {
const bodySite = decryptText(row.bodySiteEncrypted ?? null);
return {
occurredAt: row.occurredAt.toISOString(),
kind: row.kind,
@@ -98,6 +109,9 @@ function toEntry(row: EncounterRow): CoachVisitEntry {
: null,
reason: decryptText(row.reasonEncrypted),
outcome: decryptText(row.outcomeEncrypted),
...(bodySite
? { bodySite, ...(row.laterality ? { laterality: row.laterality } : {}) }
: {}),
};
}
+3
View File
@@ -305,6 +305,9 @@ export const ENCRYPTED_COLUMNS: readonly EncryptedColumn[] = [
// structured health records above make.
{ model: "Encounter", field: "reasonEncrypted", kind: "bytes" },
{ model: "Encounter", field: "outcomeEncrypted", kind: "bytes" },
// v1.39.1 — where on the body a procedure was done. The side beside it
// (`laterality`) stays plaintext: a side alone says nothing.
{ model: "Encounter", field: "bodySiteEncrypted", kind: "bytes" },
{ model: "Practitioner", field: "noteEncrypted", kind: "bytes" },
// ───── v1.38.0 dose free text (Bytes column) ─────
@@ -1,7 +1,10 @@
import type { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import type { EncounterKind } from "@/generated/prisma/client";
import { encounterKindLabelKey } from "../encounters/kind-label";
import type { EncounterKind, Laterality } from "@/generated/prisma/client";
import {
encounterKindLabelKey,
lateralityLabelKey,
} from "../encounters/kind-label";
import {
classifyReferenceRange,
formatReferenceRange,
@@ -289,6 +292,72 @@ export function buildClinicalRecordsNotesSection(
.finalY + 8;
}
// The surgical history. Reference data (not time-windowed), populated when
// the SURGICAL_HISTORY leaf is selected AND a procedure happened. Oldest
// first, the order an intake form asks for it in. What was done is the
// visit's reason; the site carries its side after it in the report's
// language. Same calm register as the tables around it.
if (data.surgicalHistory && data.surgicalHistory.length > 0) {
y = ensureSpace(y, 6 + 18);
doc.setFontSize(14);
doc.setFont("helvetica", "bold");
doc.setTextColor(30, 30, 30);
doc.text(t("doctorReport.surgicalHistoryTitle"), margin, y);
y += 6;
const siteCell = (site: string | null, side: string | null): string => {
if (!site) return "—";
if (!side) return site;
return t("encounters.bodySiteWithSide", {
site,
side: t(lateralityLabelKey(side as Laterality)),
});
};
const procedureRows = data.surgicalHistory.map((row) => [
fmtDate(row.occurredAt),
row.procedure ?? "—",
siteCell(row.bodySite, row.laterality),
row.outcome ?? "—",
]);
autoTable(doc, {
startY: y,
head: [
[
t("doctorReport.surgicalHistoryColDate"),
t("doctorReport.surgicalHistoryColProcedure"),
t("doctorReport.surgicalHistoryColBodySite"),
t("doctorReport.surgicalHistoryColOutcome"),
],
],
body: procedureRows,
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;
}
// The immunization history. Reference data (not time-windowed), populated
// when the `IMMUNIZATIONS` leaf is selected AND the `vaccinations` module is
// on AND live doses exist. A compact chronological table — date, vaccine
+21
View File
@@ -308,6 +308,27 @@ export interface DoctorReportData {
/** Labels of the conditions this visit was filed against. */
conditionLabels: string[];
}> | null;
/**
* The surgical history (v1.39.1): every visit of kind PROCEDURE that
* happened, oldest first. Reference data, not time-windowed, like the
* immunization record below — an operation fifteen years ago is still the
* answer to "what surgeries have you had". Null when the SURGICAL_HISTORY
* leaf was not selected or no procedure exists; both builders then skip the
* section. Optional so older fixtures still typecheck.
*
* `procedure` is the visit's reason, which is where a person writes what was
* done. `procedure`, `bodySite` and `outcome` are decrypted free text and
* null on a key-rotation gap. `laterality` rides as the enum constant; the
* renderer names it in the report's language.
*/
surgicalHistory?: Array<{
occurredAt: string;
procedure: string | null;
bodySite: string | null;
laterality: string | null;
outcome: string | null;
practitionerName: string | null;
}> | null;
/**
* The immunization history. Reference data, not time-windowed — an Impfpass
* is a lifetime document and a doctor wants the whole of it, so this mirrors
@@ -299,6 +299,7 @@ describe("per-leaf gating sweep", () => {
expect(allPayload.familyHistory).not.toBeNull();
expect(allPayload.illnessEpisodes).not.toBeNull();
expect(allPayload.visits).not.toBeNull();
expect(allPayload.surgicalHistory).not.toBeNull();
expect(allPayload.mood).not.toBeNull();
expect(allPayload.cycle).not.toBeNull();
expect(allPayload.anamnesis).not.toBeNull();
@@ -454,18 +455,23 @@ describe("zero read for unchosen leaves", () => {
["LAB_RESULTS", "labResult"],
["ILLNESS_EPISODES", "illnessEpisode"],
["VISITS", "encounter"],
["SURGICAL_HISTORY", "encounter"],
["IMMUNIZATIONS", "vaccinationRecord"],
["ANAMNESIS", "userHealthProfile"],
["EMERGENCY", "userHealthProfile"],
["ANAMNESIS", "healthProfileFactRevision"],
];
// ANAMNESIS and EMERGENCY both read `userHealthProfile`, so withholding one
// ANAMNESIS and EMERGENCY both read `userHealthProfile` (and VISITS and
// SURGICAL_HISTORY both read `encounter`), so withholding one
// while the other stays selected still queries the table. Both must be off
// before the read stops — the zero-read guarantee is over the SET of leaves
// that touch a table, not each one in isolation.
const TABLE_READERS: Record<string, ReportLeafId[]> = {
userHealthProfile: ["ANAMNESIS", "EMERGENCY"],
// The visits in the window and the lifetime surgical history both read
// the encounter table, under their own leaves.
encounter: ["VISITS", "SURGICAL_HISTORY"],
};
it.each(gated)(
@@ -0,0 +1,95 @@
/**
* The surgical history's read for the doctor report.
*
* Lifetime reference data, like the immunization record: a knee operated on
* fifteen years ago is still the answer to "what surgeries have you had", so
* the read ignores the report window. It reads only procedures that happened,
* and the free text (what was done, where, what came of it) decrypts fail-soft
* per row, so one key-rotation gap does not blank the section.
*
* Mutation checks (each run, each seen red):
* - add the report window to the `where` → "ignores the report window" goes
* red;
* - drop `status: "DONE"` → "reads only procedures that happened" goes red;
* - let a decrypt error throw → "reads a row it cannot decrypt as a blank"
* goes red with the thrown error.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
process.env.ENCRYPTION_KEY ??=
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const findMany = vi.hoisted(() => vi.fn());
vi.mock("@/lib/db", () => ({ prisma: { encounter: { findMany } } }));
vi.mock("@/lib/logging/context", () => ({ getEvent: () => undefined }));
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { loadSurgicalHistory } from "../clinical-records";
beforeEach(() => {
findMany.mockReset();
});
describe("loadSurgicalHistory", () => {
it("reads only procedures that happened, over the whole record", async () => {
findMany.mockResolvedValue([]);
await loadSurgicalHistory("u1");
const args = findMany.mock.calls[0][0];
expect(args.where).toEqual({
userId: "u1",
deletedAt: null,
kind: "PROCEDURE",
status: "DONE",
});
expect(args.orderBy).toEqual({ occurredAt: "asc" });
});
it("ignores the report window", async () => {
findMany.mockResolvedValue([]);
await loadSurgicalHistory("u1");
expect(findMany.mock.calls[0][0].where).not.toHaveProperty("occurredAt");
});
it("returns null when there is no procedure", async () => {
findMany.mockResolvedValue([]);
expect(await loadSurgicalHistory("u1")).toBeNull();
});
it("maps a procedure to date, what, where and outcome", async () => {
findMany.mockResolvedValue([
{
occurredAt: new Date("2011-03-14T09:00:00.000Z"),
reasonEncrypted: encryptToBytes("Meniscus repair"),
outcomeEncrypted: encryptToBytes("Full recovery"),
bodySiteEncrypted: encryptToBytes("Knee"),
laterality: "LEFT",
practitioner: { name: "Sample clinic" },
},
]);
expect(await loadSurgicalHistory("u1")).toEqual([
{
occurredAt: "2011-03-14T09:00:00.000Z",
procedure: "Meniscus repair",
bodySite: "Knee",
laterality: "LEFT",
outcome: "Full recovery",
practitionerName: "Sample clinic",
},
]);
});
it("reads a row it cannot decrypt as a blank rather than failing the report", async () => {
findMany.mockResolvedValue([
{
occurredAt: new Date("2019-07-02T09:00:00.000Z"),
reasonEncrypted: new Uint8Array([1, 2, 3, 4]),
outcomeEncrypted: null,
bodySiteEncrypted: null,
laterality: null,
practitioner: null,
},
]);
const rows = await loadSurgicalHistory("u1");
expect(rows?.[0].procedure).toBeNull();
});
});
+52
View File
@@ -199,6 +199,58 @@ export async function loadVisits(
return mapped.length > 0 ? mapped : null;
}
/**
* The surgical history: every procedure that happened, oldest first.
*
* Reference data, not windowed — like the immunization history below, it is a
* lifetime answer, and a report over the last 90 days that left out a knee
* operation from 2011 would answer "what surgeries have you had" wrongly.
* Planned, cancelled and missed procedures are not surgical history. The three
* free-text columns decrypt fail-soft per row, the same stance `loadVisits`
* takes.
*/
export async function loadSurgicalHistory(
userId: string,
): Promise<DoctorReportData["surgicalHistory"]> {
const rows = await prisma.encounter.findMany({
where: { userId, deletedAt: null, kind: "PROCEDURE", status: "DONE" },
orderBy: { occurredAt: "asc" },
select: {
occurredAt: true,
reasonEncrypted: true,
outcomeEncrypted: true,
bodySiteEncrypted: true,
laterality: true,
practitioner: { select: { name: true } },
},
});
if (rows.length === 0) return null;
const decrypt = (
value: Uint8Array | null,
field: "reason" | "outcome" | "bodySite",
): string | null => {
if (!value || value.byteLength === 0) return null;
try {
return decryptFromBytes(value);
} catch {
getEvent()?.addWarning(
`doctor-report: procedure ${field} decrypt failed for ${userId}`,
);
return null;
}
};
return rows.map((row) => ({
occurredAt: row.occurredAt.toISOString(),
procedure: decrypt(row.reasonEncrypted, "reason"),
bodySite: decrypt(row.bodySiteEncrypted, "bodySite"),
laterality: row.laterality,
outcome: decrypt(row.outcomeEncrypted, "outcome"),
practitionerName: row.practitioner?.name ?? null,
}));
}
/**
* The immunization history. Reference data, not time-windowed — an Impfpass is
* a lifetime document, so like allergies it ignores the report window.
+7
View File
@@ -70,6 +70,7 @@ import {
loadIllnessEpisodes,
loadImmunizations,
loadVisits,
loadSurgicalHistory,
loadLabResults,
} from "./clinical-records";
@@ -508,6 +509,7 @@ export async function collectDoctorReportData(
labResults,
illnessEpisodes,
visits,
surgicalHistory,
immunizations,
allergies,
familyHistory,
@@ -526,6 +528,10 @@ export async function collectDoctorReportData(
gate.admits("VISITS")
? loadVisits(userId, start, end)
: Promise.resolve(null),
// Reference data, not windowed, like the immunization history below.
gate.admits("SURGICAL_HISTORY")
? loadSurgicalHistory(userId)
: Promise.resolve(null),
// Reference data, not windowed — the immunization history is a lifetime
// document, so the whole live set rides when the leaf and module admit it.
gate.admits("IMMUNIZATIONS")
@@ -601,6 +607,7 @@ export async function collectDoctorReportData(
labResults,
illnessEpisodes,
visits,
surgicalHistory,
immunizations,
allergies,
familyHistory,
@@ -0,0 +1,150 @@
/**
* The procedure search and the body-site facets, pinned.
*
* The body site is ciphertext at rest, so the only place a search over it can
* run is here, after the decrypt. Three properties carry the feature:
*
* - every word of the query has to be found, in the site or the reason, so
* "left knee" finds a procedure filed as site "Knee", side LEFT;
* - accents and case do not matter, because a person types "Hufte" on a
* keyboard without umlauts and still means "Hüfte";
* - the side filter is exact, so asking for the right side never returns the
* left one.
*
* Mutation checks (each run, each seen red):
* - match ANY token instead of EVERY token → "needs every word" goes red;
* - drop the diacritic fold in `normalizeSearchText` → the umlaut case goes
* red;
* - key the facet on the raw text instead of the folded text → "folds case
* and spacing into one site" goes red with two facets.
*/
import { describe, expect, it } from "vitest";
import {
groupBodySites,
matchesProcedureQuery,
normalizeSearchText,
type ProcedureSearchItem,
} from "../procedures";
const terms = (laterality: ProcedureSearchItem["laterality"]) =>
laterality === "LEFT"
? ["left", "links"]
: laterality === "RIGHT"
? ["right", "rechts"]
: laterality === "BOTH"
? ["both", "beidseitig"]
: [];
function item(
bodySite: string | null,
laterality: ProcedureSearchItem["laterality"] = null,
reason: string | null = null,
): ProcedureSearchItem {
return { bodySite, laterality, reason };
}
describe("normalizeSearchText", () => {
it("folds case, accents and runs of whitespace", () => {
expect(normalizeSearchText(" Hüfte LINKS ")).toBe("hufte links");
});
});
describe("matchesProcedureQuery", () => {
it("matches everything when the query is empty", () => {
expect(matchesProcedureQuery(item(null), {}, terms)).toBe(true);
expect(matchesProcedureQuery(item("Knee"), { q: " " }, terms)).toBe(true);
});
it("finds a word in the body site", () => {
expect(matchesProcedureQuery(item("Left knee"), { q: "knee" }, terms)).toBe(
true,
);
});
it("finds a word in the reason when no site was typed", () => {
expect(
matchesProcedureQuery(
item(null, null, "Knee arthroscopy"),
{ q: "arthroscopy" },
terms,
),
).toBe(true);
});
it("finds the side word through the side field", () => {
expect(
matchesProcedureQuery(item("Knee", "LEFT"), { q: "left knee" }, terms),
).toBe(true);
expect(
matchesProcedureQuery(item("Knie", "LEFT"), { q: "Knie links" }, terms),
).toBe(true);
});
it("needs every word, not any word", () => {
expect(
matchesProcedureQuery(item("Knee", "RIGHT"), { q: "left knee" }, terms),
).toBe(false);
});
it("ignores accents on either side", () => {
expect(matchesProcedureQuery(item("Hüfte"), { q: "hufte" }, terms)).toBe(
true,
);
expect(matchesProcedureQuery(item("Hufte"), { q: "Hüfte" }, terms)).toBe(
true,
);
});
it("filters the side exactly", () => {
expect(
matchesProcedureQuery(
item("Knee", "LEFT"),
{ laterality: "RIGHT" },
terms,
),
).toBe(false);
expect(
matchesProcedureQuery(
item("Knee", "RIGHT"),
{ laterality: "RIGHT" },
terms,
),
).toBe(true);
expect(
matchesProcedureQuery(item("Knee", null), { laterality: "RIGHT" }, terms),
).toBe(false);
});
it("does not match a procedure with nothing to search when a query is set", () => {
expect(matchesProcedureQuery(item(null), { q: "knee" }, terms)).toBe(false);
});
});
describe("groupBodySites", () => {
it("counts one facet per site and side", () => {
const facets = groupBodySites([
item("Knee", "LEFT"),
item("Knee", "LEFT"),
item("Knee", "RIGHT"),
item("Gallbladder"),
item(null),
]);
expect(facets).toEqual([
{ bodySite: "Knee", laterality: "LEFT", count: 2 },
{ bodySite: "Knee", laterality: "RIGHT", count: 1 },
{ bodySite: "Gallbladder", laterality: null, count: 1 },
]);
});
it("folds case and spacing into one site, keeping the first spelling", () => {
const facets = groupBodySites([
item("Left knee "),
item("left knee"),
item("LEFT KNEE"),
]);
expect(facets).toEqual([
{ bodySite: "Left knee", laterality: null, count: 3 },
]);
});
});
+32 -1
View File
@@ -17,6 +17,7 @@ import type {
Encounter,
EncounterKind,
EncounterStatus,
Laterality,
MeasurementReminder,
Practitioner,
} from "@/generated/prisma/client";
@@ -58,6 +59,13 @@ export interface EncounterDTO {
practitioner: PractitionerDTO | null;
reason: string | null;
outcome: string | null;
/**
* Where on the body, decrypted. Carried on every kind, not only PROCEDURE,
* so a visit switched away from PROCEDURE and back keeps what was typed.
*/
bodySite: string | null;
/** The side of the body site, or null when not stated. */
laterality: Laterality | null;
/**
* The server-computed instant the appointment reminder next fires, when this
* visit minted one and it has not fired yet. `null` for a visit that already
@@ -91,7 +99,7 @@ export interface EncounterDTO {
function decryptField(
value: Uint8Array | null,
field: "reason" | "outcome",
field: "reason" | "outcome" | "bodySite",
): string | null {
if (!value || value.byteLength === 0) return null;
try {
@@ -124,6 +132,8 @@ export function toEncounterDTO(
practitioner: row.practitioner ? toPractitionerDTO(row.practitioner) : null,
reason: decryptField(row.reasonEncrypted, "reason"),
outcome: decryptField(row.outcomeEncrypted, "outcome"),
bodySite: decryptField(row.bodySiteEncrypted, "bodySite"),
laterality: row.laterality,
reminderNextDueAt: row.reminder?.nextDueAt?.toISOString() ?? null,
...(links ? { links } : {}),
...(skipped ? { skipped } : {}),
@@ -145,3 +155,24 @@ export interface EncounterListDTO {
upcoming: EncounterDTO[];
past: EncounterDTO[];
}
/** One body site and side the procedure history holds, with how often. */
export interface BodySiteFacetDTO {
/** The first spelling seen; the facet itself is keyed case-insensitively. */
bodySite: string;
laterality: Laterality | null;
count: number;
}
/**
* The procedure history response.
*
* `procedures` is the filtered list, newest first. `bodySites` and `total` are
* computed over the whole history, before the filter, so the filter choices a
* client offers never shrink to the one it just picked.
*/
export interface ProcedureListDTO {
procedures: EncounterDTO[];
bodySites: BodySiteFacetDTO[];
total: number;
}
+21 -1
View File
@@ -11,7 +11,7 @@
* attached is read off a lock screen. A raw enum constant there is the schema
* leaking into the product.
*/
import type { EncounterKind } from "@/generated/prisma/client";
import type { EncounterKind, Laterality } from "@/generated/prisma/client";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import { defaultLocale, locales, type Locale } from "@/lib/i18n/config";
@@ -41,6 +41,8 @@ export function encounterKindLabel(
return t("encounters.kind.hospital");
case "THERAPY":
return t("encounters.kind.therapy");
case "PROCEDURE":
return t("encounters.kind.procedure");
default:
return t("encounters.kind.other");
}
@@ -73,7 +75,25 @@ export function encounterKindLabelKey(kind: EncounterKind): string {
return "encounters.kind.hospital";
case "THERAPY":
return "encounters.kind.therapy";
case "PROCEDURE":
return "encounters.kind.procedure";
default:
return "encounters.kind.other";
}
}
/**
* The side of a body site as a key, for the same translator-holding callers:
* the doctor-report PDF and the clinician share view name it in the reading
* clinician's language.
*/
export function lateralityLabelKey(laterality: Laterality): string {
switch (laterality) {
case "LEFT":
return "encounters.laterality.left";
case "RIGHT":
return "encounters.laterality.right";
default:
return "encounters.laterality.both";
}
}
+191
View File
@@ -0,0 +1,191 @@
/**
* The procedure and surgery history: every visit filed as PROCEDURE that
* happened, newest first, searchable by body site.
*
* The body site is ciphertext at rest (`Encounter.bodySiteEncrypted`), so the
* search cannot run in SQL. It runs here, after the decrypt, over the account's
* own procedures only. That set is a person's surgical history: tens of rows,
* not thousands, and a decrypt pass per search costs less than a plaintext
* search column would cost in exposure. The read is still bounded
* (`MAX_PROCEDURES`), so an account that somehow holds more cannot turn one
* search into an unbounded decrypt loop.
*
* Only DONE visits count. "What surgeries have you had" is asked about things
* that happened: a booked operation sits in the visits list's upcoming half,
* and a cancelled one or a no-show did not happen at all.
*
* The search and the facet grouping are pure functions, exported for the unit
* test, and the route is a thin wrapper over `loadProcedureHistory`.
*/
import type { Laterality, Prisma } from "@/generated/prisma/client";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import { defaultLocale, locales, type Locale } from "@/lib/i18n/config";
import type { ShareDomain } from "@/lib/sharing/scope";
import {
toEncounterDTO,
type BodySiteFacetDTO,
type ProcedureListDTO,
} from "@/lib/encounters/dto";
import {
ENCOUNTER_INCLUDE,
loadEncounterLinksForMany,
} from "@/lib/encounters/service";
import type { ProcedureListQuery } from "@/lib/validations/encounters";
/** Upper bound on the procedures one read decrypts. */
export const MAX_PROCEDURES = 500;
/** What the search reads off one procedure, already decrypted. */
export interface ProcedureSearchItem {
bodySite: string | null;
laterality: Laterality | null;
reason: string | null;
}
/** Lower-case, accents folded, whitespace collapsed. */
export function normalizeSearchText(value: string): string {
return value
.normalize("NFKD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/\s+/g, " ")
.trim();
}
/**
* Whether one procedure matches the query.
*
* Every word of `q` has to appear somewhere in the site, the side or the
* reason. The side is searchable through its words (`lateralityTerms`), so
* "left knee" finds a procedure whose site says "Knee" and whose side is LEFT:
* the person reads those as one phrase and should not have to know they are
* stored apart. `laterality`, when given, is an exact filter on the field.
*/
export function matchesProcedureQuery(
item: ProcedureSearchItem,
query: ProcedureListQuery,
lateralityTerms: (laterality: Laterality | null) => string[],
): boolean {
if (query.laterality && item.laterality !== query.laterality) return false;
const words = normalizeSearchText(query.q ?? "")
.split(" ")
.filter(Boolean);
if (words.length === 0) return true;
const haystack = normalizeSearchText(
[item.bodySite, item.reason, ...lateralityTerms(item.laterality)]
.filter(Boolean)
.join(" "),
);
return words.every((word) => haystack.includes(word));
}
/**
* One facet per body site and side, most frequent first.
*
* Keyed on the folded text, so "Left knee" and "left knee" are one site; the
* first spelling seen is the one shown. Procedures with no site contribute no
* facet: there is nothing to filter them by.
*/
export function groupBodySites(
items: readonly ProcedureSearchItem[],
): BodySiteFacetDTO[] {
const facets = new Map<string, BodySiteFacetDTO>();
for (const item of items) {
const shown = item.bodySite?.replace(/\s+/g, " ").trim();
if (!shown) continue;
const key = `${normalizeSearchText(shown)}|${item.laterality ?? ""}`;
const facet = facets.get(key);
if (facet) facet.count += 1;
else
facets.set(key, {
bodySite: shown,
laterality: item.laterality,
count: 1,
});
}
// A stable sort, so equal counts keep the order they were first met in —
// newest procedure first, because that is the order the rows arrive in.
return [...facets.values()].sort((a, b) => b.count - a.count);
}
function resolveLocale(locale: string | null | undefined): Locale {
return locales.includes(locale as Locale)
? (locale as Locale)
: defaultLocale;
}
/**
* The words a side can be searched by: the English word, which the API and
* the MCP tool speak, and the record owner's own word, which the person types.
*/
export function lateralityTermsFor(
locale: string | null | undefined,
): (laterality: Laterality | null) => string[] {
const { t } = getServerTranslator(resolveLocale(locale));
const en = getServerTranslator("en").t;
const key = (laterality: Laterality) => {
switch (laterality) {
case "LEFT":
return "encounters.laterality.left";
case "RIGHT":
return "encounters.laterality.right";
default:
return "encounters.laterality.both";
}
};
return (laterality) =>
laterality ? [en(key(laterality)), t(key(laterality))] : [];
}
/**
* Read, decrypt, facet and filter the account's procedure history.
*
* The facets and the total are computed before the filter; the list after it.
* Links ride each row for the same reason they ride the visits list: the edit
* sheet seeds its pickers from the row it was handed.
*/
export async function loadProcedureHistory(
tx: Prisma.TransactionClient,
userId: string,
query: ProcedureListQuery,
options: {
locale: string | null;
visible: (domain: ShareDomain) => boolean;
now?: Date;
},
): Promise<ProcedureListDTO> {
const rows = await tx.encounter.findMany({
where: {
userId,
deletedAt: null,
kind: "PROCEDURE",
status: "DONE",
occurredAt: { lte: options.now ?? new Date() },
},
orderBy: { occurredAt: "desc" },
take: MAX_PROCEDURES,
include: ENCOUNTER_INCLUDE,
});
const decrypted = rows.map((row) => ({ row, dto: toEncounterDTO(row) }));
const terms = lateralityTermsFor(options.locale);
const matching = decrypted.filter(({ dto }) =>
matchesProcedureQuery(dto, query, terms),
);
const links = await loadEncounterLinksForMany(
tx,
userId,
matching.map(({ row }) => row.id),
options.visible,
);
return {
procedures: matching.map(({ row, dto }) => ({
...dto,
links: links.get(row.id),
})),
bodySites: groupBodySites(decrypted.map(({ dto }) => dto)),
total: decrypted.length,
};
}
+25 -2
View File
@@ -35,7 +35,11 @@
*/
import { Buffer } from "node:buffer";
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
import type { EncounterKind, EncounterStatus } from "@/generated/prisma/client";
import type {
EncounterKind,
EncounterStatus,
Laterality,
} from "@/generated/prisma/client";
import {
recordUnknownKeys,
@@ -74,6 +78,9 @@ export interface EncounterBackupEntry {
practitionerId: string | null;
reasonEncrypted: string | null;
outcomeEncrypted: string | null;
/** The procedure's body site, ciphertext like the two above (v1.39.1). */
bodySiteEncrypted: string | null;
laterality: Laterality | null;
/**
* The appointment's reminder row, which restores in the same run since
* v1.37.20. The restore remaps it against the restored reminders and drops
@@ -141,6 +148,8 @@ const ENCOUNTER_BACKUP_SELECT = {
practitionerId: true,
reasonEncrypted: true,
outcomeEncrypted: true,
bodySiteEncrypted: true,
laterality: true,
reminderId: true,
createdAt: true,
updatedAt: true,
@@ -244,6 +253,8 @@ export async function buildVisitsBackupSection(
practitionerId: row.practitionerId,
reasonEncrypted: encodeCiphertext(row.reasonEncrypted),
outcomeEncrypted: encodeCiphertext(row.outcomeEncrypted),
bodySiteEncrypted: encodeCiphertext(row.bodySiteEncrypted),
laterality: row.laterality,
reminderId: row.reminderId,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
@@ -336,7 +347,12 @@ export type RestoredEncounter = Pick<
OptionalNullable<
Pick<
EncounterBackupEntry,
"practitionerId" | "reasonEncrypted" | "outcomeEncrypted" | "reminderId"
| "practitionerId"
| "reasonEncrypted"
| "outcomeEncrypted"
| "bodySiteEncrypted"
| "laterality"
| "reminderId"
>
> & { deletedAt?: string | null };
@@ -457,6 +473,13 @@ export async function restoreVisitsData(
entry.outcomeEncrypted == null
? null
: decodeCiphertext(entry.outcomeEncrypted),
// Absent in a file written before v1.39.1: the visit comes back
// with no site, which is what it had.
bodySiteEncrypted:
entry.bodySiteEncrypted == null
? null
: decodeCiphertext(entry.bodySiteEncrypted),
laterality: entry.laterality ?? null,
reminderId,
createdAt: new Date(entry.createdAt),
updatedAt: new Date(entry.updatedAt),
+7
View File
@@ -277,6 +277,13 @@ export function buildFhirDocumentBundle(
// both carry the doses; the Bundle does not, and this comment is where a
// reader who notices should land.
//
// The surgical history (v1.39.1) rides the same decision. A procedure is a
// visit of kind PROCEDURE, and FHIR's `Procedure` resource would map it
// cleanly (`code.text` from the reason, `bodySite.text` from the site), but
// emitting one without its REST route and capability entry is the same
// half-shipped state. The PDF and the clinician view carry the section; the
// Bundle does not.
//
// 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.
+61
View File
@@ -989,6 +989,67 @@ describe("get_visits", () => {
mode: "insensitive",
});
});
// v1.39.1 — the procedure history. A surgery fifteen years ago is still the
// answer to "what surgeries have I had", so `kind: PROCEDURE` without a
// `months` argument reads the whole record rather than the default year.
//
// Mutation checks (each run, each seen red):
// - keep the 12-month default for PROCEDURE → "reads the whole record"
// goes red with an `occurredAt` floor;
// - drop the fence around `bodySite` → the fence assertion goes red.
it("narrows to one kind", async () => {
vi.mocked(prisma.encounter.findMany).mockResolvedValue([] as never);
await tool("get_visits").run(CTX, { kind: "SPECIALIST" });
const arg = vi.mocked(prisma.encounter.findMany).mock.calls[0][0] as {
where: Record<string, unknown>;
};
expect(arg.where.kind).toBe("SPECIALIST");
});
it("reads the whole record for procedures when no window is named", async () => {
vi.mocked(prisma.encounter.findMany).mockResolvedValue([] as never);
await tool("get_visits").run(CTX, { kind: "PROCEDURE" });
const arg = vi.mocked(prisma.encounter.findMany).mock.calls[0][0] as {
where: { kind?: string; occurredAt?: { gte?: Date; lte?: Date } };
};
expect(arg.where.kind).toBe("PROCEDURE");
expect(arg.where.occurredAt?.gte).toBeUndefined();
expect(arg.where.occurredAt?.lte).toBeInstanceOf(Date);
});
it("keeps a named window for procedures", async () => {
vi.mocked(prisma.encounter.findMany).mockResolvedValue([] as never);
await tool("get_visits").run(CTX, { kind: "PROCEDURE", months: 6 });
const arg = vi.mocked(prisma.encounter.findMany).mock.calls[0][0] as {
where: { occurredAt?: { gte?: Date } };
};
expect(arg.where.occurredAt?.gte).toBeInstanceOf(Date);
});
it("carries the body site fenced and the side as a constant", async () => {
vi.mocked(decryptFromBytes).mockImplementation((buf: Uint8Array) =>
Buffer.from(buf).toString("utf8"),
);
vi.mocked(prisma.encounter.findMany).mockResolvedValue([
visitRow({
kind: "PROCEDURE",
bodySiteEncrypted: Buffer.from("knee", "utf8"),
laterality: "LEFT",
}),
] as never);
vi.mocked(listTargetsBySource).mockResolvedValue(new Map());
const result = (await tool("get_visits").run(CTX, {
kind: "PROCEDURE",
})) as {
windowMonths: number | null;
visits: Array<Record<string, unknown>>;
};
expect(result.windowMonths).toBeNull();
expect(result.visits[0].bodySite).toContain("<<<USER_TEXT_START>>>");
expect(result.visits[0].bodySite).toContain("knee");
expect(result.visits[0].laterality).toBe("LEFT");
});
});
describe("search — cursor pagination", () => {
+26 -6
View File
@@ -70,6 +70,7 @@ import { calendarDaysUntil } from "@/lib/measurement-reminders/due-day";
import { fenceUserText, scrubFenceMarkers } from "@/lib/ai/coach/data-fence";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import { listTargetsBySource } from "@/lib/links";
import { encounterKindEnum } from "@/lib/validations/encounters";
import type { McpAuthContext } from "./auth";
/**
@@ -929,7 +930,9 @@ const getPreventiveCareOutput: z.ZodRawShape = {
*/
const getVisitsOutput: z.ZodRawShape = {
present: z.boolean(),
windowMonths: z.number().optional(),
// Null when the read covered the whole record: a procedure history asked
// for without a window (v1.39.1).
windowMonths: z.number().nullable().optional(),
visits: z
.array(
z.object({
@@ -940,6 +943,8 @@ const getVisitsOutput: z.ZodRawShape = {
specialty: z.string().nullable(),
reason: z.string().nullable(),
outcome: z.string().nullable(),
bodySite: z.string().nullable(),
laterality: z.enum(["LEFT", "RIGHT", "BOTH"]).nullable(),
conditions: z.array(z.string()),
}),
)
@@ -1898,7 +1903,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
name: "get_visits",
title: "Get past doctor visits",
description:
"Fetch the user's own past doctor visits over a bounded window (default: the last 12 months) so a question like 'when did I last see a cardiologist' is answerable from the record. Each visit carries its date, lifecycle status (DONE / CANCELLED / NO_SHOW — a no-show is not a visit that happened), kind, practitioner name + specialty, the visit's own free-text reason and outcome, and the labels of any conditions it was filed against. Optionally narrow to one practitioner by a name substring. Newest first, bounded. Returns { present: false } when the user has never recorded a visit — distinct from a filtered read that simply matched none.",
"Fetch the user's own past doctor visits over a bounded window (default: the last 12 months) so a question like 'when did I last see a cardiologist' is answerable from the record. Each visit carries its date, lifecycle status (DONE / CANCELLED / NO_SHOW — a no-show is not a visit that happened), kind, practitioner name + specialty, the visit's own free-text reason and outcome, the body site and side (set on procedures), and the labels of any conditions it was filed against. Optionally narrow to one practitioner by a name substring, or to one kind. kind PROCEDURE is the procedure and surgery history: without a months argument it reads the whole record, because a surgery years ago is still the answer to 'what surgeries have I had'. Newest first, bounded. Returns { present: false } when the user has never recorded a visit — distinct from a filtered read that simply matched none.",
inputShape: {
months: z
.number()
@@ -1917,21 +1922,32 @@ export const MCP_TOOLS: McpToolDefinition[] = [
.describe(
"Optional case-insensitive name substring to narrow to one practitioner (e.g. a surname read back from an earlier result). Omit for every practitioner.",
),
kind: encounterKindEnum
.optional()
.describe(
"Optional visit kind to narrow to. PROCEDURE lists procedures and surgeries, over the whole record unless months is given.",
),
},
annotations: READ_ONLY_ANNOTATIONS,
outputShape: getVisitsOutput,
async run(ctx, args) {
const kindArg = encounterKindEnum.safeParse(args.kind);
const kind = kindArg.success ? kindArg.data : undefined;
// A procedure history is lifetime reference data; every other read keeps
// the default year. A window the caller names always wins.
const months =
typeof args.months === "number"
? args.months
: DEFAULT_VISITS_WINDOW_MONTHS;
: kind === "PROCEDURE"
? null
: DEFAULT_VISITS_WINDOW_MONTHS;
const practitioner =
typeof args.practitioner === "string" && args.practitioner.trim()
? args.practitioner.trim()
: undefined;
const now = new Date();
const cutoff = new Date(now);
cutoff.setMonth(cutoff.getMonth() - months);
const cutoff = months === null ? null : new Date(now);
cutoff?.setMonth(cutoff.getMonth() - (months ?? 0));
const rows = await prisma.encounter.findMany({
// `userId` is the resolved session's, never an argument — a visit
@@ -1939,7 +1955,8 @@ export const MCP_TOOLS: McpToolDefinition[] = [
where: {
userId: ctx.userId,
deletedAt: null,
occurredAt: { gte: cutoff, lte: now },
occurredAt: { ...(cutoff ? { gte: cutoff } : {}), lte: now },
...(kind ? { kind } : {}),
...(practitioner
? {
practitioner: {
@@ -1979,6 +1996,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
const visits = rows.map((r) => {
const reason = decryptVisitText(r.reasonEncrypted);
const outcome = decryptVisitText(r.outcomeEncrypted);
const bodySite = decryptVisitText(r.bodySiteEncrypted);
return {
occurredAt: r.occurredAt.toISOString(),
status: r.status,
@@ -1995,6 +2013,8 @@ export const MCP_TOOLS: McpToolDefinition[] = [
// too — scrubbed of any forged marker before it enters the payload.
reason: reason !== null ? fenceUserText(reason) : null,
outcome: outcome !== null ? fenceUserText(outcome) : null,
bodySite: bodySite !== null ? fenceUserText(bodySite) : null,
laterality: r.laterality,
conditions: (conditionsBySource.get(r.id) ?? []).map((c) =>
scrubFenceMarkers(c.label),
),
+58 -3
View File
@@ -25,6 +25,8 @@ import {
encounterLinkSchema,
encounterStatusEnum,
encounterKindEnum,
lateralityEnum,
procedureListQuerySchema,
} from "@/lib/validations/encounters";
import {
practitionerCreateSchema,
@@ -49,13 +51,13 @@ import {
const createEncounterRequest = encounterCreateSchema.meta({
id: "CreateEncounterRequest",
description:
"File a visit, or book one. `occurredAt` is the only required field — a visit saves with a date and nothing else. A future instant with `status: PLANNED` books an appointment and mints exactly one reminder for it. `reason` and `outcome` are encrypted at rest. The three id arrays pre-link documents, lab results and condition episodes; an id naming nothing the caller owns is dropped rather than refused, so a link never blocks a save.",
"File a visit, or book one. `occurredAt` is the only required field — a visit saves with a date and nothing else. A future instant with `status: PLANNED` books an appointment and mints exactly one reminder for it. `reason`, `outcome` and `bodySite` are encrypted at rest. `kind: PROCEDURE` marks a procedure or surgery; `bodySite` (free text) and `laterality` (LEFT / RIGHT / BOTH, null when not stated) say where, and are accepted on any kind. The three id arrays pre-link documents, lab results and condition episodes; an id naming nothing the caller owns is dropped rather than refused, so a link never blocks a save.",
});
const updateEncounterRequest = encounterUpdateSchema.meta({
id: "UpdateEncounterRequest",
description:
"Partial edit of a visit; an omitted key leaves the column untouched, and a body naming nothing is a 422. Moving `occurredAt` re-anchors the appointment reminder the visit already owns and never mints a second. Moving `status` to DONE closes the checkup named by `reminderId`, on the transition only. CANCELLED and NO_SHOW stop the reminder without deleting the row. A present id array replaces that link family, empty array included.",
"Partial edit of a visit; an omitted key leaves the column untouched, and a body naming nothing is a 422. Moving `occurredAt` re-anchors the appointment reminder the visit already owns and never mints a second. Moving `status` to DONE closes the checkup named by `reminderId`, on the transition only. CANCELLED and NO_SHOW stop the reminder without deleting the row. A present id array replaces that link family, empty array included. Switching an existing visit to `kind: PROCEDURE` is an ordinary edit of this kind; nothing has to be entered again.",
});
const listEncountersQuery = encounterListQuerySchema.meta({
@@ -76,6 +78,12 @@ const encounterLinkRequest = encounterLinkSchema.meta({
"Targets to file against, or unfile from, a visit. Idempotent in both directions and capped at 100 ids. Ids naming nothing the caller owns come back in `unknown` rather than failing the request.",
});
const listProceduresQuery = procedureListQuerySchema.meta({
id: "ListProceduresQuery",
description:
"Filters for the procedure history. `q` must match every word, case- and accent-insensitively, somewhere in the body site, the side (English or the record owner's language) or the reason. `laterality` filters the side exactly. Both run server-side after the decrypt, because the body site is encrypted at rest.",
});
const createPractitionerRequest = practitionerCreateSchema.meta({
id: "CreatePractitionerRequest",
description:
@@ -163,6 +171,8 @@ const encounter = z
practitioner: practitioner.nullable(),
reason: z.string().nullable(),
outcome: z.string().nullable(),
bodySite: z.string().nullable(),
laterality: lateralityEnum.nullable(),
reminderNextDueAt: z.string().nullable(),
links: encounterLinks.optional(),
skipped: skipReport.optional(),
@@ -172,7 +182,7 @@ const encounter = z
.meta({
id: "Encounter",
description:
"One contact with the healthcare system: a visit that happened, or one that is booked. `practitioner` is resolved rather than an id. `reason` and `outcome` are the decrypted free text (null on a key-rotation gap). `reminderNextDueAt` is the server-computed instant a booked appointment next nudges, and is null for a visit that already happened or whose one-shot reminder is spent.",
"One contact with the healthcare system: a visit that happened, or one that is booked. `practitioner` is resolved rather than an id. `reason`, `outcome` and `bodySite` are the decrypted free text (null on a key-rotation gap). `kind: PROCEDURE` marks a procedure or surgery, and `bodySite` with `laterality` say where; both are carried on every kind so switching a visit's kind away and back loses nothing. `reminderNextDueAt` is the server-computed instant a booked appointment next nudges, and is null for a visit that already happened or whose one-shot reminder is spent.",
});
const encounterList = z
@@ -186,6 +196,30 @@ const encounterList = z
"Visits split server-side rather than client-side. `upcoming` reads soonest-first and `past` reads newest-first — opposite directions, resolved once here so the ordering lives in one place.",
});
const bodySiteFacet = z
.object({
bodySite: z.string(),
laterality: lateralityEnum.nullable(),
count: z.number().int(),
})
.meta({
id: "BodySiteFacet",
description:
"One body site and side in the procedure history, with how many procedures carry it. Keyed case- and space-insensitively; `bodySite` is the first spelling seen.",
});
const procedureList = z
.object({
procedures: z.array(encounter),
bodySites: z.array(bodySiteFacet),
total: z.number().int(),
})
.meta({
id: "ProcedureList",
description:
"The procedure history. `procedures` is the filtered list, newest first. `bodySites` and `total` are computed over the whole history before the filter, so the filter choices never shrink to the one just picked.",
});
const suggestionCandidate = z
.object({
id: z.string(),
@@ -278,6 +312,27 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/encounters/procedures": {
get: {
tags: ["Records"],
summary: "List procedures and surgeries",
description:
"The caller's procedure and surgery history: every live visit of kind PROCEDURE with status DONE, newest first, bounded at 500. Planned, cancelled and missed procedures are not in it; a booked one stays in the visit list's `upcoming` half. Read at the same section and level as the visit list.",
requestParams: { query: listProceduresQuery },
responses: {
...recordRefusal(),
"200": {
description: "The procedure history.",
content: {
"application/json": {
schema: dataEnvelope(procedureList, "ListProceduresEnvelope"),
},
},
},
...stdResponses,
},
},
},
"/api/encounters/suggest": {
get: {
tags: ["Records"],
+8
View File
@@ -46,6 +46,14 @@ export const encounterKeys = {
episodeId ?? null,
] as const,
encounter: (id: string) => ["encounters", "detail", id] as const,
/**
* The procedure history for one filter. Under the `["encounters"]` root, so
* every visit write (switching a kind, editing a site) evicts it with the
* list. The filter is part of the key because it is part of the question:
* the search runs server-side over the decrypted site.
*/
encounterProcedures: (q: string, laterality: string | null) =>
["encounters", "procedures", q, laterality] as const,
/**
* The "which visit does this belong to" verdict for one anchor date. The
* anchor is part of the key because it IS the question: a document dated the
@@ -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(17);
expect(ALL_LEAF_IDS).toHaveLength(94);
expect(STRUCTURED_LEAF_IDS).toHaveLength(18);
expect(ALL_LEAF_IDS).toHaveLength(95);
});
it("resolves a label for every leaf", () => {
+5 -1
View File
@@ -48,6 +48,7 @@ export type StructuredLeafId =
| "ALLERGIES"
| "ILLNESS_EPISODES"
| "VISITS"
| "SURGICAL_HISTORY"
| "IMMUNIZATIONS"
| "FAMILY_HISTORY"
| "MOOD"
@@ -204,6 +205,7 @@ export const STRUCTURED_LEAF_GROUP: Record<StructuredLeafId, ReportGroupId> = {
ALLERGIES: "history",
ILLNESS_EPISODES: "history",
VISITS: "history",
SURGICAL_HISTORY: "history",
IMMUNIZATIONS: "history",
FAMILY_HISTORY: "sensitive",
MOOD: "sensitive",
@@ -211,7 +213,7 @@ export const STRUCTURED_LEAF_GROUP: Record<StructuredLeafId, ReportGroupId> = {
ANAMNESIS: "sensitive",
};
/** i18n label keys for the 17 structured leaves. */
/** i18n label keys for the 18 structured leaves. */
export const STRUCTURED_LEAF_LABEL_KEYS: Record<StructuredLeafId, string> = {
PATIENT_IDENTITY: "reportSelection.leafPatientIdentity",
EMERGENCY: "reportSelection.leafEmergency",
@@ -225,6 +227,7 @@ export const STRUCTURED_LEAF_LABEL_KEYS: Record<StructuredLeafId, string> = {
ALLERGIES: "reportSelection.leafAllergies",
ILLNESS_EPISODES: "reportSelection.leafIllnessEpisodes",
VISITS: "reportSelection.leafVisits",
SURGICAL_HISTORY: "reportSelection.leafSurgicalHistory",
IMMUNIZATIONS: "reportSelection.leafImmunizations",
FAMILY_HISTORY: "reportSelection.leafFamilyHistory",
MOOD: "reportSelection.leafMood",
@@ -323,6 +326,7 @@ export const LEAF_MODULE: Partial<Record<ReportLeafId, ModuleKey>> = {
// 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.
// SURGICAL_HISTORY is absent for the same reason: a procedure is a visit.
};
/** Every measurement leaf id, in enum order. */
+3 -1
View File
@@ -16,7 +16,8 @@ import { type ReportLeafId } from "./catalogue";
/**
* Identity and insurer (the cover page a practice files the document under),
* the three classic vitals, weight and BMI, the glucose series and its panel,
* labs, the drug list and adherence, allergies and past illness episodes.
* labs, the drug list and adherence, allergies, past illness episodes, the
* surgical history and the immunization record.
*
* Deliberately not in it: everything a wearable produces, gait and mobility,
* environment exposure, the per-dose administration ledger (a clinician asks
@@ -39,6 +40,7 @@ export const STANDARD_TEMPLATE_LEAVES: readonly ReportLeafId[] = [
"MEDICATION_COMPLIANCE",
"ALLERGIES",
"ILLNESS_EPISODES",
"SURGICAL_HISTORY",
"IMMUNIZATIONS",
];
+5
View File
@@ -48,6 +48,7 @@ import {
InjectionSite,
IntakeAttributionSource,
IntakeSource,
Laterality,
MeasurementAggregationProvenance,
MeasurementReminderEventKind,
MeasurementSource,
@@ -1088,6 +1089,10 @@ const encounterBackupSchema = z
practitionerId: z.string().nullable().optional(),
reasonEncrypted: base64BytesSchema.nullable().optional(),
outcomeEncrypted: base64BytesSchema.nullable().optional(),
// v1.39.1 — the procedure's body site and side. Optional so a file written
// before they existed still parses; the visit restores with neither.
bodySiteEncrypted: base64BytesSchema.nullable().optional(),
laterality: z.enum(Laterality).nullable().optional(),
// Remapped against the restored reminders (they travel since v1.37.20);
// dropped to NULL, with the drop named, only when the file lacks the row.
reminderId: z.string().nullable().optional(),
+33
View File
@@ -61,10 +61,22 @@ export const encounterKindEnum = z.enum([
"HOSPITAL",
"THERAPY",
"OTHER",
"PROCEDURE",
]);
/** The side a procedure's body site is on. Absent or null: not stated. */
export const lateralityEnum = z.enum(["LEFT", "RIGHT", "BOTH"]);
export type EncounterStatusInput = z.infer<typeof encounterStatusEnum>;
export type EncounterKindInput = z.infer<typeof encounterKindEnum>;
export type LateralityInput = z.infer<typeof lateralityEnum>;
/**
* Where on the body, in the person's own words. Becomes `bodySiteEncrypted`.
* Bounded like a label rather than like prose: "left knee, medial meniscus" is
* the long end of what belongs here, and the reason field holds the rest.
*/
const bodySite = z.string().max(200).nullable().optional();
const id = z.string().min(1).max(40);
@@ -88,6 +100,8 @@ export const encounterCreateSchema = z
reason: z.string().max(2000).nullable().optional(),
/** Becomes `outcomeEncrypted`. */
outcome: z.string().max(4000).nullable().optional(),
bodySite,
laterality: lateralityEnum.nullable().optional(),
/** The checkup this visit closes, when it was filed from a due one. */
reminderId: id.nullable().optional(),
documentIds: linkIds,
@@ -113,6 +127,8 @@ export const encounterUpdateSchema = z
practitionerId: id.nullable().optional(),
reason: z.string().max(2000).nullable().optional(),
outcome: z.string().max(4000).nullable().optional(),
bodySite,
laterality: lateralityEnum.nullable().optional(),
reminderId: id.nullable().optional(),
documentIds: linkIds,
labResultIds: linkIds,
@@ -173,6 +189,23 @@ export const encounterSuggestQuerySchema = z
export type EncounterSuggestQuery = z.infer<typeof encounterSuggestQuerySchema>;
/**
* The procedure history query.
*
* `q` is matched after the decrypt, over the body site, the side and the
* reason, every word required (see `src/lib/encounters/procedures.ts`). It is
* named `q` and not `bodySite` because it also searches the reason: a knee
* operation recorded before the site field existed says "knee" only there.
*/
export const procedureListQuerySchema = z
.object({
q: z.string().max(200).optional(),
laterality: lateralityEnum.optional(),
})
.strict();
export type ProcedureListQuery = z.infer<typeof procedureListQuerySchema>;
/* ── links ────────────────────────────────────────────────────────── */
export const encounterLinkTargetEnum = z.enum([