Merge remote-tracking branch 'origin/main' into feat/mood-prognosis

This commit is contained in:
Marc-André Bombeck committed 2026-08-08 13:00:02 +02:00
commit 8d48e3e262
73 files changed
+8916 -285

No files matched your search

@@ -0,0 +1,249 @@
/**
* A booked visit's reminder appears on no preventive-care surface.
*
* A planned encounter mints one `MeasurementReminder` with `origin:
* ENCOUNTER`, because an appointment is a reminder with a date and a second
* engine would be a second cron, a second queue and a second set of
* preferences. The cost of that decision is this: every READ that means "the
* checkups this person keeps" now has to say so, or the checkup list fills up
* with appointments.
*
* The research that proposed the feature called this "a one-line `where`". It
* is four, and the fourth is in a different subsystem, which is exactly why it
* is worth a guard rather than a comment.
*
* Two halves, deliberately:
*
* 1. **By source text** — each of the four read sites contains an origin
* exclusion. Whitespace-tolerant, and it ASSERTS A NON-ZERO MATCH COUNT.
* A matcher that matches nothing is green for the wrong reason; the
* Bearer-scope guard in this directory stayed blind for months because
* its regex demanded a literal a two-line call never produced, and it
* passed by finding nothing rather than by finding everything.
* 2. **By behaviour** — the DTO mapper refuses an `ENCOUNTER` row. Source
* text cannot tell a filter that runs from one that is written, and the
* refusal is what turns a lost filter into a loud failure instead of an
* appointment relabelled as a checkup.
*
* What this file does NOT prove: that the four queries run. That is what the
* mapper's throw is for, and what an integration test against real rows would
* add. Written down so the limit is visible rather than assumed away.
*/
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { toMeasurementReminderDto } from "@/lib/measurement-reminders/dto";
import type { MeasurementReminder } from "@/generated/prisma/client";
const REPO_ROOT = resolve(__dirname, "../..");
function read(relativePath: string): string {
return readFileSync(resolve(REPO_ROOT, relativePath), "utf8");
}
/**
* Every read that answers "what preventive care is due", and what each one
* feeds. Named rather than discovered: a discovery sweep would have to guess
* which reminder reads are Vorsorge surfaces and which are the engine itself,
* and the engine's two reads must NOT carry the exclusion — firing the
* appointment and satisfying it is the whole point of the row.
*/
const VORSORGE_READ_SITES: ReadonlyArray<{ file: string; surface: string }> = [
{
file: "src/app/api/measurement-reminders/route.ts",
surface: "the reminder list the checkups page renders",
},
{
file: "src/lib/daily/load-digest.ts",
surface: "the daily digest's due list",
},
{
file: "src/lib/insights/feature-blocks.ts",
surface: "the insights preventive-care block",
},
{
file: "src/lib/mcp/tools.ts",
surface: "the MCP get_preventive_care tool",
},
];
/**
* `origin: { not: "ENCOUNTER" }`, tolerant of any formatting Prettier might
* choose — line breaks between the key and the object, single or double
* quotes, a trailing comma.
*/
const EXCLUSION = /origin\s*:\s*\{\s*not\s*:\s*["']ENCOUNTER["']\s*,?\s*\}/g;
function reminderRow(
origin: MeasurementReminder["origin"],
): MeasurementReminder {
const at = new Date("2026-07-01T09:00:00.000Z");
return {
id: "reminder-1",
userId: "user-1",
label: "Dr. Example",
measurementType: null,
intervalDays: null,
rrule: null,
anchorDate: at,
endsOn: null,
origin,
notifyHour: 9,
location: null,
nextDueAt: at,
lastSatisfiedAt: null,
enabled: true,
createdAt: at,
updatedAt: at,
deletedAt: null,
};
}
/**
* The BY-ID family: the published measurement-reminder surface.
*
* The list reads above answer "what preventive care is due". These answer
* "this reminder", by id, and they were the larger hole. An appointment row is
* not addressable here at all — it belongs to a visit, is managed through the
* visit routes, and is classified under a different sharing domain — so each
* of these treats one as not found rather than filtering it out of a list.
*
* What reaching them actually cost, before the fix:
*
* - `complete` and `satisfy` committed the mutation and THEN threw in the
* DTO mapper, answering 500 after the write had already landed. `complete`
* is the documented flow behind the iOS notification's Done button, so
* every appointment push a person acknowledged ended in an error.
* - `PATCH` could give a one-shot a cadence, turning a spent appointment
* into an eternal re-nag that appears in no list, or flip `enabled` back
* on for a cancelled one.
* - `DELETE` hard-deletes, so a delegate holding only the measurements
* domain could destroy a reminder belonging to a visit in the profile
* domain — a cross-domain reach the sharing model refuses everywhere else.
*
* The count per file is part of the expectation: three of these live in one
* module, and a matcher that only asked "does this file mention the exclusion"
* would stay green after two of the three lost it.
*/
const BY_ID_SITES: ReadonlyArray<{
file: string;
sites: number;
surface: string;
}> = [
{
file: "src/app/api/measurement-reminders/[id]/route.ts",
sites: 3,
surface: "the by-id read, edit and delete verbs",
},
{
file: "src/app/api/measurement-reminders/[id]/complete/route.ts",
sites: 1,
surface:
"the explicit complete action behind the notification's Done button",
},
{
file: "src/app/api/measurement-reminders/[id]/satisfy/route.ts",
sites: 1,
surface: "the manual satisfy action",
},
{
file: "src/lib/telegram-webhook-handlers.ts",
sites: 2,
surface: "the chat buttons that mark a reminder done or postpone it",
},
];
describe("an appointment reminder is not addressable by id", () => {
it("names a by-id set that is not empty (no vacuous pass)", () => {
expect(BY_ID_SITES.length).toBe(4);
expect(BY_ID_SITES.reduce((total, entry) => total + entry.sites, 0)).toBe(
7,
);
});
for (const { file, sites, surface } of BY_ID_SITES) {
it(`refuses an ENCOUNTER row on ${surface}`, () => {
const matches = read(file).match(EXCLUSION) ?? [];
expect(
matches.length,
`${file} owns ${sites} by-id lookup(s) for ${surface}; ` +
`${matches.length} of them exclude ENCOUNTER-origin rows. An ` +
"appointment reminder reaching this family commits a write it should " +
"have refused, or 500s after committing one.",
).toBe(sites);
});
}
});
describe("appointment reminders are excluded from every Vorsorge read", () => {
it("names a read set that is not empty (no vacuous pass)", () => {
expect(VORSORGE_READ_SITES.length).toBe(4);
});
for (const { file, surface } of VORSORGE_READ_SITES) {
it(`excludes ENCOUNTER rows from ${surface}`, () => {
const source = read(file);
const matches = source.match(EXCLUSION) ?? [];
expect(
matches.length,
`${file} feeds ${surface} and no longer excludes ENCOUNTER-origin ` +
"rows, so a booked appointment will surface there as a checkup",
).toBeGreaterThan(0);
});
}
it("leaves the engine's own reads alone", () => {
// The cron fires these rows and the satisfy primitive resolves them. An
// exclusion in either would mean a booked appointment that never nudges,
// which is the opposite failure and just as silent.
for (const file of [
"src/lib/jobs/measurement-reminder.ts",
"src/lib/measurement-reminders/satisfy.ts",
]) {
const matches = read(file).match(EXCLUSION) ?? [];
expect(
matches.length,
`${file} is the engine, not a Vorsorge surface — excluding ENCOUNTER ` +
"rows here would stop appointments firing at all",
).toBe(0);
}
});
it("the Coach dedup read needs nothing, because it is already narrow", () => {
// It filters to `origin: "COACH"`, so an ENCOUNTER row cannot reach it.
// Asserted rather than assumed: if that narrowing ever widened, this file
// is where the consequence should surface.
expect(read("src/lib/ai/coach/suggest-gate.ts")).toMatch(
/origin\s*:\s*["']COACH["']/,
);
});
});
describe("the reminder DTO refuses an appointment row", () => {
it("maps a VORSORGE row normally", () => {
expect(toMeasurementReminderDto(reminderRow("VORSORGE")).origin).toBe(
"VORSORGE",
);
});
it("maps a COACH row normally", () => {
expect(toMeasurementReminderDto(reminderRow("COACH")).origin).toBe("COACH");
});
it("throws on an ENCOUNTER row rather than relabelling it", () => {
// The invariant: every query feeding this mapper excludes them, so one
// arriving means a read site lost its filter. Failing loudly is the only
// honest answer — the alternative is an appointment shown as a checkup.
expect(() => toMeasurementReminderDto(reminderRow("ENCOUNTER"))).toThrow(
/ENCOUNTER-origin reminder/,
);
});
it("names the guard file in the message, so the next reader finds the proof", () => {
expect(() => toMeasurementReminderDto(reminderRow("ENCOUNTER"))).toThrow(
/encounter-reminder-exclusion/,
);
});
});
+54 -5
View File
@@ -931,6 +931,22 @@ const DELEGABLE_ROUTES: Record<string, DelegableEntry> = {
domain: "measurements",
why: "One nutrient's daily series over the record, scoped by the resolved user id.",
},
"app/api/encounters/route.ts": {
domain: "profile",
why: "The record's visits — what happened at a practice and what is booked. Record content in the same sense as the allergies and family history already under this domain: it names no credential, no integration and no notification channel. Carries the honest cost of that classification, which is that a delegate granted `profile` for allergies also sees the visit list; the consent copy names visits for exactly this reason. The create arm is a delegable write.",
},
"app/api/encounters/[id]/route.ts": {
domain: "profile",
why: "One visit of the record, fetch-then-guard against the resolved user. The links it resolves are read through the link service, which narrows both ends to the same resolved id.",
},
"app/api/practitioners/route.ts": {
domain: "profile",
why: "The record's own address book of doctors and practices. Record content, not account configuration — it touches no credential, no integration and no notification channel, which is the fence the classification turns on. The create arm is a delegable write.",
},
"app/api/practitioners/[id]/route.ts": {
domain: "profile",
why: "One practitioner of the record, fetch-then-guard against the resolved user.",
},
"app/api/illness/episodes/route.ts": {
domain: "illness",
why: "The record's illness episodes. Module-gated on the record on both arms, so a delegate gets the surface only where the owner switched it on; the create arm is a delegable write.",
@@ -1116,6 +1132,14 @@ const DELEGABLE_ROUTES: Record<string, DelegableEntry> = {
domain: "illness",
why: "Reopening a deleted episode with its day logs intact. Reached only through this module's MANAGE arm; the argument for admitting it is the manage literal's reason line, and the entry here is what leg (a) freezes and leg (f) checks the section against.",
},
"app/api/encounters/[id]/restore/route.ts": {
domain: "profile",
why: "Reopening a deleted visit with its links intact. Reached only through this module's MANAGE arm; the argument for admitting it is the manage literal's reason line, and the entry here is what leg (a) freezes and leg (f) checks the section against.",
},
"app/api/practitioners/[id]/restore/route.ts": {
domain: "profile",
why: "Reopening a deleted address-book entry. Reached only through this module's MANAGE arm; the argument for admitting it is the manage literal's reason line, and the entry here is what leg (a) freezes and leg (f) checks the section against.",
},
"app/api/mood-entries/bulk-delete/route.ts": {
domain: "mind",
why: "Tombstoning a selection. Reached only through this module's MANAGE arm; the argument for admitting it is the manage literal's reason line, and the entry here is what leg (a) freezes and leg (f) checks the section against.",
@@ -1355,6 +1379,10 @@ const DELEGABLE_WRITE_ROUTES: Record<string, string> = {
"Adding an analyte to the record's catalogue. A name the record already tracks is the ordinary 409 from the same `(userId, name)` uniqueness the owner would hit themselves.",
"app/api/illness/episodes/route.ts":
"Opening an illness episode. The module gate runs against the RECORD before the write, so a delegate cannot create an episode inside a record whose owner switched the module off.",
"app/api/encounters/route.ts":
"Filing a visit, or booking one. Every id the body may carry — the practitioner, the checkup it closes, the three link arrays — is re-narrowed to the resolved record before anything is written, so a delegate cannot attach one record's document to another's visit. Booking mints the appointment reminder under the RECORD, which is correct: it is the owner's appointment and the owner's channels that should be nudged about it.",
"app/api/practitioners/route.ts":
"Adding a doctor or practice to the record's address book. Nothing is unique across accounts here by design, so a delegate adding a practice the owner already has produces a second row rather than a collision with somebody else's namespace.",
"app/api/medications/[id]/side-effects/route.ts":
"Recording a side effect. Admitted on one condition, met at the call site: the POST rate bucket keys on the ACTOR, so a delegate burns their own allowance rather than the owner's and cannot collect a fresh one by switching records.",
"app/api/medications/route.ts":
@@ -1461,6 +1489,26 @@ const DELEGABLE_MANAGE_ROUTES: Record<string, ManageEntry> = {
conditions: ["C4"],
why: "Editing and deleting an episode; the delete soft-deletes. C4 on the edit.",
},
"app/api/encounters/[id]/route.ts": {
domain: "profile",
conditions: ["C4"],
why: "Editing and deleting a visit; the delete soft-deletes and retires the visit's own appointment reminder with it, never a checkup the visit closed. C4 on the edit: the date, the status, the kind and the practitioner are filed before and after, and the encrypted reason and outcome deliberately are not.",
},
"app/api/encounters/[id]/restore/route.ts": {
domain: "profile",
conditions: [],
why: "Reopening a deleted visit with its links intact.",
},
"app/api/practitioners/[id]/route.ts": {
domain: "profile",
conditions: ["C4"],
why: "Correcting and removing one address-book entry; the delete soft-deletes and leaves every visit that named it, because the reference nulls rather than cascades. C4 on the edit, over the plaintext fields only.",
},
"app/api/practitioners/[id]/restore/route.ts": {
domain: "profile",
conditions: [],
why: "Reopening a deleted address-book entry. It does not re-attach the visits whose reference was nulled, because which visits meant this practice is not recoverable.",
},
"app/api/illness/episodes/[id]/resolve/route.ts": {
domain: "illness",
conditions: [],
@@ -1816,11 +1864,12 @@ const ACTOR_ROUTES: Record<string, string> = {
* managed-record configuration adds one more: 196 → 197. The bounded
* read-only profile summary makes the next explicit admission: 197 → 198.
* The two initial Cycle reads follow as separate, scoped admissions: 198 → 200.
* The mood day's linked figures, read-only, add one: 200 → 201. The mood
* prognosis, read-only and admitted on the whole record for the same reason,
* adds one: 201 → 202.
* The mood day's linked figures, read-only, add one: 200 → 201. The visit
* record and its address book bring twelve: 201 → 213. The mood prognosis,
* read-only and admitted on the whole record for the same reason as the linked
* figures, adds one: 213 → 214.
*/
const FROZEN_ENTRY_COUNT = 202;
const FROZEN_ENTRY_COUNT = 214;
/**
* The two surfaces that authenticate a Bearer token outside `requireAuth` —
@@ -2581,7 +2630,7 @@ describe("(g) the MANAGE route set is frozen", () => {
it("keeps the admitted mutation inventory complete and discoverable", () => {
expect(ADMITTED_MUTATING_HANDLERS.length).toBeGreaterThan(0);
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(62);
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(70);
const expected = ADMITTED_MUTATING_HANDLERS.map(
({ handlerModule, action, level }) =>
@@ -26,7 +26,7 @@ describe("sharing and handler inventories", () => {
});
it("keeps every admitted mutation uniquely addressable and fully controlled", () => {
expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(62);
expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(70);
expect(
new Set(
ADMITTED_MUTATING_HANDLERS.map(
@@ -282,6 +282,14 @@ function sourceClient() {
},
]),
},
// The visit tables. Empty here: this file asserts the sections it seeds,
// and an account with no visits is the ordinary case the builder must
// still answer for.
practitioner: { findMany: vi.fn().mockResolvedValue([]) },
encounter: { findMany: vi.fn().mockResolvedValue([]) },
encounterDocumentLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterLabLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterConditionLink: { findMany: vi.fn().mockResolvedValue([]) },
customMetric: {
findMany: vi.fn().mockResolvedValue([
{
@@ -48,6 +48,7 @@ import {
import { restoreProfileData } from "@/lib/export/profile-backup";
import { restoreIntradayProfileData } from "@/lib/export/intraday-profile-backup";
import { restoreHealthScoreData } from "@/lib/export/health-score-backup";
import { restoreVisitsData } from "@/lib/export/visits-backup";
import { invalidateUserData } from "@/lib/cache/invalidate";
export const dynamic = "force-dynamic";
@@ -88,6 +89,9 @@ interface RestoreResponse {
correlationPatterns: number;
intradayProfiles: number;
healthScoreRecords: number;
practitioners: number;
encounters: number;
encounterLinks: number;
};
}
@@ -1315,6 +1319,19 @@ const handler = apiHandler(
});
}
// Visits, the address book and the three link tables. Last on
// purpose: a link is written only when both of its ends exist, and
// the documents above are the final far side to land. Both ends of
// this section live in `src/lib/export/visits-backup.ts`, so a grep
// of THIS file alone will not find them — the same delegation as the
// cycle, profile, intraday and score restores above.
const visitsCleared = await restoreVisitsData(
tx,
ownerId,
payload,
skips,
);
const cleared = {
measurements: measurements.count,
medications: meds.count,
@@ -1341,6 +1358,9 @@ const handler = apiHandler(
correlationPatterns: profileCleared.correlationPatterns,
intradayProfiles: intradayCleared.intradayProfiles,
healthScoreRecords: healthScoreCleared.healthScoreRecords,
practitioners: visitsCleared.practitioners,
encounters: visitsCleared.encounters,
encounterLinks: visitsCleared.encounterLinks,
};
return { cleared, skipped: summarizeRestoreSkips(skips) };
},
@@ -14,6 +14,7 @@ vi.mock("@/lib/db", () => ({
prisma: {
inboundDocument: {
findFirst: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
findFirstOrThrow: vi.fn(),
},
@@ -131,6 +132,11 @@ beforeEach(() => {
vi.mocked(prisma.documentConditionLink.findMany).mockResolvedValue(
[] as never,
);
// The link service re-narrows both ends before it writes: the document it is
// filing, and the episodes it is filing against.
vi.mocked(prisma.inboundDocument.findMany).mockResolvedValue([
{ id: "doc-1" },
] as never);
vi.mocked(prisma.documentConditionLink.deleteMany).mockResolvedValue({
count: 0,
} as never);
@@ -14,16 +14,27 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
process.env.ENCRYPTION_KEY =
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const { txQueryRaw, txCreate, txCreateMany } = vi.hoisted(() => ({
const {
txQueryRaw,
txCreate,
txCreateMany,
txDocumentFindMany,
txEpisodeFindMany,
} = vi.hoisted(() => ({
txQueryRaw: vi.fn(),
txCreate: vi.fn(),
txCreateMany: vi.fn(),
// The link service re-narrows BOTH ends inside the transaction before it
// writes, so the transaction double has to answer for them.
txDocumentFindMany: vi.fn(),
txEpisodeFindMany: vi.fn(),
}));
vi.mock("@/lib/db", () => {
const tx = {
$queryRaw: txQueryRaw,
inboundDocument: { create: txCreate },
inboundDocument: { create: txCreate, findMany: txDocumentFindMany },
illnessEpisode: { findMany: txEpisodeFindMany },
documentConditionLink: { createMany: txCreateMany },
};
return {
@@ -186,6 +197,8 @@ beforeEach(() => {
txQueryRaw.mockResolvedValue([{ used: BigInt(0) }]);
txCreate.mockResolvedValue(docRow() as never);
txCreateMany.mockResolvedValue({ count: 0 } as never);
txDocumentFindMany.mockResolvedValue([{ id: "doc-1" }] as never);
txEpisodeFindMany.mockResolvedValue([] as never);
});
describe("POST /api/documents/inbound (vault upload)", () => {
@@ -294,10 +307,14 @@ describe("POST /api/documents/inbound (vault upload)", () => {
vi.mocked(prisma.illnessEpisode.findMany).mockResolvedValue([
{ id: "ep-1" },
] as never);
txEpisodeFindMany.mockResolvedValue([{ id: "ep-1" }] as never);
let res = await post(mkUpload({ episodeIds: ["ep-1"] }));
expect(res.status).toBe(201);
expect(txCreateMany).toHaveBeenCalledWith({
data: [{ documentId: "doc-1", episodeId: "ep-1", userId: "user-1" }],
// The link service is idempotent by construction, so a retried upload
// that reaches the same pair succeeds instead of hitting the unique index.
skipDuplicates: true,
});
// Foreign/unknown episode id → 404-shaped refusal, nothing persisted.
@@ -433,12 +450,13 @@ describe("GET /api/documents/inbound (list)", () => {
{ documentId: "d2", status: "APPROVED", _count: { _all: 1 } },
{ documentId: "d2", status: "REJECTED", _count: { _all: 3 } },
] as never);
// The link read resolves labels in a second query rather than through a
// relation join, so both halves are mocked.
vi.mocked(prisma.documentConditionLink.findMany).mockResolvedValue([
{
documentId: "d1",
episodeId: "ep-1",
episode: { label: "Knie" },
},
{ documentId: "d1", episodeId: "ep-1" },
] as never);
vi.mocked(prisma.illnessEpisode.findMany).mockResolvedValue([
{ id: "ep-1", label: "Knie", onsetAt: new Date("2026-06-01T00:00:00Z") },
] as never);
const res = await get(
+13 -5
View File
@@ -20,6 +20,7 @@ import {
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { linkTargets, unlinkTargets } from "@/lib/links";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { isP2002 } from "@/lib/prisma-errors";
@@ -116,15 +117,22 @@ export const POST = apiHandler(async (request: NextRequest) => {
results.push({ id, ok: false, error: "notFound" });
continue;
}
await prisma.documentConditionLink.createMany({
data: [{ documentId: id, episodeId: episodeId!, userId: user.id }],
skipDuplicates: true,
await linkTargets(prisma, {
userId: user.id,
sourceKind: "document",
sourceId: id,
targetKind: "conditionEpisode",
targetIds: [episodeId!],
});
break;
}
case "unlinkEpisode": {
await prisma.documentConditionLink.deleteMany({
where: { documentId: id, episodeId: episodeId!, userId: user.id },
await unlinkTargets(prisma, {
userId: user.id,
sourceKind: "document",
sourceId: id,
targetKind: "conditionEpisode",
targetIds: [episodeId!],
});
break;
}
+7 -6
View File
@@ -56,6 +56,7 @@ import {
} from "@/lib/documents/upload-policy";
import { withIdempotency } from "@/lib/idempotency";
import { BodyTooLargeError, readBoundedBody } from "@/lib/labs/ocr-upload";
import { linkTargets } from "@/lib/links";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { isP2002 } from "@/lib/prisma-errors";
@@ -337,12 +338,12 @@ async function processUpload(
});
if (episodeIds.length > 0) {
await tx.documentConditionLink.createMany({
data: episodeIds.map((episodeId) => ({
documentId: created.id,
episodeId,
userId: user.id,
})),
await linkTargets(tx, {
userId: user.id,
sourceKind: "document",
sourceId: created.id,
targetKind: "conditionEpisode",
targetIds: episodeIds,
});
}
return created;
+7 -7
View File
@@ -15,6 +15,7 @@ import {
resolveDocumentLimits,
} from "@/lib/documents/upload-policy";
import { resolveOcrCapability } from "@/lib/labs/ocr-capability";
import { listDistinctTargets } from "@/lib/links";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import type { DocumentUsageDto } from "@/lib/validations/inbound-documents";
@@ -50,11 +51,10 @@ export const GET = apiHandler(async () => {
// bar's condition chips. Sourced here (not from the loaded corpus) so
// a chip exists even when its documents sit pages deep in the
// timeline; one indexed grouped query, no blobs.
prisma.documentConditionLink.findMany({
where: { userId: user.id, document: { deletedAt: null } },
select: { episodeId: true, episode: { select: { label: true } } },
distinct: ["episodeId"],
orderBy: { episodeId: "asc" },
listDistinctTargets(prisma, {
userId: user.id,
sourceKind: "document",
targetKind: "conditionEpisode",
}),
// Whether an AI action can run for this caller (assist + indexing share
// the same provider precondition). Honest availability so the UI never
@@ -85,8 +85,8 @@ export const GET = apiHandler(async () => {
maxFileBytes: limits.maxFileBytes,
acceptedExtensions: [...DOCUMENT_ACCEPTED_EXTENSIONS],
linkedEpisodes: linkRows.map((row) => ({
episodeId: row.episodeId,
name: row.episode.label,
episodeId: row.id,
name: row.label,
})),
assistAvailable: capability.available,
contentIndex: {
+100
View File
@@ -0,0 +1,100 @@
/**
* `POST /api/encounters/{id}/links` — file things against a visit.
* `DELETE /api/encounters/{id}/links` — unfile them.
*
* Deliberately bare `requireAuth()` rather than a delegable declaration, and
* the reason is consistency rather than oversight: document link and unlink are
* not delegable today — only the vault reads are — and an encounter link is the
* same verb one layer up. Making one delegable and not the other would mean two
* answers to the same question. The pair is revisited as one decision when the
* polymorphic-linking work lands.
*
* Both verbs are idempotent, both are capped, and neither ever blocks a save:
* an id that names nothing this account owns comes back in `unknown` rather
* than failing the request, because a visit must never be un-saveable because
* one document it pointed at has since been deleted.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import {
apiSuccess,
apiError,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { encounterLinkSchema } from "@/lib/validations/encounters";
import { linkTargets, unlinkTargets } from "@/lib/links";
import {
actingDomainVisibility,
loadEncounterLinks,
} from "@/lib/encounters/service";
type RouteParams = { params: Promise<{ id: string }> };
async function handle(
request: NextRequest,
{ params }: RouteParams,
verb: "link" | "unlink",
): Promise<Response> {
const { user } = await requireAuth();
const { id } = await params;
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = encounterLinkSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "encounter.link.invalid",
});
}
const apply = verb === "link" ? linkTargets : unlinkTargets;
const result = await apply(prisma, {
userId: user.id,
sourceKind: "encounter",
sourceId: id,
targetKind: parsed.data.targetKind,
targetIds: parsed.data.targetIds,
});
if (result.unknownSource) {
return apiError("Visit not found", 404);
}
annotate({
action: {
name: `encounter.link.${verb}`,
entity_type: "encounter",
entity_id: id,
},
meta: {
target_kind: parsed.data.targetKind,
changed: result.changed,
unknown: result.unknownTargetIds.length,
},
});
// Bare `requireAuth()` resolves the caller's OWN record — this route is
// not delegable — so there is no narrowed grant to honour and every
// domain is the caller's own.
const visible = await actingDomainVisibility(prisma, null);
const links = await loadEncounterLinks(prisma, user.id, id, visible);
return apiSuccess({ links, unknown: result.unknownTargetIds });
}
export const POST = apiHandler(
async (request: NextRequest, context: RouteParams) =>
handle(request, context, "link"),
);
export const DELETE = apiHandler(
async (request: NextRequest, context: RouteParams) =>
handle(request, context, "unlink"),
);
@@ -0,0 +1,105 @@
/**
* `POST /api/encounters/{id}/restore` — clear a visit's tombstone.
*
* MANAGE rather than WRITE: undoing a deletion is a management act when the
* manager is the one who holds delete.
*
* The link rows survived the soft delete — they cascade only on a hard one —
* so a restored visit comes back with its documents, labs and conditions still
* filed against it. Its appointment reminder comes back too, but only if the
* appointment is still in the future: restoring a visit whose date has passed
* must not produce a nudge for something that already did or did not happen.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
import { encounterKindLabel } from "@/lib/encounters/kind-label";
import { toEncounterDTO } from "@/lib/encounters/dto";
import {
ENCOUNTER_INCLUDE,
actingDomainVisibility,
loadEncounterLinks,
resolveOwnerNotificationContext,
shouldHaveReminder,
} from "@/lib/encounters/service";
import { reanchorAppointmentReminder } from "@/lib/encounters/appointment-reminder";
type RouteParams = { params: Promise<{ id: string }> };
export const POST = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user, grantId } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.encounter.findUnique({
where: { id },
include: { practitioner: true },
});
if (!existing || existing.userId !== user.id) {
return apiError("Visit not found", 404);
}
if (existing.deletedAt !== null) {
const { timezone, locale } = await resolveOwnerNotificationContext(
user.id,
);
const now = new Date();
await prisma.$transaction(async (tx) => {
await tx.encounter.update({
where: { id },
data: { deletedAt: null },
});
if (
existing.reminderId &&
shouldHaveReminder(existing.status, existing.occurredAt, now)
) {
const reminder = await tx.measurementReminder.findUnique({
where: { id: existing.reminderId },
select: { id: true, origin: true },
});
if (reminder?.origin === "ENCOUNTER") {
await reanchorAppointmentReminder(
tx,
reminder.id,
{
userId: user.id,
occurredAt: existing.occurredAt,
practitionerName: existing.practitioner?.name ?? null,
practitionerLocation: existing.practitioner?.location ?? null,
kindLabel: encounterKindLabel(existing.kind, locale),
},
timezone,
);
}
}
});
}
const row = await prisma.encounter.findUniqueOrThrow({
where: { id },
include: ENCOUNTER_INCLUDE,
});
const visible = await actingDomainVisibility(prisma, grantId);
const links = await loadEncounterLinks(prisma, user.id, id, visible);
await auditLog("encounter.visit.restore", {
userId: user.id,
ipAddress: getClientIp(request),
details: { encounterId: id, occurredAt: row.occurredAt.toISOString() },
});
annotate({
action: {
name: "encounter.visit.restore",
entity_type: "encounter",
entity_id: id,
},
});
return apiSuccess(toEncounterDTO(row, links));
},
);
+405
View File
@@ -0,0 +1,405 @@
/**
* `GET /api/encounters/{id}` — one owned, live visit with its links resolved.
* `PATCH /api/encounters/{id}` — edit it (partial; field-by-field).
* `DELETE /api/encounters/{id}` — soft-delete it, and retire its appointment
* reminder with it.
*
* Owner-scoped by fetch-then-guard. `userId` is narrowed from auth; the body
* never carries it.
*
* The status transitions are where the appointment arm lives. Moving a visit to
* DONE closes the checkup it was filed against — on the transition, so re-saving
* a completed visit does not push that checkup's next due date out again.
* Moving it to CANCELLED or NO_SHOW stops its reminder without deleting the
* row, so the history stays honest. Moving its date re-anchors the reminder it
* already owns and never mints a second.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { overwriteDetails } from "@/lib/sharing/audit-details";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { encounterUpdateSchema } from "@/lib/validations/encounters";
import { encounterKindLabel } from "@/lib/encounters/kind-label";
import { toEncounterDTO } from "@/lib/encounters/dto";
import {
ENCOUNTER_INCLUDE,
actingDomainVisibility,
applyEncounterLinks,
closeCheckupForVisit,
findOwnAppointmentReminderId,
loadEncounterLinks,
resolveClosableReminder,
resolveOwnedPractitioner,
resolveOwnerNotificationContext,
retireAppointmentReminderForVisit,
retireOrphanedAppointmentReminders,
shouldHaveReminder,
syncAppointmentReminder,
} from "@/lib/encounters/service";
import {
recordUnknownKeys,
summarizeRestoreSkips,
type RestoreSkipLog,
} from "@/lib/export/restore-skips";
import type { Prisma } from "@/generated/prisma/client";
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user, grantId } = await requireRecordAuth("read", "profile");
const { id } = await params;
const row = await prisma.encounter.findUnique({
where: { id },
include: ENCOUNTER_INCLUDE,
});
if (!row || row.userId !== user.id || row.deletedAt !== null) {
return apiError("Visit not found", 404);
}
const visible = await actingDomainVisibility(prisma, grantId);
const links = await loadEncounterLinks(prisma, user.id, id, visible);
annotate({
action: {
name: "encounter.visit.read",
entity_type: "encounter",
entity_id: id,
},
});
return apiSuccess(toEncounterDTO(row, links));
},
);
export const PATCH = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user, grantId } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.encounter.findUnique({ where: { id } });
if (
!existing ||
existing.userId !== user.id ||
existing.deletedAt !== null
) {
return apiError("Visit not found", 404);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 32 * 1024,
});
if (jsonError) return jsonError;
const parsed = encounterUpdateSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "encounter.invalid",
});
}
const entry = parsed.data;
const { timezone, locale } = await resolveOwnerNotificationContext(user.id);
const now = new Date();
// The state the visit will be in once this edit lands. Both the reminder
// decision and the checkup decision read from here rather than from the
// body, so an edit that moves only the date is judged against the status
// the visit already has.
const nextOccurredAt = entry.occurredAt
? new Date(entry.occurredAt)
: existing.occurredAt;
const nextStatus = entry.status ?? existing.status;
const skips: RestoreSkipLog = [];
const outcome = await prisma.$transaction(async (tx) => {
const visible = await actingDomainVisibility(tx, grantId);
let practitionerId = existing.practitionerId;
let practitionerName: string | null = null;
let practitionerLocation: string | null = null;
if (entry.practitionerId !== undefined) {
if (entry.practitionerId === null) {
practitionerId = null;
} else {
const resolved = await resolveOwnedPractitioner(
tx,
user.id,
entry.practitionerId,
);
if (!resolved) return "unknown-practitioner" as const;
practitionerId = resolved.id;
practitionerName = resolved.name;
practitionerLocation = resolved.location;
}
} else if (practitionerId) {
const resolved = await resolveOwnedPractitioner(
tx,
user.id,
practitionerId,
);
practitionerName = resolved?.name ?? null;
practitionerLocation = resolved?.location ?? null;
}
const data: Prisma.EncounterUpdateInput = {};
if (entry.occurredAt !== undefined) data.occurredAt = nextOccurredAt;
if (entry.status !== undefined) data.status = entry.status;
if (entry.kind !== undefined) data.kind = entry.kind;
if (entry.reason !== undefined) {
data.reasonEncrypted = entry.reason
? encryptToBytes(entry.reason)
: null;
}
if (entry.outcome !== undefined) {
data.outcomeEncrypted = entry.outcome
? encryptToBytes(entry.outcome)
: null;
}
if (entry.practitionerId !== undefined) {
data.practitioner = practitionerId
? { connect: { id: practitionerId } }
: { disconnect: true };
}
// The appointment reminder this visit OWNS, resolved through the engine
// table rather than by reading the visit's own foreign key. Reading the
// key answers a different question — what the visit points at — and the
// two stop agreeing the moment the key is re-pointed at a checkup.
const ownAppointmentReminderId = await findOwnAppointmentReminderId(
tx,
user.id,
id,
);
let reminderId = existing.reminderId;
if (shouldHaveReminder(nextStatus, nextOccurredAt, now)) {
// The same contradiction the create arm refuses, and it has to be
// refused here too: a body that books a visit AND names the checkup it
// closed would walk the foreign key off the visit's own reminder,
// leaving it live, armed and unreachable.
if (entry.reminderId) return "contradictory-reminder" as const;
reminderId = await syncAppointmentReminder(
tx,
{
userId: user.id,
occurredAt: nextOccurredAt,
practitionerName,
practitionerLocation,
kindLabel: encounterKindLabel(entry.kind ?? existing.kind, locale),
status: nextStatus,
existingReminderId: ownAppointmentReminderId,
},
timezone,
now,
);
} else if (ownAppointmentReminderId) {
// No longer a future appointment: the row stays, switched off.
reminderId = await syncAppointmentReminder(
tx,
{
userId: user.id,
occurredAt: nextOccurredAt,
practitionerName,
practitionerLocation,
kindLabel: encounterKindLabel(entry.kind ?? existing.kind, locale),
status: nextStatus,
existingReminderId: ownAppointmentReminderId,
},
timezone,
now,
);
}
// A body may re-point the visit at the checkup it closes.
if (entry.reminderId !== undefined) {
if (entry.reminderId === null) {
reminderId = ownAppointmentReminderId;
} else {
const checkup = await resolveClosableReminder(
tx,
user.id,
entry.reminderId,
);
if (!checkup) return "unknown-reminder" as const;
reminderId = checkup.id;
}
}
if (reminderId !== existing.reminderId) {
data.reminder = reminderId
? { connect: { id: reminderId } }
: { disconnect: true };
}
const updated = await tx.encounter.update({ where: { id }, data });
await applyEncounterLinks(tx, user.id, id, entry);
// Filing the visit as done closes the checkup it names — on the
// TRANSITION, not on every edit of a visit that is already done.
//
// `satisfyReminder` is forward-only, which means an older instant is a
// no-op and a NEWER one always advances. So re-saving a completed visit
// would push the checkup's next due date out again, as if the person had
// been a second time. Gating on the transition is what makes re-filing
// genuinely idempotent rather than merely non-erroring.
const closesCheckupNow =
nextStatus === "DONE" && existing.status !== "DONE";
if (closesCheckupNow && reminderId) {
const checkup = await resolveClosableReminder(tx, user.id, reminderId);
if (checkup) {
// Same domain fence as the create arm: closing a checkup is a
// measurements write, and a health-background delegate may edit the
// visit without being able to perform it.
if (visible("measurements")) {
await closeCheckupForVisit(
tx,
checkup,
timezone,
nextOccurredAt,
now,
);
} else {
recordUnknownKeys(
skips,
"checkupClosure",
[checkup.id],
[checkup.id],
);
}
}
}
// Nothing this account owns may be left armed for a visit that does not
// point at it. Runs after the write so the row just minted, whose key is
// set one statement earlier, is never mistaken for a stray.
await retireOrphanedAppointmentReminders(tx, user.id, now);
return { updated };
});
if (outcome === "contradictory-reminder") {
return apiError(
"A booked visit cannot also close a checkup — it has not happened yet",
422,
{ errorCode: "encounter.reminder-conflict" },
);
}
if (outcome === "unknown-practitioner") {
return apiError("Practitioner not found", 404, {
errorCode: "encounter.practitioner-not-found",
});
}
if (outcome === "unknown-reminder") {
return apiError("Checkup not found", 404, {
errorCode: "encounter.reminder-not-found",
});
}
const row = await prisma.encounter.findUniqueOrThrow({
where: { id },
include: ENCOUNTER_INCLUDE,
});
const visible = await actingDomainVisibility(prisma, grantId);
const links = await loadEncounterLinks(prisma, user.id, id, visible);
await auditLog("encounter.visit.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
encounterId: id,
// The free text is deliberately absent: it is encrypted PHI and the
// audit table is not a second copy of the record.
...overwriteDetails({
before: {
occurredAt: existing.occurredAt,
status: existing.status,
kind: existing.kind,
practitionerId: existing.practitionerId,
},
after: {
occurredAt: outcome.updated.occurredAt,
status: outcome.updated.status,
kind: outcome.updated.kind,
practitionerId: outcome.updated.practitionerId,
},
}),
},
});
annotate({
action: {
name: "encounter.visit.update",
entity_type: "encounter",
entity_id: id,
},
meta: { status: row.status },
});
return apiSuccess(toEncounterDTO(row, links, summarizeRestoreSkips(skips)));
},
);
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.encounter.findUnique({ where: { id } });
if (!existing || existing.userId !== user.id) {
return apiError("Visit not found", 404);
}
// Already tombstoned: deleting twice is a no-op that still succeeds.
if (existing.deletedAt === null) {
const at = new Date();
await prisma.$transaction(async (tx) => {
// Only the visit's OWN appointment reminder goes with it, and it is
// found by the relation rather than by the foreign key: a visit whose
// key points at a checkup still owns its appointment row, and reading
// the key would leave that row armed for a visit that no longer exists.
// Retired BEFORE the tombstone, while the relation still resolves.
await retireAppointmentReminderForVisit(tx, user.id, id, at);
await tx.encounter.update({ where: { id }, data: { deletedAt: at } });
// A checkup the visit closed belongs to the person's preventive-care
// list and outlives it; the sweep below only reaps appointment rows.
await retireOrphanedAppointmentReminders(tx, user.id, at);
});
}
await auditLog("encounter.visit.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
encounterId: id,
occurredAt: existing.occurredAt.toISOString(),
status: existing.status,
},
});
annotate({
action: {
name: "encounter.visit.delete",
entity_type: "encounter",
entity_id: id,
},
});
return apiSuccess({ deleted: true });
},
);
+296
View File
@@ -0,0 +1,296 @@
/**
* `GET /api/encounters` — the account's visits, split into upcoming and past.
* `POST /api/encounters` — file one, optionally pre-linked and optionally
* booked as a future appointment.
*
* No module gate: a visit is core. The reasoning is written at the `Encounter`
* model in `prisma/schema.prisma`, and the gate is relocated to the link
* pickers, which follow the modules that own what they point at.
*
* `userId` is narrowed from auth and fed to the Prisma `where`; it is never a
* body field. The `data` object is built field-by-field. Nothing is mandatory
* except the date: a visit saves with an instant and nothing else.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { withIdempotency } from "@/lib/idempotency";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import {
encounterCreateSchema,
encounterListQuerySchema,
} from "@/lib/validations/encounters";
import { encounterKindLabel } from "@/lib/encounters/kind-label";
import { toEncounterDTO, type EncounterListDTO } from "@/lib/encounters/dto";
import {
ENCOUNTER_INCLUDE,
actingDomainVisibility,
applyEncounterLinks,
closeCheckupForVisit,
resolveClosableReminder,
resolveOwnedPractitioner,
resolveOwnerNotificationContext,
shouldHaveReminder,
syncAppointmentReminder,
} from "@/lib/encounters/service";
import {
recordUnknownKeys,
summarizeRestoreSkips,
type RestoreSkipLog,
} from "@/lib/export/restore-skips";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireRecordAuth("read", "profile");
const params = new URL(request.url).searchParams;
const parsed = encounterListQuerySchema.safeParse({
from: params.get("from") ?? undefined,
to: params.get("to") ?? undefined,
status: params.get("status") ?? undefined,
practitionerId: params.get("practitionerId") ?? undefined,
limit: params.get("limit") ?? undefined,
});
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "encounter.invalid",
});
}
const query = parsed.data;
const take = query.limit ?? 100;
const now = new Date();
const where = {
userId: user.id,
deletedAt: null,
...(query.status ? { status: query.status } : {}),
...(query.practitionerId ? { practitionerId: query.practitionerId } : {}),
...(query.from || query.to
? {
occurredAt: {
...(query.from ? { gte: new Date(query.from) } : {}),
...(query.to ? { lte: new Date(query.to) } : {}),
},
}
: {}),
};
// The past arm's own upper bound is `now`, and the caller may have asked for
// an earlier one. Both have to hold, so they COMBINE to the tighter of the
// two rather than one overwriting the other — spreading the caller's
// `occurredAt` and then restating `lte` silently widened every window that
// ended before today back out to "everything up to now".
const requestedTo = query.to ? new Date(query.to) : null;
const pastCeiling =
requestedTo && requestedTo.getTime() < now.getTime() ? requestedTo : now;
// Two queries rather than one sorted list. Upcoming reads soonest-first and
// past reads newest-first, which is the opposite direction; resolving both
// here means the client renders two lists instead of splitting and
// re-sorting one, and the ordering lives in one place.
const [upcoming, past] = await Promise.all([
prisma.encounter.findMany({
// `gt` and `gte` are different keys, so the caller's lower bound and this
// arm's floor both survive the spread; only the `lte` pair collided.
where: { ...where, occurredAt: { ...where.occurredAt, gt: now } },
orderBy: { occurredAt: "asc" },
take,
include: ENCOUNTER_INCLUDE,
}),
prisma.encounter.findMany({
where: {
...where,
occurredAt: { ...where.occurredAt, lte: pastCeiling },
},
orderBy: { occurredAt: "desc" },
take,
include: ENCOUNTER_INCLUDE,
}),
]);
annotate({
action: { name: "encounter.visit.list", entity_type: "encounter" },
meta: { upcoming: upcoming.length, past: past.length },
});
const body: EncounterListDTO = {
upcoming: upcoming.map((row) => toEncounterDTO(row)),
past: past.map((row) => toEncounterDTO(row)),
};
return apiSuccess(body);
});
// A double-tap on "save" must not file the same visit twice.
export const POST = apiHandler(withIdempotency<[NextRequest]>(postEncounter));
async function postEncounter(request: NextRequest): Promise<Response> {
const { user, grantId } = await requireRecordAuth("write", "profile");
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 32 * 1024,
});
if (jsonError) return jsonError;
const parsed = encounterCreateSchema.safeParse(rawBody);
if (!parsed.success) {
annotate({
action: { name: "encounter.visit.validation-failed" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422, {
errorCode: "encounter.invalid",
});
}
const entry = parsed.data;
const occurredAt = new Date(entry.occurredAt);
const { timezone, locale } = await resolveOwnerNotificationContext(user.id);
const now = new Date();
const skips: RestoreSkipLog = [];
const created = await prisma.$transaction(async (tx) => {
const visible = await actingDomainVisibility(tx, grantId);
// A practitioner the caller does not own is a refusal rather than a
// silently dropped field: the person named a practice and would otherwise
// see the visit save without it.
let practitioner:
{ id: string; name: string; location: string | null } | undefined;
if (entry.practitionerId) {
practitioner = await resolveOwnedPractitioner(
tx,
user.id,
entry.practitionerId,
);
if (!practitioner) return null;
}
// Field-by-field — never spread the parsed object whole.
const row = await tx.encounter.create({
data: {
userId: user.id,
occurredAt,
status: entry.status,
kind: entry.kind,
practitionerId: practitioner?.id ?? null,
reasonEncrypted: entry.reason ? encryptToBytes(entry.reason) : null,
outcomeEncrypted: entry.outcome ? encryptToBytes(entry.outcome) : null,
},
select: { id: true },
});
await applyEncounterLinks(tx, user.id, row.id, entry);
// `Encounter.reminderId` carries one of two things, never both, and which
// one follows from the visit's own state. A booked appointment owns a
// reminder this code mints; a completed visit may instead close a checkup
// the person already had. A body claiming both is contradictory — a visit
// that has not happened cannot have closed anything — and is refused.
let reminderId: string | null = null;
if (shouldHaveReminder(entry.status, occurredAt, now)) {
if (entry.reminderId) return "contradictory-reminder" as const;
reminderId = await syncAppointmentReminder(
tx,
{
userId: user.id,
occurredAt,
practitionerName: practitioner?.name ?? null,
practitionerLocation: practitioner?.location ?? null,
kindLabel: encounterKindLabel(entry.kind, locale),
status: entry.status,
existingReminderId: null,
},
timezone,
now,
);
} else if (entry.reminderId) {
const checkup = await resolveClosableReminder(
tx,
user.id,
entry.reminderId,
);
if (!checkup) return "unknown-reminder" as const;
reminderId = checkup.id;
// Filing a visit as done against a due checkup closes it — but closing
// one re-anchors a preventive-care cadence, which is a write in the
// measurements domain. A delegate holding only the health background may
// file the visit and may not perform that side effect, so the visit
// saves and the closure is reported as skipped rather than done in
// silence: somebody who believes a checkup was closed will not look at
// it again.
if (entry.status === "DONE") {
if (visible("measurements")) {
await closeCheckupForVisit(tx, checkup, timezone, occurredAt, now);
} else {
recordUnknownKeys(
skips,
"checkupClosure",
[checkup.id],
[checkup.id],
);
}
}
}
if (reminderId) {
await tx.encounter.update({
where: { id: row.id },
data: { reminderId },
});
}
return tx.encounter.findUniqueOrThrow({
where: { id: row.id },
include: ENCOUNTER_INCLUDE,
});
});
if (created === null) {
return apiError("Practitioner not found", 404, {
errorCode: "encounter.practitioner-not-found",
});
}
if (created === "unknown-reminder") {
return apiError("Checkup not found", 404, {
errorCode: "encounter.reminder-not-found",
});
}
if (created === "contradictory-reminder") {
return apiError(
"A planned visit cannot also close a checkup — it has not happened yet",
422,
{ errorCode: "encounter.reminder-conflict" },
);
}
await auditLog("encounter.visit.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: { encounterId: created.id, status: created.status },
});
annotate({
action: {
name: "encounter.visit.create",
entity_type: "encounter",
entity_id: created.id,
},
meta: { status: created.status, kind: created.kind },
});
return apiSuccess(
toEncounterDTO(created, undefined, summarizeRestoreSkips(skips)),
201,
);
}
@@ -28,6 +28,14 @@ vi.mock("@/lib/db", () => ({
// `buildIntradayProfileBackupSection`.
intradayCumulativeProfile: { findMany: vi.fn().mockResolvedValue([]) },
healthScoreRecord: { findMany: vi.fn().mockResolvedValue([]) },
// The visit tables. Empty here: this file asserts the sections it seeds,
// and an account with no visits is the ordinary case the builder must
// still answer for.
practitioner: { findMany: vi.fn().mockResolvedValue([]) },
encounter: { findMany: vi.fn().mockResolvedValue([]) },
encounterDocumentLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterLabLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterConditionLink: { findMany: vi.fn().mockResolvedValue([]) },
// v1.15.0 — cycle tables read by the full-backup helper.
cycleProfile: { findUnique: vi.fn() },
menstrualCycle: { findMany: vi.fn() },
@@ -98,6 +106,15 @@ beforeEach(() => {
[] as never,
);
vi.mocked(prisma.healthScoreRecord.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.practitioner.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.encounter.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.encounterDocumentLink.findMany).mockResolvedValue(
[] as never,
);
vi.mocked(prisma.encounterLabLink.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.encounterConditionLink.findMany).mockResolvedValue(
[] as never,
);
});
afterEach(() => {
@@ -26,6 +26,14 @@ vi.mock("@/lib/db", () => ({
// `buildIntradayProfileBackupSection`.
intradayCumulativeProfile: { findMany: vi.fn().mockResolvedValue([]) },
healthScoreRecord: { findMany: vi.fn().mockResolvedValue([]) },
// The visit tables. Empty here: this file asserts the sections it seeds,
// and an account with no visits is the ordinary case the builder must
// still answer for.
practitioner: { findMany: vi.fn().mockResolvedValue([]) },
encounter: { findMany: vi.fn().mockResolvedValue([]) },
encounterDocumentLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterLabLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterConditionLink: { findMany: vi.fn().mockResolvedValue([]) },
cycleProfile: { findUnique: vi.fn().mockResolvedValue(null) },
menstrualCycle: { findMany: vi.fn().mockResolvedValue([]) },
cycleDayLog: { findMany: vi.fn().mockResolvedValue([]) },
@@ -41,8 +41,13 @@ export const POST = apiHandler(
const { user } = await requireRecordAuth("manage", "measurements");
const { id } = await params;
// An appointment reminder is not addressable here. It belongs to a visit,
// is managed through the visit routes, and sits in a different sharing
// domain — so this family treats one as not found rather than acting on
// it. Filtering in the lookup rather than after it is what keeps a write
// from committing before the refusal.
const existing = await prisma.measurementReminder.findFirst({
where: { id, deletedAt: null },
where: { id, deletedAt: null, origin: { not: "ENCOUNTER" } },
});
if (!existing || existing.userId !== user.id) {
return apiError("Measurement reminder not found", 404);
@@ -48,8 +48,13 @@ export const GET = apiHandler(
const { user } = await requireRecordAuth("read", "measurements");
const { id } = await params;
// An appointment reminder is not addressable here. It belongs to a visit,
// is managed through the visit routes, and sits in a different sharing
// domain — so this family treats one as not found rather than acting on
// it. Filtering in the lookup rather than after it is what keeps a write
// from committing before the refusal.
const reminder = await prisma.measurementReminder.findFirst({
where: { id, deletedAt: null },
where: { id, deletedAt: null, origin: { not: "ENCOUNTER" } },
});
if (!reminder || reminder.userId !== user.id) {
return apiError("Measurement reminder not found", 404);
@@ -71,8 +76,13 @@ export const PATCH = apiHandler(
const { user } = await requireRecordAuth("manage", "measurements");
const { id } = await params;
// An appointment reminder is not addressable here. It belongs to a visit,
// is managed through the visit routes, and sits in a different sharing
// domain — so this family treats one as not found rather than acting on
// it. Filtering in the lookup rather than after it is what keeps a write
// from committing before the refusal.
const existing = await prisma.measurementReminder.findFirst({
where: { id, deletedAt: null },
where: { id, deletedAt: null, origin: { not: "ENCOUNTER" } },
});
if (!existing || existing.userId !== user.id) {
return apiError("Measurement reminder not found", 404);
@@ -234,8 +244,15 @@ export const DELETE = apiHandler(
const { user } = await requireRecordAuth("manage", "measurements");
const { id } = await params;
const existing = await prisma.measurementReminder.findUnique({
where: { id },
// An appointment reminder is not addressable here. It belongs to a visit,
// is managed through the visit routes, and sits in a different sharing
// domain — so this family treats one as not found rather than acting on
// it. Filtering in the lookup rather than after it is what keeps a write
// from committing before the refusal.
// `findFirst` rather than `findUnique`: the origin is not part of any
// unique key, so the predicate cannot ride a unique lookup.
const existing = await prisma.measurementReminder.findFirst({
where: { id, origin: { not: "ENCOUNTER" } },
});
if (!existing || existing.userId !== user.id) {
return apiError("Measurement reminder not found", 404);
@@ -27,8 +27,13 @@ export const POST = apiHandler(
const { user } = await requireRecordAuth("manage", "measurements");
const { id } = await params;
// An appointment reminder is not addressable here. It belongs to a visit,
// is managed through the visit routes, and sits in a different sharing
// domain — so this family treats one as not found rather than acting on
// it. Filtering in the lookup rather than after it is what keeps a write
// from committing before the refusal.
const existing = await prisma.measurementReminder.findFirst({
where: { id, deletedAt: null },
where: { id, deletedAt: null, origin: { not: "ENCOUNTER" } },
});
if (!existing || existing.userId !== user.id) {
return apiError("Measurement reminder not found", 404);
+7 -1
View File
@@ -39,7 +39,13 @@ export const GET = apiHandler(async () => {
const { user } = await requireRecordAuth("read", "measurements");
const reminders = await prisma.measurementReminder.findMany({
where: { userId: user.id, deletedAt: null },
// 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, deletedAt: null, origin: { not: "ENCOUNTER" } },
// Most-urgent first; a null next-due (uncomputable / disabled) sinks
// to the end so the actionable items float to the top.
orderBy: [
@@ -0,0 +1,58 @@
/**
* `POST /api/practitioners/{id}/restore` — clear a practitioner's tombstone.
*
* MANAGE rather than WRITE: undoing a deletion is a management act when the
* manager is the one who holds delete.
*
* Restoring the address-book entry does NOT re-attach it to the visits that
* named it. Those references were nulled when the row was deleted, and
* inventing them back would be guessing at which visits meant this practice.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { apiSuccess, apiError, getClientIp } from "@/lib/api-response";
import { toPractitionerDTO } from "@/lib/practitioners/dto";
type RouteParams = { params: Promise<{ id: string }> };
export const POST = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.practitioner.findUnique({ where: { id } });
if (!existing || existing.userId !== user.id) {
return apiError("Practitioner not found", 404);
}
// Restoring a live row is a no-op that still succeeds, so a retry after a
// dropped response does not answer 404 for work that already happened.
const restored =
existing.deletedAt === null
? existing
: await prisma.practitioner.update({
where: { id },
data: { deletedAt: null },
});
await auditLog("practitioner.contact.restore", {
userId: user.id,
ipAddress: getClientIp(request),
details: { practitionerId: id, name: restored.name },
});
annotate({
action: {
name: "practitioner.contact.restore",
entity_type: "practitioner",
entity_id: id,
},
});
return apiSuccess(toPractitionerDTO(restored));
},
);
+174
View File
@@ -0,0 +1,174 @@
/**
* `GET /api/practitioners/{id}` — one owned, live practitioner.
* `PATCH /api/practitioners/{id}` — edit it (partial; field-by-field).
* `DELETE /api/practitioners/{id}` — soft-delete it (idempotent).
*
* Owner-scoped by fetch-then-guard, the episode-detail pattern: the row is
* read by id and then checked against the resolved user, so a foreign id and a
* missing id give the same 404 and probing learns nothing.
*
* Deleting a practitioner keeps every visit that named it. The foreign key is
* SetNull, so the visits survive with no practice attached rather than
* disappearing with the address-book entry.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { overwriteDetails } from "@/lib/sharing/audit-details";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { practitionerUpdateSchema } from "@/lib/validations/practitioners";
import { toPractitionerDTO } from "@/lib/practitioners/dto";
import type { Prisma } from "@/generated/prisma/client";
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("read", "profile");
const { id } = await params;
const row = await prisma.practitioner.findUnique({ where: { id } });
if (!row || row.userId !== user.id || row.deletedAt !== null) {
return apiError("Practitioner not found", 404);
}
annotate({
action: {
name: "practitioner.contact.read",
entity_type: "practitioner",
entity_id: id,
},
});
return apiSuccess(toPractitionerDTO(row));
},
);
export const PATCH = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.practitioner.findUnique({ where: { id } });
if (
!existing ||
existing.userId !== user.id ||
existing.deletedAt !== null
) {
return apiError("Practitioner not found", 404);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = practitionerUpdateSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "practitioner.invalid",
});
}
const entry = parsed.data;
// Field-by-field, and only the keys the body actually named: an absent key
// leaves the column alone, an explicit null clears it.
const data: Prisma.PractitionerUpdateInput = {};
if (entry.name !== undefined) data.name = entry.name;
if (entry.specialty !== undefined) data.specialty = entry.specialty;
if (entry.practice !== undefined) data.practice = entry.practice;
if (entry.location !== undefined) data.location = entry.location;
if (entry.phone !== undefined) data.phone = entry.phone;
if (entry.note !== undefined) {
data.noteEncrypted = entry.note ? encryptToBytes(entry.note) : null;
}
const updated = await prisma.practitioner.update({ where: { id }, data });
await auditLog("practitioner.contact.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
practitionerId: id,
// A manager may edit somebody else's address book, so the owner's
// activity feed has to say what changed rather than only that
// something did. The note is deliberately absent: it is encrypted PHI
// and the audit table is not a second copy of the record.
...overwriteDetails({
before: {
name: existing.name,
specialty: existing.specialty,
practice: existing.practice,
location: existing.location,
phone: existing.phone,
},
after: {
name: updated.name,
specialty: updated.specialty,
practice: updated.practice,
location: updated.location,
phone: updated.phone,
},
}),
},
});
annotate({
action: {
name: "practitioner.contact.update",
entity_type: "practitioner",
entity_id: id,
},
});
return apiSuccess(toPractitionerDTO(updated));
},
);
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "profile");
const { id } = await params;
const existing = await prisma.practitioner.findUnique({ where: { id } });
if (!existing || existing.userId !== user.id) {
return apiError("Practitioner not found", 404);
}
// Already tombstoned: deleting twice is a no-op that still succeeds.
if (existing.deletedAt === null) {
await prisma.practitioner.update({
where: { id },
data: { deletedAt: new Date() },
});
}
await auditLog("practitioner.contact.delete", {
userId: user.id,
ipAddress: getClientIp(request),
// Soft delete: the row and its name survive, so the id is enough to
// reconstruct what went missing from the list.
details: { practitionerId: id, name: existing.name },
});
annotate({
action: {
name: "practitioner.contact.delete",
entity_type: "practitioner",
entity_id: id,
},
});
return apiSuccess({ deleted: true });
},
);
+123
View File
@@ -0,0 +1,123 @@
/**
* `GET /api/practitioners` — the account's own address book of doctors and
* practices, name-ordered and searchable.
* `POST /api/practitioners` — add one.
*
* No module gate: an address book is core, like the checkups page the visits
* that reference it live on. The reasoning is written at the `Practitioner`
* model in `prisma/schema.prisma`.
*
* `userId` is narrowed from auth and fed to the Prisma `where`; it is never a
* body field. The `data` object is built field-by-field, never spread from the
* parsed body. `note` is encrypted at rest; `name` stays plaintext so the
* picker can search and sort it in SQL.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { withIdempotency } from "@/lib/idempotency";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import {
practitionerCreateSchema,
practitionerListQuerySchema,
} from "@/lib/validations/practitioners";
import { toPractitionerDTO } from "@/lib/practitioners/dto";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireRecordAuth("read", "profile");
const params = new URL(request.url).searchParams;
const parsed = practitionerListQuerySchema.safeParse({
q: params.get("q") ?? undefined,
limit: params.get("limit") ?? undefined,
});
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "practitioner.invalid",
});
}
const rows = await prisma.practitioner.findMany({
where: {
userId: user.id,
deletedAt: null,
...(parsed.data.q
? { name: { contains: parsed.data.q, mode: "insensitive" as const } }
: {}),
},
orderBy: { name: "asc" },
take: parsed.data.limit ?? 100,
});
annotate({
action: { name: "practitioner.contact.list", entity_type: "practitioner" },
meta: { count: rows.length },
});
return apiSuccess(rows.map(toPractitionerDTO));
});
// A double-tap on "save" must not mint a second copy of the same practice.
export const POST = apiHandler(
withIdempotency<[NextRequest]>(postPractitioner),
);
async function postPractitioner(request: NextRequest): Promise<Response> {
const { user } = await requireRecordAuth("write", "profile");
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = practitionerCreateSchema.safeParse(rawBody);
if (!parsed.success) {
annotate({
action: { name: "practitioner.contact.validation-failed" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422, {
errorCode: "practitioner.invalid",
});
}
const entry = parsed.data;
// Field-by-field — never spread the parsed object whole.
const created = await prisma.practitioner.create({
data: {
userId: user.id,
name: entry.name,
specialty: entry.specialty ?? null,
practice: entry.practice ?? null,
location: entry.location ?? null,
phone: entry.phone ?? null,
noteEncrypted: entry.note ? encryptToBytes(entry.note) : null,
},
});
await auditLog("practitioner.contact.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: { practitionerId: created.id },
});
annotate({
action: {
name: "practitioner.contact.create",
entity_type: "practitioner",
entity_id: created.id,
},
});
return apiSuccess(toPractitionerDTO(created), 201);
}
+6
View File
@@ -198,6 +198,12 @@ function catalogueLabel(
if (catalogue === "moodTag") {
return t("admin.section.backups.restoreSkippedMoodTag");
}
if (catalogue === "visitReference") {
return t("admin.section.backups.restoreSkippedVisitReference");
}
if (catalogue === "checkupClosure") {
return t("admin.section.backups.restoreSkippedCheckupClosure");
}
return t("admin.section.backups.restoreSkippedMoodFactor");
}
+9
View File
@@ -233,6 +233,15 @@ export const ENCRYPTED_COLUMNS: readonly EncryptedColumn[] = [
{ model: "Allergy", field: "notesEncrypted", kind: "bytes" },
{ model: "FamilyHistoryEntry", field: "notesEncrypted", kind: "bytes" },
// ───── v1.38.0 visit free text (Bytes columns) ─────
// Why the person went, what came out of it, and the practice note. The
// structured columns a picker sorts and searches on — the practitioner's
// name, the kind, the status — stay queryable plaintext, the same split the
// structured health records above make.
{ model: "Encounter", field: "reasonEncrypted", kind: "bytes" },
{ model: "Encounter", field: "outcomeEncrypted", kind: "bytes" },
{ model: "Practitioner", field: "noteEncrypted", kind: "bytes" },
// ───── Inbound clinical document (Bytes column, codec-dispatched) ─────
// The raw uploaded document (the most sensitive blob in the corpus; never
// logged, never in wide-event meta). Two layouts, recorded per row in
+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 },
+14
View File
@@ -86,6 +86,17 @@ export const WIPE_MODELS = [
"MoodReminderDispatch",
"MoodTagHidden",
// ── Visits ──────────────────────────────────────────────────────────────
// The three link tables cascade from the encounter AND from the far side
// they point at — a lab result, a document, a condition episode — so they
// are deleted before any of those, or their per-model counts read zero on an
// audit row that claims to say what was removed. The encounter follows its
// own links; the address book it points at is a parent and goes last.
"EncounterDocumentLink",
"EncounterLabLink",
"EncounterConditionLink",
"Encounter",
// ── Clinical record ─────────────────────────────────────────────────────
"MentalHealthAssessment",
"LabResult",
@@ -198,6 +209,9 @@ export const WIPE_MODELS = [
"IllnessEpisode",
"Workout",
"InboundDocument",
// Encounters point here with SetNull, so the address book outlives the
// visits it is attached to and is removed after them.
"Practitioner",
"ApiToken",
] as const;
+28 -26
View File
@@ -5,7 +5,9 @@
* id a client sends is re-narrowed against the caller's live episodes before
* it can land in `document_condition_links`.
*/
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import { listTargetsBySource, replaceTargets } from "@/lib/links";
import type { DocumentConditionLinkDto } from "@/lib/validations/inbound-documents";
/**
@@ -18,19 +20,21 @@ export async function loadConditionLinks(
): Promise<Map<string, DocumentConditionLinkDto[]>> {
const map = new Map<string, DocumentConditionLinkDto[]>();
if (documentIds.length === 0) return map;
const links = await prisma.documentConditionLink.findMany({
where: { userId, documentId: { in: documentIds } },
select: {
documentId: true,
episodeId: true,
episode: { select: { label: true } },
},
orderBy: { createdAt: "asc" },
// `includeDeletedTargets` keeps the long-standing behaviour: the chip has
// always come off a relation join with no tombstone filter, so a document
// filed against a condition the person later deleted still shows it.
const byDocument = await listTargetsBySource(prisma, {
userId,
sourceKind: "document",
sourceIds: documentIds,
targetKind: "conditionEpisode",
includeDeletedTargets: true,
});
for (const link of links) {
const entry = map.get(link.documentId) ?? [];
entry.push({ episodeId: link.episodeId, name: link.episode.label });
map.set(link.documentId, entry);
for (const [documentId, targets] of byDocument) {
map.set(
documentId,
targets.map((target) => ({ episodeId: target.id, name: target.label })),
);
}
return map;
}
@@ -59,25 +63,23 @@ export async function narrowOwnedEpisodeIds(
/**
* Replace-set a document's condition links inside the given transaction-ish
* client: delete links no longer in the set, insert the missing ones.
* `episodeIds` MUST already be owner-narrowed (`narrowOwnedEpisodeIds`).
*
* `episodeIds` should already be owner-narrowed (`narrowOwnedEpisodeIds`), so
* the route can answer a foreign id with the 404-shaped refusal it does today.
* The link service narrows them again regardless — the routes decide the reply,
* the service decides what reaches the table.
*/
export async function replaceConditionLinks(
tx: Pick<typeof prisma, "documentConditionLink">,
tx: Prisma.TransactionClient,
userId: string,
documentId: string,
episodeIds: string[],
): Promise<void> {
await tx.documentConditionLink.deleteMany({
where: { userId, documentId, episodeId: { notIn: episodeIds } },
await replaceTargets(tx, {
userId,
sourceKind: "document",
sourceId: documentId,
targetKind: "conditionEpisode",
targetIds: episodeIds,
});
if (episodeIds.length > 0) {
await tx.documentConditionLink.createMany({
data: episodeIds.map((episodeId) => ({
documentId,
episodeId,
userId,
})),
skipDuplicates: true,
});
}
}
@@ -0,0 +1,86 @@
/**
* The never-nag property, proven rather than asserted in prose.
*
* A booked visit's reminder is a one-shot: both cadence columns are NULL, which
* the schema documents as "anchored on `anchorDate`". The claim that follows —
* that it can fire once and never again — is a claim about the SAME function
* the cron calls to advance a fired reminder. If that function returned an
* instant here, the row would re-arm every tick and nag forever about an
* appointment that already happened, and nothing else in the system would
* notice: the row is excluded from every list a person can see.
*
* The module said this test existed. It did not. That is the reason it does
* now: a comment claiming a proof is worse than no comment, because it stops
* the next reader looking.
*/
import { describe, expect, it } from "vitest";
import {
appointmentNextDueAfterFiring,
appointmentNotifyHour,
} from "@/lib/encounters/appointment-reminder";
const TZ = "Europe/Berlin";
const APPOINTMENT = new Date("2026-09-14T07:40:00.000Z");
/** The row shape a minted appointment reminder actually carries. */
const oneShot = {
intervalDays: null,
rrule: null,
anchorDate: APPOINTMENT,
notifyHour: 9,
createdAt: new Date("2026-08-01T00:00:00.000Z"),
};
describe("a fired appointment reminder can never re-arm", () => {
it("has no next occurrence once its instant has passed", () => {
const afterItFired = new Date("2026-09-14T08:00:00.000Z");
expect(appointmentNextDueAfterFiring(oneShot, TZ, afterItFired)).toBeNull();
});
it("still has none a year later", () => {
// The failure this rules out is a cadence quietly inferred from the anchor,
// which would look correct on the day and nag every year after it.
expect(
appointmentNextDueAfterFiring(
oneShot,
TZ,
new Date("2027-10-01T00:00:00.000Z"),
),
).toBeNull();
});
it("is not vacuous: a cadenced reminder DOES get a next occurrence", () => {
// Without this, "returns null" would also pass for a function that returns
// null unconditionally, which is the shape of green this repository keeps
// being bitten by.
const cadenced = { ...oneShot, intervalDays: 30 };
expect(
appointmentNextDueAfterFiring(
cadenced,
TZ,
new Date("2026-09-14T08:00:00.000Z"),
),
).not.toBeNull();
});
});
describe("the hour the nudge fires", () => {
it("is the appointment's own local hour, not the server's", () => {
// 07:40 UTC is 09:40 in Berlin, so the nudge belongs at 9.
expect(appointmentNotifyHour(APPOINTMENT, TZ)).toBe(9);
});
it("reads midnight as hour zero rather than twenty-four", () => {
// Some locales format midnight as "24"; the column is 0–23.
expect(
appointmentNotifyHour(new Date("2026-09-14T22:00:00.000Z"), TZ),
).toBe(0);
});
it("follows the record's zone, so the same instant differs by zone", () => {
expect(appointmentNotifyHour(APPOINTMENT, "UTC")).toBe(7);
});
});
+180
View File
@@ -0,0 +1,180 @@
/**
* 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 `__tests__/appointment-reminder.test.ts`, which 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 to advance a
* reminder it has just fired.
*/
export function appointmentNextDueAfterFiring(
reminder: Pick<
ReminderScheduleInput,
"intervalDays" | "rrule" | "anchorDate" | "notifyHour" | "createdAt"
>,
timezone: string,
now: Date,
): Date | null {
return computeReminderNextDueAt(
{ ...reminder, lastSatisfiedAt: null },
timezone,
now,
);
}
+138
View File
@@ -0,0 +1,138 @@
/**
* 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 { RestoreSkipSummary } from "@/lib/export/restore-skips";
import {
toPractitionerDTO,
type PractitionerDTO,
} from "@/lib/practitioners/dto";
/**
* One thing a visit produced, as the caller is allowed to see it.
*
* `label` and `date` go null together when the caller's grant does not cover
* the target's own domain — a health-background delegate may know the visit
* produced a lab result without being told which analyte. `redacted` says
* which of those nulls is a withholding and which is simply a target with no
* date, so a client never has to guess.
*/
export interface EncounterLinkDTO {
id: string;
label: string | null;
date: string | null;
redacted: boolean;
}
/** The three link families a visit can carry, each already resolved. */
export interface EncounterLinksDTO {
documents: EncounterLinkDTO[];
labResults: EncounterLinkDTO[];
conditions: EncounterLinkDTO[];
}
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;
/**
* What the write could not do, named.
*
* Present on create and edit. `links: 0` is the ordinary answer and says so.
* Anything else is a side effect the caller's grant did not reach — today
* only the closing of a checkup, which is a measurements-domain write that a
* health-background delegate cannot perform. Reported rather than skipped in
* silence, because a person who believes a checkup was closed will not look
* at it again.
*/
skipped?: RestoreSkipSummary;
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,
skipped?: RestoreSkipSummary,
): 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 } : {}),
...(skipped ? { skipped } : {}),
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[];
}
+47
View File
@@ -0,0 +1,47 @@
/**
* The human name of a visit kind, in the record owner's language.
*
* Spelled out with literal `t()` calls rather than an interpolated key, for the
* same reason the restore-skip catalogue labels are: an interpolated key is
* invisible to `i18n-call-site-coverage`, so a renamed or missing kind would
* ship as raw dot notation instead of failing CI.
*
* This is not decoration. The value becomes a `MeasurementReminder.label`, and
* that label IS the push body — so the fallback for a visit with no practice
* 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 { getServerTranslator } from "@/lib/i18n/server-translator";
import { defaultLocale, locales, type Locale } from "@/lib/i18n/config";
function resolveLocale(locale: string | null | undefined): Locale {
return locales.includes(locale as Locale)
? (locale as Locale)
: defaultLocale;
}
export function encounterKindLabel(
kind: EncounterKind,
locale: string | null | undefined,
): string {
const { t } = getServerTranslator(resolveLocale(locale));
switch (kind) {
case "ROUTINE":
return t("encounters.kind.routine");
case "ACUTE":
return t("encounters.kind.acute");
case "SPECIALIST":
return t("encounters.kind.specialist");
case "PREVENTIVE":
return t("encounters.kind.preventive");
case "EMERGENCY":
return t("encounters.kind.emergency");
case "HOSPITAL":
return t("encounters.kind.hospital");
case "THERAPY":
return t("encounters.kind.therapy");
default:
return t("encounters.kind.other");
}
}
+439
View File
@@ -0,0 +1,439 @@
/**
* 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 { grantCoversDomain } from "@/lib/sharing/grants";
import type { ShareDomain } from "@/lib/sharing/scope";
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 record owner's zone AND language, read together.
*
* Both are properties of the RECORD rather than of whoever is acting on it: a
* delegate booking an appointment in somebody else's record produces a nudge
* that rings on the owner's phone, at the owner's hour, in the owner's
* language. Reading the actor's locale here would localise a stranger's
* notification into the helper's tongue.
*/
export async function resolveOwnerNotificationContext(
userId: string,
): Promise<{ timezone: string; locale: string | null }> {
const row = await prisma.user.findUnique({
where: { id: userId },
select: { timezone: true, locale: true },
});
return {
timezone: row?.timezone || DEFAULT_TIMEZONE,
locale: row?.locale ?? null,
};
}
/** The relations the detail and list responses resolve. */
export const ENCOUNTER_INCLUDE = {
practitioner: true,
reminder: { select: { nextDueAt: true } },
} as const satisfies Prisma.EncounterInclude;
/**
* Which sections of the record the caller is actually inside.
*
* Returns a predicate rather than a set so the owner path costs nothing: with
* no grant there is nothing to look up and every domain is open. A grant that
* vanished between the auth check and here answers "no" to everything, which
* is the fail-closed direction.
*/
export async function actingDomainVisibility(
tx: Prisma.TransactionClient,
grantId: string | null,
): Promise<(domain: ShareDomain) => boolean> {
if (grantId === null) return () => true;
const grant = await tx.accountGrant.findUnique({
where: { id: grantId },
select: { scopeJson: true },
});
if (!grant) return () => false;
return (domain) => grantCoversDomain(grant, domain);
}
/** Which section of the record each link family's TARGET belongs to. */
const TARGET_DOMAIN: Record<LinkTargetKind, ShareDomain> = {
document: "documents",
labResult: "labs",
conditionEpisode: "illness",
};
/**
* The three link families, resolved for one visit and redacted per family.
*
* A visit is a seam between four domains: it lives in the health background
* and points at the vault, the lab results and the illness journal. A grant
* that opened only the health background was never consent for what is on the
* other side of that seam — and while the VALUES never crossed it (the list
* carries a label and a date, not a document body or a result), the names are
* themselves the sensitive part. "Oncology discharge letter" and "Ferritin,
* 30 June" say most of what the person was worried about.
*
* So the name and the date are withheld per family, and the LINK is not: the
* caller may know the visit produced a lab result, because the visit is theirs
* to read. `label: null` rather than an invented placeholder, so an absence
* reads as an absence; the array an entry sits in already carries the kind, so
* a client renders "a linked lab result" from its own bundle without the
* server shipping prose down the wire.
*
* Owners and entire-record delegates see everything, so the ordinary case is
* untouched.
*/
export async function loadEncounterLinks(
tx: Prisma.TransactionClient,
userId: string,
encounterId: string,
visible: (domain: ShareDomain) => boolean,
): Promise<EncounterLinksDTO> {
const read = async (targetKind: LinkTargetKind) => {
const rows = await listTargets(tx, {
userId,
sourceKind: "encounter",
sourceId: encounterId,
targetKind,
});
if (visible(TARGET_DOMAIN[targetKind])) {
return rows.map((row) => ({ ...row, redacted: false }));
}
return rows.map((row) => ({
id: row.id,
label: null,
date: null,
redacted: true,
}));
};
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. There is no second
* mechanism; the only decision here is WHICH INSTANT to satisfy at.
*
* It is the visit's own instant, bounded by now — not `now`. The plan said
* `now`, and two things it did not anticipate say otherwise:
*
* - **Anchoring.** A yearly panel drawn thirty days ago is next due 335 days
* from today, not 365. Satisfying at `now` moves every backdated entry's
* next due date forward by however long the person took to record it, so
* the more honest they are about the date, the more wrong the cadence gets.
* - **Re-transitions.** Correcting a mis-filed visit — DONE, then NO_SHOW,
* then DONE again — is a transition each way, so the status gate alone
* does not stop a second satisfy. At `now` the second one is strictly
* later and advances the cadence again; at the visit instant it is not
* strictly after the first, and the primitive's forward-only guard makes
* it the no-op it should always have been.
*
* Bounded by `now` because a visit can be booked into the future: a
* PLANNED-to-DONE correction on tomorrow's appointment must not stamp a
* satisfy the engine would read as ahead of its own clock.
*
* This also matches how the rest of the engine is fed — the cron and the
* ingest worker pass the EVENT instant, not the moment they happened to run.
*/
export async function closeCheckupForVisit(
tx: Prisma.TransactionClient,
reminder: SatisfiableReminder,
timezone: string,
occurredAt: Date,
now: Date,
): Promise<void> {
const satisfiedAt = occurredAt.getTime() < now.getTime() ? occurredAt : now;
await satisfyReminder(
tx as unknown as PrismaClient,
reminder,
timezone,
satisfiedAt,
);
}
/**
* The live appointment reminder this visit owns, found by the relation rather
* than by reading the visit's foreign key.
*
* The distinction is the whole of the orphan defect. Reading `reminderId` and
* checking its origin answers "what does this visit point at", which stops
* being the same question the moment the column is re-pointed at a checkup:
* the appointment row is still live, still armed, and now invisible to the
* code that owns it, so the next reschedule mints a second one. Asking the
* engine table which of ITS rows this visit owns cannot drift that way, and it
* filters the origin and the tombstone in SQL instead of in a branch.
*/
export async function findOwnAppointmentReminderId(
tx: Prisma.TransactionClient,
userId: string,
encounterId: string,
): Promise<string | null> {
const row = await tx.measurementReminder.findFirst({
where: {
userId,
origin: "ENCOUNTER",
deletedAt: null,
encounters: { some: { id: encounterId } },
},
select: { id: true },
});
return row?.id ?? null;
}
/**
* Retire every live appointment reminder this account owns that no visit
* points at.
*
* A reminder nobody points at still fires — the cron reads the engine table,
* not the visit list — so an orphan pushes notifications for an appointment
* the person can no longer see, edit or cancel. The refusal in the edit route
* stops the one sequence that produced them; this makes the state itself
* unreachable, so a future path that finds a new way to strand one cannot
* leave it armed.
*
* A soft-deleted VISIT still points at its reminder, so this never reaps a
* deleted visit's row — that retirement belongs to the delete route, which
* knows it is deliberate.
*/
export async function retireOrphanedAppointmentReminders(
tx: Prisma.TransactionClient,
userId: string,
at: Date,
): Promise<number> {
const result = await tx.measurementReminder.updateMany({
where: {
userId,
origin: "ENCOUNTER",
deletedAt: null,
encounters: { none: {} },
},
data: { deletedAt: at, enabled: false, nextDueAt: null },
});
return result.count;
}
/**
* Retire the appointment reminder a visit owns, alongside the visit.
*
* Takes the visit rather than a reminder id, and resolves the row by the
* relation: deleting a visit must reach the reminder it owns even if its
* foreign key is pointing somewhere else.
*/
export async function retireAppointmentReminderForVisit(
tx: Prisma.TransactionClient,
userId: string,
encounterId: string,
at: Date,
): Promise<void> {
const reminderId = await findOwnAppointmentReminderId(
tx,
userId,
encounterId,
);
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 };
}
@@ -247,6 +247,14 @@ function makePrisma() {
]),
},
healthScoreRecord: { findMany: vi.fn().mockResolvedValue([]) },
// The visit tables. Empty here: this file asserts the sections it seeds,
// and an account with no visits is the ordinary case the builder must
// still answer for.
practitioner: { findMany: vi.fn().mockResolvedValue([]) },
encounter: { findMany: vi.fn().mockResolvedValue([]) },
encounterDocumentLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterLabLink: { findMany: vi.fn().mockResolvedValue([]) },
encounterConditionLink: { findMany: vi.fn().mockResolvedValue([]) },
// Left unmocked on purpose: `buildProfileBackupSection` runs for real
// against these, so the assertions below exercise the builder rather than
// a stand-in that would agree with whatever the payload happened to do.
+25
View File
@@ -135,6 +135,13 @@ export const BACKED_UP_MODELS = [
"DocumentConditionLink",
"ExtractedFact",
// ── Visits ────────────────────────────────────────────────────────────────
"Practitioner",
"Encounter",
"EncounterDocumentLink",
"EncounterLabLink",
"EncounterConditionLink",
// ── Coach ─────────────────────────────────────────────────────────────────
"CoachConversation",
"CoachMessage",
@@ -177,6 +184,12 @@ export const BACKUP_WRITER_FILES: readonly string[] = [
"src/lib/export/profile-backup.ts",
"src/lib/export/intraday-profile-backup.ts",
"src/lib/export/health-score-backup.ts",
// Visits, the address book and the three link tables. Each model reads
// through its OWN delegate here rather than riding a relation, because
// `documentLinks` is a field name on two different models and a
// relation-shaped proof would be attributed to whichever one a matcher found
// first — the `symptomLinks` confusion, avoided by construction.
"src/lib/export/visits-backup.ts",
"src/lib/cycle/backup.ts",
];
@@ -185,6 +198,7 @@ export const BACKUP_RESTORE_FILES: readonly string[] = [
"src/lib/export/profile-backup.ts",
"src/lib/export/intraday-profile-backup.ts",
"src/lib/export/health-score-backup.ts",
"src/lib/export/visits-backup.ts",
"src/lib/cycle/backup.ts",
];
@@ -237,6 +251,17 @@ export const TWO_ENDED_MODELS = [
"Workout",
"NutrientIntakeDay",
"InboundDocument",
// Visits travel both ways from the release that introduces them. Two
// COVERAGE_PENDING neighbours already say what the alternative costs:
// reminders restore silent, and the filing between documents and conditions
// is lost. Leaving the visit links pending would return visits and documents
// with nothing between them — the same loss, one layer deeper — so the links
// land carried rather than owed.
"Practitioner",
"Encounter",
"EncounterDocumentLink",
"EncounterLabLink",
"EncounterConditionLink",
] as const;
/** One model claimed to travel both ways. */
+18 -1
View File
@@ -37,6 +37,12 @@ import {
type HealthScoreBackupCounts,
type HealthScoreBackupSection,
} from "@/lib/export/health-score-backup";
import {
buildVisitsBackupSection,
countVisitsBackupSection,
type VisitsBackupCounts,
type VisitsBackupSection,
} from "@/lib/export/visits-backup";
import {
buildIntradayProfileBackupSection,
countIntradayProfileBackupSection,
@@ -49,7 +55,8 @@ export interface FullBackupCounts
RecordsBackupCounts,
ProfileBackupCounts,
IntradayProfileBackupCounts,
HealthScoreBackupCounts {
HealthScoreBackupCounts,
VisitsBackupCounts {
measurements: number;
medications: number;
intakeEvents: number;
@@ -261,6 +268,7 @@ export async function buildFullBackupPayload(
profile,
intradayProfiles,
healthScoreRecords,
visits,
nutrientDays,
] = await Promise.all([
disasterRecovery
@@ -388,6 +396,12 @@ export async function buildFullBackupPayload(
buildHealthScoreBackupSection(prisma, userId, {
purpose: disasterRecovery ? "disaster-recovery" : "portable-export",
}),
// Visits, the address book behind them, and the three link tables. Both
// ends live in `src/lib/export/visits-backup.ts` beside each other, so a
// grep of the restore route alone will not find them.
buildVisitsBackupSection(prisma, userId, {
purpose: disasterRecovery ? "disaster-recovery" : "portable-export",
}),
// Nutrient day totals were absent from every export path, which
// contradicted the schema's own reason for denormalising the unit column
// ("rows stay self-describing in exports even if the catalog ever drifts").
@@ -414,6 +428,7 @@ export async function buildFullBackupPayload(
const profileSection: ProfileBackupSection = profile;
const intradaySection: IntradayProfileBackupSection = intradayProfiles;
const healthScoreSection: HealthScoreBackupSection = healthScoreRecords;
const visitsSection: VisitsBackupSection = visits;
const payload = {
schemaVersion: BACKUP_SCHEMA_VERSION,
@@ -643,6 +658,7 @@ export async function buildFullBackupPayload(
...profileSection,
...intradaySection,
...healthScoreSection,
...visitsSection,
nutrientDays: nutrientDays.map((n) => ({
day: n.day,
nutrient: n.nutrient,
@@ -670,6 +686,7 @@ export async function buildFullBackupPayload(
...countProfileBackupSection(profile),
...countIntradayProfileBackupSection(intradayProfiles),
...countHealthScoreBackupSection(healthScoreRecords),
...countVisitsBackupSection(visits),
},
};
}
+26 -2
View File
@@ -28,9 +28,33 @@
* edge rather than a record.
*/
/** Which seeded catalogue a key failed to resolve against. */
/**
* Which lookup a key failed to resolve against.
*
* Four are seeded catalogues, as described above. The fifth, `visitReference`,
* is a different kind of unresolvable and is here rather than in its own
* mechanism because the cost and the honest response are identical: an edge is
* lost, the record it hangs off survives, and the operator is told which one.
* What it names is a row the file pointed at that the restore did not put
* back — a reminder, which is on the coverage-pending register and never
* travels, or a document, lab result or condition episode whose id a portable
* export does not carry.
*
* The sixth, `checkupClosure`, is not about a restore at all, and it borrows
* this shape deliberately rather than growing a second reporting mechanism
* beside it. The situation is the same one: something a write was asked to do
* could not be done, the record itself survives, and the person is told which
* one rather than left to assume it worked. It is filed when a delegate files
* a visit against a preventive-care checkup their grant does not reach — the
* visit saves, the checkup stays due, and the response says so.
*/
export type SkippedCatalogue =
"cycleSymptom" | "illnessSymptom" | "moodFactor" | "moodTag";
| "cycleSymptom"
| "illnessSymptom"
| "moodFactor"
| "moodTag"
| "visitReference"
| "checkupClosure";
/** One key this instance does not know, and the links it cost. */
export interface SkippedCatalogueKey {
+573
View File
@@ -0,0 +1,573 @@
/**
* Visits and the address book behind them, with both backup ends in one file.
*
* The builder and the restore live together deliberately, the way
* `health-score-backup.ts` and `src/lib/cycle/backup.ts` do: a reader asking
* "is this carried at both ends?" answers it here, and a reader who greps only
* the restore ROUTE gets a false negative, because the route delegates.
*
* Five models ride: the practitioners, the encounters, and the three link
* tables between an encounter and a document, a lab result or a condition
* episode. All five are carried rather than owed. Two neighbours on the debt
* register already say what the alternative costs — reminders restore silent,
* and the filing between documents and conditions is lost — and a restore that
* returned visits and documents with nothing between them would be the same
* loss one layer deeper.
*
* Every read is scoped to the owner. Each model uses its own named select
* constant and its own delegate call rather than riding a parent's `include`:
* `documentLinks` is a relation field name on two different models, so a
* relation-shaped write here would be attributed to whichever of them a
* matcher happened to find first. Delegate calls cannot be confused that way.
*
* Two references deliberately do not survive a restore, and both are reported
* rather than dropped:
*
* - `Encounter.reminderId` points at a `MeasurementReminder`, which is on the
* coverage-pending register and does not come back. The column resolves to
* NULL, never to a dangling id.
* - A link whose far side was not restored. A portable export carries no lab
* result ids, so a lab link in one cannot resolve; a disaster-recovery
* payload carries every id and they all do.
*/
import { Buffer } from "node:buffer";
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
import type { EncounterKind, EncounterStatus } from "@/generated/prisma/client";
import {
recordUnknownKeys,
type RestoreSkipLog,
} from "@/lib/export/restore-skips";
export interface VisitsBackupOptions {
purpose?: "portable-export" | "disaster-recovery";
}
/** One entry in the account's own address book of doctors and practices. */
export interface PractitionerBackupEntry {
/** Always carried: an encounter references a practitioner by id and nothing
* else about the row is unique enough to rebuild the reference from. */
id: string;
name: string;
specialty: string | null;
practice: string | null;
location: string | null;
phone: string | null;
/** Base64 ciphertext, carried verbatim — never decrypted into the file. */
noteEncrypted: string | null;
createdAt: string;
updatedAt: string;
deletedAt?: string | null;
}
/** One contact with the healthcare system: happened, or booked. */
export interface EncounterBackupEntry {
/** Always carried, for the same reason as the practitioner id above: the
* three link tables address an encounter by it. */
id: string;
occurredAt: string;
status: EncounterStatus;
kind: EncounterKind;
practitionerId: string | null;
reasonEncrypted: string | null;
outcomeEncrypted: string | null;
/**
* Carried so the loss is visible in the file rather than inferred from its
* absence. The restore resolves it to NULL and names the drop: the reminder
* it points at is not in the backup.
*/
reminderId: string | null;
createdAt: string;
updatedAt: string;
deletedAt?: string | null;
}
/** One edge from a visit to something it produced. */
export interface EncounterLinkBackupEntry {
encounterId: string;
targetId: string;
createdAt: string;
}
export interface VisitsBackupSection {
practitioners: PractitionerBackupEntry[];
encounters: EncounterBackupEntry[];
encounterDocumentLinks: EncounterLinkBackupEntry[];
encounterLabLinks: EncounterLinkBackupEntry[];
encounterConditionLinks: EncounterLinkBackupEntry[];
}
export interface VisitsBackupCounts {
practitioners: number;
encounters: number;
encounterLinks: number;
}
/** Base64 for a `Bytes` ciphertext column, or null when the column is empty. */
function encodeCiphertext(value: Uint8Array | null): string | null {
if (!value || value.byteLength === 0) return null;
return Buffer.from(value).toString("base64");
}
/**
* Named select constants, one per model.
*
* Named rather than inline because a structural matcher binds a model to the
* literal beside its delegate call, and an inline object inside a `Promise.all`
* is a shape earlier work in this repository had to refactor away from for
* exactly that reason.
*/
const PRACTITIONER_BACKUP_SELECT = {
id: true,
name: true,
specialty: true,
practice: true,
location: true,
phone: true,
noteEncrypted: true,
createdAt: true,
updatedAt: true,
deletedAt: true,
} as const;
const ENCOUNTER_BACKUP_SELECT = {
id: true,
occurredAt: true,
status: true,
kind: true,
practitionerId: true,
reasonEncrypted: true,
outcomeEncrypted: true,
reminderId: true,
createdAt: true,
updatedAt: true,
deletedAt: true,
} as const;
const ENCOUNTER_DOCUMENT_LINK_BACKUP_SELECT = {
encounterId: true,
documentId: true,
createdAt: true,
} as const;
const ENCOUNTER_LAB_LINK_BACKUP_SELECT = {
encounterId: true,
labResultId: true,
createdAt: true,
} as const;
const ENCOUNTER_CONDITION_LINK_BACKUP_SELECT = {
encounterId: true,
episodeId: true,
createdAt: true,
} as const;
/**
* Build the visits slice of a user's full backup.
*
* Takes the delegates it uses rather than a whole client, matching the other
* section builders. A portable export omits tombstones so a restore cannot
* resurrect them; a disaster-recovery payload keeps them so the account comes
* back as itself.
*/
export async function buildVisitsBackupSection(
prisma: Pick<
PrismaClient,
| "practitioner"
| "encounter"
| "encounterDocumentLink"
| "encounterLabLink"
| "encounterConditionLink"
>,
userId: string,
options: VisitsBackupOptions = {},
): Promise<VisitsBackupSection> {
const disasterRecovery = options.purpose === "disaster-recovery";
const [
practitionerRows,
encounterRows,
documentLinkRows,
labLinkRows,
conditionLinkRows,
] = await Promise.all([
prisma.practitioner.findMany({
where: disasterRecovery ? { userId } : { userId, deletedAt: null },
orderBy: { name: "asc" },
select: PRACTITIONER_BACKUP_SELECT,
}),
prisma.encounter.findMany({
where: disasterRecovery ? { userId } : { userId, deletedAt: null },
orderBy: { occurredAt: "desc" },
select: ENCOUNTER_BACKUP_SELECT,
}),
prisma.encounterDocumentLink.findMany({
where: { userId },
orderBy: { createdAt: "asc" },
select: ENCOUNTER_DOCUMENT_LINK_BACKUP_SELECT,
}),
prisma.encounterLabLink.findMany({
where: { userId },
orderBy: { createdAt: "asc" },
select: ENCOUNTER_LAB_LINK_BACKUP_SELECT,
}),
prisma.encounterConditionLink.findMany({
where: { userId },
orderBy: { createdAt: "asc" },
select: ENCOUNTER_CONDITION_LINK_BACKUP_SELECT,
}),
]);
return {
practitioners: practitionerRows.map((row) => ({
id: row.id,
name: row.name,
specialty: row.specialty,
practice: row.practice,
location: row.location,
phone: row.phone,
noteEncrypted: encodeCiphertext(row.noteEncrypted),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
...(disasterRecovery
? { deletedAt: row.deletedAt?.toISOString() ?? null }
: {}),
})),
encounters: encounterRows.map((row) => ({
id: row.id,
occurredAt: row.occurredAt.toISOString(),
status: row.status,
kind: row.kind,
practitionerId: row.practitionerId,
reasonEncrypted: encodeCiphertext(row.reasonEncrypted),
outcomeEncrypted: encodeCiphertext(row.outcomeEncrypted),
reminderId: row.reminderId,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
...(disasterRecovery
? { deletedAt: row.deletedAt?.toISOString() ?? null }
: {}),
})),
encounterDocumentLinks: documentLinkRows.map((row) => ({
encounterId: row.encounterId,
targetId: row.documentId,
createdAt: row.createdAt.toISOString(),
})),
encounterLabLinks: labLinkRows.map((row) => ({
encounterId: row.encounterId,
targetId: row.labResultId,
createdAt: row.createdAt.toISOString(),
})),
encounterConditionLinks: conditionLinkRows.map((row) => ({
encounterId: row.encounterId,
targetId: row.episodeId,
createdAt: row.createdAt.toISOString(),
})),
};
}
/** Row counts for the audit trail, mirroring the other section counters. */
export function countVisitsBackupSection(
section: VisitsBackupSection,
): VisitsBackupCounts {
return {
practitioners: section.practitioners.length,
encounters: section.encounters.length,
encounterLinks:
section.encounterDocumentLinks.length +
section.encounterLabLinks.length +
section.encounterConditionLinks.length,
};
}
/** Counts the visit restore wiped, for the audit trail. */
export interface VisitsRestoreCleared {
practitioners: number;
encounters: number;
encounterLinks: number;
}
/**
* The slice of a parsed backup this restore consumes.
*
* Required rather than optional: the payload schema defaults every key, so
* every caller already satisfies this, and one that stops satisfying it fails
* to compile instead of passing `undefined` into a loop that iterates zero
* times and reports success.
*/
export interface VisitsRestoreInput {
practitioners: RestoredPractitioner[];
encounters: RestoredEncounter[];
encounterDocumentLinks: EncounterLinkBackupEntry[];
encounterLabLinks: EncounterLinkBackupEntry[];
encounterConditionLinks: EncounterLinkBackupEntry[];
}
/**
* What the restore reads, as the parsed file actually presents it.
*
* The builder's entry types above describe what this release WRITES. These
* describe what a restore may be handed, which is a wider set: a portable
* export omits the tombstone, and every optional column in the payload schema
* arrives as `undefined` rather than `null`. Modelling the read side as the
* write side would compile only because the two happen to agree today, and
* would break the first time an older file reached it.
*/
type OptionalNullable<T> = { [K in keyof T]?: T[K] | undefined };
export type RestoredPractitioner = Pick<
PractitionerBackupEntry,
"id" | "name" | "createdAt" | "updatedAt"
> &
OptionalNullable<
Pick<
PractitionerBackupEntry,
"specialty" | "practice" | "location" | "phone" | "noteEncrypted"
>
> & { deletedAt?: string | null };
export type RestoredEncounter = Pick<
EncounterBackupEntry,
"id" | "occurredAt" | "status" | "kind" | "createdAt" | "updatedAt"
> &
OptionalNullable<
Pick<
EncounterBackupEntry,
"practitionerId" | "reasonEncrypted" | "outcomeEncrypted" | "reminderId"
>
> & { deletedAt?: string | null };
function decodeCiphertext(encoded: string): Uint8Array<ArrayBuffer> {
const decoded = Buffer.from(encoded, "base64");
const bytes = new Uint8Array(new ArrayBuffer(decoded.byteLength));
bytes.set(decoded);
return bytes;
}
/**
* Re-create the account's visits, address book and link rows.
*
* Delete-then-recreate inside the caller's transaction, matching every other
* section. Parents first — practitioners, then encounters, then the links —
* because a link addresses both of its ends by id.
*
* MUST be called after the documents, lab results and condition episodes have
* been restored: a link is written only when both of its ends exist, and the
* existence check is what decides. Calling it earlier would report every link
* as unresolvable and be counted as a successful restore of nothing.
*/
export async function restoreVisitsData(
tx: Prisma.TransactionClient,
ownerId: string,
payload: VisitsRestoreInput,
skips: RestoreSkipLog,
): Promise<VisitsRestoreCleared> {
const clearedLinks =
(await tx.encounterDocumentLink.deleteMany({ where: { userId: ownerId } }))
.count +
(await tx.encounterLabLink.deleteMany({ where: { userId: ownerId } }))
.count +
(await tx.encounterConditionLink.deleteMany({ where: { userId: ownerId } }))
.count;
const clearedEncounters = await tx.encounter.deleteMany({
where: { userId: ownerId },
});
const clearedPractitioners = await tx.practitioner.deleteMany({
where: { userId: ownerId },
});
if (payload.practitioners.length > 0) {
await tx.practitioner.createMany({
data: payload.practitioners.map((entry) => ({
id: entry.id,
userId: ownerId,
name: entry.name,
specialty: entry.specialty ?? null,
practice: entry.practice ?? null,
location: entry.location ?? null,
phone: entry.phone ?? null,
noteEncrypted:
entry.noteEncrypted == null
? null
: decodeCiphertext(entry.noteEncrypted),
createdAt: new Date(entry.createdAt),
updatedAt: new Date(entry.updatedAt),
deletedAt: entry.deletedAt ? new Date(entry.deletedAt) : null,
})),
});
}
// A practitioner the file references but does not carry cannot be invented,
// and a dangling id would fail the foreign key and roll the whole restore
// back over one visit. The reference is dropped to NULL instead — the visit
// itself, its date, its reason and its outcome all survive.
const restoredPractitioners = new Set(
payload.practitioners.map((entry) => entry.id),
);
const droppedPractitioners: string[] = [];
// The reminder is on the coverage-pending register: it is not in the file at
// all, so every reference to one is a known, reportable drop.
const droppedReminders: string[] = [];
if (payload.encounters.length > 0) {
await tx.encounter.createMany({
data: payload.encounters.map((entry) => {
const practitionerId =
entry.practitionerId &&
restoredPractitioners.has(entry.practitionerId)
? entry.practitionerId
: null;
if (entry.practitionerId && practitionerId === null) {
droppedPractitioners.push(entry.practitionerId);
}
if (entry.reminderId) droppedReminders.push(entry.reminderId);
return {
id: entry.id,
userId: ownerId,
occurredAt: new Date(entry.occurredAt),
status: entry.status,
kind: entry.kind,
practitionerId,
reasonEncrypted:
entry.reasonEncrypted == null
? null
: decodeCiphertext(entry.reasonEncrypted),
outcomeEncrypted:
entry.outcomeEncrypted == null
? null
: decodeCiphertext(entry.outcomeEncrypted),
// Never the id the file carried: the row it named is not restored.
reminderId: null,
createdAt: new Date(entry.createdAt),
updatedAt: new Date(entry.updatedAt),
deletedAt: entry.deletedAt ? new Date(entry.deletedAt) : null,
};
}),
});
}
recordUnknownKeys(
skips,
"visitReference",
[...new Set(droppedPractitioners)],
droppedPractitioners,
);
recordUnknownKeys(
skips,
"visitReference",
[...new Set(droppedReminders)],
droppedReminders,
);
const restoredEncounters = new Set(payload.encounters.map((e) => e.id));
/**
* Write the links whose far side actually came back, and name the rest.
*
* The far side is checked against the database rather than against the
* payload, because the document, the lab result and the episode are restored
* by other branches in the same transaction and this is the only place that
* can see all three.
*/
async function restoreLinks(
entries: EncounterLinkBackupEntry[],
existingTargetIds: Set<string>,
write: (
rows: Array<{
encounterId: string;
targetId: string;
createdAt: Date;
}>,
) => Promise<void>,
): Promise<void> {
const writable: Array<{
encounterId: string;
targetId: string;
createdAt: Date;
}> = [];
const dropped: string[] = [];
for (const entry of entries) {
if (
restoredEncounters.has(entry.encounterId) &&
existingTargetIds.has(entry.targetId)
) {
writable.push({
encounterId: entry.encounterId,
targetId: entry.targetId,
createdAt: new Date(entry.createdAt),
});
} else {
dropped.push(entry.targetId);
}
}
if (writable.length > 0) await write(writable);
recordUnknownKeys(skips, "visitReference", [...new Set(dropped)], dropped);
}
const [documentIds, labResultIds, episodeIds] = await Promise.all([
tx.inboundDocument.findMany({
where: { userId: ownerId },
select: { id: true },
}),
tx.labResult.findMany({
where: { userId: ownerId },
select: { id: true },
}),
tx.illnessEpisode.findMany({
where: { userId: ownerId },
select: { id: true },
}),
]);
await restoreLinks(
payload.encounterDocumentLinks,
new Set(documentIds.map((row) => row.id)),
async (rows) => {
await tx.encounterDocumentLink.createMany({
data: rows.map((row) => ({
userId: ownerId,
encounterId: row.encounterId,
documentId: row.targetId,
createdAt: row.createdAt,
})),
});
},
);
await restoreLinks(
payload.encounterLabLinks,
new Set(labResultIds.map((row) => row.id)),
async (rows) => {
await tx.encounterLabLink.createMany({
data: rows.map((row) => ({
userId: ownerId,
encounterId: row.encounterId,
labResultId: row.targetId,
createdAt: row.createdAt,
})),
});
},
);
await restoreLinks(
payload.encounterConditionLinks,
new Set(episodeIds.map((row) => row.id)),
async (rows) => {
await tx.encounterConditionLink.createMany({
data: rows.map((row) => ({
userId: ownerId,
encounterId: row.encounterId,
episodeId: row.targetId,
createdAt: row.createdAt,
})),
});
},
);
return {
practitioners: clearedPractitioners.count,
encounters: clearedEncounters.count,
encounterLinks: clearedLinks,
};
}
+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" },
+49
View File
@@ -0,0 +1,49 @@
/**
* One service for every link between two of an account's own records.
*
* Two families live behind it today: a visit's links to the documents, lab
* results and conditions it produced, and a document's links to the conditions
* it is filed against. They are separate tables and one call signature.
*
* The reason for the shape rather than four more call sites: the standing
* lesson from the polymorphic-linking work is "one shared service", and this
* release adds three narrow link tables, which is a bounded step the other way.
* Bounded by this module. Every caller speaks one vocabulary — a source, a
* target kind and a list of target ids — so replacing the storage underneath
* later is a change here and not a sweep across every route that files
* something.
*
* Rules the module owns, so no call site re-implements them:
*
* - **Ownership is verified here.** Both ends are re-read scoped by `userId`
* before a row is written. Passing another account's document id links
* nothing; the id comes back in `unknownTargetIds` and the caller decides
* whether that is a refusal or a silent no-op.
* - **Idempotent.** Linking a pair that already exists succeeds and changes
* nothing, matching the document bulk route's behaviour today.
* - **Bounded.** At most {@link MAX_TARGETS_PER_CALL} ids per call.
* - **Soft-deleted rows are not linkable**, on either end. A tombstoned
* document cannot be filed against a visit, and a deleted visit cannot
* collect new links.
*
* One documented exemption: `src/lib/export/visits-backup.ts` writes the link
* tables directly. A restore is rebuilding an account rather than filing
* something in one — it preserves ids and creation instants, and it must not
* re-run an ownership narrowing against rows it is in the middle of creating.
* It is the same exemption the wipe plan and the key rotation hold, for the
* same reason, and it is the only one.
*/
export {
MAX_TARGETS_PER_CALL,
linkTargets,
unlinkTargets,
replaceTargets,
listTargets,
listTargetsBySource,
listDistinctTargets,
type LinkSourceKind,
type LinkTargetKind,
type LinkRequest,
type LinkResult,
type LinkedTarget,
} from "@/lib/links/link-service";
+561
View File
@@ -0,0 +1,561 @@
/**
* The link service itself. See `index.ts` for why it exists and what it
* guarantees; this file is the implementation and the table of link kinds.
*/
import type { Prisma } from "@/generated/prisma/client";
/**
* A bound matching the document bulk route's own cap. A link call is a
* user-driven filing action, not an import path, so a request naming more ids
* than this is a client defect rather than a large but legitimate batch.
*/
export const MAX_TARGETS_PER_CALL = 100;
/** The record a link hangs off. */
export type LinkSourceKind = "encounter" | "document";
/** The record a link points at. */
export type LinkTargetKind = "document" | "labResult" | "conditionEpisode";
export interface LinkRequest {
userId: string;
sourceKind: LinkSourceKind;
sourceId: string;
targetKind: LinkTargetKind;
targetIds: string[];
}
export interface LinkResult {
/**
* Rows actually written or removed.
*
* Zero is a success, not a failure: linking a pair that already exists, or
* unlinking one that never did, is the idempotent no-op the callers rely on.
*/
changed: number;
/**
* Ids that named nothing this account owns, or a row it has deleted.
*
* Returned rather than thrown. A bulk filing action treats one unknown id as
* one failed row and keeps going; an upload treats it as a refusal of the
* whole request. Both are legitimate and neither belongs in here.
*/
unknownTargetIds: string[];
/** True when the source itself is unknown, foreign or deleted. */
unknownSource: boolean;
}
/** One resolved link target, ready for a DTO. Never just an id. */
export interface LinkedTarget {
id: string;
label: string;
/** The date that makes the target sortable and recognisable, ISO-8601. */
date: string | null;
}
/**
* Prisma's generated delegates are structurally compatible with the narrow
* shapes below, but each model's argument types are nominally distinct, so a
* table keyed by link kind cannot be written without one narrowing per
* accessor. The casts are confined to {@link LINK_TABLES} and every call in
* this file goes through it.
*/
interface LinkRowDelegate {
createMany(args: {
data: Array<Record<string, string>>;
skipDuplicates?: boolean;
}): Promise<{ count: number }>;
deleteMany(args: {
where: Record<string, unknown>;
}): Promise<{ count: number }>;
findMany(args: {
where: Record<string, unknown>;
select: Record<string, boolean | Record<string, unknown>>;
orderBy?: Record<string, unknown>;
}): Promise<Array<Record<string, unknown>>>;
}
interface OwnedRowDelegate {
findMany(args: {
where: Record<string, unknown>;
select: Record<string, boolean>;
}): Promise<Array<Record<string, unknown>>>;
}
interface EndpointSpec {
/** The owning model's delegate, for the ownership re-read. */
delegate: (tx: Prisma.TransactionClient) => OwnedRowDelegate;
/** Columns the label and date are derived from. */
select: Record<string, boolean>;
label: (row: Record<string, unknown>) => string;
date: (row: Record<string, unknown>) => string | null;
}
interface LinkTableSpec {
delegate: (tx: Prisma.TransactionClient) => LinkRowDelegate;
sourceColumn: string;
targetColumn: string;
target: EndpointSpec;
}
/**
* The one narrowing point.
*
* Prisma generates a distinct argument type per model, so a table keyed by
* link kind cannot hold them without erasing the difference. Going through
* `unknown` here rather than at each accessor keeps the unsafety countable:
* every delegate in this file is narrowed by this function and nowhere else,
* and the column names it is narrowed FOR are declared beside it in
* {@link LINK_TABLES}.
*/
function narrow<T>(delegate: unknown): T {
return delegate as T;
}
function asDate(value: unknown): string | null {
return value instanceof Date ? value.toISOString() : null;
}
function asString(value: unknown): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
}
/** Where a source record lives, and how to prove the caller owns a live one. */
const SOURCES: Record<
LinkSourceKind,
{
delegate: (tx: Prisma.TransactionClient) => OwnedRowDelegate;
/** The link row's relation field back to the source, for a joined filter. */
relationField: string;
}
> = {
encounter: {
delegate: (tx) => narrow<OwnedRowDelegate>(tx.encounter),
relationField: "encounter",
},
document: {
delegate: (tx) => narrow<OwnedRowDelegate>(tx.inboundDocument),
relationField: "document",
},
};
const DOCUMENT_ENDPOINT: EndpointSpec = {
delegate: (tx) => narrow<OwnedRowDelegate>(tx.inboundDocument),
select: {
id: true,
title: true,
filename: true,
documentDate: true,
reportDate: true,
createdAt: true,
},
// A vault document may carry neither a title nor a filename; the id is the
// last honest thing left rather than an invented placeholder.
label: (row) =>
asString(row.title) ?? asString(row.filename) ?? String(row.id),
date: (row) =>
asDate(row.documentDate) ?? asDate(row.reportDate) ?? asDate(row.createdAt),
};
const LAB_RESULT_ENDPOINT: EndpointSpec = {
delegate: (tx) => narrow<OwnedRowDelegate>(tx.labResult),
select: { id: true, analyte: true, panel: true, takenAt: true },
label: (row) => {
const panel = asString(row.panel);
const analyte = String(row.analyte);
return panel ? `${panel} · ${analyte}` : analyte;
},
date: (row) => asDate(row.takenAt),
};
const CONDITION_ENDPOINT: EndpointSpec = {
delegate: (tx) => narrow<OwnedRowDelegate>(tx.illnessEpisode),
select: { id: true, label: true, onsetAt: true },
label: (row) => String(row.label),
date: (row) => asDate(row.onsetAt),
};
/**
* Every legal (source, target) pair and the table behind it.
*
* A pair absent from here is not linkable, and asking for one is a programming
* error rather than a user error — hence the throw in {@link tableFor} rather
* than a result field. Three is the number of encounter link tables this
* design allows; a fourth is the point at which this stops being a small set
* of named relations and starts being a general edge store.
*/
const LINK_TABLES: Partial<
Record<`${LinkSourceKind}:${LinkTargetKind}`, LinkTableSpec>
> = {
"encounter:document": {
delegate: (tx) => narrow<LinkRowDelegate>(tx.encounterDocumentLink),
sourceColumn: "encounterId",
targetColumn: "documentId",
target: DOCUMENT_ENDPOINT,
},
"encounter:labResult": {
delegate: (tx) => narrow<LinkRowDelegate>(tx.encounterLabLink),
sourceColumn: "encounterId",
targetColumn: "labResultId",
target: LAB_RESULT_ENDPOINT,
},
"encounter:conditionEpisode": {
delegate: (tx) => narrow<LinkRowDelegate>(tx.encounterConditionLink),
sourceColumn: "encounterId",
targetColumn: "episodeId",
target: CONDITION_ENDPOINT,
},
"document:conditionEpisode": {
delegate: (tx) => narrow<LinkRowDelegate>(tx.documentConditionLink),
sourceColumn: "documentId",
targetColumn: "episodeId",
target: CONDITION_ENDPOINT,
},
};
function tableFor(
sourceKind: LinkSourceKind,
targetKind: LinkTargetKind,
): LinkTableSpec {
const spec = LINK_TABLES[`${sourceKind}:${targetKind}`];
if (!spec) {
throw new Error(
`No link table joins a ${sourceKind} to a ${targetKind}. The legal pairs ` +
`are declared in src/lib/links/link-service.ts; adding one is a schema ` +
`decision, not a call-site decision.`,
);
}
return spec;
}
function assertWithinCap(targetIds: string[]): void {
if (targetIds.length > MAX_TARGETS_PER_CALL) {
throw new Error(
`A link call names ${targetIds.length} targets, above the cap of ` +
`${MAX_TARGETS_PER_CALL}.`,
);
}
}
/** Does the caller own a LIVE source record with this id? */
async function ownsSource(
tx: Prisma.TransactionClient,
{
userId,
sourceKind,
sourceId,
}: Omit<LinkRequest, "targetKind" | "targetIds">,
): Promise<boolean> {
const rows = await SOURCES[sourceKind].delegate(tx).findMany({
where: { id: sourceId, userId, deletedAt: null },
select: { id: true },
});
return rows.length === 1;
}
/** The subset of `targetIds` the caller owns and has not deleted. */
async function ownedTargetIds(
tx: Prisma.TransactionClient,
userId: string,
spec: LinkTableSpec,
targetIds: string[],
): Promise<Set<string>> {
if (targetIds.length === 0) return new Set();
const rows = await spec.target.delegate(tx).findMany({
where: { id: { in: targetIds }, userId, deletedAt: null },
select: { id: true },
});
return new Set(rows.map((row) => String(row.id)));
}
/**
* Split a requested id list into the ones that may be written and the ones
* that named nothing. Deduplicated first: a list naming the same document
* twice is one link, and reporting it as two would overstate what happened.
*/
async function resolveTargets(
tx: Prisma.TransactionClient,
request: LinkRequest,
spec: LinkTableSpec,
): Promise<{ owned: string[]; unknown: string[] }> {
const unique = [...new Set(request.targetIds)];
const owned = await ownedTargetIds(tx, request.userId, spec, unique);
return {
owned: unique.filter((id) => owned.has(id)),
unknown: unique.filter((id) => !owned.has(id)),
};
}
/**
* Add links, leaving any that already exist untouched.
*
* `skipDuplicates` is what makes a re-post a success that changed nothing,
* which is the contract the document bulk route already offers and the one a
* client retrying a request depends on.
*/
export async function linkTargets(
tx: Prisma.TransactionClient,
request: LinkRequest,
): Promise<LinkResult> {
assertWithinCap(request.targetIds);
const spec = tableFor(request.sourceKind, request.targetKind);
if (!(await ownsSource(tx, request))) {
return { changed: 0, unknownTargetIds: [], unknownSource: true };
}
const { owned, unknown } = await resolveTargets(tx, request, spec);
if (owned.length === 0) {
return { changed: 0, unknownTargetIds: unknown, unknownSource: false };
}
const created = await spec.delegate(tx).createMany({
data: owned.map((targetId) => ({
[spec.sourceColumn]: request.sourceId,
[spec.targetColumn]: targetId,
userId: request.userId,
})),
skipDuplicates: true,
});
return {
changed: created.count,
unknownTargetIds: unknown,
unknownSource: false,
};
}
/**
* Remove links.
*
* Ownership of the TARGET is deliberately not required here. A document the
* account has since deleted still has a link row, and refusing to unlink it
* would leave a filing nobody can clear. The link rows are scoped by `userId`
* regardless, so nothing another account owns is reachable.
*/
export async function unlinkTargets(
tx: Prisma.TransactionClient,
request: LinkRequest,
): Promise<LinkResult> {
assertWithinCap(request.targetIds);
const spec = tableFor(request.sourceKind, request.targetKind);
const unique = [...new Set(request.targetIds)];
if (unique.length === 0) {
return { changed: 0, unknownTargetIds: [], unknownSource: false };
}
const removed = await spec.delegate(tx).deleteMany({
where: {
userId: request.userId,
[spec.sourceColumn]: request.sourceId,
[spec.targetColumn]: { in: unique },
},
});
return {
changed: removed.count,
unknownTargetIds: [],
unknownSource: false,
};
}
/**
* Make the link set exactly `targetIds`: drop what is no longer named, add
* what is missing.
*
* The delete runs before the ownership check on purpose. Clearing a link is
* always allowed (see {@link unlinkTargets}), and doing it first means a
* request naming one unknown id still applies the part of itself that was
* valid, rather than leaving the set in a state the caller did not ask for.
*/
export async function replaceTargets(
tx: Prisma.TransactionClient,
request: LinkRequest,
): Promise<LinkResult> {
assertWithinCap(request.targetIds);
const spec = tableFor(request.sourceKind, request.targetKind);
if (!(await ownsSource(tx, request))) {
return { changed: 0, unknownTargetIds: [], unknownSource: true };
}
const { owned, unknown } = await resolveTargets(tx, request, spec);
const removed = await spec.delegate(tx).deleteMany({
where: {
userId: request.userId,
[spec.sourceColumn]: request.sourceId,
[spec.targetColumn]: { notIn: owned },
},
});
let created = 0;
if (owned.length > 0) {
const result = await spec.delegate(tx).createMany({
data: owned.map((targetId) => ({
[spec.sourceColumn]: request.sourceId,
[spec.targetColumn]: targetId,
userId: request.userId,
})),
skipDuplicates: true,
});
created = result.count;
}
return {
changed: removed.count + created,
unknownTargetIds: unknown,
unknownSource: false,
};
}
/**
* The resolved targets currently linked to one source.
*
* Returns labels and dates, never bare ids: a client that had to fetch each
* target to render a list would be re-deriving something the server already
* knows, and the two would drift.
*/
export async function listTargets(
tx: Prisma.TransactionClient,
request: Omit<LinkRequest, "targetIds">,
): Promise<LinkedTarget[]> {
const spec = tableFor(request.sourceKind, request.targetKind);
const links = await spec.delegate(tx).findMany({
where: {
userId: request.userId,
[spec.sourceColumn]: request.sourceId,
},
select: { [spec.targetColumn]: true },
orderBy: { createdAt: "asc" },
});
const targetIds = links.map((link) => String(link[spec.targetColumn]));
if (targetIds.length === 0) return [];
// Re-read the targets rather than joining through the link's relation: the
// soft-delete filter belongs on the target, and a tombstoned row must drop
// out of the list even though its link row survives the soft delete.
const rows = await spec.target.delegate(tx).findMany({
where: { id: { in: targetIds }, userId: request.userId, deletedAt: null },
select: spec.target.select,
});
const byId = new Map(rows.map((row) => [String(row.id), row]));
// Ordered by the link's own creation, so the list reads in the order the
// person filed things rather than in whatever order the id lookup returned.
return targetIds.flatMap((id) => {
const row = byId.get(id);
if (!row) return [];
return [{ id, label: spec.target.label(row), date: spec.target.date(row) }];
});
}
/**
* The resolved targets for MANY sources at once, as a map keyed by source id.
*
* One grouped query for the links and one for the targets, so a page of
* documents costs two round trips rather than two per row. Sources with no
* links are absent from the map rather than present with an empty array.
*
* `includeDeletedTargets` exists for one caller and is off by default. The
* document vault has always rendered a condition chip through a relation join
* with no tombstone filter, so a document filed against a condition the person
* later deleted still shows it. Whether that is right is a product question
* this refactor does not answer; changing it silently while moving the query
* would be the wrong place to answer it.
*/
export async function listTargetsBySource(
tx: Prisma.TransactionClient,
request: {
userId: string;
sourceKind: LinkSourceKind;
sourceIds: string[];
targetKind: LinkTargetKind;
includeDeletedTargets?: boolean;
},
): Promise<Map<string, LinkedTarget[]>> {
const map = new Map<string, LinkedTarget[]>();
const sourceIds = [...new Set(request.sourceIds)];
if (sourceIds.length === 0) return map;
const spec = tableFor(request.sourceKind, request.targetKind);
const links = await spec.delegate(tx).findMany({
where: {
userId: request.userId,
[spec.sourceColumn]: { in: sourceIds },
},
select: { [spec.sourceColumn]: true, [spec.targetColumn]: true },
orderBy: { createdAt: "asc" },
});
if (links.length === 0) return map;
const targetIds = [
...new Set(links.map((link) => String(link[spec.targetColumn]))),
];
const rows = await spec.target.delegate(tx).findMany({
where: {
id: { in: targetIds },
userId: request.userId,
...(request.includeDeletedTargets ? {} : { deletedAt: null }),
},
select: spec.target.select,
});
const byId = new Map(rows.map((row) => [String(row.id), row]));
for (const link of links) {
const targetId = String(link[spec.targetColumn]);
const row = byId.get(targetId);
if (!row) continue;
const sourceId = String(link[spec.sourceColumn]);
const entry = map.get(sourceId) ?? [];
entry.push({
id: targetId,
label: spec.target.label(row),
date: spec.target.date(row),
});
map.set(sourceId, entry);
}
return map;
}
/**
* Every distinct target this account has linked at least one LIVE source to.
*
* What a filter bar needs: the chips exist because something is filed under
* them, whether or not that something is on the page currently loaded. The
* source's tombstone is what "live" means here — a condition whose only
* documents were all deleted is not offered as a filter.
*/
export async function listDistinctTargets(
tx: Prisma.TransactionClient,
request: {
userId: string;
sourceKind: LinkSourceKind;
targetKind: LinkTargetKind;
},
): Promise<LinkedTarget[]> {
const spec = tableFor(request.sourceKind, request.targetKind);
const sourceRelation = SOURCES[request.sourceKind].relationField;
const links = await spec.delegate(tx).findMany({
where: {
userId: request.userId,
[sourceRelation]: { deletedAt: null },
},
select: { [spec.targetColumn]: true },
orderBy: { [spec.targetColumn]: "asc" },
});
const targetIds = [
...new Set(links.map((link) => String(link[spec.targetColumn]))),
];
if (targetIds.length === 0) return [];
const rows = await spec.target.delegate(tx).findMany({
where: { id: { in: targetIds }, userId: request.userId },
select: spec.target.select,
});
const byId = new Map(rows.map((row) => [String(row.id), row]));
return targetIds.flatMap((id) => {
const row = byId.get(id);
if (!row) return [];
return [{ id, label: spec.target.label(row), date: spec.target.date(row) }];
});
}
+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" } },
@@ -112,4 +112,43 @@ describe("findSatisfyingEvent", () => {
});
expect(at).toBeNull();
});
it("never auto-satisfies a booked visit, whatever landed", async () => {
// An appointment reminder is free-text by construction (there is nothing a
// person could measure that means "you went"), and the free-text arm above
// resolves from ANY lab result. Left alone, a routine blood panel would
// mark next month's cardiology appointment as attended and silence it.
//
// Going is the only thing that satisfies a visit, and the visit routes are
// where that is recorded, so this matcher must refuse the row outright
// rather than look for evidence it cannot have.
const takenAt = new Date("2026-07-04T09:00:00Z");
const prisma = makePrisma({ lab: { takenAt } });
const at = await findSatisfyingEvent(prisma as never, "u1", {
...base,
measurementType: null,
origin: "ENCOUNTER",
});
expect(at).toBeNull();
// Refused before the query, not filtered after it: an appointment is not a
// question this matcher should be asking the database.
expect(prisma.labResult.findFirst).not.toHaveBeenCalled();
expect(prisma.measurement.findFirst).not.toHaveBeenCalled();
});
it("still auto-satisfies an ordinary free-text checkup", async () => {
// The counterpart, so the refusal above cannot be "never resolve anything".
const takenAt = new Date("2026-07-04T09:00:00Z");
const prisma = makePrisma({ lab: { takenAt } });
const at = await findSatisfyingEvent(prisma as never, "u1", {
...base,
measurementType: null,
origin: "VORSORGE",
});
expect(at).toEqual(takenAt);
});
});
+32
View File
@@ -24,6 +24,13 @@ export interface MeasurementReminderDtoShape {
/**
* v1.18.1 — provenance: `VORSORGE` (user-created) or `COACH` (minted from
* a Coach cadence suggestion). The UI labels the source.
*
* Deliberately two members, while `ReminderOrigin` in the schema has three.
* The third, `ENCOUNTER`, belongs to a booked visit and does not appear on
* this surface: every lookup that feeds this mapper excludes it, and the
* published enum stays closed at these two so the reminder contract does not
* move. Widening this union is the wrong repair for a type error here — the
* right one is finding the lookup that lost its exclusion.
*/
origin: "VORSORGE" | "COACH";
notifyHour: number;
@@ -35,9 +42,34 @@ export interface MeasurementReminderDtoShape {
updatedAt: string;
}
/**
* The invariant this mapper enforces: an `ENCOUNTER`-origin row is a booked
* visit's one-shot reminder and is not part of the measurement-reminder
* surface at all. Nine lookups keep it out — four list reads (the reminder
* list route, the daily digest, the insights preventive-care block and the MCP
* preventive-care tool) and five by-id lookups (read, edit, delete, complete
* and satisfy), which answer 404 rather than filtering, because an appointment
* is not addressable by that family.
*
* Reaching here means one of the nine lost its filter. The failure is loud on
* purpose, but note what it cannot undo: on `complete` and `satisfy` the throw
* used to land AFTER the write, so the caller got a 500 for a mutation that
* had already happened. Those two now refuse in the lookup, which is why the
* exclusion belongs in the query and not in a check after it.
*
* Proven by `src/__tests__/encounter-reminder-exclusion.test.ts`.
*/
export function toMeasurementReminderDto(
row: MeasurementReminder,
): MeasurementReminderDtoShape {
if (row.origin === "ENCOUNTER") {
throw new Error(
`toMeasurementReminderDto received an ENCOUNTER-origin reminder (${row.id}). ` +
"Appointment reminders are excluded from every Vorsorge read surface; " +
"a read site has lost its origin filter. See " +
"src/__tests__/encounter-reminder-exclusion.test.ts.",
);
}
return {
id: row.id,
label: row.label,
+17
View File
@@ -27,6 +27,12 @@ export interface ResolvableReminder {
anchorDate: Date | null;
lastSatisfiedAt: Date | null;
createdAt: Date;
/**
* Optional so the many callers that construct this shape by hand keep
* compiling; absent means "an ordinary reminder", which is the safe reading.
* Only `ENCOUNTER` changes the answer.
*/
origin?: import("@/generated/prisma/client").ReminderOrigin;
}
/**
@@ -50,6 +56,17 @@ export async function findSatisfyingEvent(
userId: string,
reminder: ResolvableReminder,
): Promise<Date | null> {
// An appointment is not satisfied by a measurement, and refusing it here is
// not a filter — it is the absence of a question worth asking.
//
// An appointment reminder is free-text by construction: there is no reading
// that means "you went". The free-text arm below resolves from ANY lab
// result, so without this a routine blood panel would mark next month's
// cardiology appointment as attended and silence its nudge. Going is the only
// thing that satisfies a visit, and that is recorded by moving the visit to
// DONE through the encounter routes.
if (reminder.origin === "ENCOUNTER") return null;
const floor = satisfactionFloor(reminder);
if (reminder.measurementType !== null) {
+523
View File
@@ -0,0 +1,523 @@
/**
* OpenAPI route table for visits (`/api/encounters`) and the address book
* behind them (`/api/practitioners`).
*
* Part of the OpenAPI route table; aggregated in `./index.ts`. Request bodies
* and queries reuse the runtime Zod schemas so the wire contract stays
* single-source. Response shapes are declared here to mirror the
* server-authoritative DTOs: the practitioner arrives resolved rather than as
* an id, the links arrive with a label and a date, and the appointment's next
* due instant arrives computed. A client renders these, it never rebuilds them.
*
* Note what is NOT here: the reminder `origin` enum is unchanged. A booked
* visit mints a reminder with a third origin value internally, and that value
* reaches no response, because every preventive-care read excludes it. The
* published contract stays at two members deliberately.
*/
import type { ZodOpenApiObject } from "zod-openapi";
import { z } from "zod/v4";
import {
encounterCreateSchema,
encounterUpdateSchema,
encounterListQuerySchema,
encounterLinkSchema,
encounterStatusEnum,
encounterKindEnum,
} from "@/lib/validations/encounters";
import {
practitionerCreateSchema,
practitionerUpdateSchema,
practitionerListQuerySchema,
} from "@/lib/validations/practitioners";
import {
dataEnvelope,
errorEnvelope,
recordRefusal,
stdResponses,
} from "./shared";
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.",
});
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.",
});
encounterListQuerySchema.meta({
id: "ListEncountersQuery",
description:
"Window and filters for the visit list: `from` / `to` (ISO-8601 instants), `status`, `practitionerId`, and `limit` (1–200, default 100).",
});
encounterLinkSchema.meta({
id: "EncounterLinkRequest",
description:
"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.",
});
practitionerCreateSchema.meta({
id: "CreatePractitionerRequest",
description:
"Add a doctor or practice to the caller's own address book. `name` is the only required field and is stored as queryable plaintext so the picker can search and sort it; `note` is encrypted at rest. `specialty` is free text rather than an enum. Nothing is unique across accounts.",
});
practitionerUpdateSchema.meta({
id: "UpdatePractitionerRequest",
description:
"Partial edit; an omitted key leaves the column untouched, an explicit null clears it, and a body naming nothing is a 422.",
});
practitionerListQuerySchema.meta({
id: "ListPractitionersQuery",
description:
"Query params for the address book: `q` (case-insensitive substring of the name) and `limit` (1–200, default 100). Name-ordered.",
});
const practitioner = z
.object({
id: z.string(),
name: z.string(),
specialty: z.string().nullable(),
practice: z.string().nullable(),
location: z.string().nullable(),
phone: z.string().nullable(),
note: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
})
.meta({
id: "Practitioner",
description:
"One entry in the caller's address book. `note` is the decrypted free text, or null on a key-rotation gap — fail-soft, never a 500.",
});
const linkedTarget = z
.object({
id: z.string(),
label: z.string().nullable(),
date: z.string().nullable(),
redacted: z.boolean(),
})
.meta({
id: "EncounterLinkedTarget",
description:
"One thing filed against a visit, resolved. The label and date are computed server-side from the target itself — a document's title and filing date, a lab result's panel and analyte and draw date, a condition's label and onset — so the client never re-derives them and the two cannot drift. Both go null together, with `redacted: true`, when the caller's grant does not cover the target's own domain: a visit lives in the health background but points at the vault, the labs and the illness journal, and a grant that opened only the first was never consent for the names in the other three. The link itself is still listed — the caller may know the visit produced a lab result — and `redacted` is what tells a withheld name apart from a target that simply has no date.",
});
const encounterLinks = z
.object({
documents: z.array(linkedTarget),
labResults: z.array(linkedTarget),
conditions: z.array(linkedTarget),
})
.meta({
id: "EncounterLinks",
description:
"The three link families of one visit, each ordered by when it was filed. Present on the detail response, absent from the list.",
});
const skipReport = z
.object({
catalogueKeys: z.array(
z.object({
catalogue: z.string(),
key: z.string(),
links: z.number(),
}),
),
links: z.number(),
})
.meta({
id: "EncounterSkipReport",
description:
"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 encounter = z
.object({
id: z.string(),
occurredAt: z.string(),
status: encounterStatusEnum,
kind: encounterKindEnum,
practitioner: practitioner.nullable(),
reason: z.string().nullable(),
outcome: z.string().nullable(),
reminderNextDueAt: z.string().nullable(),
links: encounterLinks.optional(),
skipped: skipReport.optional(),
createdAt: z.string(),
updatedAt: z.string(),
})
.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.",
});
const encounterList = z
.object({
upcoming: z.array(encounter),
past: z.array(encounter),
})
.meta({
id: "EncounterList",
description:
"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 encounterNotFound = {
"404": {
description: "Visit not found (or owned by another user).",
content: { "application/json": { schema: errorEnvelope } },
},
} as const;
const practitionerNotFound = {
"404": {
description: "Practitioner not found (or owned by another user).",
content: { "application/json": { schema: errorEnvelope } },
},
} as const;
const idPath = { path: z.object({ id: z.string() }) };
export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/encounters": {
get: {
tags: ["Records"],
summary: "List visits",
description:
"Returns the caller's live visits, split into `upcoming` and `past`. Bounded and windowed; soft-deleted visits are excluded.",
requestParams: { query: encounterListQuerySchema },
responses: {
...recordRefusal(),
"200": {
description: "The caller's visits.",
content: {
"application/json": {
schema: dataEnvelope(encounterList, "ListEncountersEnvelope"),
},
},
},
...stdResponses,
},
},
post: {
tags: ["Records"],
summary: "File or book a visit",
description:
"Creates one visit. A future instant with `status: PLANNED` books an appointment and mints its reminder; a past instant with `status: DONE` and a `reminderId` closes that checkup. Claiming both is a 422 — a visit that has not happened cannot have closed anything. Honours `Idempotency-Key`. Audits as `encounter.visit.create`.",
requestBody: {
required: true,
content: { "application/json": { schema: encounterCreateSchema } },
},
responses: {
...recordRefusal(),
"201": {
description: "Visit filed.",
content: {
"application/json": {
schema: dataEnvelope(encounter, "CreateEncounterEnvelope"),
},
},
},
...stdResponses,
},
},
},
"/api/encounters/{id}": {
get: {
tags: ["Records"],
summary: "Read a single visit",
description:
"Returns the visit with its three link families resolved. Owner-scoped; a cross-user or tombstoned id 404s.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "The visit.",
content: {
"application/json": {
schema: dataEnvelope(encounter, "GetEncounterEnvelope"),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
patch: {
tags: ["Records"],
summary: "Edit a visit",
description:
"Partial edit; omitted fields are left untouched. Audits as `encounter.visit.update`. Owner-scoped.",
requestParams: idPath,
requestBody: {
required: true,
content: { "application/json": { schema: encounterUpdateSchema } },
},
responses: {
...recordRefusal(),
"200": {
description: "Visit updated.",
content: {
"application/json": {
schema: dataEnvelope(encounter, "UpdateEncounterEnvelope"),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
delete: {
tags: ["Records"],
summary: "Soft-delete a visit",
description:
"Stamps `deletedAt` and retires the visit's own appointment reminder with it — never a checkup the visit closed, which belongs to the preventive-care list and outlives it. Idempotent. Audits as `encounter.visit.delete`.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "Soft-deleted.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ deleted: z.boolean() }),
"DeleteEncounterEnvelope",
),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
},
"/api/encounters/{id}/restore": {
post: {
tags: ["Records"],
summary: "Restore a soft-deleted visit",
description:
"Clears the tombstone. The link rows survived the soft delete, so the visit returns with its documents, labs and conditions still filed against it. Its appointment reminder returns only if the appointment is still in the future. Restoring a live visit is a no-op that still succeeds.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "Visit restored.",
content: {
"application/json": {
schema: dataEnvelope(encounter, "RestoreEncounterEnvelope"),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
},
"/api/encounters/{id}/links": {
post: {
tags: ["Records"],
summary: "File targets against a visit",
description:
"Adds links. Idempotent: a pair that already exists succeeds and changes nothing. Session-authenticated only, matching document link and unlink.",
requestParams: idPath,
requestBody: {
required: true,
content: { "application/json": { schema: encounterLinkSchema } },
},
responses: {
"200": {
description: "The visit's links after the change.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
links: encounterLinks,
unknown: z.array(z.string()),
}),
"LinkEncounterEnvelope",
),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
delete: {
tags: ["Records"],
summary: "Unfile targets from a visit",
description:
"Removes links. Idempotent, and it still works for a target the account has since deleted — refusing would leave a filing nobody can clear.",
requestParams: idPath,
requestBody: {
required: true,
content: { "application/json": { schema: encounterLinkSchema } },
},
responses: {
"200": {
description: "The visit's links after the change.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
links: encounterLinks,
unknown: z.array(z.string()),
}),
"UnlinkEncounterEnvelope",
),
},
},
},
...encounterNotFound,
...stdResponses,
},
},
},
"/api/practitioners": {
get: {
tags: ["Records"],
summary: "List practitioners",
description:
"Returns the caller's address book, name-ordered, with an optional case-insensitive name search.",
requestParams: { query: practitionerListQuerySchema },
responses: {
...recordRefusal(),
"200": {
description: "The caller's address book.",
content: {
"application/json": {
schema: dataEnvelope(
z.array(practitioner),
"ListPractitionersEnvelope",
),
},
},
},
...stdResponses,
},
},
post: {
tags: ["Records"],
summary: "Add a practitioner",
description:
"Creates one address-book entry. Honours `Idempotency-Key`. Audits as `practitioner.contact.create`.",
requestBody: {
required: true,
content: { "application/json": { schema: practitionerCreateSchema } },
},
responses: {
...recordRefusal(),
"201": {
description: "Practitioner added.",
content: {
"application/json": {
schema: dataEnvelope(practitioner, "CreatePractitionerEnvelope"),
},
},
},
...stdResponses,
},
},
},
"/api/practitioners/{id}": {
get: {
tags: ["Records"],
summary: "Read a single practitioner",
description:
"Returns the entry including its decrypted `note`. Owner-scoped; a cross-user or tombstoned id 404s.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "The practitioner.",
content: {
"application/json": {
schema: dataEnvelope(practitioner, "GetPractitionerEnvelope"),
},
},
},
...practitionerNotFound,
...stdResponses,
},
},
patch: {
tags: ["Records"],
summary: "Edit a practitioner",
description:
"Partial edit; omitted fields are left untouched. Audits as `practitioner.contact.update`. Owner-scoped.",
requestParams: idPath,
requestBody: {
required: true,
content: { "application/json": { schema: practitionerUpdateSchema } },
},
responses: {
...recordRefusal(),
"200": {
description: "Practitioner updated.",
content: {
"application/json": {
schema: dataEnvelope(practitioner, "UpdatePractitionerEnvelope"),
},
},
},
...practitionerNotFound,
...stdResponses,
},
},
delete: {
tags: ["Records"],
summary: "Soft-delete a practitioner",
description:
"Stamps `deletedAt`. Every visit that named this entry survives with no practice attached, because the reference nulls rather than cascades. Idempotent. Audits as `practitioner.contact.delete`.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "Soft-deleted.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ deleted: z.boolean() }),
"DeletePractitionerEnvelope",
),
},
},
},
...practitionerNotFound,
...stdResponses,
},
},
},
"/api/practitioners/{id}/restore": {
post: {
tags: ["Records"],
summary: "Restore a soft-deleted practitioner",
description:
"Clears the tombstone. It does NOT re-attach the visits whose reference was nulled on delete — which visits meant this practice is not recoverable, and guessing would be worse than the gap. Restoring a live entry is a no-op that still succeeds.",
requestParams: idPath,
responses: {
...recordRefusal(),
"200": {
description: "Practitioner restored.",
content: {
"application/json": {
schema: dataEnvelope(practitioner, "RestorePractitionerEnvelope"),
},
},
},
...practitionerNotFound,
...stdResponses,
},
},
},
};
+2
View File
@@ -48,6 +48,7 @@ import { devicePaths } from "./devices";
import { exportPaths } from "./export";
import { familyHistoryPaths } from "./family-history";
import { healthRecordPaths } from "./health-record";
import { encounterPaths } from "./encounters";
import { illnessPaths } from "./illness";
import { importPaths } from "./import";
import { insightsPaths } from "./insights";
@@ -102,6 +103,7 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
...labsPaths,
...ocrPaths,
...biomarkerPaths,
...encounterPaths,
...illnessPaths,
...mentalHealthPaths,
...allergyPaths,
+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(),
};
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Query keys — visits and the address book behind them.
* Part of the centralized factory; aggregated in `./index.ts`.
*
* These exist before any client reads them, because the in-repo
* `healthlog/queryKey-factory` rule errors on a bare array: the first
* component that lists visits cannot compile without a slot here. Same key
* with a different `queryFn` shape silently poisons the cache, which is the
* whole reason the factory is the only legal source.
*
* There is deliberately no matching `invalidateUserVisits` in
* `src/lib/cache/invalidate.ts`. That module evicts SERVER-side cached
* payloads, and no cached payload reads a visit: the dashboard snapshot, the
* insights targets and the analytics buckets are all computed from
* measurements, medications and mood. Adding a sweep over caches nothing reads
* would be a placeholder that looks like coverage. It belongs in the release
* that puts visits into one of those payloads, alongside the reader that makes
* it necessary.
*/
export const encounterKeys = {
/**
* The root prefix every visit write invalidates through
* (`encounterDependentKeys` in `./index.ts`). TanStack's hierarchical
* prefix semantics mean evicting `["encounters"]` clears the windowed list
* and every open detail in one tick, so a visit edited in a sheet and the
* list behind it never disagree.
*/
encounters: () => ["encounters"] as const,
/**
* The windowed list. The window is part of the key: the page can ask for a
* year at a time, and two windows are two different answers rather than one
* answer that overwrites the other.
*/
encounterList: (from: string | null, to: string | null, status?: string) =>
["encounters", "list", from, to, status ?? null] as const,
encounter: (id: string) => ["encounters", "detail", id] as const,
/**
* The address book. Under its own root rather than nested beneath
* `["encounters"]`: a practitioner outlives the visits that name it, and a
* visit write should not evict a list that did not change.
*/
practitioners: () => ["practitioners"] as const,
practitionerList: (q?: string) =>
["practitioners", "list", q ?? null] as const,
practitioner: (id: string) => ["practitioners", "detail", id] as const,
};
+16
View File
@@ -25,6 +25,7 @@ import { dailyKeys } from "./daily";
import { dashboardKeys } from "./dashboard";
import { environmentKeys } from "./environment";
import { documentKeys } from "./documents";
import { encounterKeys } from "./encounters";
import { illnessKeys } from "./illness";
import { insightsKeys } from "./insights";
import { integrationKeys } from "./integrations";
@@ -63,6 +64,7 @@ export const queryKeys = {
...familyHistoryKeys,
...environmentKeys,
...documentKeys,
...encounterKeys,
...customMetrics,
...nutrientKeys,
...recordSettingsKeys,
@@ -236,6 +238,20 @@ export const medicationDependentKeys = [
*/
export const cycleDependentKeys = [queryKeys.cycle(), queryKeys.insightsRoot()];
/**
* Keys invalidated when a visit or an address-book entry changes.
*
* Both roots ride together in one bundle rather than two, because the two
* writes reach each other: renaming a practice changes the label every visit
* that names it renders, and deleting one nulls the reference on visits that
* stay. A bundle that evicted only the surface being written would leave the
* other showing the pre-write name.
*/
export const encounterDependentKeys = [
queryKeys.encounters(),
queryKeys.practitioners(),
];
/**
* Invalidate every key in the bundle in parallel. Use this from mutation
* `onSuccess` handlers so the call site stays a one-liner instead of repeating
+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":
+11 -1
View File
@@ -46,7 +46,17 @@ export const SHARE_DOMAINS = [
"medications",
/** Lab results and the biomarker catalogue behind them. */
"labs",
/** Health background: allergies, family history, anamnesis facts. */
/**
* Health background: allergies, family history, anamnesis facts, and visits
* and practitioners.
*
* Visits joined this domain rather than getting one of their own, and the
* cost is worth naming: somebody granted `profile` so a relative could see
* an allergy list also gains the record of every appointment and the address
* book behind it. The mitigation is not this comment — it is the consent
* copy, which names visits in all six locales, so the widening is stated
* where it is agreed to rather than inferred from the code.
*/
"profile",
/** Illness episodes and the day logs under them. */
"illness",
+24 -2
View File
@@ -823,8 +823,19 @@ export async function handleCallback(update: TelegramUpdate) {
// v1.19.0 — mark a Vorsorge/measurement reminder done; satisfy the
// cadence via the shared primitive.
const reminderId = data.slice("measure_done:".length).trim();
// An appointment reminder is not addressable here, the same refusal the
// by-id HTTP family makes: it belongs to a visit, is managed through the
// visit routes, and sits in a different sharing domain. The lookup answers
// "not found" rather than acting on it — satisfying one would mark an
// appointment attended from a chat button, and postponing one would move a
// date the visit record still believes it owns.
const reminder = await prisma.measurementReminder.findFirst({
where: { id: reminderId, userId: user.id, deletedAt: null },
where: {
id: reminderId,
userId: user.id,
deletedAt: null,
origin: { not: "ENCOUNTER" },
},
select: {
id: true,
// v1.19.2 — the target metric; drives the optional numeric capture.
@@ -912,8 +923,19 @@ export async function handleCallback(update: TelegramUpdate) {
);
return;
}
// An appointment reminder is not addressable here, the same refusal the
// by-id HTTP family makes: it belongs to a visit, is managed through the
// visit routes, and sits in a different sharing domain. The lookup answers
// "not found" rather than acting on it — satisfying one would mark an
// appointment attended from a chat button, and postponing one would move a
// date the visit record still believes it owns.
const reminder = await prisma.measurementReminder.findFirst({
where: { id: reminderId, userId: user.id, deletedAt: null },
where: {
id: reminderId,
userId: user.id,
deletedAt: null,
origin: { not: "ENCOUNTER" },
},
select: { id: true },
});
if (!reminder) {
+61
View File
@@ -32,6 +32,8 @@ import {
ContraceptiveKind,
CycleTrackingGoal,
DocumentSummaryState,
EncounterKind,
EncounterStatus,
FamilyRelationship,
FlowLevel,
GlucoseContext,
@@ -832,6 +834,56 @@ const illnessEpisodeBackupSchema = z
})
.passthrough();
/**
* A practitioner, an encounter, and the edges between an encounter and the
* things it produced.
*
* `id` is required on both records, unlike the lab result above: a link
* addresses an encounter and its far side by id and nothing else on either row
* is unique enough to rebuild the reference from. The ciphertext columns ride
* verbatim as base64 — a visit note is never decrypted into the file.
*/
const practitionerBackupSchema = z
.object({
id: z.string().min(1),
name: z.string().min(1),
specialty: z.string().nullable().optional(),
practice: z.string().nullable().optional(),
location: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
noteEncrypted: base64BytesSchema.nullable().optional(),
createdAt: isoDateTime,
updatedAt: isoDateTime,
deletedAt: isoDateTime.nullable().optional(),
})
.passthrough();
const encounterBackupSchema = z
.object({
id: z.string().min(1),
occurredAt: isoDateTime,
status: z.enum(EncounterStatus),
kind: z.enum(EncounterKind),
practitionerId: z.string().nullable().optional(),
reasonEncrypted: base64BytesSchema.nullable().optional(),
outcomeEncrypted: base64BytesSchema.nullable().optional(),
// Carried so the loss is visible in the file. The restore resolves it to
// NULL and names the drop: the reminder it points at does not travel.
reminderId: z.string().nullable().optional(),
createdAt: isoDateTime,
updatedAt: isoDateTime,
deletedAt: isoDateTime.nullable().optional(),
})
.passthrough();
const encounterLinkBackupSchema = z
.object({
encounterId: z.string().min(1),
targetId: z.string().min(1),
createdAt: isoDateTime,
})
.passthrough();
const allergyBackupSchema = z
.object({
id: z.string().min(1),
@@ -975,6 +1027,15 @@ export const backupPayloadSchema = z
// the sections above: a file written before the table existed carries no
// key, and an account whose score never resolved writes [].
healthScoreRecords: z.array(healthScoreRecordBackupSchema).default([]),
// Visits, the address book behind them, and the three link tables.
// Defaulted for the same reason as the sections above: a file written
// before the tables existed carries no key, and an account that has never
// filed a visit writes [].
practitioners: z.array(practitionerBackupSchema).default([]),
encounters: z.array(encounterBackupSchema).default([]),
encounterDocumentLinks: z.array(encounterLinkBackupSchema).default([]),
encounterLabLinks: z.array(encounterLinkBackupSchema).default([]),
encounterConditionLinks: z.array(encounterLinkBackupSchema).default([]),
manifest: backupManifestSchema.nullable().default(null),
})
.passthrough()
+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>;