feat(links): close the relation matrix and publish related[] on six details

The link service gains medication and lab result sources and the five new
tables, each readable from both ends. POST/DELETE /api/medications/{id}/links
and /api/labs/{id}/links replace their 501 stubs; the visit links route also
files medications and doses, the dose links route its visit. A scan commit
with a documentId files each written result against its report.

GET on a lab result, visit, document, condition, medication and dose now
carries related[]: stored links, the condition a result shares a visit with,
and the medication whose efficacy target is the result's marker, each with
its web path. A kind is listed only when its module is on and the caller's
grant covers its section. relation-matrix.test.ts holds every one of the
fifteen pairs to a table, a reader or a written exception.
This commit is contained in:
Marc-André Bombeck committed 2026-10-15 23:57:34 +02:00
1 parent ffd46b017b
commit b4bc039d16
25 files changed
+1569 -82

No files matched your search

@@ -57,6 +57,15 @@ vi.mock("@/lib/db", () => ({
},
}));
// `related[]` has its own tests (`src/lib/links/__tests__`); here it is the
// empty list, so the detail assertions stay about the document.
vi.mock("@/lib/links/related", () => ({
withRelated: async (_tx: unknown, detail: object) => ({
...detail,
related: [],
}),
}));
vi.mock("@/lib/crypto", () => ({
encrypt: vi.fn((s: string) => `v1.${s}`),
decrypt: vi.fn((s: string) => s.replace(/^v1\./u, "")),
+16 -11
View File
@@ -45,6 +45,7 @@ import {
} from "@/lib/validations/inbound-documents";
import type { Prisma } from "@/generated/prisma/client";
import { dateOnlyAtNoonUtc } from "@/lib/tz/date-only";
import { withRelated } from "@/lib/links/related";
type RouteParams = { params: Promise<{ id: string }> };
@@ -132,17 +133,21 @@ export const GET = apiHandler(
});
return apiSuccess(
serialiseDocumentDetail(
document,
document.facts,
links.get(document.id) ?? [],
contentIndex !== null,
toContentIndexSource(contentIndex?.source),
thumbnail !== null,
visitLinks.get(document.id) ?? [],
doseLinks === null ? null : (doseLinks.get(document.id) ?? []),
// v1.43 — the marker each pending lab value resolves to, or choices.
await markerIndexForFacts(user.id, document.facts),
await withRelated(
prisma,
serialiseDocumentDetail(
document,
document.facts,
links.get(document.id) ?? [],
contentIndex !== null,
toContentIndexSource(contentIndex?.source),
thumbnail !== null,
visitLinks.get(document.id) ?? [],
doseLinks === null ? null : (doseLinks.get(document.id) ?? []),
// v1.43 — the marker each pending lab value resolves to, or choices.
await markerIndexForFacts(user.id, document.facts),
),
{ userId: user.id, grantId, kind: "document", id: document.id },
),
);
},
+2 -1
View File
@@ -1,5 +1,6 @@
/**
* `POST /api/encounters/{id}/links` — file things against a visit.
* `POST /api/encounters/{id}/links` — file things against a visit: documents,
* lab results, conditions and, since v1.43, medications and doses.
* `DELETE /api/encounters/{id}/links` — unfile them.
*
* Deliberately bare `requireAuth()` rather than a delegable declaration, and
+9 -1
View File
@@ -54,6 +54,7 @@ import {
} from "@/lib/export/restore-skips";
import type { Prisma } from "@/generated/prisma/client";
import { actingDomainVisibility } from "@/lib/sharing/acting-domains";
import { withRelated } from "@/lib/links/related";
type RouteParams = { params: Promise<{ id: string }> };
@@ -81,7 +82,14 @@ export const GET = apiHandler(
},
});
return apiSuccess(toEncounterDTO(row, links));
return apiSuccess(
await withRelated(prisma, toEncounterDTO(row, links), {
userId: user.id,
grantId,
kind: "encounter",
id,
}),
);
},
);
+10 -2
View File
@@ -27,12 +27,13 @@ import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { illnessEpisodeUpdateSchema } from "@/lib/validations/illness";
import { toIllnessEpisodeDTO } from "@/lib/illness/dto";
import type { Prisma } from "@/generated/prisma/client";
import { withRelated } from "@/lib/links/related";
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("read", "illness");
const { user, grantId } = await requireRecordAuth("read", "illness");
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
@@ -51,7 +52,14 @@ export const GET = apiHandler(
},
});
return apiSuccess(toIllnessEpisodeDTO(row));
return apiSuccess(
await withRelated(prisma, toIllnessEpisodeDTO(row), {
userId: user.id,
grantId,
kind: "conditionEpisode",
id,
}),
);
},
);
+43 -5
View File
@@ -11,8 +11,15 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { returnAllZodIssues, safeJson } from "@/lib/api-response";
import { notImplemented } from "@/lib/http/not-implemented";
import {
apiError,
apiSuccess,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { prisma } from "@/lib/db";
import { linkTargets, unlinkTargets } from "@/lib/links";
import { annotate } from "@/lib/logging/context";
import { labResultLinkSchema } from "@/lib/validations/relation-links";
type RouteParams = { params: Promise<{ id: string }> };
@@ -22,8 +29,8 @@ async function handle(
{ params }: RouteParams,
verb: "link" | "unlink",
): Promise<Response> {
await requireAuth();
await params;
const { user } = await requireAuth();
const { id } = await params;
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
@@ -36,7 +43,38 @@ async function handle(
});
}
return notImplemented(`labs.link.${verb}`);
const apply = verb === "link" ? linkTargets : unlinkTargets;
const result = await apply(prisma, {
userId: user.id,
sourceKind: "labResult",
sourceId: id,
targetKind: parsed.data.targetKind,
targetIds: parsed.data.targetIds,
});
// Like the visit and vaccination link routes: a link to a source this
// account does not own is a 404; an unlink is scoped to the account's own
// link rows and so is an idempotent no-op instead.
if (result.unknownSource) {
return apiError("Lab result not found", 404);
}
annotate({
action: {
name: `labs.link.${verb}`,
entity_type: "lab_result",
entity_id: id,
},
meta: {
target_kind: parsed.data.targetKind,
changed: result.changed,
unknown: result.unknownTargetIds.length,
},
});
return apiSuccess({
changed: result.changed,
unknown: result.unknownTargetIds,
});
}
export const POST = apiHandler(
+10 -5
View File
@@ -20,6 +20,7 @@ import {
} from "@/lib/labs/serialise";
import { decryptNoteFromBytes, encryptNoteToBytes } from "@/lib/labs/store";
import { annotate } from "@/lib/logging/context";
import { withRelated } from "@/lib/links/related";
import {
effectiveBound,
isInvertedRange,
@@ -66,7 +67,7 @@ function toResolved(
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("read", "labs");
const { user, grantId } = await requireRecordAuth("read", "labs");
const { id } = await params;
const row = await prisma.labResult.findFirst({
@@ -80,10 +81,14 @@ export const GET = apiHandler(
annotate({ action: { name: "labs.get" }, meta: { labResultId: id } });
return apiSuccess(
serialiseLabResultDetail(
row,
toResolved(row.biomarker),
row.noteEncrypted ? decryptNoteFromBytes(row.noteEncrypted) : null,
await withRelated(
prisma,
serialiseLabResultDetail(
row,
toResolved(row.biomarker),
row.noteEncrypted ? decryptNoteFromBytes(row.noteEncrypted) : null,
),
{ userId: user.id, grantId, kind: "labResult", id },
),
);
},
+11
View File
@@ -371,6 +371,17 @@ async function commitOcrRows(request: NextRequest) {
parsed.data.documentId,
linkable,
).catch(() => {});
// v1.43 — the stored relation as well: each written result points at the
// report it was read from (`lab_result_document_links`), so the result's
// and the document's `related` lists name each other. Best-effort for the
// same reason; the service narrows both ends to this record.
await linkTargets(prisma, {
userId: user.id,
sourceKind: "document",
sourceId: parsed.data.documentId,
targetKind: "labResult",
targetIds: linkable.map((row) => row.labResultId),
}).catch(() => {});
}
// The visit the review step offered, if it offered one. ONE LINK PER RESULT
+43 -5
View File
@@ -11,8 +11,15 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { returnAllZodIssues, safeJson } from "@/lib/api-response";
import { notImplemented } from "@/lib/http/not-implemented";
import {
apiError,
apiSuccess,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { prisma } from "@/lib/db";
import { linkTargets, unlinkTargets } from "@/lib/links";
import { annotate } from "@/lib/logging/context";
import { medicationLinkSchema } from "@/lib/validations/relation-links";
type RouteParams = { params: Promise<{ id: string }> };
@@ -22,8 +29,8 @@ async function handle(
{ params }: RouteParams,
verb: "link" | "unlink",
): Promise<Response> {
await requireAuth();
await params;
const { user } = await requireAuth();
const { id } = await params;
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
@@ -36,7 +43,38 @@ async function handle(
});
}
return notImplemented(`medication.link.${verb}`);
const apply = verb === "link" ? linkTargets : unlinkTargets;
const result = await apply(prisma, {
userId: user.id,
sourceKind: "medication",
sourceId: id,
targetKind: parsed.data.targetKind,
targetIds: parsed.data.targetIds,
});
// Like the visit and vaccination link routes: a link to a source this
// account does not own is a 404; an unlink is scoped to the account's own
// link rows and so is an idempotent no-op instead.
if (result.unknownSource) {
return apiError("Medication not found", 404);
}
annotate({
action: {
name: `medication.link.${verb}`,
entity_type: "medication",
entity_id: id,
},
meta: {
target_kind: parsed.data.targetKind,
changed: result.changed,
unknown: result.unknownTargetIds.length,
},
});
return apiSuccess({
changed: result.changed,
unknown: result.unknownTargetIds,
});
}
export const POST = apiHandler(
+9 -1
View File
@@ -62,6 +62,7 @@ import {
import { floorWhole } from "@/lib/medications/units-per-dose";
import { resolveIntakeActionability } from "@/lib/medications/intake-actionable";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { buildRelated } from "@/lib/links/related";
type RouteParams = { params: Promise<{ id: string }> };
@@ -103,7 +104,7 @@ function reconcileScheduleWindow(
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("read", "medications");
const { user, grantId } = await requireRecordAuth("read", "medications");
const { id } = await params;
const medication = await prisma.medication.findUnique({
@@ -294,6 +295,13 @@ export const GET = apiHandler(
stockUnitsRemaining,
stockDosesRemaining,
runwayDays,
// v1.43 — the records this medication relates to (`src/lib/links/`).
related: await buildRelated(prisma, {
userId: user.id,
grantId,
kind: "medication",
id,
}),
});
},
);
+2 -1
View File
@@ -1,5 +1,6 @@
/**
* `POST /api/vaccinations/{id}/links` — file a scanned page against a dose.
* `POST /api/vaccinations/{id}/links` — file a scanned page, or since v1.43
* the visit it was given at, against a dose.
* `DELETE /api/vaccinations/{id}/links` — unfile it.
*
* Deliberately bare `requireAuth()` rather than a delegable declaration, and
+8 -1
View File
@@ -41,6 +41,7 @@ import {
} from "@/lib/vaccinations/service";
import type { Prisma } from "@/generated/prisma/client";
import { actingDomainVisibility } from "@/lib/sharing/acting-domains";
import { withRelated } from "@/lib/links/related";
type RouteParams = { params: Promise<{ id: string }> };
@@ -71,7 +72,13 @@ export const GET = apiHandler(
},
});
return apiSuccess(toVaccinationDTO(row, series.get(id) ?? [], documents));
return apiSuccess(
await withRelated(
prisma,
toVaccinationDTO(row, series.get(id) ?? [], documents),
{ userId: user.id, grantId, kind: "vaccination", id },
),
);
},
);