Add the visit and address-book API, and the appointment arm

Nine visit routes and five practitioner routes, all classified under the
existing profile domain and each reviewed into the frozen sharing
literal with the sentence that argues for it. An address book of a
person's own doctors is record content, not account configuration: it
names no credential, no integration and no notification channel, which
is the fence that classification turns on. The eight sharing domains are
unchanged. Link and unlink stay bare, matching document link and unlink,
and the pair is revisited as one decision later.

Nothing is a required field. A visit saves with a date and nothing else.
Every id a body may carry is re-narrowed to the caller before anything
is written, and an unknown link id never blocks a save.

A booked visit mints exactly one reminder on the existing engine with
the new origin, and the appointment half is the part worth reading
twice. Both cadence columns stay null, which is the schema's one-shot,
so the first due instant is stamped directly and the never-nag property
is structural rather than guarded: after it fires, the cadence helper
has no occurrence to return. Rescheduling re-anchors that row and never
mints a second, which the tests assert by counting rows rather than by
checking the date moved.

Filing a visit as done closes the checkup it was filed against, on the
transition rather than on every later edit. Writing the test first found
that: satisfying is forward-only, so re-saving a completed visit was
pushing the checkup's next due date out again as if the person had been
a second time.

An appointment must appear on no preventive-care surface, and that is
four separate reads, one of them in the assistant tooling. Each carries
the exclusion, a guard proves all four by source text with a non-zero
match count, and the reminder mapper refuses such a row outright — so a
read site that loses its filter fails loudly instead of showing an
appointment as a checkup. The published origin enum is untouched.
This commit is contained in:
Marc-André Bombeck committed 2026-08-08 07:51:29 +02:00
1 parent ba21c3a9bc
commit f158494def
30 files changed
+2743 -6

No files matched your search

+7
View File
@@ -364,10 +364,17 @@ export async function loadDailyDigest(
orderBy: { integration: "asc" },
}),
prisma.measurementReminder.findMany({
// A booked visit's one-shot reminder rides this same engine with
// `origin: ENCOUNTER`. It is not a checkup and must not appear on a
// Vorsorge surface, or the list fills with appointments. Four read
// sites carry this exclusion; `encounter-reminder-exclusion.test.ts`
// proves every one of them, and the DTO mapper refuses such a row
// outright so a site that lost its filter fails loudly.
where: {
userId: user.id,
enabled: true,
deletedAt: null,
origin: { not: "ENCOUNTER" },
nextDueAt: { not: null, lte: now },
},
select: { label: true },
+179
View File
@@ -0,0 +1,179 @@
/**
* A booked visit's reminder — one row on the EXISTING engine, not a second one.
*
* A planned encounter mints exactly one `MeasurementReminder` with
* `origin = ENCOUNTER`. No new queue, no new cron, no new notification event
* type, no new preference key: the enum's own docblock states the rule, and an
* appointment is a reminder with a date like every other reminder with a date.
*
* ── Why the row is shaped the way it is ─────────────────────────────────────
*
* `measurementType` is NULL, which is the engine's free-text arm: there is no
* measurement that could satisfy "you have an appointment", so it resolves only
* on an explicit satisfy. `intervalDays` and `rrule` are both NULL, which the
* schema documents as a one-shot anchored on `anchorDate`.
*
* That last part carries a consequence worth stating rather than discovering:
* `computeReminderNextDueAt` returns NULL when there is no cadence, so a
* one-shot's first `nextDueAt` cannot come from it and is stamped here
* directly. The same fact is what makes the never-nag property STRUCTURAL —
* after the cron fires the row it calls that function to advance the slot, gets
* NULL, and the reminder can never fire again. There is no guard enforcing
* this and there should not be one; it is a property of having no cadence.
*
* ── One row per visit, ever ─────────────────────────────────────────────────
*
* Rescheduling re-anchors the existing row. It never mints a second, which is
* why `Encounter.reminderId` is a single column and not a list. Deliberately NO
* partial unique index enforces this: the COACH one is `WHERE origin = 'COACH'`
* so ENCOUNTER rows do not inherit it, and a similar index here would break
* anyone who books two appointments.
*/
import type { Prisma } from "@/generated/prisma/client";
import {
computeReminderNextDueAt,
type ReminderScheduleInput,
} from "@/lib/measurement-reminders/scheduling";
/** What the reminder needs to know about the visit that owns it. */
export interface AppointmentReminderInput {
userId: string;
occurredAt: Date;
/** Used as the label when present; the kind label is the fallback. */
practitionerName: string | null;
/** Copied onto the reminder's free-text `location`. */
practitionerLocation: string | null;
/** The fallback label when the visit names no practice. */
kindLabel: string;
}
/** The local hour the nudge fires, read off the appointment in the user's zone. */
export function appointmentNotifyHour(
occurredAt: Date,
timezone: string,
): number {
const hour = new Intl.DateTimeFormat("en-GB", {
timeZone: timezone,
hour: "2-digit",
hour12: false,
}).format(occurredAt);
const parsed = Number.parseInt(hour, 10);
// `24` is a legal formatter output for midnight in some locales; the column
// is 0–23 and midnight is 0.
if (!Number.isFinite(parsed)) return 9;
return parsed % 24;
}
function reminderLabel(input: AppointmentReminderInput): string {
return input.practitionerName?.trim() || input.kindLabel;
}
/**
* Mint the one reminder a planned visit owns, inside the caller's transaction.
*
* Returns the row's id for `Encounter.reminderId`.
*/
export async function mintAppointmentReminder(
tx: Prisma.TransactionClient,
input: AppointmentReminderInput,
timezone: string,
): Promise<string> {
const created = await tx.measurementReminder.create({
data: {
userId: input.userId,
label: reminderLabel(input),
// The free-text arm: nothing a person could measure satisfies this.
measurementType: null,
// Both NULL — a one-shot anchored on `anchorDate`.
intervalDays: null,
rrule: null,
anchorDate: input.occurredAt,
origin: "ENCOUNTER",
notifyHour: appointmentNotifyHour(input.occurredAt, timezone),
location: input.practitionerLocation,
// Stamped directly: see the note at the top of this file on why the
// cadence helper cannot produce a one-shot's first slot.
nextDueAt: input.occurredAt,
},
select: { id: true },
});
return created.id;
}
/**
* Move an existing appointment reminder to a new instant.
*
* Re-anchors and re-stamps the same row rather than minting a second, and
* re-enables it: a visit that was cancelled and then rebooked should nudge
* again, which is the whole reason the person moved the date.
*/
export async function reanchorAppointmentReminder(
tx: Prisma.TransactionClient,
reminderId: string,
input: AppointmentReminderInput,
timezone: string,
): Promise<void> {
await tx.measurementReminder.update({
where: { id: reminderId },
data: {
label: reminderLabel(input),
anchorDate: input.occurredAt,
notifyHour: appointmentNotifyHour(input.occurredAt, timezone),
location: input.practitionerLocation,
nextDueAt: input.occurredAt,
enabled: true,
deletedAt: null,
},
});
}
/**
* Stop an appointment reminder without deleting it.
*
* A cancelled or missed appointment keeps its row so the history stays honest,
* but must never nudge again. `enabled: false` is the engine's own master
* switch and is distinct from the tombstone.
*/
export async function disableAppointmentReminder(
tx: Prisma.TransactionClient,
reminderId: string,
): Promise<void> {
await tx.measurementReminder.update({
where: { id: reminderId },
data: { enabled: false, nextDueAt: null },
});
}
/** Soft-delete the reminder alongside the visit that owns it. */
export async function deleteAppointmentReminder(
tx: Prisma.TransactionClient,
reminderId: string,
at: Date,
): Promise<void> {
await tx.measurementReminder.update({
where: { id: reminderId },
data: { deletedAt: at, enabled: false, nextDueAt: null },
});
}
/**
* What a one-shot appointment reminder's next slot becomes once it has fired.
*
* Exported for the test that proves the never-nag property rather than
* asserting it in prose: the answer must be NULL, and it must come from the
* same function the cron uses.
*/
export function appointmentNextDueAfterFiring(
reminder: Pick<
ReminderScheduleInput,
"intervalDays" | "rrule" | "anchorDate" | "notifyHour" | "createdAt"
>,
timezone: string,
now: Date,
): Date | null {
return computeReminderNextDueAt(
{ ...reminder, lastSatisfiedAt: null },
timezone,
now,
);
}
+109
View File
@@ -0,0 +1,109 @@
/**
* Encounter row → wire DTO.
*
* Everything is published resolved. The practitioner comes back as an object
* and never as a bare id, the links come back with a label and a date, and the
* appointment's next-due instant comes back computed. A client that had to
* re-derive any of them would drift from the server the first time one of the
* derivations changed on one side only.
*
* The two free-text columns are `Bytes` ciphertext and decrypt fail-soft: a
* key-rotation gap on one row reads as a missing reason, not as a 500 on the
* whole list.
*/
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import { getEvent } from "@/lib/logging/context";
import type {
Encounter,
EncounterKind,
EncounterStatus,
MeasurementReminder,
Practitioner,
} from "@/generated/prisma/client";
import type { LinkedTarget } from "@/lib/links";
import {
toPractitionerDTO,
type PractitionerDTO,
} from "@/lib/practitioners/dto";
/** The three link families a visit can carry, each already resolved. */
export interface EncounterLinksDTO {
documents: LinkedTarget[];
labResults: LinkedTarget[];
conditions: LinkedTarget[];
}
export interface EncounterDTO {
id: string;
occurredAt: string;
status: EncounterStatus;
kind: EncounterKind;
/** Resolved, never just an id. `null` when the visit names no practice. */
practitioner: PractitionerDTO | null;
reason: string | null;
outcome: string | 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
* happened, or once the one-shot reminder is spent.
*/
reminderNextDueAt: string | null;
/** Present on the detail response; omitted from the list. */
links?: EncounterLinksDTO;
createdAt: string;
updatedAt: string;
}
function decryptField(
value: Uint8Array | null,
field: "reason" | "outcome",
): string | null {
if (!value || value.byteLength === 0) return null;
try {
return decryptFromBytes(value);
} catch (err) {
getEvent()?.addWarning(
`encounter ${field} decrypt failed: ${
err instanceof Error ? err.message : String(err)
}`,
);
return null;
}
}
export type EncounterWithRelations = Encounter & {
practitioner?: Practitioner | null;
reminder?: Pick<MeasurementReminder, "nextDueAt"> | null;
};
export function toEncounterDTO(
row: EncounterWithRelations,
links?: EncounterLinksDTO,
): EncounterDTO {
return {
id: row.id,
occurredAt: row.occurredAt.toISOString(),
status: row.status,
kind: row.kind,
practitioner: row.practitioner ? toPractitionerDTO(row.practitioner) : null,
reason: decryptField(row.reasonEncrypted, "reason"),
outcome: decryptField(row.outcomeEncrypted, "outcome"),
reminderNextDueAt: row.reminder?.nextDueAt?.toISOString() ?? null,
...(links ? { links } : {}),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
/**
* The list response.
*
* Two arrays rather than one sorted list, resolved server-side: "what is
* coming up" and "what happened" are read in opposite directions, and making
* the client split and re-sort one array would put that decision in two
* places.
*/
export interface EncounterListDTO {
upcoming: EncounterDTO[];
past: EncounterDTO[];
}
+257
View File
@@ -0,0 +1,257 @@
/**
* The work the encounter routes share: resolving a visit, wiring its links,
* and keeping its appointment reminder in step with its status.
*
* Lives beside the routes rather than inside one of them because create and
* edit both do most of it, and a copy in each is how the two drift.
*/
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import {
satisfyReminder,
type SatisfiableReminder,
} from "@/lib/measurement-reminders/satisfy";
import { listTargets, replaceTargets, type LinkTargetKind } from "@/lib/links";
import type { EncounterLinksDTO } from "@/lib/encounters/dto";
import {
deleteAppointmentReminder,
disableAppointmentReminder,
mintAppointmentReminder,
reanchorAppointmentReminder,
type AppointmentReminderInput,
} from "@/lib/encounters/appointment-reminder";
const DEFAULT_TIMEZONE = "Europe/Berlin";
export async function resolveTimezone(userId: string): Promise<string> {
const row = await prisma.user.findUnique({
where: { id: userId },
select: { timezone: true },
});
return row?.timezone || DEFAULT_TIMEZONE;
}
/** The relations the detail and list responses resolve. */
export const ENCOUNTER_INCLUDE = {
practitioner: true,
reminder: { select: { nextDueAt: true } },
} as const satisfies Prisma.EncounterInclude;
/** The three link families, resolved for one visit. */
export async function loadEncounterLinks(
tx: Prisma.TransactionClient,
userId: string,
encounterId: string,
): Promise<EncounterLinksDTO> {
const read = (targetKind: LinkTargetKind) =>
listTargets(tx, {
userId,
sourceKind: "encounter",
sourceId: encounterId,
targetKind,
});
const [documents, labResults, conditions] = await Promise.all([
read("document"),
read("labResult"),
read("conditionEpisode"),
]);
return { documents, labResults, conditions };
}
/**
* Apply whichever of the three link arrays the request actually named.
*
* An absent array leaves that family alone; a present one replaces it, empty
* array included. Unknown ids are dropped by the link service and never block
* the save — a visit is never refused because one document it pointed at has
* since been deleted.
*/
export async function applyEncounterLinks(
tx: Prisma.TransactionClient,
userId: string,
encounterId: string,
arrays: {
documentIds?: string[];
labResultIds?: string[];
episodeIds?: string[];
},
): Promise<void> {
const families: Array<[LinkTargetKind, string[] | undefined]> = [
["document", arrays.documentIds],
["labResult", arrays.labResultIds],
["conditionEpisode", arrays.episodeIds],
];
for (const [targetKind, targetIds] of families) {
if (targetIds === undefined) continue;
await replaceTargets(tx, {
userId,
sourceKind: "encounter",
sourceId: encounterId,
targetKind,
targetIds,
});
}
}
/**
* Whether a visit in this state, at this instant, should be nudging.
*
* Only a PLANNED visit in the future does. A visit that already happened needs
* no reminder, and a terminal one must not produce a nudge for an appointment
* that is not going to occur.
*/
export function shouldHaveReminder(
status: string,
occurredAt: Date,
now: Date,
): boolean {
return status === "PLANNED" && occurredAt.getTime() > now.getTime();
}
export interface ReminderSyncInput extends AppointmentReminderInput {
status: string;
/**
* The APPOINTMENT reminder this visit already owns, or null.
*
* Never a checkup the visit closes. `Encounter.reminderId` carries either
* one, and the two are kept apart by their origin: an appointment reminder
* is `ENCOUNTER`, a checkup is not. Confusing them would re-anchor a
* person's own Vorsorge cadence onto an appointment date, which is why the
* routes resolve the origin before calling this.
*/
existingReminderId: string | null;
}
/**
* Bring the visit's appointment reminder in line with the visit.
*
* Returns the id to store on `Encounter.reminderId` — the existing one, a
* freshly minted one, or the existing one left in place but switched off.
* Never mints a second row for a visit that already has one.
*/
export async function syncAppointmentReminder(
tx: Prisma.TransactionClient,
input: ReminderSyncInput,
timezone: string,
now: Date,
): Promise<string | null> {
const wanted = shouldHaveReminder(input.status, input.occurredAt, now);
if (!wanted) {
// The row stays — the history of a cancelled appointment is worth keeping —
// but it stops nudging.
if (input.existingReminderId) {
await disableAppointmentReminder(tx, input.existingReminderId);
}
return input.existingReminderId;
}
if (input.existingReminderId) {
await reanchorAppointmentReminder(
tx,
input.existingReminderId,
input,
timezone,
);
return input.existingReminderId;
}
return mintAppointmentReminder(tx, input, timezone);
}
/**
* The checkup a visit says it closes, re-narrowed to the caller.
*
* Refuses an `ENCOUNTER`-origin row outright. Those belong to a booked visit
* and are not a checkup anybody can close by filing one; accepting it here
* would let a client re-point one visit's appointment reminder at another
* visit and re-anchor it on the wrong date.
*
* Returns `undefined` when the id names nothing closeable.
*/
export async function resolveClosableReminder(
tx: Prisma.TransactionClient,
userId: string,
reminderId: string,
): Promise<SatisfiableReminder | undefined> {
const row = await tx.measurementReminder.findUnique({
where: { id: reminderId },
select: {
id: true,
userId: true,
origin: true,
deletedAt: true,
intervalDays: true,
rrule: true,
anchorDate: true,
notifyHour: true,
lastSatisfiedAt: true,
createdAt: true,
},
});
if (!row || row.userId !== userId || row.deletedAt !== null) return undefined;
if (row.origin === "ENCOUNTER") return undefined;
return {
id: row.id,
intervalDays: row.intervalDays,
rrule: row.rrule,
anchorDate: row.anchorDate,
notifyHour: row.notifyHour,
lastSatisfiedAt: row.lastSatisfiedAt,
createdAt: row.createdAt,
};
}
/**
* Close the checkup a completed visit was filed against.
*
* `satisfyReminder` is the one shared primitive the cron, the ingest worker
* and the explicit user action all route through, and it is forward-only and
* idempotent — so filing the same visit as DONE twice is a no-op that still
* succeeds. That is the whole of "the appointment closes the checkup"; there
* is no second mechanism.
*/
export async function closeCheckupForVisit(
tx: Prisma.TransactionClient,
reminder: SatisfiableReminder,
timezone: string,
now: Date,
): Promise<void> {
await satisfyReminder(tx as unknown as PrismaClient, reminder, timezone, now);
}
/** Soft-delete a visit's reminder alongside the visit. */
export async function retireAppointmentReminder(
tx: Prisma.TransactionClient,
reminderId: string | null,
at: Date,
): Promise<void> {
if (!reminderId) return;
await deleteAppointmentReminder(tx, reminderId, at);
}
/**
* The practitioner a visit names, re-narrowed to the caller.
*
* Returns `undefined` when the id names nothing this account owns, which the
* routes turn into a 404 — the same refusal shape a foreign encounter id gets.
*/
export async function resolveOwnedPractitioner(
tx: Prisma.TransactionClient,
userId: string,
practitionerId: string,
): Promise<{ id: string; name: string; location: string | null } | undefined> {
const row = await tx.practitioner.findUnique({
where: { id: practitionerId },
select: {
id: true,
name: true,
location: true,
userId: true,
deletedAt: true,
},
});
if (!row || row.userId !== userId || row.deletedAt !== null) return undefined;
return { id: row.id, name: row.name, location: row.location };
}
+7
View File
@@ -271,10 +271,17 @@ export async function readPreventiveCareBlock(
): Promise<AggregatedFeatures["preventiveCare"] | undefined> {
const horizon = new Date(now + PREVENTIVE_DUE_HORIZON_DAYS * MS_PER_DAY);
const rows = await prisma.measurementReminder.findMany({
// A booked visit's one-shot reminder rides this same engine with
// `origin: ENCOUNTER`. It is not a checkup and must not appear on a
// Vorsorge surface, or the list fills with appointments. Four read
// sites carry this exclusion; `encounter-reminder-exclusion.test.ts`
// proves every one of them, and the DTO mapper refuses such a row
// outright so a site that lost its filter fails loudly.
where: {
userId,
deletedAt: null,
enabled: true,
origin: { not: "ENCOUNTER" },
nextDueAt: { not: null, lte: horizon },
},
orderBy: { nextDueAt: "asc" },
+8 -1
View File
@@ -667,7 +667,14 @@ describe("get_preventive_care", () => {
};
expect(prisma.measurementReminder.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { userId: "user-1", deletedAt: null, enabled: true },
where: {
userId: "user-1",
deletedAt: null,
enabled: true,
// A booked visit's reminder rides the same engine and is not a
// checkup; the tool must not offer one as preventive care.
origin: { not: "ENCOUNTER" },
},
}),
);
expect(result.present).toBe(true);
+12 -1
View File
@@ -1552,7 +1552,18 @@ export const MCP_TOOLS: McpToolDefinition[] = [
outputShape: getPreventiveCareOutput,
async run(ctx) {
const reminders = await prisma.measurementReminder.findMany({
where: { userId: ctx.userId, deletedAt: null, enabled: true },
// A booked visit's one-shot reminder rides this same engine with
// `origin: ENCOUNTER`. It is not a checkup and must not appear on a
// Vorsorge surface, or the list fills with appointments. Four read
// sites carry this exclusion; `encounter-reminder-exclusion.test.ts`
// proves every one of them, and the DTO mapper refuses such a row
// outright so a site that lost its filter fails loudly.
where: {
userId: ctx.userId,
deletedAt: null,
enabled: true,
origin: { not: "ENCOUNTER" },
},
// Most-urgent first; a null next-due (uncomputable) sinks to the end.
orderBy: [
{ nextDueAt: { sort: "asc", nulls: "last" } },
+54
View File
@@ -0,0 +1,54 @@
/**
* Practitioner row → wire DTO.
*
* Server-authoritative: the client renders these values, it never rebuilds
* them. The free-text note lives in `noteEncrypted` (Bytes) and is decrypted
* fail-soft on read, so a key-rotation gap on one row reads as a missing note
* rather than 500-ing the address book.
*/
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import { getEvent } from "@/lib/logging/context";
import type { Practitioner } from "@/generated/prisma/client";
export interface PractitionerDTO {
id: string;
name: string;
specialty: string | null;
practice: string | null;
location: string | null;
phone: string | null;
note: string | null;
createdAt: string;
updatedAt: string;
}
/** Decrypt a Bytes note fail-soft (null on missing / undecryptable). */
export function decryptPractitionerNote(
noteEncrypted: Uint8Array | null,
): string | null {
if (!noteEncrypted || noteEncrypted.byteLength === 0) return null;
try {
return decryptFromBytes(noteEncrypted);
} catch (err) {
getEvent()?.addWarning(
`practitioner note decrypt failed: ${
err instanceof Error ? err.message : String(err)
}`,
);
return null;
}
}
export function toPractitionerDTO(row: Practitioner): PractitionerDTO {
return {
id: row.id,
name: row.name,
specialty: row.specialty,
practice: row.practice,
location: row.location,
phone: row.phone,
note: decryptPractitionerNote(row.noteEncrypted),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
+25
View File
@@ -72,6 +72,12 @@ export function recordActivityVerbLine(
return t("recordSharing.activityVerb.familyHistoryCreate", { name });
case "illness.episode.create":
return t("recordSharing.activityVerb.illnessEpisodeCreate", { name });
case "encounter.visit.create":
return t("recordSharing.activityVerb.encounterVisitCreate", { name });
case "practitioner.contact.create":
return t("recordSharing.activityVerb.practitionerContactCreate", {
name,
});
case "biomarker.create":
return t("recordSharing.activityVerb.biomarkerCreate", { name });
case "customMetricEntry.create":
@@ -175,6 +181,25 @@ export function recordActivityVerbLine(
case "illness.day-log.upsert":
return t("recordSharing.activityVerb.illnessDayLogUpsert", { name });
case "encounter.visit.update":
return t("recordSharing.activityVerb.encounterVisitUpdate", { name });
case "encounter.visit.delete":
return t("recordSharing.activityVerb.encounterVisitDelete", { name });
case "encounter.visit.restore":
return t("recordSharing.activityVerb.encounterVisitRestore", { name });
case "practitioner.contact.update":
return t("recordSharing.activityVerb.practitionerContactUpdate", {
name,
});
case "practitioner.contact.delete":
return t("recordSharing.activityVerb.practitionerContactDelete", {
name,
});
case "practitioner.contact.restore":
return t("recordSharing.activityVerb.practitionerContactRestore", {
name,
});
case "medication.update":
return t("recordSharing.activityVerb.medicationUpdate", { name });
case "medication.delete":
+166
View File
@@ -0,0 +1,166 @@
/**
* Visit (encounter) request/response validation.
*
* Source of truth for the `/api/encounters*` wire contract; the OpenAPI
* registry reuses these schemas so the spec stays single-source. `userId` is
* NEVER a body field — it is narrowed from the session or Bearer in every
* route and fed to the Prisma `where`.
*
* Nothing here is mandatory except the date. A visit saves with an instant and
* nothing else: no practitioner, no kind, no reason, no link. That is a
* deliberate product constraint and not an oversight — a required field on a
* form somebody fills after a doctor's appointment is the bureaucracy this
* whole feature exists to avoid.
*
* The one exception to "no future instants" that the rest of the record keeps:
* `occurredAt` may be in the future, because a booked appointment IS a visit
* with a future date. It is bounded on both sides regardless, so a typo cannot
* park a row a century out.
*/
import { z } from "zod/v4";
/** Ten years out. Long enough for any real appointment, short enough that a
* mistyped year lands as a 422 rather than as a row nobody sees again. */
const MAX_FUTURE_MS = 10 * 365 * 24 * 60 * 60 * 1000;
/**
* An instant a visit can plausibly carry.
*
* Deliberately NOT `isPlausibleEntryInstant`, which refuses anything beyond a
* five-minute clock skew. That bound is right for a measurement, which can only
* describe something that already happened, and wrong here.
*/
const visitInstant = z.iso.datetime({ offset: true }).refine(
(value) => {
const at = new Date(value).getTime();
if (Number.isNaN(at)) return false;
if (at < Date.UTC(1900, 0, 1)) return false;
return at <= Date.now() + MAX_FUTURE_MS;
},
{
message:
"must be a plausible visit instant (not before 1900, not more than ten years ahead)",
},
);
/* ── enums (mirror the Prisma enums) ─────────────────────────────── */
export const encounterStatusEnum = z.enum([
"PLANNED",
"DONE",
"CANCELLED",
"NO_SHOW",
]);
export const encounterKindEnum = z.enum([
"ROUTINE",
"ACUTE",
"SPECIALIST",
"PREVENTIVE",
"EMERGENCY",
"HOSPITAL",
"THERAPY",
"OTHER",
]);
export type EncounterStatusInput = z.infer<typeof encounterStatusEnum>;
export type EncounterKindInput = z.infer<typeof encounterKindEnum>;
const id = z.string().min(1).max(40);
/**
* The three optional pre-link arrays.
*
* Bounded at the link service's own cap so an over-long list is a 422 with a
* field path rather than a thrown error from two layers down.
*/
const linkIds = z.array(id).max(100).optional();
/* ── encounter CRUD ───────────────────────────────────────────────── */
export const encounterCreateSchema = z
.object({
occurredAt: visitInstant,
status: encounterStatusEnum.optional().default("DONE"),
kind: encounterKindEnum.optional().default("OTHER"),
practitionerId: id.nullable().optional(),
/** Becomes `reasonEncrypted`. */
reason: z.string().max(2000).nullable().optional(),
/** Becomes `outcomeEncrypted`. */
outcome: z.string().max(4000).nullable().optional(),
/** The checkup this visit closes, when it was filed from a due one. */
reminderId: id.nullable().optional(),
documentIds: linkIds,
labResultIds: linkIds,
episodeIds: linkIds,
})
.strict();
export type EncounterCreate = z.infer<typeof encounterCreateSchema>;
/**
* Edit a visit. Every field optional; an omitted field is left untouched.
*
* A body naming nothing is a 422 rather than a silent success: a PATCH that
* changed nothing and answered 200 is indistinguishable from one that worked,
* which is how a client bug survives a release.
*/
export const encounterUpdateSchema = z
.object({
occurredAt: visitInstant.optional(),
status: encounterStatusEnum.optional(),
kind: encounterKindEnum.optional(),
practitionerId: id.nullable().optional(),
reason: z.string().max(2000).nullable().optional(),
outcome: z.string().max(4000).nullable().optional(),
reminderId: id.nullable().optional(),
documentIds: linkIds,
labResultIds: linkIds,
episodeIds: linkIds,
})
.strict()
.refine((body) => Object.keys(body).length > 0, {
message: "name at least one field to change",
});
export type EncounterUpdate = z.infer<typeof encounterUpdateSchema>;
/**
* List query.
*
* Windowed and bounded. The response splits past from upcoming server-side, so
* there is no `order` parameter: the client renders two lists rather than
* sorting one.
*/
export const encounterListQuerySchema = z
.object({
from: z.iso.datetime({ offset: true }).optional(),
to: z.iso.datetime({ offset: true }).optional(),
status: encounterStatusEnum.optional(),
practitionerId: id.optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
})
.strict()
.refine((q) => !(q.from && q.to) || q.from <= q.to, {
path: ["to"],
message: "to must be on or after from",
});
export type EncounterListQuery = z.infer<typeof encounterListQuerySchema>;
/* ── links ────────────────────────────────────────────────────────── */
export const encounterLinkTargetEnum = z.enum([
"document",
"labResult",
"conditionEpisode",
]);
export const encounterLinkSchema = z
.object({
targetKind: encounterLinkTargetEnum,
targetIds: z.array(id).min(1).max(100),
})
.strict();
export type EncounterLinkInput = z.infer<typeof encounterLinkSchema>;
+56
View File
@@ -0,0 +1,56 @@
/**
* Practitioner (address-book) request/response validation.
*
* Source of truth for the `/api/practitioners*` wire contract; the OpenAPI
* registry reuses these schemas. `userId` is NEVER a body field.
*
* `name` is the only required field, and it is plaintext rather than encrypted
* so the picker can search and sort it in SQL — the same tradeoff the document
* title makes, stated there too. `note` is the encrypted one.
*/
import { z } from "zod/v4";
export const practitionerCreateSchema = z
.object({
name: z.string().min(1).max(160),
/** Free text, not an enum: practice signage does not fit a closed list. */
specialty: z.string().max(120).nullable().optional(),
practice: z.string().max(160).nullable().optional(),
location: z.string().max(300).nullable().optional(),
phone: z.string().max(60).nullable().optional(),
/** Becomes `noteEncrypted`. */
note: z.string().max(2000).nullable().optional(),
})
.strict();
export type PractitionerCreate = z.infer<typeof practitionerCreateSchema>;
/**
* Edit a practitioner. A body naming nothing is a 422, for the same reason as
* the visit edit: a no-op that answers 200 hides a client defect.
*/
export const practitionerUpdateSchema = z
.object({
name: z.string().min(1).max(160).optional(),
specialty: z.string().max(120).nullable().optional(),
practice: z.string().max(160).nullable().optional(),
location: z.string().max(300).nullable().optional(),
phone: z.string().max(60).nullable().optional(),
note: z.string().max(2000).nullable().optional(),
})
.strict()
.refine((body) => Object.keys(body).length > 0, {
message: "name at least one field to change",
});
export type PractitionerUpdate = z.infer<typeof practitionerUpdateSchema>;
/** List query — a substring search over the plaintext name, bounded. */
export const practitionerListQuerySchema = z
.object({
q: z.string().min(1).max(160).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
})
.strict();
export type PractitionerListQuery = z.infer<typeof practitionerListQuerySchema>;