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

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