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

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

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

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

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

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

No files matched your search

@@ -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);
}