mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(visits): record procedures and surgeries with a body site
A visit can be filed as a procedure or surgery (new EncounterKind PROCEDURE) and carry a body site in the person's own words, encrypted at rest, plus an optional side (LEFT, RIGHT, BOTH). An existing visit switches to the new kind by an ordinary edit, keeping its date, reason, outcome and links. - migration 0349: enum value, laterality type, two nullable columns - GET /api/encounters/procedures: the DONE procedures, newest first, searched after the decrypt over site, side and reason, with body-site choices and a total computed over the whole history - create and edit accept bodySite and laterality on any kind - /checkups gains a Procedures tab with a body-site filter; the visit form offers the site for a procedure and keeps it in view on any visit that carries one - backup and restore carry both fields; the body site is registered as ciphertext and rotates with the key - MCP get_visits narrows by kind and reads the whole record for procedures when no window is named; the Coach visit block names a procedure's site - i18n in all seven locales, OpenAPI regenerated Refs #1025
This commit is contained in:
1 parent
ee23409b77
commit
ad0d50fa28
43 files changed
+2486
-61
No files matched your search
@@ -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");
|
||||
|
||||
@@ -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 } : {}) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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) ─────
|
||||
|
||||
@@ -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 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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
@@ -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),
|
||||
),
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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([
|
||||
|
||||
Reference in new issue
Block a user