feat(visits): resolve where the window before a booked visit starts

The visit preparation and the doctor report offered for an appointment
started at the last visit of any kind. An internist one week and a
dermatologist the next gave the dermatologist a one-week window of
nothing it is about.

The list read now publishes `preparation` on every booked upcoming
visit: the first day of the window, the rule that chose it and the
earlier visit it is the day of. First match wins over the visits that
took place before it: the same practitioner, else a practitioner of
the same specialty (free text, compared without case or spacing), else
the same kind for routine, preventive and therapy visits, else the last
90 days. One query of past visits per page, independent of the list's
own filters. Null on every other row; absent on the detail and on
write responses.
This commit is contained in:
Marc-André Bombeck committed 2026-10-21 12:32:12 +02:00
1 parent 0dcafeeb70
commit 402cf1a35a
8 files changed
+781 -8

No files matched your search

+20 -8
View File
@@ -35,6 +35,7 @@ import {
} from "@/lib/validations/encounters";
import { encounterKindLabel } from "@/lib/encounters/kind-label";
import { toEncounterDTO, type EncounterListDTO } from "@/lib/encounters/dto";
import { loadVisitPreparations } from "@/lib/encounters/preparation-read";
import {
ENCOUNTER_INCLUDE,
applyEncounterLinks,
@@ -143,12 +144,17 @@ export const GET = apiHandler(async (request: NextRequest) => {
// them makes the first read zero and the second unfile everything on save.
// Three grouped queries for the page, not three per row.
const visible = await actingDomainVisibility(prisma, grantId);
const links = await loadEncounterLinksForMany(
prisma,
user.id,
[...upcoming, ...past].map((row) => row.id),
visible,
);
// The window before each booked visit reads the whole history, not this
// page of it: the visit it starts at may sit outside the caller's filter.
const [links, preparations] = await Promise.all([
loadEncounterLinksForMany(
prisma,
user.id,
[...upcoming, ...past].map((row) => row.id),
visible,
),
loadVisitPreparations(prisma, user.id, upcoming, now),
]);
annotate({
action: { name: "encounter.visit.list", entity_type: "encounter" },
@@ -156,8 +162,14 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const body: EncounterListDTO = {
upcoming: upcoming.map((row) => toEncounterDTO(row, links.get(row.id))),
past: past.map((row) => toEncounterDTO(row, links.get(row.id))),
upcoming: upcoming.map((row) => ({
...toEncounterDTO(row, links.get(row.id)),
preparation: preparations.get(row.id) ?? null,
})),
past: past.map((row) => ({
...toEncounterDTO(row, links.get(row.id)),
preparation: null,
})),
};
return apiListSuccess(body, combinedCap(upcomingCap, pastCap));
});
@@ -0,0 +1,177 @@
import { describe, expect, it } from "vitest";
import type { EncounterKind } from "@/generated/prisma/client";
import {
PREPARATION_DEFAULT_DAYS,
resolvePreparation,
specialtyKey,
type PreparationVisit,
} from "../preparation";
const TZ = "Europe/Berlin";
const TODAY = "2026-10-21";
function visit(
id: string,
occurredAt: string,
over: {
kind?: EncounterKind;
practitionerId?: string | null;
name?: string;
specialty?: string | null;
} = {},
): PreparationVisit {
const practitionerId =
over.practitionerId === undefined ? null : over.practitionerId;
return {
id,
occurredAt: new Date(occurredAt),
kind: over.kind ?? "OTHER",
practitionerId,
practitioner: practitionerId
? { name: over.name ?? practitionerId, specialty: over.specialty ?? null }
: null,
};
}
const internist = (id: string, at: string) =>
visit(id, at, {
kind: "SPECIALIST",
practitionerId: "p-int",
name: "Internal practice",
specialty: "Internal medicine",
});
// The report from the issue: an internist a week ago, a dermatologist next.
const next = visit("next", "2026-10-23T08:00:00.000Z", {
kind: "SPECIALIST",
practitionerId: "p-derm",
name: "Skin practice",
specialty: "Dermatology",
});
function resolve(target: PreparationVisit, done: PreparationVisit[]) {
return resolvePreparation({ next: target, done, tz: TZ, today: TODAY });
}
describe("the window before a booked visit", () => {
it("starts at the last visit with the same practitioner", () => {
const prep = resolve(next, [
internist("int", "2026-10-16T09:00:00.000Z"),
visit("derm", "2026-03-02T09:00:00.000Z", {
kind: "SPECIALIST",
practitionerId: "p-derm",
name: "Skin practice",
specialty: "Dermatology",
}),
]);
expect(prep).toEqual({
from: "2026-03-02",
basis: "practitioner",
since: {
id: "derm",
occurredAt: "2026-03-02T09:00:00.000Z",
kind: "SPECIALIST",
practitionerName: "Skin practice",
specialty: "Dermatology",
},
});
});
it("else at the last visit in the same specialty, compared without case", () => {
const prep = resolve(next, [
internist("int", "2026-10-16T09:00:00.000Z"),
visit("other-derm", "2025-11-20T09:00:00.000Z", {
kind: "SPECIALIST",
practitionerId: "p-derm-old",
name: "Former skin practice",
specialty: " dermatology ",
}),
]);
expect(prep.basis).toBe("specialty");
expect(prep.from).toBe("2025-11-20");
expect(prep.since?.id).toBe("other-derm");
expect(prep.since?.specialty).toBe("dermatology");
});
it("never falls back to the last visit of any kind", () => {
// The issue: one week of internist data offered for the dermatologist.
const prep = resolve(next, [internist("int", "2026-10-16T09:00:00.000Z")]);
expect(prep).toEqual({
from: "2026-07-23",
basis: "default",
since: null,
});
expect(PREPARATION_DEFAULT_DAYS).toBe(90);
});
it("matches on kind only for a kind that names one line of care", () => {
const therapy = visit("next-t", "2026-10-25T08:00:00.000Z", {
kind: "THERAPY",
});
const done = [
visit("acute", "2026-10-18T09:00:00.000Z", { kind: "ACUTE" }),
visit("t1", "2026-10-11T09:00:00.000Z", { kind: "THERAPY" }),
];
const prep = resolve(therapy, done);
expect(prep.basis).toBe("kind");
expect(prep.from).toBe("2026-10-11");
// A specialist visit with no specialty says nothing about which one.
const specialist = visit("next-s", "2026-10-25T08:00:00.000Z", {
kind: "SPECIALIST",
});
expect(
resolve(specialist, [
visit("s1", "2026-10-11T09:00:00.000Z", { kind: "SPECIALIST" }),
]).basis,
).toBe("default");
// Neither does "other", the kind nobody picked.
const other = visit("next-o", "2026-10-25T08:00:00.000Z");
expect(
resolve(other, [visit("o1", "2026-10-11T09:00:00.000Z")]).basis,
).toBe("default");
});
it("prefers the practitioner over a newer visit in the same specialty", () => {
const prep = resolve(next, [
visit("derm-b", "2026-09-01T09:00:00.000Z", {
kind: "SPECIALIST",
practitionerId: "p-derm-b",
specialty: "Dermatology",
}),
visit("derm-a", "2026-01-15T09:00:00.000Z", {
kind: "SPECIALIST",
practitionerId: "p-derm",
specialty: "Dermatology",
}),
]);
expect(prep.basis).toBe("practitioner");
expect(prep.since?.id).toBe("derm-a");
});
it("only counts visits before the booked one", () => {
const later = visit("later", "2026-10-24T09:00:00.000Z", {
practitionerId: "p-derm",
});
expect(resolve(next, [later]).basis).toBe("default");
});
it("starts on the matched visit's own day in the record's zone", () => {
// 23:30 UTC is the next calendar day in Berlin.
const prep = resolve(next, [
visit("late", "2026-05-04T23:30:00.000Z", { practitionerId: "p-derm" }),
]);
expect(prep.from).toBe("2026-05-05");
});
});
describe("specialty comparison", () => {
it("folds case and spacing, and nothing else", () => {
expect(specialtyKey(" Internal Medicine ")).toBe("internal medicine");
expect(specialtyKey("")).toBeNull();
expect(specialtyKey(" ")).toBeNull();
expect(specialtyKey(null)).toBeNull();
expect(specialtyKey("Dermatology")).not.toBe(specialtyKey("Skin doctor"));
});
});
+9
View File
@@ -21,6 +21,7 @@ import type {
MeasurementReminder,
Practitioner,
} from "@/generated/prisma/client";
import type { EncounterPreparationDTO } from "@/lib/encounters/preparation";
import type { RestoreSkipSummary } from "@/lib/export/restore-skips";
import {
toPractitionerDTO,
@@ -93,6 +94,14 @@ export interface EncounterDTO {
* at it again.
*/
skipped?: RestoreSkipSummary;
/**
* The window before a booked visit: the day the visit preparation and the
* doctor report offered for it start, the rule that chose it, and the
* earlier visit it is the day of (`src/lib/encounters/preparation.ts`).
*
* On the list read. Null on every row but a booked upcoming one.
*/
preparation?: EncounterPreparationDTO | null;
createdAt: string;
updatedAt: string;
}
+61
View File
@@ -0,0 +1,61 @@
/**
* The read behind `EncounterDTO.preparation`: one query of the record's past
* visits for every booked visit on the page, resolved by the rule in
* `preparation.ts`.
*/
import type { EncounterStatus, PrismaClient } from "@/generated/prisma/client";
import { userDayKey } from "@/lib/tz/format";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import {
resolvePreparation,
type EncounterPreparationDTO,
type PreparationVisit,
} from "./preparation";
/**
* How many past visits the rule looks through, newest first. Far more than a
* person files in years; a match older than the cap falls to the next rule,
* which on an account this busy is never the default.
*/
export const PREPARATION_HISTORY_CAP = 500;
type Booked = PreparationVisit & { status: EncounterStatus };
/** The window before each booked visit in `upcoming`, by visit id. */
export async function loadVisitPreparations(
db: Pick<PrismaClient, "encounter">,
recordId: string,
upcoming: readonly Booked[],
now: Date,
): Promise<Map<string, EncounterPreparationDTO>> {
const booked = upcoming.filter((visit) => visit.status === "PLANNED");
if (booked.length === 0) return new Map();
const [tz, done] = await Promise.all([
resolveUserTimezone(recordId),
db.encounter.findMany({
where: {
userId: recordId,
deletedAt: null,
status: "DONE",
occurredAt: { lte: now },
},
select: {
id: true,
occurredAt: true,
kind: true,
practitionerId: true,
practitioner: { select: { name: true, specialty: true } },
},
orderBy: [{ occurredAt: "desc" }, { id: "desc" }],
take: PREPARATION_HISTORY_CAP,
}),
]);
const today = userDayKey(now, tz);
return new Map(
booked.map((next) => [
next.id,
resolvePreparation({ next, done, tz, today }),
]),
);
}
+157
View File
@@ -0,0 +1,157 @@
/**
* Where the window before a booked visit starts, and why.
*
* The visit preparation ("what happened since the last visit") and the doctor
* report offered for an appointment both need a start date. It used to be the
* last visit of any kind: a person seeing an internist on one day and a
* dermatologist a week later was offered a one-week report for the
* dermatologist, covering nothing that visit is about.
*
* The rule, first match wins, over the visits that took place (DONE) before
* the booked one:
*
* 1. practitioner — the last visit with the same practitioner;
* 2. specialty — else the last visit with a practitioner of the same
* specialty (the free-text field, compared without case
* or extra spaces, so "Dermatology" and "dermatology "
* match and "Dermatology" and "Skin doctor" do not);
* 3. kind — else the last visit of the same kind, for the kinds that
* name one line of care (routine, preventive, therapy);
* 4. default — else the last {@link PREPARATION_DEFAULT_DAYS} days.
*
* The other kinds never match by kind alone. A specialist visit says nothing
* about which specialty (that is what rule 2 is for), "other" is the default
* nobody picked, and an acute visit, an emergency, a hospital stay or a
* procedure is an event rather than a recurring line of care, so the last one
* is no better a start than the default.
*
* The window starts on the matched visit's own day: a dose changed at that
* visit belongs to what the next one should know.
*
* Resolved on the server, published on the visit list, never recomputed by a
* client. A person can still change both dates on the report.
*
* Pure and client-safe; the read lives in `preparation-read.ts`.
*/
import type { EncounterKind } from "@/generated/prisma/client";
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
/** The window when no earlier visit matches the booked one. */
export const PREPARATION_DEFAULT_DAYS = 90;
/** The kinds a visit is matched on when neither practitioner nor specialty is. */
export const PREPARATION_KIND_MATCHES = [
"ROUTINE",
"PREVENTIVE",
"THERAPY",
] as const satisfies readonly EncounterKind[];
export const PREPARATION_BASES = [
"practitioner",
"specialty",
"kind",
"default",
] as const;
export type PreparationBasis = (typeof PREPARATION_BASES)[number];
/** The earlier visit the window starts at. */
export interface PreparationAnchorDTO {
id: string;
occurredAt: string;
kind: EncounterKind;
practitionerName: string | null;
specialty: string | null;
}
/** The window before one booked visit, resolved. */
export interface EncounterPreparationDTO {
/** First day of the window, `YYYY-MM-DD` on the record's own calendar. */
from: string;
/** Which rule chose `from`. */
basis: PreparationBasis;
/** The visit `from` is the day of; null on `default`. */
since: PreparationAnchorDTO | null;
}
/** The fields the rule reads, off a booked visit or an earlier one. */
export interface PreparationVisit {
id: string;
occurredAt: Date;
kind: EncounterKind;
practitionerId: string | null;
practitioner: { name: string; specialty: string | null } | null;
}
/** A specialty as compared: no case, no outer or doubled spaces. */
export function specialtyKey(value: string | null | undefined): string | null {
const key = value
?.normalize("NFKC")
.trim()
.replace(/\s+/g, " ")
.toLocaleLowerCase();
return key ? key : null;
}
/**
* The window before `next`.
*
* `done` is the record's visits that took place, newest first. Only those
* before `next` are considered; `today` (the record's local day) anchors the
* default window.
*/
export function resolvePreparation(args: {
next: PreparationVisit;
done: readonly PreparationVisit[];
tz: string;
today: string;
}): EncounterPreparationDTO {
const { next, tz, today } = args;
const earlier = args.done.filter(
(visit) =>
visit.id !== next.id &&
visit.occurredAt.getTime() < next.occurredAt.getTime(),
);
const specialty = specialtyKey(next.practitioner?.specialty);
const kindMatches = (
PREPARATION_KIND_MATCHES as readonly EncounterKind[]
).includes(next.kind);
const rules: Array<[PreparationBasis, (visit: PreparationVisit) => boolean]> =
[
[
"practitioner",
(visit) =>
next.practitionerId !== null &&
visit.practitionerId === next.practitionerId,
],
[
"specialty",
(visit) =>
specialty !== null &&
specialtyKey(visit.practitioner?.specialty) === specialty,
],
["kind", (visit) => kindMatches && visit.kind === next.kind],
];
for (const [basis, matches] of rules) {
const hit = earlier.find(matches);
if (!hit) continue;
return {
from: userDayKey(hit.occurredAt, tz),
basis,
since: {
id: hit.id,
occurredAt: hit.occurredAt.toISOString(),
kind: hit.kind,
practitionerName: hit.practitioner?.name ?? null,
specialty: hit.practitioner?.specialty?.trim() || null,
},
};
}
return {
from: shiftDateKey(today, -PREPARATION_DEFAULT_DAYS),
basis: "default",
since: null,
};
}
+41
View File
@@ -35,6 +35,7 @@ import {
practitionerListQuerySchema,
} from "@/lib/validations/practitioners";
import { bodySiteQuerySchema } from "@/lib/validations/body-sites";
import { PREPARATION_BASES } from "@/lib/encounters/preparation";
import {
illnessLifecycleEnum,
illnessTypeEnum,
@@ -169,6 +170,40 @@ const skipReport = z
"What the write could not do, named. `links: 0` with an empty list is the ordinary answer. Anything else is a side effect the caller's grant did not reach — today only `checkupClosure`, the closing of a preventive-care checkup, which is a measurements-domain write a health-background delegate cannot perform. The visit still saves; the checkup stays due and the response says so, because somebody who believes a checkup was closed will not look at it again.",
});
const preparationAnchor = z
.object({
id: z.string(),
occurredAt: z.string(),
kind: encounterKindEnum,
practitionerName: z.string().nullable(),
specialty: z.string().nullable(),
})
.meta({
id: "EncounterPreparationAnchor",
description:
"The earlier visit the window starts at: its id, instant and kind, and the practitioner's name and specialty as they read now.",
});
const encounterPreparation = z
.object({
from: z
.string()
.describe(
"First day of the window, `YYYY-MM-DD` on the record's own calendar: the day of `since`, or 90 days before today on `default`.",
),
basis: z
.enum(PREPARATION_BASES)
.describe(
"The rule that chose `from`, first match wins over the visits that took place (DONE) before this one: `practitioner` (the last visit with the same practitioner), `specialty` (the last visit with a practitioner of the same specialty, compared without case or extra spaces), `kind` (the last visit of the same kind, for ROUTINE, PREVENTIVE and THERAPY only), `default` (none matched: the last 90 days).",
),
since: preparationAnchor.nullable(),
})
.meta({
id: "EncounterPreparation",
description:
"The window before a booked visit, resolved server-side: where the visit preparation and the doctor report offered for the appointment start, and why there. Never the last visit of any kind, which is how a dermatology appointment was offered a week of data from an internist visit. A client shows `from` with its reason and lets the person change the dates; it does not recompute the rule.",
});
const encounter = z
.object({
id: z.string(),
@@ -183,6 +218,12 @@ const encounter = z
reminderNextDueAt: z.string().nullable(),
links: encounterLinks.optional(),
skipped: skipReport.optional(),
preparation: encounterPreparation
.nullable()
.optional()
.describe(
"On the list read only (`GET /api/encounters`): the window before this visit when it is booked (PLANNED, upcoming), null on every other row. Absent on the detail and on write responses.",
),
createdAt: z.string(),
updatedAt: z.string(),
})