mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 04:50:59 +00:00
Merge branch 'v143/labs' into release/v1.43.0
This commit is contained in:
commit
74fa4e10b6
96 files changed
+6992
-626
No files matched your search
@@ -39,7 +39,6 @@ const CONTRACT_STUBS: Readonly<Record<string, readonly string[]>> = {
|
||||
"anamnesis/life-circumstances/route.ts": ["anamnesis.life_circumstances.get"],
|
||||
"auth/claim/sso/route.ts": ["profile_claim.sso.start"],
|
||||
"auth/me/ai-usage/route.ts": ["auth.me.ai_usage.put"],
|
||||
"biomarkers/[id]/merge/route.ts": ["labs.biomarker.merge"],
|
||||
"dawarich/connect/route.ts": ["dawarich.connect"],
|
||||
"dawarich/disconnect/route.ts": ["dawarich.disconnect"],
|
||||
"dawarich/places/route.ts": ["dawarich.places.get"],
|
||||
|
||||
@@ -859,6 +859,10 @@ const DELEGABLE_ROUTES: Record<string, DelegableEntry> = {
|
||||
domain: "labs",
|
||||
why: "One biomarker of the record, fetch-then-guard against the resolved user.",
|
||||
},
|
||||
"app/api/biomarkers/[id]/merge/route.ts": {
|
||||
domain: "labs",
|
||||
why: "Merging markers of the record into one (v1.43): every read and write is narrowed to the resolved user, and the sources must be that record's markers.",
|
||||
},
|
||||
"app/api/allergies/route.ts": {
|
||||
domain: "profile",
|
||||
why: "The record's allergy list — the single most useful thing a caregiver can read, and a plain list of the owner's own rows. The POST beside it is NOT delegable and is deliberately absent from the write literal below: the only surface that posts to it lives under `/settings`, which a switch closes, so admitting the write would freeze a permission ahead of any caller for it. The route comment carries the argument.",
|
||||
@@ -1612,6 +1616,11 @@ const DELEGABLE_MANAGE_ROUTES: Record<string, ManageEntry> = {
|
||||
conditions: ["C3", "C4"],
|
||||
why: "Editing an analyte's reference range, the one admitted edit whose error is silent, which is why C4 puts it in the feed. The DELETE beside it resolves through the same labs authority since v1.43 instead of a bare requireAuth; it hard-deletes the marker with its readings, so C3 files the name, unit and reading count it took.",
|
||||
},
|
||||
"app/api/biomarkers/[id]/merge/route.ts": {
|
||||
domain: "labs",
|
||||
conditions: ["C3"],
|
||||
why: "Merging markers moves their readings into one and deletes the sources, with no undo, so it sits at the same level as the delete beside it. C3: each deleted source files its id and how many readings went with it; the name stays in the merge ledger. The shared record-write ceiling is charged to the actor, like every record write.",
|
||||
},
|
||||
"app/api/allergies/route.ts": {
|
||||
domain: "profile",
|
||||
conditions: [],
|
||||
@@ -2117,8 +2126,11 @@ const ACTOR_ROUTES: Record<string, string> = {
|
||||
* facts (`profile`) and the nutrient catalogue beside the nutrient reads
|
||||
* (`measurements`). The biomarker DELETE joins the manage literal on a module
|
||||
* that was already there. 256 -> 258.
|
||||
*
|
||||
* v1.43 -- merging biomarkers joins the record list and the manage literal
|
||||
* (D1223). 258 -> 260.
|
||||
*/
|
||||
const FROZEN_ENTRY_COUNT = 258;
|
||||
const FROZEN_ENTRY_COUNT = 260;
|
||||
|
||||
/**
|
||||
* The two surfaces that authenticate a Bearer token outside `requireAuth` —
|
||||
@@ -2879,7 +2891,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(88);
|
||||
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(89);
|
||||
|
||||
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(88);
|
||||
expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(89);
|
||||
expect(
|
||||
new Set(
|
||||
ADMITTED_MUTATING_HANDLERS.map(
|
||||
|
||||
@@ -89,7 +89,7 @@ const SERVER_FEATURES = {
|
||||
// form work; until then a client must not send it (contract §0.6).
|
||||
cumulativeHourBuckets: false,
|
||||
syncTriggerBackfill: false,
|
||||
biomarkerMerge: false,
|
||||
biomarkerMerge: true,
|
||||
lifeCircumstances: false,
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
biomarker: { findFirst: vi.fn(), update: vi.fn(), delete: vi.fn() },
|
||||
vi.mock("@/lib/db", () => {
|
||||
const prisma = {
|
||||
biomarker: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(async () => []),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
// v1.43 — the marker's other spellings, read and replaced with it.
|
||||
biomarkerAlias: {
|
||||
findMany: vi.fn(async () => []),
|
||||
deleteMany: vi.fn(),
|
||||
createMany: vi.fn(),
|
||||
},
|
||||
biomarkerMerge: { findFirst: vi.fn(async () => null) },
|
||||
labResult: { deleteMany: vi.fn() },
|
||||
auditLog: { create: vi.fn().mockResolvedValue({}) },
|
||||
$transaction: vi.fn(async (ops: Promise<unknown>[]) => Promise.all(ops)),
|
||||
},
|
||||
}));
|
||||
};
|
||||
// `$transaction` is set in `beforeEach`: the batch form for the delete, the
|
||||
// callback form for the edit.
|
||||
return { prisma: { ...prisma, $transaction: vi.fn() } };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
|
||||
@@ -82,9 +96,13 @@ beforeEach(() => {
|
||||
// v1.37.0 — the 422 breadcrumb goes through `auditLog()` and the route
|
||||
// chains `.catch()` on it; `resetAllMocks` clears the factory's resolution.
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined as never);
|
||||
vi.mocked(prisma.$transaction).mockImplementation((async (
|
||||
ops: Promise<unknown>[],
|
||||
) => Promise.all(ops)) as never);
|
||||
vi.mocked(prisma.$transaction).mockImplementation((async (arg: unknown) =>
|
||||
typeof arg === "function"
|
||||
? (arg as (tx: unknown) => Promise<unknown>)(prisma)
|
||||
: Promise.all(arg as Promise<unknown>[])) as never);
|
||||
vi.mocked(prisma.biomarkerAlias.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarker.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerMerge.findFirst).mockResolvedValue(null as never);
|
||||
});
|
||||
|
||||
describe("DELETE /api/biomarkers/[id]", () => {
|
||||
|
||||
@@ -7,19 +7,32 @@
|
||||
* (`MERGE`), one `biomarker_merges` row is written per source and the sources
|
||||
* are deleted. A pair of units without a known conversion refuses the whole
|
||||
* merge (422 `labs.biomarker.merge.unitMismatch`); nothing moves. `dryRun`
|
||||
* answers the same result and writes nothing. There is no undo.
|
||||
* answers the same result and writes nothing, refusals included, so the
|
||||
* preview can show them. There is no undo. See `src/lib/labs/biomarker-merge.ts`.
|
||||
*
|
||||
* Contract authority: `requireRecordAuth("manage", "labs")` with the shared
|
||||
* record-write ceiling. Until the merge lands the stub resolves the caller's
|
||||
* own record only.
|
||||
* Authority: `requireRecordAuth("manage", "labs")`, the same as the edit and
|
||||
* the delete beside it, because a merge rewrites and deletes markers. The
|
||||
* shared record-write ceiling is charged to the ACTOR (C1). Each deleted
|
||||
* source files what was destroyed (C3): its id and how many readings it took
|
||||
* along, never its name; the name stays in the merge ledger.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiError, returnAllZodIssues, safeJson } from "@/lib/api-response";
|
||||
import { notImplemented } from "@/lib/http/not-implemented";
|
||||
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { mergeBiomarkers as runMerge } from "@/lib/labs/biomarker-merge";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
import { destroyedDetails } from "@/lib/sharing/audit-details";
|
||||
import { biomarkerMergeSchema } from "@/lib/validations/biomarker-merge";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
@@ -32,10 +45,10 @@ async function mergeBiomarkers(
|
||||
request: NextRequest,
|
||||
{ params }: RouteParams,
|
||||
): Promise<Response> {
|
||||
const { user } = await requireAuth();
|
||||
const { user, actor } = await requireRecordAuth("manage", "labs");
|
||||
const { id } = await params;
|
||||
|
||||
const writeRl = await checkRecordWriteRateLimit(user.id);
|
||||
const writeRl = await checkRecordWriteRateLimit(actor.id);
|
||||
if (!writeRl.allowed) {
|
||||
return apiError("Too many writes, try again later", 429, {
|
||||
errorCode: "record_write.rate_limited",
|
||||
@@ -58,5 +71,74 @@ async function mergeBiomarkers(
|
||||
});
|
||||
}
|
||||
|
||||
return notImplemented("labs.biomarker.merge");
|
||||
const outcome = await runMerge({
|
||||
userId: user.id,
|
||||
targetId: id,
|
||||
sourceIds: parsed.data.sourceIds,
|
||||
dryRun: parsed.data.dryRun,
|
||||
});
|
||||
|
||||
if (outcome.kind === "notFound") {
|
||||
return apiError("Biomarker not found", 404, {
|
||||
errorCode: "labs.biomarker.notFound",
|
||||
ids: outcome.ids,
|
||||
});
|
||||
}
|
||||
if (outcome.kind === "unitMismatch") {
|
||||
annotate({
|
||||
action: { name: "labs.biomarker.merge.unit-mismatch" },
|
||||
meta: { biomarkerId: id, refused: outcome.sources.length },
|
||||
});
|
||||
return apiError(
|
||||
"Some readings are in a unit that cannot be converted to the target's unit",
|
||||
422,
|
||||
{
|
||||
errorCode: "labs.biomarker.merge.unitMismatch",
|
||||
sources: outcome.sources,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = outcome;
|
||||
annotate({
|
||||
action: {
|
||||
name: result.dryRun
|
||||
? "labs.biomarker.merge.preview"
|
||||
: "labs.biomarker.merge",
|
||||
},
|
||||
meta: {
|
||||
biomarkerId: id,
|
||||
sources: result.sources.length,
|
||||
movedReadings: result.movedReadings,
|
||||
convertedReadings: result.convertedReadings,
|
||||
},
|
||||
});
|
||||
if (result.dryRun) return apiSuccess(result);
|
||||
|
||||
invalidateUserHealthScore(user.id);
|
||||
const ipAddress = getClientIp(request);
|
||||
for (const source of result.sources) {
|
||||
await auditLog("labs.biomarker.merge", {
|
||||
userId: user.id,
|
||||
ipAddress,
|
||||
// IDs and numbers only. The source's name is not filed here; the merge
|
||||
// ledger keeps it with the row this audit points at.
|
||||
details: {
|
||||
biomarkerId: id,
|
||||
mergeId: result.mergeId,
|
||||
...destroyedDetails({
|
||||
model: "Biomarker",
|
||||
id: source.id,
|
||||
label: null,
|
||||
effectiveAt: new Date(),
|
||||
extra: {
|
||||
readingCount: source.readingCount,
|
||||
converted: source.conversion === "converted",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess(result);
|
||||
}
|
||||
@@ -17,9 +17,13 @@ import {
|
||||
import { prisma } from "@/lib/db";
|
||||
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
|
||||
import {
|
||||
decryptContextFromBytes,
|
||||
encryptContextToBytes,
|
||||
} from "@/lib/labs/biomarker-store";
|
||||
aliasNamesByMarker,
|
||||
findAliasConflict,
|
||||
replaceAliases,
|
||||
} from "@/lib/labs/biomarker-aliases";
|
||||
import { serialiseBiomarker } from "@/lib/labs/biomarker-dto";
|
||||
import { mergedInto } from "@/lib/labs/biomarker-merge";
|
||||
import { encryptContextToBytes } from "@/lib/labs/biomarker-store";
|
||||
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { updateBiomarkerSchema } from "@/lib/validations/biomarkers";
|
||||
@@ -38,37 +42,6 @@ import { effectiveBound, isInvertedRange } from "@/lib/validations/labs";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
function serialiseBiomarker(row: {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
lowerBound: number | null;
|
||||
upperBound: number | null;
|
||||
panel: string | null;
|
||||
analyteKey: string | null;
|
||||
hidden: boolean;
|
||||
contextEncrypted: Uint8Array | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
unit: row.unit,
|
||||
lowerBound: row.lowerBound,
|
||||
upperBound: row.upperBound,
|
||||
panel: row.panel,
|
||||
analyteKey: row.analyteKey,
|
||||
hasContext: row.contextEncrypted !== null,
|
||||
context: row.contextEncrypted
|
||||
? decryptContextFromBytes(row.contextEncrypted)
|
||||
: null,
|
||||
hidden: row.hidden,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireRecordAuth("read", "labs");
|
||||
@@ -76,15 +49,23 @@ export const GET = apiHandler(
|
||||
|
||||
const row = await prisma.biomarker.findFirst({ where: { id } });
|
||||
if (!row || row.userId !== user.id) {
|
||||
return apiError("Biomarker not found", 404);
|
||||
// v1.43 — a marker merged into another names where it went, so a
|
||||
// client holding the old id (a cached screen, a bookmark) can follow.
|
||||
const into = await mergedInto(user.id, id);
|
||||
return apiError("Biomarker not found", 404, {
|
||||
errorCode: "labs.biomarker.notFound",
|
||||
...(into ? { mergedInto: into } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const aliases = await aliasNamesByMarker(prisma, user.id, [row]);
|
||||
|
||||
annotate({
|
||||
action: { name: "labs.biomarker.get" },
|
||||
meta: { biomarkerId: id },
|
||||
});
|
||||
|
||||
return apiSuccess(serialiseBiomarker(row));
|
||||
return apiSuccess(serialiseBiomarker(row, aliases.get(row.id) ?? []));
|
||||
},
|
||||
);
|
||||
|
||||
@@ -171,6 +152,20 @@ export const PUT = apiHandler(
|
||||
}
|
||||
}
|
||||
|
||||
// v1.43 — the aliases, when sent, become the marker's whole set. A
|
||||
// spelling another marker already answers to (its name or one of its
|
||||
// aliases) is refused rather than silently moved.
|
||||
if (d.aliases !== undefined) {
|
||||
const conflict = await findAliasConflict(prisma, user.id, id, d.aliases);
|
||||
if (conflict) {
|
||||
return apiError("Another biomarker already answers to this name", 409, {
|
||||
errorCode: "labs.biomarker.alias.taken",
|
||||
alias: conflict.alias,
|
||||
biomarkerId: conflict.biomarkerId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Build `data` field-by-field. `undefined` → leave the column untouched;
|
||||
// an explicit `null` on `context` / `panel` / a bound clears it.
|
||||
const data: Record<string, unknown> = {};
|
||||
@@ -212,7 +207,17 @@ export const PUT = apiHandler(
|
||||
: null;
|
||||
}
|
||||
|
||||
const updated = await prisma.biomarker.update({ where: { id }, data });
|
||||
const aliasesBefore =
|
||||
(await aliasNamesByMarker(prisma, user.id, [existing])).get(id) ?? [];
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
const row = await tx.biomarker.update({ where: { id }, data });
|
||||
if (d.aliases !== undefined) {
|
||||
await replaceAliases(tx, user.id, row, d.aliases);
|
||||
}
|
||||
return row;
|
||||
});
|
||||
const aliasesAfter =
|
||||
(await aliasNamesByMarker(prisma, user.id, [updated])).get(id) ?? [];
|
||||
invalidateUserHealthScore(user.id);
|
||||
|
||||
await auditLog("biomarker.update", {
|
||||
@@ -241,7 +246,13 @@ export const PUT = apiHandler(
|
||||
panel: updated.panel,
|
||||
hidden: updated.hidden,
|
||||
},
|
||||
redacted: d.context !== undefined ? ["context"] : [],
|
||||
redacted: [
|
||||
...(d.context !== undefined ? ["context"] : []),
|
||||
// Named, not quoted: the spellings are the person's own text.
|
||||
...(aliasesBefore.join("\n") !== aliasesAfter.join("\n")
|
||||
? ["aliases"]
|
||||
: []),
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -251,7 +262,7 @@ export const PUT = apiHandler(
|
||||
meta: { biomarkerId: id },
|
||||
});
|
||||
|
||||
return apiSuccess(serialiseBiomarker(updated));
|
||||
return apiSuccess(serialiseBiomarker(updated, aliasesAfter));
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -13,10 +13,9 @@ import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import {
|
||||
decryptContextSoft,
|
||||
encryptContextToBytes,
|
||||
} from "@/lib/labs/biomarker-store";
|
||||
import { aliasNamesByMarker } from "@/lib/labs/biomarker-aliases";
|
||||
import { serialiseBiomarker } from "@/lib/labs/biomarker-dto";
|
||||
import { encryptContextToBytes } from "@/lib/labs/biomarker-store";
|
||||
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { createBiomarkerSchema } from "@/lib/validations/biomarkers";
|
||||
@@ -45,35 +44,6 @@ import { createBiomarkerSchema } from "@/lib/validations/biomarkers";
|
||||
// a bad-key / malformed row) so one un-decryptable row never 500s the whole
|
||||
// catalog — the single-resource GET is the authoritative read for the
|
||||
// plaintext context. This bounds the fail-closed blast radius to one marker.
|
||||
function serialiseBiomarker(row: {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
lowerBound: number | null;
|
||||
upperBound: number | null;
|
||||
panel: string | null;
|
||||
analyteKey: string | null;
|
||||
hidden: boolean;
|
||||
contextEncrypted: Uint8Array | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
unit: row.unit,
|
||||
lowerBound: row.lowerBound,
|
||||
upperBound: row.upperBound,
|
||||
panel: row.panel,
|
||||
analyteKey: row.analyteKey,
|
||||
hasContext: row.contextEncrypted !== null,
|
||||
context: decryptContextSoft(row.contextEncrypted),
|
||||
hidden: row.hidden,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireRecordAuth("read", "labs");
|
||||
|
||||
@@ -84,12 +54,19 @@ export const GET = apiHandler(async () => {
|
||||
orderBy: [{ hidden: "asc" }, { name: "asc" }],
|
||||
});
|
||||
|
||||
// v1.43 — every marker's other spellings, one read for the whole list.
|
||||
const aliases = await aliasNamesByMarker(prisma, user.id, rows);
|
||||
|
||||
annotate({
|
||||
action: { name: "labs.biomarker.list" },
|
||||
meta: { total: rows.length },
|
||||
});
|
||||
|
||||
return apiSuccess({ biomarkers: rows.map(serialiseBiomarker) });
|
||||
return apiSuccess({
|
||||
biomarkers: rows.map((row) =>
|
||||
serialiseBiomarker(row, aliases.get(row.id) ?? [], { soft: true }),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postBiomarker));
|
||||
@@ -179,5 +156,5 @@ async function postBiomarker(request: NextRequest) {
|
||||
meta: { biomarkerId: created.id },
|
||||
});
|
||||
|
||||
return apiSuccess(serialiseBiomarker(created), 201);
|
||||
return apiSuccess(serialiseBiomarker(created, [], { soft: true }), 201);
|
||||
}
|
||||
@@ -100,7 +100,12 @@ async function confirmDocument(
|
||||
}
|
||||
|
||||
try {
|
||||
const ref = await commitApprovedFact(user.id, fact);
|
||||
// v1.43 (D1223) — an OBSERVATION may name the marker the person chose
|
||||
// on the review screen; the label is then remembered as its alias.
|
||||
const ref = await commitApprovedFact(user.id, fact, {
|
||||
biomarkerId: decision.biomarkerId,
|
||||
rememberAlias: decision.rememberAlias,
|
||||
});
|
||||
await prisma.extractedFact.update({
|
||||
where: { id: fact.id },
|
||||
data: {
|
||||
|
||||
@@ -51,6 +51,7 @@ vi.mock("@/lib/documents/store", () => ({
|
||||
encryptFactData: vi.fn(() => new Uint8Array([1])),
|
||||
encryptFactProvenance: vi.fn(() => new Uint8Array([2])),
|
||||
serialiseDocumentDetail: vi.fn(() => ({ id: "doc-1", facts: [] })),
|
||||
markerIndexForFacts: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock("@/lib/documents/content-index", () => ({
|
||||
loadDocumentChatText: vi.fn(),
|
||||
|
||||
@@ -55,7 +55,10 @@ import {
|
||||
} from "@/lib/ai/coach/budget";
|
||||
import type { ProviderChainType } from "@/lib/ai/provider-chain";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { serialiseDocumentDetail } from "@/lib/documents/store";
|
||||
import {
|
||||
markerIndexForFacts,
|
||||
serialiseDocumentDetail,
|
||||
} from "@/lib/documents/store";
|
||||
import {
|
||||
requireDocumentTextProvider,
|
||||
requireDocumentVisionProvider,
|
||||
@@ -241,7 +244,19 @@ async function runNow(
|
||||
origin: { ipAddress: getClientIp(request), worker: false },
|
||||
});
|
||||
if (!outcome.ok) return outcomeResponse(outcome);
|
||||
return apiSuccess(serialiseDocumentDetail(outcome.data, outcome.data.facts));
|
||||
return apiSuccess(
|
||||
serialiseDocumentDetail(
|
||||
outcome.data,
|
||||
outcome.data.facts,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
await markerIndexForFacts(userId, outcome.data.facts),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** TEXT mode — structure in-browser-OCR'd text against the stored row. */
|
||||
|
||||
@@ -18,7 +18,11 @@ import {
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { encryptFactData, serialiseFact } from "@/lib/documents/store";
|
||||
import {
|
||||
encryptFactData,
|
||||
markerIndexForFacts,
|
||||
serialiseFact,
|
||||
} from "@/lib/documents/store";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import {
|
||||
@@ -125,6 +129,8 @@ export const PATCH = apiHandler(
|
||||
meta: { documentId: id, factId: fact.id, factType: fact.factType },
|
||||
});
|
||||
|
||||
return apiSuccess(serialiseFact(updated));
|
||||
return apiSuccess(
|
||||
serialiseFact(updated, await markerIndexForFacts(user.id, [updated])),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -32,7 +32,10 @@ import {
|
||||
replaceVaccinationLinks,
|
||||
} from "@/lib/documents/links";
|
||||
import { actingDomainVisibility } from "@/lib/sharing/acting-domains";
|
||||
import { serialiseDocumentDetail } from "@/lib/documents/store";
|
||||
import {
|
||||
markerIndexForFacts,
|
||||
serialiseDocumentDetail,
|
||||
} from "@/lib/documents/store";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { requireModuleEnabled } from "@/lib/modules/gate";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
@@ -138,6 +141,8 @@ export const GET = apiHandler(
|
||||
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),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -86,6 +86,8 @@ vi.mock("@/lib/db", () => ({
|
||||
// helper now also reads (`buildRecordsBackupSection`).
|
||||
labResult: { findMany: vi.fn() },
|
||||
biomarker: { findMany: vi.fn() },
|
||||
biomarkerAlias: { findMany: vi.fn() },
|
||||
biomarkerMerge: { findMany: vi.fn() },
|
||||
illnessEpisode: { findMany: vi.fn() },
|
||||
allergy: { findMany: vi.fn() },
|
||||
familyHistoryEntry: { findMany: vi.fn() },
|
||||
@@ -135,6 +137,8 @@ beforeEach(() => {
|
||||
// `resetAllMocks` clears the inline defaults, and the full-backup payload
|
||||
// builder reads these unconditionally.
|
||||
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerAlias.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerMerge.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.medicationCategoryLabel.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
|
||||
@@ -67,6 +67,8 @@ vi.mock("@/lib/db", () => ({
|
||||
cycleDayLog: { findMany: vi.fn() },
|
||||
labResult: { findMany: vi.fn() },
|
||||
biomarker: { findMany: vi.fn() },
|
||||
biomarkerAlias: { findMany: vi.fn() },
|
||||
biomarkerMerge: { findMany: vi.fn() },
|
||||
allergy: { findMany: vi.fn() },
|
||||
familyHistoryEntry: { findMany: vi.fn() },
|
||||
workout: { findMany: vi.fn() },
|
||||
@@ -205,6 +207,8 @@ beforeEach(() => {
|
||||
vi.mocked(prisma.cycleDayLog.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarker.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerAlias.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerMerge.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.allergy.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.familyHistoryEntry.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.workout.findMany).mockResolvedValue([] as never);
|
||||
|
||||
@@ -77,6 +77,8 @@ vi.mock("@/lib/db", () => ({
|
||||
// builder now also reads (`buildRecordsBackupSection`).
|
||||
labResult: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
biomarker: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
biomarkerAlias: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
biomarkerMerge: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
illnessEpisode: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
allergy: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
familyHistoryEntry: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
|
||||
@@ -16,6 +16,9 @@ vi.mock("@/lib/db", () => ({
|
||||
findMany: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
// v1.43 — the account's markers and aliases, loaded once per commit.
|
||||
biomarker: { findMany: vi.fn() },
|
||||
biomarkerAlias: { findMany: vi.fn(), upsert: vi.fn() },
|
||||
auditLog: { create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
@@ -107,6 +110,8 @@ beforeEach(() => {
|
||||
// No live reading collides at commit time — the in-batch path is what's
|
||||
// under test, so the DB-visibility check returns empty for every row.
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarker.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.biomarkerAlias.findMany).mockResolvedValue([] as never);
|
||||
let nextId = 0;
|
||||
vi.mocked(prisma.labResult.create).mockImplementation((() =>
|
||||
Promise.resolve({ id: `lr-${++nextId}` })) as never);
|
||||
|
||||
@@ -34,6 +34,13 @@ import { withIdempotency } from "@/lib/idempotency";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
import { enqueueReminderSatisfy } from "@/lib/jobs/reminder-satisfy";
|
||||
import { emitDataArrival } from "@/lib/arrivals/emit-shared";
|
||||
import { rememberImportAlias } from "@/lib/labs/biomarker-aliases";
|
||||
import {
|
||||
addAliasToIndex,
|
||||
loadMarkerIndex,
|
||||
resolveInIndex,
|
||||
type IndexedMarker,
|
||||
} from "@/lib/labs/biomarker-resolve";
|
||||
import { resolveOrMintBiomarker } from "@/lib/labs/biomarker-store";
|
||||
import { readingInMarkerUnit } from "@/lib/labs/reading-conversion";
|
||||
import { sameLabUnit } from "@/lib/labs/unit-normalise";
|
||||
@@ -69,13 +76,20 @@ async function isDuplicate(
|
||||
userId: string,
|
||||
row: OcrCommitRow,
|
||||
tz: string,
|
||||
/** The marker the row resolves to, when it resolves to one already. */
|
||||
biomarkerId: string | null,
|
||||
): Promise<boolean> {
|
||||
const day = labReadingDay(new Date(row.takenAt), tz);
|
||||
const rows = await prisma.labResult.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
analyte: { equals: row.analyte.trim(), mode: "insensitive" },
|
||||
// The printed name, or a reading already filed under the marker this
|
||||
// name resolves to: an earlier report may have spelled it another way.
|
||||
OR: [
|
||||
{ analyte: { equals: row.analyte.trim(), mode: "insensitive" } },
|
||||
...(biomarkerId ? [{ biomarkerId }] : []),
|
||||
],
|
||||
takenAt: labReadingDaySearchRange(day),
|
||||
},
|
||||
select: {
|
||||
@@ -123,8 +137,15 @@ async function isDuplicate(
|
||||
* Mirrors the `isDuplicate` match semantics so in-batch dedup no longer depends
|
||||
* on a prior row autocommitting before the next row's live query runs.
|
||||
*/
|
||||
function inBatchKey(row: OcrCommitRow, tz: string): string {
|
||||
const analyte = row.analyte.trim().toLowerCase();
|
||||
function inBatchKey(
|
||||
row: OcrCommitRow,
|
||||
tz: string,
|
||||
biomarkerId: string | null,
|
||||
): string {
|
||||
// Two spellings of one marker in one document are one marker (D1223).
|
||||
const analyte = biomarkerId
|
||||
? `bm:${biomarkerId}`
|
||||
: row.analyte.trim().toLowerCase();
|
||||
const dayKey = labReadingDay(new Date(row.takenAt), tz);
|
||||
const valuePart =
|
||||
row.value !== undefined
|
||||
@@ -188,14 +209,59 @@ async function commitOcrRows(request: NextRequest) {
|
||||
const writtenInBatch = new Set<string>();
|
||||
|
||||
const tz = await resolveUserTimezone(user.id);
|
||||
// v1.43 (D1223) — the account's markers and aliases, loaded once: every row
|
||||
// resolves its name against them (name, alias, catalog abbreviation) the
|
||||
// way the review did, and a marker minted for one row is found by the next.
|
||||
const markerIndex = await loadMarkerIndex(prisma, user.id);
|
||||
let aliasesRemembered = 0;
|
||||
for (const row of parsed.data.rows) {
|
||||
const key = inBatchKey(row, tz);
|
||||
if (writtenInBatch.has(key) || (await isDuplicate(user.id, row, tz))) {
|
||||
const isQualitative = row.valueText !== undefined;
|
||||
|
||||
// The marker the person picked on the review screen, if they picked one.
|
||||
let chosen: IndexedMarker | null = null;
|
||||
if (row.biomarkerId) {
|
||||
chosen =
|
||||
markerIndex.markers.find((m) => m.id === row.biomarkerId) ?? null;
|
||||
if (!chosen) {
|
||||
skipped.push({
|
||||
analyte: row.analyte.trim(),
|
||||
reason: "unknown_biomarker",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// The choice is remembered, so the next report spelled this way
|
||||
// matches on its own.
|
||||
if (row.rememberAlias !== false) {
|
||||
const wrote = await rememberImportAlias(
|
||||
prisma,
|
||||
user.id,
|
||||
chosen,
|
||||
row.analyte,
|
||||
);
|
||||
if (wrote) {
|
||||
addAliasToIndex(markerIndex, chosen.id, row.analyte);
|
||||
aliasesRemembered += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolvedId =
|
||||
chosen?.id ??
|
||||
resolveInIndex(
|
||||
markerIndex,
|
||||
row.analyte,
|
||||
isQualitative ? null : (row.unit ?? null),
|
||||
)?.marker.id ??
|
||||
null;
|
||||
|
||||
const key = inBatchKey(row, tz, resolvedId);
|
||||
if (
|
||||
writtenInBatch.has(key) ||
|
||||
(await isDuplicate(user.id, row, tz, resolvedId))
|
||||
) {
|
||||
skipped.push({ analyte: row.analyte.trim(), reason: "duplicate" });
|
||||
continue;
|
||||
}
|
||||
|
||||
const isQualitative = row.valueText !== undefined;
|
||||
// The window the scan read off the report. The confirmed numeric bounds
|
||||
// win over a re-parse of the string (the human may have corrected them on
|
||||
// the review screen); the string rides along either way.
|
||||
@@ -203,14 +269,20 @@ async function commitOcrRows(request: NextRequest) {
|
||||
const sourceLow = row.referenceLow ?? printed?.low ?? null;
|
||||
const sourceHigh = row.referenceHigh ?? printed?.high ?? null;
|
||||
const sourceText = printed?.text ?? null;
|
||||
const biomarker = await resolveOrMintBiomarker(user.id, {
|
||||
analyte: row.analyte,
|
||||
// A qualitative reading has no numeric unit / range.
|
||||
unit: isQualitative ? (row.unit ?? "") : (row.unit as string),
|
||||
referenceLow: isQualitative ? null : sourceLow,
|
||||
referenceHigh: isQualitative ? null : sourceHigh,
|
||||
panel: row.panel ?? null,
|
||||
});
|
||||
const biomarker = chosen
|
||||
? chosen
|
||||
: await resolveOrMintBiomarker(
|
||||
user.id,
|
||||
{
|
||||
analyte: row.analyte,
|
||||
// A qualitative reading has no numeric unit / range.
|
||||
unit: isQualitative ? (row.unit ?? "") : (row.unit as string),
|
||||
referenceLow: isQualitative ? null : sourceLow,
|
||||
referenceHigh: isQualitative ? null : sourceHigh,
|
||||
panel: row.panel ?? null,
|
||||
},
|
||||
{ index: markerIndex },
|
||||
);
|
||||
|
||||
// The marker's unit is the one the reading is stored under. A row that
|
||||
// states another unit is converted when the marker's analyte is known and
|
||||
@@ -273,6 +345,8 @@ async function commitOcrRows(request: NextRequest) {
|
||||
});
|
||||
|
||||
writtenInBatch.add(key);
|
||||
// A freshly minted marker is now the row's; key the batch on it too.
|
||||
writtenInBatch.add(inBatchKey(row, tz, biomarker.id));
|
||||
inserted.push(serialiseLabResult(created, biomarker));
|
||||
linkable.push({
|
||||
labResultId: created.id,
|
||||
@@ -319,7 +393,11 @@ async function commitOcrRows(request: NextRequest) {
|
||||
await auditLog("labs.ocr.commit", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { count: inserted.length, skipped: skipped.length },
|
||||
details: {
|
||||
count: inserted.length,
|
||||
skipped: skipped.length,
|
||||
aliasesRemembered,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
|
||||
@@ -18,6 +18,7 @@ vi.mock("@/components/links/use-link-picker-pages", async (importOriginal) => ({
|
||||
setTerm: vi.fn(),
|
||||
searchPending: false,
|
||||
filterLocally: true,
|
||||
period: null,
|
||||
hasOlder: false,
|
||||
hasNewer: false,
|
||||
loadingOlder: false,
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
*/
|
||||
import { useCalendarDate } from "@/hooks/use-calendar-date";
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { FlaskConical, Loader2, ScanSearch } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { showErrorToast } from "@/lib/errors/error-toast";
|
||||
@@ -36,7 +37,11 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { DateField } from "@/components/ui/date-field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { MarkerMatchField } from "@/components/labs/marker-match-field";
|
||||
import type { BiomarkerListResponse } from "@/components/labs/types";
|
||||
import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
ConditionFactData,
|
||||
@@ -62,6 +67,8 @@ function commitFailureKey(reason: string): string {
|
||||
return "documents.review.failUnitRequired";
|
||||
case "observation.unitMismatch":
|
||||
return "documents.review.failUnitMismatch";
|
||||
case "observation.unknownBiomarker":
|
||||
return "documents.review.failUnknownBiomarker";
|
||||
default:
|
||||
return "documents.review.failGeneric";
|
||||
}
|
||||
@@ -203,6 +210,9 @@ function FactRow({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
failure,
|
||||
chosenBiomarkerId,
|
||||
onChooseBiomarker,
|
||||
markerName,
|
||||
}: {
|
||||
documentId: string;
|
||||
fact: ExtractedFactDto;
|
||||
@@ -210,6 +220,11 @@ function FactRow({
|
||||
onCheckedChange: (checked: boolean) => void;
|
||||
/** A per-fact commit refusal from the last confirm attempt, or null. */
|
||||
failure: string | null;
|
||||
/** v1.43 — the suggestion the person picked for a lab value, or null. */
|
||||
chosenBiomarkerId: string | null;
|
||||
onChooseBiomarker: (biomarkerId: string | null) => void;
|
||||
/** The account's marker name by id, for the matched marker. */
|
||||
markerName: (biomarkerId: string) => string | null;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const calendarDate = useCalendarDate();
|
||||
@@ -265,6 +280,25 @@ function FactRow({
|
||||
{typeLabel}
|
||||
{date ? `, ${calendarDate(date)}` : ""}
|
||||
</p>
|
||||
{isObservation &&
|
||||
(fact.biomarkerId !== undefined ||
|
||||
(fact.suggestions?.length ?? 0) > 0) ? (
|
||||
<MarkerMatchField
|
||||
matchedName={
|
||||
fact.biomarkerId
|
||||
? (markerName(fact.biomarkerId) ??
|
||||
(fact.data as ObservationFactData).label)
|
||||
: null
|
||||
}
|
||||
matchKind={fact.matchKind ?? null}
|
||||
suggestions={fact.suggestions ?? []}
|
||||
chosenId={chosenBiomarkerId}
|
||||
onChoose={(suggestion) =>
|
||||
onChooseBiomarker(suggestion?.biomarkerId ?? null)
|
||||
}
|
||||
slot="document-fact-marker"
|
||||
/>
|
||||
) : null}
|
||||
{isObservation && (fact.data as ObservationFactData).referenceText ? (
|
||||
<p className="text-muted-foreground text-xs break-words">
|
||||
{t("documents.review.statedRange", {
|
||||
@@ -461,6 +495,18 @@ export function DocumentFactsSection({
|
||||
// until it is verified (which checks it).
|
||||
const [included, setIncluded] = useState<Record<string, boolean>>({});
|
||||
const [failures, setFailures] = useState<Record<string, string>>({});
|
||||
// v1.43 — the marker the person picked per lab value, keyed by fact.
|
||||
const [chosen, setChosen] = useState<Record<string, string | null>>({});
|
||||
const hasObservations = doc.facts.some(
|
||||
(fact) => fact.factType === "OBSERVATION" && fact.status === "PENDING",
|
||||
);
|
||||
const markers = useQuery({
|
||||
queryKey: queryKeys.biomarkers(),
|
||||
queryFn: () => apiGet<BiomarkerListResponse>("/api/biomarkers"),
|
||||
enabled: canManage && hasObservations && open,
|
||||
});
|
||||
const markerName = (id: string) =>
|
||||
markers.data?.biomarkers.find((m) => m.id === id)?.name ?? null;
|
||||
|
||||
const pending = doc.facts.filter((fact) => fact.status === "PENDING");
|
||||
const approvedCount = doc.facts.filter(
|
||||
@@ -483,6 +529,7 @@ export function DocumentFactsSection({
|
||||
const decisions = decidable.map((fact) => ({
|
||||
factId: fact.id,
|
||||
action: isChecked(fact) ? ("approve" as const) : ("reject" as const),
|
||||
...(chosen[fact.id] ? { biomarkerId: chosen[fact.id] as string } : {}),
|
||||
}));
|
||||
confirmFacts.mutate(
|
||||
{ documentId: doc.id, decisions },
|
||||
@@ -567,6 +614,11 @@ export function DocumentFactsSection({
|
||||
checked={isChecked(fact)}
|
||||
onCheckedChange={(checked) => setChecked(fact.id, checked)}
|
||||
failure={failures[fact.id] ?? null}
|
||||
chosenBiomarkerId={chosen[fact.id] ?? null}
|
||||
onChooseBiomarker={(id) =>
|
||||
setChosen((prev) => ({ ...prev, [fact.id]: id }))
|
||||
}
|
||||
markerName={markerName}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -114,7 +114,12 @@ export function useConfirmFacts() {
|
||||
Error,
|
||||
{
|
||||
documentId: string;
|
||||
decisions: { factId: string; action: "approve" | "reject" }[];
|
||||
decisions: {
|
||||
factId: string;
|
||||
action: "approve" | "reject";
|
||||
/** v1.43 — the marker the person chose for a lab value. */
|
||||
biomarkerId?: string;
|
||||
}[];
|
||||
}
|
||||
>({
|
||||
mutationFn: ({ documentId, decisions }) =>
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
|
||||
vi.mock("@/hooks/use-record-capabilities", () => ({
|
||||
useRecordCapabilities: () => ({ canManageDomain: () => true }),
|
||||
}));
|
||||
|
||||
import { BiomarkerAliases } from "../biomarker-aliases";
|
||||
import { BiomarkerMergeSheet } from "../biomarker-merge-sheet";
|
||||
import type { BiomarkerDto } from "../types";
|
||||
|
||||
vi.mock("@/components/ui/responsive-sheet", () => ({
|
||||
ResponsiveSheet: ({
|
||||
children,
|
||||
title,
|
||||
footer,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
title: string;
|
||||
footer?: React.ReactNode;
|
||||
}) => (
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{children}
|
||||
{footer}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
function wrap(node: React.ReactNode, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<I18nProvider initialLocale={locale}>{node}</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const marker = (overrides: Partial<BiomarkerDto>): BiomarkerDto => ({
|
||||
id: "bm-1",
|
||||
name: "Alkaline Phosphatase",
|
||||
unit: "U/L",
|
||||
lowerBound: null,
|
||||
upperBound: null,
|
||||
panel: null,
|
||||
analyteKey: null,
|
||||
hasContext: false,
|
||||
context: null,
|
||||
hidden: false,
|
||||
aliases: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("<BiomarkerAliases>", () => {
|
||||
it("shows the other spellings as chips, removable for a manager", () => {
|
||||
const html = wrap(
|
||||
<BiomarkerAliases
|
||||
marker={marker({ aliases: ["Alk.P", "AP"] })}
|
||||
canEdit
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain("Also written as");
|
||||
expect(html).toContain("Alk.P");
|
||||
expect(html).toContain('aria-label="Remove AP"');
|
||||
expect(html).toContain("Another name for this biomarker");
|
||||
});
|
||||
|
||||
it("is read-only without the manage right, and absent when there is nothing to show", () => {
|
||||
const readOnly = wrap(
|
||||
<BiomarkerAliases
|
||||
marker={marker({ aliases: ["Alk.P"] })}
|
||||
canEdit={false}
|
||||
/>,
|
||||
);
|
||||
expect(readOnly).toContain("Alk.P");
|
||||
expect(readOnly).not.toContain("Remove Alk.P");
|
||||
expect(readOnly).not.toContain("<form");
|
||||
expect(wrap(<BiomarkerAliases marker={marker({})} canEdit={false} />)).toBe(
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
it("speaks German too", () => {
|
||||
expect(
|
||||
wrap(<BiomarkerAliases marker={marker({})} canEdit />, "de"),
|
||||
).toContain("Auch geschrieben als");
|
||||
});
|
||||
});
|
||||
|
||||
describe("<BiomarkerMergeSheet>", () => {
|
||||
it("opens on the pick step with every marker and no preview yet", () => {
|
||||
const html = wrap(
|
||||
<BiomarkerMergeSheet
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
markers={[
|
||||
marker({ id: "a", name: "Alkaline Phosphatase" }),
|
||||
marker({ id: "b", name: "Alk.P" }),
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain("Merge biomarkers");
|
||||
expect(html).toContain('data-slot="biomarker-merge-select"');
|
||||
expect(html).toContain("Alk.P");
|
||||
expect(html).toContain("Select at least two biomarkers.");
|
||||
// The preview button waits for a selection.
|
||||
expect(html).toMatch(
|
||||
/<button[^>]*data-slot="biomarker-merge-preview"[^>]*disabled=""/,
|
||||
);
|
||||
expect(html).not.toContain('data-slot="biomarker-merge-confirm"');
|
||||
});
|
||||
});
|
||||
@@ -26,7 +26,9 @@ vi.mock("@/hooks/use-ai-capability", () => ({
|
||||
onDeviceAllowed: true,
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/lib/api/api-fetch", () => ({
|
||||
vi.mock("@/lib/api/api-fetch", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/lib/api/api-fetch")>())
|
||||
.ApiError,
|
||||
apiGet: () => new Promise(() => {}),
|
||||
apiDelete: vi.fn(),
|
||||
apiPut: vi.fn(),
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import type { OcrExtractedRowDto } from "@/lib/validations/labs-ocr";
|
||||
|
||||
import {
|
||||
chooseMarker,
|
||||
seedReviewRows,
|
||||
type OcrReviewRow,
|
||||
} from "../ocr-review-types";
|
||||
import { toCommitRow } from "../ocr-review-validation";
|
||||
import { OcrRowEditor } from "../ocr-row-editor";
|
||||
|
||||
const dto: OcrExtractedRowDto = {
|
||||
analyte: "Bilirubin ges.",
|
||||
value: 0.8,
|
||||
valueText: null,
|
||||
unit: "mg/dL",
|
||||
referenceLow: null,
|
||||
referenceHigh: null,
|
||||
referenceText: null,
|
||||
takenAt: "2026-06-01",
|
||||
confidence: { analyte: 1, value: 1, unit: 1, range: 1 },
|
||||
biomarkerMatch: "new",
|
||||
markerUnit: null,
|
||||
markerAnalyteKey: null,
|
||||
duplicateOf: null,
|
||||
biomarkerId: null,
|
||||
matchKind: null,
|
||||
suggestions: [
|
||||
{
|
||||
biomarkerId: "bm-bili",
|
||||
name: "Bilirubin (Total)",
|
||||
unit: "µmol/L",
|
||||
matchKind: "similar",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const lookup = (id: string) =>
|
||||
id === "bm-bili"
|
||||
? { name: "Bilirubin (Total)", analyteKey: "bilirubin-total" }
|
||||
: id === "bm-alp"
|
||||
? { name: "Alkaline Phosphatase", analyteKey: null }
|
||||
: null;
|
||||
|
||||
function render(row: OcrReviewRow, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<OcrRowEditor row={row} onChange={() => {}} markerLookup={lookup} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("the scan review's marker choice (D1223)", () => {
|
||||
it("seeds the match and the suggestions, with nothing chosen", () => {
|
||||
const [row] = seedReviewRows([dto], null);
|
||||
expect(row).toMatchObject({
|
||||
biomarkerId: null,
|
||||
matchKind: null,
|
||||
chosenBiomarkerId: null,
|
||||
suggestions: dto.suggestions,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a scan from before the fields existed as no match", () => {
|
||||
const legacy = { ...dto } as Partial<OcrExtractedRowDto>;
|
||||
delete legacy.biomarkerId;
|
||||
delete legacy.matchKind;
|
||||
delete legacy.suggestions;
|
||||
const [row] = seedReviewRows([legacy as OcrExtractedRowDto], null);
|
||||
expect(row.suggestions).toEqual([]);
|
||||
expect(row.biomarkerId).toBeNull();
|
||||
});
|
||||
|
||||
it("offers the suggestions and a new marker, new by default", () => {
|
||||
const [row] = seedReviewRows([dto], null);
|
||||
const html = render(row);
|
||||
expect(html).toContain('data-slot="ocr-row-marker-choice"');
|
||||
expect(html).toContain("Bilirubin (Total) (µmol/L)");
|
||||
expect(html).toContain("A new biomarker");
|
||||
expect(html).toMatch(/<option value="" selected="">/);
|
||||
});
|
||||
|
||||
it("names the matched marker and how it was found", () => {
|
||||
const [row] = seedReviewRows(
|
||||
[
|
||||
{
|
||||
...dto,
|
||||
analyte: "Alk.P",
|
||||
biomarkerId: "bm-alp",
|
||||
matchKind: "catalog",
|
||||
suggestions: [],
|
||||
biomarkerMatch: "existing",
|
||||
markerUnit: "U/L",
|
||||
},
|
||||
],
|
||||
null,
|
||||
);
|
||||
const html = render(row);
|
||||
expect(html).toContain("Links to existing Alkaline Phosphatase");
|
||||
expect(html).toContain("recognised as a common abbreviation");
|
||||
expect(html).not.toContain('data-slot="ocr-row-marker-choice"');
|
||||
expect(render(row, "de")).toContain("als übliche Abkürzung erkannt");
|
||||
});
|
||||
|
||||
it("files a chosen row under the marker, judged in its unit", () => {
|
||||
const [row] = seedReviewRows([dto], null);
|
||||
const chosen = chooseMarker(
|
||||
row,
|
||||
dto.suggestions[0],
|
||||
(id) => lookup(id)?.analyteKey ?? null,
|
||||
);
|
||||
expect(chosen).toMatchObject({
|
||||
chosenBiomarkerId: "bm-bili",
|
||||
biomarkerMatch: "existing",
|
||||
markerUnit: "µmol/L",
|
||||
markerAnalyteKey: "bilirubin-total",
|
||||
});
|
||||
expect(toCommitRow(chosen)).toMatchObject({ biomarkerId: "bm-bili" });
|
||||
|
||||
const back = chooseMarker(chosen, null, () => null);
|
||||
expect(back).toMatchObject({
|
||||
chosenBiomarkerId: null,
|
||||
biomarkerMatch: "new",
|
||||
markerUnit: null,
|
||||
});
|
||||
expect(toCommitRow(back)).not.toHaveProperty("biomarkerId");
|
||||
});
|
||||
|
||||
it("sends no marker for an automatic match", () => {
|
||||
const [row] = seedReviewRows(
|
||||
[{ ...dto, biomarkerId: "bm-alp", matchKind: "alias", suggestions: [] }],
|
||||
null,
|
||||
);
|
||||
expect(toCommitRow(row)).not.toHaveProperty("biomarkerId");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -76,17 +77,20 @@ function render(
|
||||
consentRequired?: boolean;
|
||||
} = {},
|
||||
): string {
|
||||
// The dialog reads the account's markers once rows are on screen (v1.43).
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<OcrReviewDialog
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
mode={options.mode ?? "vision"}
|
||||
pdfSupported={options.pdfSupported ?? true}
|
||||
consentRequired={options.consentRequired}
|
||||
onCommitted={() => {}}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<OcrReviewDialog
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
mode={options.mode ?? "vision"}
|
||||
pdfSupported={options.pdfSupported ?? true}
|
||||
consentRequired={options.consentRequired}
|
||||
onCommitted={() => {}}
|
||||
/>
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,10 @@ function row(overrides: Partial<OcrReviewRow> = {}): OcrReviewRow {
|
||||
markerUnit: "mmol/L",
|
||||
markerAnalyteKey: null,
|
||||
duplicateOf: null,
|
||||
biomarkerId: "bm-ldl",
|
||||
matchKind: "name",
|
||||
suggestions: [],
|
||||
chosenBiomarkerId: null,
|
||||
confirmed: true,
|
||||
...overrides,
|
||||
};
|
||||
@@ -205,6 +209,9 @@ describe("a reading in another unit than its marker's", () => {
|
||||
markerUnit,
|
||||
markerAnalyteKey: null,
|
||||
duplicateOf: null,
|
||||
biomarkerId: "bm-glucose",
|
||||
matchKind: "name" as const,
|
||||
suggestions: [],
|
||||
});
|
||||
const [same, other, fresh] = seedReviewRows(
|
||||
[dto("mmol/L", "mmol/L"), dto("mmol/L", "mg/dL"), dto("mmol/L", null)],
|
||||
@@ -271,6 +278,9 @@ describe("a reading in another unit that can be converted", () => {
|
||||
markerUnit: "mg/dL",
|
||||
markerAnalyteKey: "fasting-glucose",
|
||||
duplicateOf: null,
|
||||
biomarkerId: "bm-glucose",
|
||||
matchKind: "name" as const,
|
||||
suggestions: [],
|
||||
};
|
||||
const [converts, blocked] = seedReviewRows(
|
||||
[dto, { ...dto, markerAnalyteKey: null }],
|
||||
|
||||
@@ -21,6 +21,10 @@ const baseRow: OcrReviewRow = {
|
||||
markerUnit: "mmol/L",
|
||||
markerAnalyteKey: null,
|
||||
duplicateOf: null,
|
||||
biomarkerId: "bm-ldl",
|
||||
matchKind: "name",
|
||||
suggestions: [],
|
||||
chosenBiomarkerId: null,
|
||||
confirmed: true,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — the other spellings a marker answers to.
|
||||
*
|
||||
* Shown as chips on the marker; with the labs manage right they can be added
|
||||
* and removed. Every change sends the whole set (`PUT /api/biomarkers/{id}`
|
||||
* with `aliases`), which is how the server reads it. A spelling another marker
|
||||
* already answers to is refused with `labs.biomarker.alias.taken`; the
|
||||
* sentence names the spelling so the person knows which one to drop.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2, Plus, X } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { TagChip } from "@/components/ui/tag-chip";
|
||||
import { ApiError, apiPut } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import type { BiomarkerDto } from "./types";
|
||||
|
||||
/** Longest alias the server stores. */
|
||||
const ALIAS_MAX = 120;
|
||||
|
||||
export function BiomarkerAliases({
|
||||
marker,
|
||||
canEdit,
|
||||
}: {
|
||||
marker: Pick<BiomarkerDto, "id" | "name" | "aliases">;
|
||||
canEdit: boolean;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const aliases = marker.aliases ?? [];
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (next: string[]) =>
|
||||
apiPut<BiomarkerDto>(`/api/biomarkers/${marker.id}`, { aliases: next }),
|
||||
onSuccess: () => {
|
||||
setError(null);
|
||||
setDraft("");
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.biomarkerDetail(marker.id),
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.biomarkers() });
|
||||
},
|
||||
onError: (err) => {
|
||||
const alias =
|
||||
err instanceof ApiError &&
|
||||
err.meta?.errorCode === "labs.biomarker.alias.taken" &&
|
||||
typeof err.meta.alias === "string"
|
||||
? err.meta.alias
|
||||
: null;
|
||||
setError(
|
||||
alias
|
||||
? t("labs.aliases.taken", { alias })
|
||||
: t("labs.aliases.saveError"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
if (aliases.length === 0 && !canEdit) return null;
|
||||
|
||||
const add = () => {
|
||||
const name = draft.trim();
|
||||
if (!name) return;
|
||||
if (aliases.some((a) => a.toLowerCase() === name.toLowerCase())) {
|
||||
setDraft("");
|
||||
return;
|
||||
}
|
||||
save.mutate([...aliases, name]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2" data-slot="biomarker-aliases">
|
||||
<p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
|
||||
{t("labs.aliases.title")}
|
||||
</p>
|
||||
{aliases.length > 0 ? (
|
||||
<ul className="flex flex-wrap gap-1.5">
|
||||
{aliases.map((alias) => (
|
||||
<li key={alias}>
|
||||
<TagChip className="inline-flex items-center gap-1">
|
||||
{alias}
|
||||
{canEdit ? (
|
||||
<button
|
||||
type="button"
|
||||
className="hover:text-foreground text-muted-foreground focus-visible:ring-ring/50 -my-1 -me-1 inline-flex size-6 items-center justify-center rounded-full focus-visible:ring-[3px] focus-visible:outline-none"
|
||||
onClick={() =>
|
||||
save.mutate(aliases.filter((a) => a !== alias))
|
||||
}
|
||||
disabled={save.isPending}
|
||||
aria-label={t("labs.aliases.remove", { alias })}
|
||||
>
|
||||
<X className="size-3" aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</TagChip>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("labs.aliases.empty", { name: marker.name })}
|
||||
</p>
|
||||
)}
|
||||
{canEdit ? (
|
||||
<form
|
||||
className="flex items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
add();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
maxLength={ALIAS_MAX}
|
||||
placeholder={t("labs.aliases.placeholder")}
|
||||
aria-label={t("labs.aliases.addLabel")}
|
||||
className="min-w-0 flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="min-h-11 shrink-0 sm:min-h-9"
|
||||
disabled={save.isPending || draft.trim() === ""}
|
||||
>
|
||||
{save.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
<Plus className="size-4" aria-hidden />
|
||||
)}
|
||||
{t("labs.aliases.add")}
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p role="alert" className="text-destructive text-xs">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Eye, EyeOff, FlaskConical, Pencil, Plus } from "lucide-react";
|
||||
import { Eye, EyeOff, FlaskConical, Merge, Pencil, Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { showErrorToast } from "@/lib/errors/error-toast";
|
||||
|
||||
@@ -18,7 +18,10 @@ import { formatReferenceRange } from "@/lib/labs/reference-range";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
|
||||
|
||||
import { BiomarkerForm } from "./biomarker-form";
|
||||
import { BiomarkerMergeSheet } from "./biomarker-merge-sheet";
|
||||
import type { BiomarkerDto, BiomarkerListResponse } from "./types";
|
||||
import { useLabNumber } from "./use-lab-format";
|
||||
|
||||
@@ -49,6 +52,10 @@ export function BiomarkerManager() {
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<BiomarkerDto | null>(null);
|
||||
const [formFooterEl, setFormFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
// v1.43 (D1223) — merging is a manage-level act, like edit and delete.
|
||||
const { canManageDomain } = useRecordCapabilities();
|
||||
const canMerge = canManageDomain("labs");
|
||||
const [mergeOpen, setMergeOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, isError, refetch } = useQuery({
|
||||
queryKey: queryKeys.biomarkers(),
|
||||
@@ -125,6 +132,16 @@ export function BiomarkerManager() {
|
||||
: t("labs.biomarker.noRange")}
|
||||
{marker.panel ? ` · ${marker.panel}` : ""}
|
||||
</p>
|
||||
{marker.aliases && marker.aliases.length > 0 ? (
|
||||
<p
|
||||
className="text-muted-foreground truncate text-xs"
|
||||
data-slot="biomarker-row-aliases"
|
||||
>
|
||||
{t("labs.aliases.alsoWritten", {
|
||||
aliases: marker.aliases.join(", "),
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
@@ -216,6 +233,18 @@ export function BiomarkerManager() {
|
||||
state's own button, so the card never offers the same action twice. */}
|
||||
{!isLoading && !isError && markers.length > 0 ? (
|
||||
<SettingsCardActions>
|
||||
{canMerge && markers.length >= 2 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setMergeOpen(true)}
|
||||
className="min-h-11 sm:min-h-9"
|
||||
data-slot="biomarker-merge-open"
|
||||
>
|
||||
<Merge className="h-4 w-4" />
|
||||
{t("labs.merge.open")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="sm" onClick={openNew} className="min-h-11 sm:min-h-9">
|
||||
<Plus className="h-4 w-4" />
|
||||
{t("labs.biomarker.define")}
|
||||
@@ -223,6 +252,14 @@ export function BiomarkerManager() {
|
||||
</SettingsCardActions>
|
||||
) : null}
|
||||
|
||||
{canMerge ? (
|
||||
<BiomarkerMergeSheet
|
||||
open={mergeOpen}
|
||||
onOpenChange={setMergeOpen}
|
||||
markers={markers}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ResponsiveSheet
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — merge markers that are one analyte written two ways.
|
||||
*
|
||||
* Three steps in one sheet: pick the markers, pick the one that stays, read
|
||||
* the preview, then confirm. The preview is the server's own dry run
|
||||
* (`POST /api/biomarkers/{id}/merge` with `dryRun: true`): how many readings
|
||||
* move, which are converted into the kept marker's unit, which names become
|
||||
* its aliases, and any marker whose unit cannot be converted, which blocks the
|
||||
* merge. A merge cannot be undone, and the sheet says so before the button.
|
||||
* Nothing is computed here; every number is the server's.
|
||||
*/
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
import { toastWrittenOutcome } from "@/components/outcome/outcome-toast";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { TagChip } from "@/components/ui/tag-chip";
|
||||
import { apiPost } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import type { BiomarkerDto, BiomarkerMergeResultDto } from "./types";
|
||||
|
||||
/** The most sources one merge takes, matching the server. */
|
||||
const MAX_SOURCES = 10;
|
||||
|
||||
export function BiomarkerMergeSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
markers,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
markers: readonly BiomarkerDto[];
|
||||
}) {
|
||||
const { t, tCount } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [targetId, setTargetId] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState<BiomarkerMergeResultDto | null>(null);
|
||||
|
||||
const target = targetId && selected.includes(targetId) ? targetId : null;
|
||||
const keepId = target ?? selected[0] ?? null;
|
||||
const sourceIds = useMemo(
|
||||
() => selected.filter((id) => id !== keepId),
|
||||
[selected, keepId],
|
||||
);
|
||||
const byId = useMemo(() => new Map(markers.map((m) => [m.id, m])), [markers]);
|
||||
|
||||
const reset = () => {
|
||||
setSelected([]);
|
||||
setTargetId(null);
|
||||
setPreview(null);
|
||||
};
|
||||
|
||||
const run = useMutation({
|
||||
mutationFn: (dryRun: boolean) =>
|
||||
apiPost<BiomarkerMergeResultDto>(`/api/biomarkers/${keepId}/merge`, {
|
||||
sourceIds,
|
||||
dryRun,
|
||||
}),
|
||||
onSuccess: (result) => {
|
||||
if (result.dryRun) {
|
||||
setPreview(result);
|
||||
return;
|
||||
}
|
||||
toastWrittenOutcome(
|
||||
"success",
|
||||
tCount("labs.merge.doneToast", result.movedReadings, {
|
||||
name: result.target.name,
|
||||
}),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.biomarkers() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.labResults() });
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: () => toast.error(t("labs.merge.error")),
|
||||
});
|
||||
|
||||
const toggle = (id: string, checked: boolean) => {
|
||||
setPreview(null);
|
||||
setSelected((prev) =>
|
||||
checked
|
||||
? prev.length > MAX_SOURCES
|
||||
? prev
|
||||
: [...prev, id]
|
||||
: prev.filter((x) => x !== id),
|
||||
);
|
||||
};
|
||||
|
||||
const refused = preview?.sources.filter((s) => s.conversion === "refused");
|
||||
const canPreview = keepId !== null && sourceIds.length > 0;
|
||||
|
||||
return (
|
||||
<ResponsiveSheet
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) reset();
|
||||
onOpenChange(next);
|
||||
}}
|
||||
title={t("labs.merge.title")}
|
||||
description={t("labs.merge.description")}
|
||||
footer={
|
||||
<div className="flex w-full flex-wrap justify-end gap-2">
|
||||
{preview ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
onClick={() => setPreview(null)}
|
||||
disabled={run.isPending}
|
||||
>
|
||||
{t("labs.merge.back")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
data-slot="biomarker-merge-confirm"
|
||||
onClick={() => run.mutate(false)}
|
||||
disabled={run.isPending || (refused?.length ?? 0) > 0}
|
||||
>
|
||||
{run.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
{t("labs.merge.confirm")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
data-slot="biomarker-merge-preview"
|
||||
onClick={() => run.mutate(true)}
|
||||
disabled={!canPreview || run.isPending}
|
||||
>
|
||||
{run.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
{t("labs.merge.showPreview")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{preview ? (
|
||||
<div className="space-y-4" data-slot="biomarker-merge-preview-body">
|
||||
<p className="text-sm">
|
||||
{tCount("labs.merge.previewSummary", preview.movedReadings, {
|
||||
name: preview.target.name,
|
||||
unit: preview.target.unit,
|
||||
})}
|
||||
</p>
|
||||
<ul className="space-y-2">
|
||||
{preview.sources.map((source) => (
|
||||
<li
|
||||
key={source.id}
|
||||
className="border-border space-y-0.5 rounded-lg border p-3"
|
||||
>
|
||||
<p className="text-sm font-medium break-words">
|
||||
{source.name}{" "}
|
||||
<span className="text-muted-foreground text-xs font-normal">
|
||||
{source.unit}
|
||||
</span>
|
||||
</p>
|
||||
<p
|
||||
className={
|
||||
source.conversion === "refused"
|
||||
? "text-destructive text-xs"
|
||||
: "text-muted-foreground text-xs"
|
||||
}
|
||||
>
|
||||
{source.conversion === "refused"
|
||||
? t("labs.merge.refused", {
|
||||
unit: source.unit,
|
||||
targetUnit: preview.target.unit,
|
||||
})
|
||||
: source.conversion === "converted"
|
||||
? tCount("labs.merge.converted", source.readingCount, {
|
||||
unit: source.unit,
|
||||
targetUnit: preview.target.unit,
|
||||
})
|
||||
: tCount("labs.merge.moves", source.readingCount)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{preview.aliasesAdded.length > 0 ? (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("labs.merge.aliasesAdded")}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{preview.aliasesAdded.map((alias) => (
|
||||
<TagChip key={alias}>{alias}</TagChip>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{(refused?.length ?? 0) > 0 ? (
|
||||
<p role="alert" className="text-destructive text-sm">
|
||||
{t("labs.merge.blocked")}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm font-medium">{t("labs.merge.noUndo")}</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4" data-slot="biomarker-merge-select">
|
||||
<ul className="space-y-1">
|
||||
{markers.map((marker) => {
|
||||
const id = `merge-pick-${marker.id}`;
|
||||
const checked = selected.includes(marker.id);
|
||||
return (
|
||||
<li key={marker.id}>
|
||||
<label
|
||||
htmlFor={id}
|
||||
className="hover:bg-muted/50 flex min-h-11 cursor-pointer items-center gap-3 rounded-md px-2 py-1.5"
|
||||
>
|
||||
<Checkbox
|
||||
id={id}
|
||||
checked={checked}
|
||||
onCheckedChange={(state) =>
|
||||
toggle(marker.id, state === true)
|
||||
}
|
||||
disabled={!checked && selected.length > MAX_SOURCES}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-sm">
|
||||
{marker.name}
|
||||
</span>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">
|
||||
{marker.unit}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{selected.length >= 2 ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="merge-keep">{t("labs.merge.keepLabel")}</Label>
|
||||
<NativeSelect
|
||||
id="merge-keep"
|
||||
value={keepId ?? ""}
|
||||
onChange={(event) => setTargetId(event.target.value)}
|
||||
>
|
||||
{selected.map((id) => (
|
||||
<option key={id} value={id}>
|
||||
{byId.get(id)?.name ?? id}
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("labs.merge.keepHint")}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("labs.merge.pickHint")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ResponsiveSheet>
|
||||
);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ import { InsightStatusCard } from "@/components/insights/insight-status-card";
|
||||
import { MetricStatStrip } from "@/components/insights/metric-stat-strip";
|
||||
import { useInsightBiomarkerAssessment } from "@/hooks/use-insight-status";
|
||||
import { useMounted } from "@/hooks/use-mounted";
|
||||
import { apiDelete, apiGet } from "@/lib/api/api-fetch";
|
||||
import { ApiError, apiDelete, apiGet } from "@/lib/api/api-fetch";
|
||||
import { summarize, type DataSummary } from "@/lib/analytics/trends";
|
||||
import { BIOMARKER_CATALOG } from "@/lib/labs/biomarker-catalog";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
@@ -52,6 +52,7 @@ import { ChartErrorBoundary } from "@/components/charts/chart-error-state";
|
||||
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
|
||||
import { importWithRetry } from "@/lib/retry-import";
|
||||
|
||||
import { BiomarkerAliases } from "./biomarker-aliases";
|
||||
import { BiomarkerForm } from "./biomarker-form";
|
||||
import { LabForm } from "./lab-form";
|
||||
import type {
|
||||
@@ -158,12 +159,29 @@ export function LabBiomarkerDetail({ biomarkerId }: { biomarkerId: string }) {
|
||||
const {
|
||||
data: marker,
|
||||
isError: markerError,
|
||||
error: markerFailure,
|
||||
refetch: refetchMarker,
|
||||
} = useQuery({
|
||||
queryKey: queryKeys.biomarkerDetail(biomarkerId),
|
||||
queryFn: () => apiGet<BiomarkerDto>(`/api/biomarkers/${biomarkerId}`),
|
||||
});
|
||||
|
||||
// v1.43 (D1223) — a marker merged into another answers 404 with the
|
||||
// marker it went into; a bookmark or a stale screen follows it there.
|
||||
const mergedInto =
|
||||
markerFailure instanceof ApiError &&
|
||||
markerFailure.status === 404 &&
|
||||
typeof markerFailure.meta?.mergedInto === "string"
|
||||
? markerFailure.meta.mergedInto
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!mergedInto) return;
|
||||
queryClient.removeQueries({
|
||||
queryKey: queryKeys.biomarkerDetail(biomarkerId),
|
||||
});
|
||||
router.replace(`/labs/${mergedInto}`);
|
||||
}, [mergedInto, biomarkerId, queryClient, router]);
|
||||
|
||||
// v1.25 — offset-paginated reading feed. The page no longer fetches a single
|
||||
// `limit=500` window (which silently truncated a marker once it crossed 500
|
||||
// readings); it loads a page at a time and a "Load more" control reveals the
|
||||
@@ -305,7 +323,8 @@ export function LabBiomarkerDetail({ biomarkerId }: { biomarkerId: string }) {
|
||||
// v1.25.1 (H2-M2) — the error state keeps the heading + description and adds a
|
||||
// retry, mirroring the insights `SubPageShell` recovery affordance rather than
|
||||
// collapsing to a bare line with no context and no way back.
|
||||
if (markerError || listError) {
|
||||
// A merged marker is on its way to its target (see above), not failed.
|
||||
if ((markerError && !mergedInto) || listError) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
@@ -409,6 +428,11 @@ export function LabBiomarkerDetail({ biomarkerId }: { biomarkerId: string }) {
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* v1.43 (D1223) — the other spellings this marker answers to. */}
|
||||
{marker ? (
|
||||
<BiomarkerAliases marker={marker} canEdit={canManageLabs} />
|
||||
) : null}
|
||||
|
||||
{/* Bridge to the source report PDFs. There is no per-value document
|
||||
relation in the data model yet, so this links to the vault filtered
|
||||
to lab-result documents rather than the exact scan behind one value.
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — which marker a reviewed lab value goes to.
|
||||
*
|
||||
* Shared by the scan review and the document review. The server resolves a
|
||||
* printed name to one of the account's markers (its name, an alias, or a
|
||||
* catalog abbreviation such as "T.Bili") and, when nothing resolves, offers up
|
||||
* to three markers to choose from. This renders that resolution: the marker a
|
||||
* value was matched to, or a choice between the suggestions and a new marker.
|
||||
* A choice is remembered by the server as another spelling of the marker, so
|
||||
* the next report from the same lab matches on its own.
|
||||
*
|
||||
* Nothing is computed here: the match, its kind and the suggestions all come
|
||||
* from the review DTO.
|
||||
*/
|
||||
import { useId } from "react";
|
||||
import { FilePlus2, Link2 } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
export interface MarkerSuggestionDto {
|
||||
biomarkerId: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
matchKind: "catalog" | "similar";
|
||||
}
|
||||
|
||||
/** The value for "a new marker" in the choice. */
|
||||
const NEW_MARKER = "";
|
||||
|
||||
export function MarkerMatchField({
|
||||
matchedName,
|
||||
matchKind,
|
||||
suggestions,
|
||||
chosenId,
|
||||
onChoose,
|
||||
slot,
|
||||
}: {
|
||||
/** The marker the server matched, by name; null when nothing matched. */
|
||||
matchedName: string | null;
|
||||
matchKind: "name" | "alias" | "catalog" | null;
|
||||
suggestions: readonly MarkerSuggestionDto[];
|
||||
/** The suggestion the person picked, or null for a new marker. */
|
||||
chosenId: string | null;
|
||||
onChoose: (suggestion: MarkerSuggestionDto | null) => void;
|
||||
/** `data-slot` prefix for tests. */
|
||||
slot: string;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const selectId = useId();
|
||||
|
||||
if (matchedName !== null) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-muted-foreground max-w-full"
|
||||
title={t("labs.ocr.linksExisting", { name: matchedName })}
|
||||
data-slot={`${slot}-matched`}
|
||||
>
|
||||
<Link2 aria-hidden />
|
||||
<span className="truncate">
|
||||
{t("labs.ocr.linksExisting", { name: matchedName })}
|
||||
</span>
|
||||
</Badge>
|
||||
{matchKind === "alias" || matchKind === "catalog" ? (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{matchKind === "alias"
|
||||
? t("labs.match.viaAlias")
|
||||
: t("labs.match.viaCatalog")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (suggestions.length === 0) {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-muted-foreground"
|
||||
data-slot={`${slot}-new`}
|
||||
>
|
||||
<FilePlus2 aria-hidden />
|
||||
{t("labs.ocr.newBiomarker")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5" data-slot={`${slot}-choice`}>
|
||||
<Label htmlFor={selectId} className="text-xs">
|
||||
{t("labs.match.chooseLabel")}
|
||||
</Label>
|
||||
<NativeSelect
|
||||
id={selectId}
|
||||
value={chosenId ?? NEW_MARKER}
|
||||
onChange={(event) =>
|
||||
onChoose(
|
||||
suggestions.find((s) => s.biomarkerId === event.target.value) ??
|
||||
null,
|
||||
)
|
||||
}
|
||||
>
|
||||
{suggestions.map((suggestion) => (
|
||||
<option key={suggestion.biomarkerId} value={suggestion.biomarkerId}>
|
||||
{t("labs.match.suggestionOption", {
|
||||
name: suggestion.name,
|
||||
unit: suggestion.unit,
|
||||
})}
|
||||
</option>
|
||||
))}
|
||||
<option value={NEW_MARKER}>{t("labs.match.newMarkerOption")}</option>
|
||||
</NativeSelect>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{chosenId ? t("labs.match.rememberHint") : t("labs.match.chooseHint")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,12 +18,16 @@ import { showErrorToast } from "@/lib/errors/error-toast";
|
||||
import { toastWrittenOutcome } from "@/components/outcome/outcome-toast";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { ApiError } from "@/lib/api/api-fetch";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { ApiError, apiGet } from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { OcrSkippedRowDto } from "@/lib/validations/labs-ocr";
|
||||
import { EncounterSuggestionField } from "@/components/encounters/encounter-suggestion-field";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import { OcrRowEditor } from "./ocr-row-editor";
|
||||
import type { BiomarkerListResponse } from "./types";
|
||||
import { seedReviewRows, type OcrReviewRow } from "./ocr-review-types";
|
||||
import { collectRowErrors, planSave } from "./ocr-review-validation";
|
||||
import {
|
||||
@@ -176,6 +180,24 @@ export function OcrReviewDialog({
|
||||
const textExtract = useOcrTextExtract();
|
||||
const extract = mode === "text" ? textExtract : visionExtract;
|
||||
const commit = useOcrCommit();
|
||||
// v1.43 — the account's markers, so a matched row names its marker and a
|
||||
// chosen suggestion brings the analyte it converts with. Only once rows are
|
||||
// on screen; the review works without it (names fall back to the printed
|
||||
// analyte).
|
||||
const markers = useQuery({
|
||||
queryKey: queryKeys.biomarkers(),
|
||||
queryFn: () => apiGet<BiomarkerListResponse>("/api/biomarkers"),
|
||||
enabled: rows.length > 0,
|
||||
});
|
||||
const markerLookup = useMemo(() => {
|
||||
const byId = new Map(
|
||||
(markers.data?.biomarkers ?? []).map((m) => [
|
||||
m.id,
|
||||
{ name: m.name, analyteKey: m.analyteKey },
|
||||
]),
|
||||
);
|
||||
return (id: string) => byId.get(id) ?? null;
|
||||
}, [markers.data]);
|
||||
// Text mode never accepts PDFs (tesseract.js can't read them).
|
||||
const allowPdf = mode === "vision" && pdfSupported;
|
||||
|
||||
@@ -439,6 +461,7 @@ export function OcrReviewDialog({
|
||||
<OcrRowEditor
|
||||
key={row.key}
|
||||
row={row}
|
||||
markerLookup={markerLookup}
|
||||
errors={showErrors ? rowErrors.get(row.key) : undefined}
|
||||
onChange={(next) =>
|
||||
setRows((prev) =>
|
||||
|
||||
@@ -34,6 +34,16 @@ export interface OcrReviewRow {
|
||||
markerAnalyteKey: string | null;
|
||||
/** Non-null when the server flagged a likely duplicate of a live reading. */
|
||||
duplicateOf: string | null;
|
||||
/**
|
||||
* v1.43 (D1223) — the marker the server matched the name to (its name, an
|
||||
* alias, or a catalog abbreviation), and how; null when nothing matched.
|
||||
*/
|
||||
biomarkerId: string | null;
|
||||
matchKind: "name" | "alias" | "catalog" | null;
|
||||
/** Up to three markers to choose from when nothing matched. */
|
||||
suggestions: OcrExtractedRowDto["suggestions"];
|
||||
/** The suggestion the person picked; null keeps the automatic outcome. */
|
||||
chosenBiomarkerId: string | null;
|
||||
/** Whether the row is selected for saving. Defaults false for duplicates. */
|
||||
confirmed: boolean;
|
||||
}
|
||||
@@ -58,6 +68,11 @@ export function seedReviewRows(
|
||||
markerUnit: row.markerUnit,
|
||||
markerAnalyteKey: row.markerAnalyteKey,
|
||||
duplicateOf: row.duplicateOf,
|
||||
// A scan read before v1.43 carries none of the three.
|
||||
biomarkerId: row.biomarkerId ?? null,
|
||||
matchKind: row.matchKind ?? null,
|
||||
suggestions: row.suggestions ?? [],
|
||||
chosenBiomarkerId: null,
|
||||
// A flagged duplicate starts unchecked, and so does a reading in another
|
||||
// unit than its marker's that cannot be converted (it carries a badge
|
||||
// saying why, and ticking it marks the unit field until it is fixed); a
|
||||
@@ -74,3 +89,31 @@ export function seedReviewRows(
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Point a row at a suggestion the person picked, or back at a new marker. The
|
||||
* marker's unit and analyte come with the choice, so the unit check and the
|
||||
* conversion badge judge the row against the marker it will be filed under.
|
||||
*/
|
||||
export function chooseMarker(
|
||||
row: OcrReviewRow,
|
||||
choice: { biomarkerId: string; unit: string } | null,
|
||||
analyteKeyOf: (biomarkerId: string) => string | null,
|
||||
): OcrReviewRow {
|
||||
if (choice === null) {
|
||||
return {
|
||||
...row,
|
||||
chosenBiomarkerId: null,
|
||||
biomarkerMatch: "new",
|
||||
markerUnit: null,
|
||||
markerAnalyteKey: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
chosenBiomarkerId: choice.biomarkerId,
|
||||
biomarkerMatch: "existing",
|
||||
markerUnit: choice.unit,
|
||||
markerAnalyteKey: analyteKeyOf(choice.biomarkerId),
|
||||
};
|
||||
}
|
||||
@@ -129,7 +129,12 @@ export function toCommitRow(row: OcrReviewRow): OcrCommitRowInput | null {
|
||||
if (isQualitativeRow(row)) {
|
||||
const valueText = (row.valueText ?? "").trim();
|
||||
if (!valueText) return null;
|
||||
return { analyte, valueText, takenAt: takenAt.toISOString() };
|
||||
return {
|
||||
analyte,
|
||||
valueText,
|
||||
takenAt: takenAt.toISOString(),
|
||||
...chosen(row),
|
||||
};
|
||||
}
|
||||
|
||||
if (row.value === null || !Number.isFinite(row.value)) return null;
|
||||
@@ -144,9 +149,15 @@ export function toCommitRow(row: OcrReviewRow): OcrCommitRowInput | null {
|
||||
...(row.referenceLow !== null ? { referenceLow: row.referenceLow } : {}),
|
||||
...(row.referenceHigh !== null ? { referenceHigh: row.referenceHigh } : {}),
|
||||
...(row.referenceText ? { referenceText: row.referenceText } : {}),
|
||||
...chosen(row),
|
||||
};
|
||||
}
|
||||
|
||||
/** The marker the person picked, which the commit then files the row under. */
|
||||
function chosen(row: OcrReviewRow): { biomarkerId?: string } {
|
||||
return row.chosenBiomarkerId ? { biomarkerId: row.chosenBiomarkerId } : {};
|
||||
}
|
||||
|
||||
/** Blocking fields per CONFIRMED row, keyed by the row's key; writable rows are absent. */
|
||||
export function collectRowErrors(
|
||||
rows: readonly OcrReviewRow[],
|
||||
|
||||
@@ -15,13 +15,7 @@
|
||||
*/
|
||||
import { useId } from "react";
|
||||
|
||||
import {
|
||||
AlertCircle,
|
||||
FilePlus2,
|
||||
Link2,
|
||||
Ruler,
|
||||
TriangleAlert,
|
||||
} from "lucide-react";
|
||||
import { AlertCircle, Ruler, TriangleAlert } from "lucide-react";
|
||||
|
||||
import { FieldError } from "@/components/forms/field-error";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -31,7 +25,8 @@ import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import type { OcrReviewRow } from "./ocr-review-types";
|
||||
import { MarkerMatchField } from "./marker-match-field";
|
||||
import { chooseMarker, type OcrReviewRow } from "./ocr-review-types";
|
||||
import {
|
||||
readingConversion,
|
||||
readingUnitBlocked,
|
||||
@@ -55,9 +50,18 @@ export function OcrRowEditor({
|
||||
row,
|
||||
onChange,
|
||||
errors,
|
||||
markerLookup = () => null,
|
||||
}: {
|
||||
row: OcrReviewRow;
|
||||
onChange: (next: OcrReviewRow) => void;
|
||||
/**
|
||||
* The account's marker by id, for the matched marker's name and the
|
||||
* analyte a chosen suggestion converts with. Absent: names fall back to the
|
||||
* printed analyte.
|
||||
*/
|
||||
markerLookup?: (
|
||||
biomarkerId: string,
|
||||
) => { name: string; analyteKey: string | null } | null;
|
||||
/** The blocking fields of this row, once a save has been attempted. */
|
||||
errors?: OcrRowErrors;
|
||||
}) {
|
||||
@@ -151,26 +155,29 @@ export function OcrRowEditor({
|
||||
className="font-medium"
|
||||
/>
|
||||
{fieldError("analyte", "labs.ocr.errorAnalyte")}
|
||||
{/* v1.43 (D1223) — the marker this value goes to: the server's
|
||||
match, or a choice between its suggestions and a new one. */}
|
||||
<MarkerMatchField
|
||||
matchedName={
|
||||
row.biomarkerId !== null
|
||||
? (markerLookup(row.biomarkerId)?.name ?? row.analyte)
|
||||
: null
|
||||
}
|
||||
matchKind={row.matchKind}
|
||||
suggestions={row.suggestions}
|
||||
chosenId={row.chosenBiomarkerId}
|
||||
onChoose={(suggestion) =>
|
||||
onChange(
|
||||
chooseMarker(
|
||||
row,
|
||||
suggestion,
|
||||
(id) => markerLookup(id)?.analyteKey ?? null,
|
||||
),
|
||||
)
|
||||
}
|
||||
slot="ocr-row-marker"
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{row.biomarkerMatch === "existing" ? (
|
||||
// The chip repeats the analyte, so a long panel name ran past
|
||||
// the row on a phone; it truncates inside the row instead.
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-muted-foreground max-w-full"
|
||||
title={t("labs.ocr.linksExisting", { name: row.analyte })}
|
||||
>
|
||||
<Link2 aria-hidden />
|
||||
<span className="truncate">
|
||||
{t("labs.ocr.linksExisting", { name: row.analyte })}
|
||||
</span>
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-muted-foreground">
|
||||
<FilePlus2 aria-hidden />
|
||||
{t("labs.ocr.newBiomarker")}
|
||||
</Badge>
|
||||
)}
|
||||
{row.duplicateOf ? (
|
||||
<Badge variant="secondary">
|
||||
<TriangleAlert aria-hidden />
|
||||
|
||||
@@ -95,6 +95,11 @@ export interface BiomarkerDto {
|
||||
analyteKey: string | null;
|
||||
hasContext: boolean;
|
||||
context: string | null;
|
||||
/**
|
||||
* v1.43 — other spellings that resolve to this marker, sorted, without its
|
||||
* own name. Absent from an older server.
|
||||
*/
|
||||
aliases?: string[];
|
||||
/** v1.22 — a hidden marker drops from the active list + lab-entry pickers. */
|
||||
hidden: boolean;
|
||||
createdAt: string;
|
||||
@@ -104,3 +109,21 @@ export interface BiomarkerDto {
|
||||
export interface BiomarkerListResponse {
|
||||
biomarkers: BiomarkerDto[];
|
||||
}
|
||||
|
||||
/** v1.43 — `POST /api/biomarkers/{id}/merge`, for the preview and the result. */
|
||||
export interface BiomarkerMergeResultDto {
|
||||
dryRun: boolean;
|
||||
target: BiomarkerDto;
|
||||
sources: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
readingCount: number;
|
||||
conversion: "none" | "converted" | "refused";
|
||||
refusal: "unknown_analyte" | "unknown_unit" | "not_finite" | null;
|
||||
}>;
|
||||
movedReadings: number;
|
||||
convertedReadings: number;
|
||||
aliasesAdded: string[];
|
||||
mergeId: string | null;
|
||||
}
|
||||
@@ -51,6 +51,11 @@ export interface OcrCommitRowInput {
|
||||
referenceHigh?: number;
|
||||
referenceText?: string;
|
||||
takenAt: string;
|
||||
/**
|
||||
* v1.43 — the marker the person chose on the review screen; the server then
|
||||
* remembers the analyte as its alias. Absent for an automatic match.
|
||||
*/
|
||||
biomarkerId?: string;
|
||||
}
|
||||
|
||||
export interface OcrCommitResult extends OcrCommitResponseDto {
|
||||
|
||||
@@ -125,6 +125,41 @@ describe("paged link picker", () => {
|
||||
expect(html).toContain('data-slot="labs-add"');
|
||||
});
|
||||
|
||||
it("names the period a date term searches, and does not filter its answer by the digits", () => {
|
||||
const html = render(
|
||||
<EntityLinkPicker
|
||||
{...base}
|
||||
options={loaded}
|
||||
selected={[]}
|
||||
server={server({
|
||||
term: "03.2019",
|
||||
filterLocally: true,
|
||||
period: {
|
||||
year: 2019,
|
||||
month: 3,
|
||||
fromDay: "2019-03-01",
|
||||
toDay: "2019-03-31",
|
||||
},
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('data-slot="labs-period"');
|
||||
expect(html).toContain("Showing March 2019");
|
||||
expect(html).toContain('data-slot="labs-option"');
|
||||
});
|
||||
|
||||
it("shows no period line for a plain term", () => {
|
||||
const html = render(
|
||||
<EntityLinkPicker
|
||||
{...base}
|
||||
options={loaded}
|
||||
selected={[]}
|
||||
server={server({ term: "metabolic" })}
|
||||
/>,
|
||||
);
|
||||
expect(html).not.toContain('data-slot="labs-period"');
|
||||
});
|
||||
|
||||
it("does not filter a server answer again by the term", () => {
|
||||
// The route matched on the panel name; the option does not render it.
|
||||
const html = render(
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* A picker term that names a year or a month becomes a date window; anything
|
||||
* else stays a text search. Every accepted form is checked in every UI
|
||||
* locale, and the near misses that must stay text are checked too.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { formatPeriod, parsePeriodQuery } from "../period-query";
|
||||
|
||||
const NOW = new Date("2026-10-15T12:00:00.000Z");
|
||||
const LOCALES = ["de", "en", "es", "fr", "it", "pl", "ko"] as const;
|
||||
|
||||
function window(term: string, locale: string) {
|
||||
const parsed = parsePeriodQuery(term, locale, NOW);
|
||||
return parsed ? `${parsed.fromDay}..${parsed.toDay}` : null;
|
||||
}
|
||||
|
||||
const MARCH = "2019-03-01..2019-03-31";
|
||||
const YEAR = "2019-01-01..2019-12-31";
|
||||
|
||||
describe("parsePeriodQuery", () => {
|
||||
describe.each(LOCALES)("%s", (locale) => {
|
||||
it("reads a year", () => {
|
||||
expect(window("2019", locale)).toBe(YEAR);
|
||||
expect(window(" 2019 ", locale)).toBe(YEAR);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"03.2019",
|
||||
"3.2019",
|
||||
"03/2019",
|
||||
"3/2019",
|
||||
"03-2019",
|
||||
"2019-03",
|
||||
"2019/03",
|
||||
"2019.03",
|
||||
"2019.3",
|
||||
" 03 . 2019 ",
|
||||
])("reads the numeric month %j", (term) => {
|
||||
expect(window(term, locale)).toBe(MARCH);
|
||||
});
|
||||
|
||||
it.each(["LDL", "2019abc", "13.2019", "00.2019", "1850", "1899", "2028"])(
|
||||
"leaves %j as text",
|
||||
(term) => {
|
||||
expect(window(term, locale)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["", " ", "2019 2020", "03.2019.04", "LDL 2019", "3 2019 x"])(
|
||||
"leaves %j as text",
|
||||
(term) => {
|
||||
expect(window(term, locale)).toBeNull();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["de", ["März 2019", "märz 2019", "MÄRZ 2019", "Maerz 2019", "Marz 2019"]],
|
||||
["de", ["mär 2019", "Mär. 2019", "2019 März", "März, 2019"]],
|
||||
["en", ["March 2019", "march 2019", "Mar 2019", "Mar. 2019", "2019 March"]],
|
||||
["es", ["marzo 2019", "Marzo de 2019", "mar 2019", "mar. 2019"]],
|
||||
["fr", ["mars 2019", "Mars 2019", "mar 2019", "2019 mars"]],
|
||||
["it", ["marzo 2019", "Marzo 2019", "mar 2019", "marzo del 2019"]],
|
||||
["pl", ["marzec 2019", "Marzec 2019", "marca 2019", "mar 2019"]],
|
||||
["ko", ["2019년 3월", "2019년3월", "2019년 03월", "3월 2019", "2019. 3."]],
|
||||
] as const)("reads March 2019 in %s", (locale, terms) => {
|
||||
for (const term of terms) {
|
||||
expect(window(term, locale), term).toBe(MARCH);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["de", "Dezember 2019", "2019-12-01..2019-12-31"],
|
||||
["de", "Okt 2019", "2019-10-01..2019-10-31"],
|
||||
["de", "Februar 2020", "2020-02-01..2020-02-29"],
|
||||
["en", "Sept 2019", "2019-09-01..2019-09-30"],
|
||||
["en", "Sep 2019", "2019-09-01..2019-09-30"],
|
||||
["en", "May 2019", "2019-05-01..2019-05-31"],
|
||||
["es", "septiembre 2019", "2019-09-01..2019-09-30"],
|
||||
["es", "ene 2019", "2019-01-01..2019-01-31"],
|
||||
["es", "dic 2019", "2019-12-01..2019-12-31"],
|
||||
["fr", "février 2019", "2019-02-01..2019-02-28"],
|
||||
["fr", "fevrier 2019", "2019-02-01..2019-02-28"],
|
||||
["fr", "févr. 2019", "2019-02-01..2019-02-28"],
|
||||
["fr", "août 2019", "2019-08-01..2019-08-31"],
|
||||
["fr", "déc 2019", "2019-12-01..2019-12-31"],
|
||||
["fr", "juil. 2019", "2019-07-01..2019-07-31"],
|
||||
["it", "gennaio 2019", "2019-01-01..2019-01-31"],
|
||||
["it", "giu 2019", "2019-06-01..2019-06-30"],
|
||||
["it", "set 2019", "2019-09-01..2019-09-30"],
|
||||
["pl", "październik 2019", "2019-10-01..2019-10-31"],
|
||||
["pl", "paź 2019", "2019-10-01..2019-10-31"],
|
||||
["pl", "października 2019", "2019-10-01..2019-10-31"],
|
||||
["pl", "luty 2019", "2019-02-01..2019-02-28"],
|
||||
["pl", "styczeń 2019", "2019-01-01..2019-01-31"],
|
||||
["ko", "2019년 12월", "2019-12-01..2019-12-31"],
|
||||
["ko", "2019년", YEAR],
|
||||
// Austrian German calls January "Jänner", and Intl knows it.
|
||||
["de-AT", "Jänner 2019", "2019-01-01..2019-01-31"],
|
||||
["de-AT", "März 2019", MARCH],
|
||||
] as const)("%s %j", (locale, term, expected) => {
|
||||
expect(window(term, locale)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
// "jui" is both juin and juillet; "ma" is too short to name one month.
|
||||
["fr", "jui 2019"],
|
||||
["en", "ma 2019"],
|
||||
["en", "Ju 2019"],
|
||||
// A month name from another language is text in this one.
|
||||
["en", "März 2019"],
|
||||
["de", "March 2019"],
|
||||
// A month without a year is not a period.
|
||||
["en", "March"],
|
||||
["de", "03"],
|
||||
// Two months, or a month name with digits glued on.
|
||||
["en", "March May"],
|
||||
["en", "March2019"],
|
||||
] as const)("%s %j stays text", (locale, term) => {
|
||||
expect(window(term, locale)).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts next year and refuses the one after", () => {
|
||||
expect(window("2027", "en")).toBe("2027-01-01..2027-12-31");
|
||||
expect(window("12.2027", "en")).toBe("2027-12-01..2027-12-31");
|
||||
expect(window("2028", "en")).toBeNull();
|
||||
expect(window("1900", "en")).toBe("1900-01-01..1900-12-31");
|
||||
});
|
||||
|
||||
it("names the year and the month", () => {
|
||||
expect(parsePeriodQuery("2019", "de", NOW)).toEqual({
|
||||
year: 2019,
|
||||
month: null,
|
||||
fromDay: "2019-01-01",
|
||||
toDay: "2019-12-31",
|
||||
});
|
||||
expect(parsePeriodQuery("Maerz 2019", "de", NOW)).toMatchObject({
|
||||
year: 2019,
|
||||
month: 3,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatPeriod", () => {
|
||||
it("names a period the way the locale writes it", () => {
|
||||
const march = parsePeriodQuery("03.2019", "de", NOW)!;
|
||||
expect(formatPeriod(march, "de")).toBe("März 2019");
|
||||
expect(formatPeriod(march, "en")).toBe("March 2019");
|
||||
expect(formatPeriod(march, "ko")).toBe("2019년 3월");
|
||||
expect(formatPeriod(parsePeriodQuery("2019", "en", NOW)!, "en")).toBe(
|
||||
"2019",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -28,15 +28,24 @@ import {
|
||||
} from "../use-link-picker-pages";
|
||||
|
||||
const pivot = pickerPivot("2019-05-10T10:00:00.000Z");
|
||||
const ctx = { locale: "en", timeZone: "UTC" } as const;
|
||||
|
||||
const REQUESTS: PickerPageRequest[] = [
|
||||
{ direction: "older", pivot, term: "", cursor: null },
|
||||
{ direction: "older", pivot, term: "", cursor: "200" },
|
||||
{ direction: "older", pivot: null, term: "", cursor: null },
|
||||
{ direction: "newer", pivot, term: "", cursor: null },
|
||||
{ direction: "newer", pivot, term: "", cursor: "100" },
|
||||
{ direction: "search", pivot: null, term: "ferritin", cursor: null },
|
||||
{ direction: "search", pivot: null, term: "ferritin", cursor: "100" },
|
||||
{ direction: "older", pivot, term: "", cursor: null, ...ctx },
|
||||
{ direction: "older", pivot, term: "", cursor: "200", ...ctx },
|
||||
{ direction: "older", pivot: null, term: "", cursor: null, ...ctx },
|
||||
{ direction: "newer", pivot, term: "", cursor: null, ...ctx },
|
||||
{ direction: "newer", pivot, term: "", cursor: "100", ...ctx },
|
||||
{ direction: "search", pivot: null, term: "ferritin", cursor: null, ...ctx },
|
||||
{ direction: "search", pivot: null, term: "ferritin", cursor: "100", ...ctx },
|
||||
{ direction: "search", pivot: null, term: "2019", cursor: null, ...ctx },
|
||||
{
|
||||
direction: "search",
|
||||
pivot: null,
|
||||
term: "March 2019",
|
||||
cursor: "100",
|
||||
...ctx,
|
||||
},
|
||||
];
|
||||
|
||||
function params(url: string): Record<string, string> {
|
||||
@@ -67,10 +76,22 @@ describe("documents picker", () => {
|
||||
|
||||
it("splits the day-granular window at the pivot's day", () => {
|
||||
const older = params(
|
||||
documentPickerUrl({ direction: "older", pivot, term: "", cursor: null }),
|
||||
documentPickerUrl({
|
||||
direction: "older",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: null,
|
||||
...ctx,
|
||||
}),
|
||||
);
|
||||
const newer = params(
|
||||
documentPickerUrl({ direction: "newer", pivot, term: "", cursor: null }),
|
||||
documentPickerUrl({
|
||||
direction: "newer",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: null,
|
||||
...ctx,
|
||||
}),
|
||||
);
|
||||
expect(older.to).toBe("2019-05-17");
|
||||
expect(newer.from).toBe("2019-05-18");
|
||||
@@ -88,10 +109,22 @@ describe("the windows around a record's date", () => {
|
||||
|
||||
it("older reads up to the split newest first, newer after it oldest first", () => {
|
||||
const older = params(
|
||||
labPickerUrl({ direction: "older", pivot, term: "", cursor: null }),
|
||||
labPickerUrl({
|
||||
direction: "older",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: null,
|
||||
...ctx,
|
||||
}),
|
||||
);
|
||||
const newer = params(
|
||||
labPickerUrl({ direction: "newer", pivot, term: "", cursor: null }),
|
||||
labPickerUrl({
|
||||
direction: "newer",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: null,
|
||||
...ctx,
|
||||
}),
|
||||
);
|
||||
expect(older).toMatchObject({ to: pivot, sortDir: "desc", offset: "0" });
|
||||
expect(newer).toMatchObject({
|
||||
@@ -107,6 +140,7 @@ describe("the windows around a record's date", () => {
|
||||
pivot: null,
|
||||
term: "ferritin",
|
||||
cursor: null,
|
||||
...ctx,
|
||||
}),
|
||||
);
|
||||
expect(search.q).toBe("ferritin");
|
||||
@@ -120,3 +154,88 @@ describe("the windows around a record's date", () => {
|
||||
expect(nextOffset("100", 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a search term that names a period", () => {
|
||||
const search = (
|
||||
term: string,
|
||||
locale = "en",
|
||||
timeZone = "UTC",
|
||||
): PickerPageRequest => ({
|
||||
direction: "search",
|
||||
pivot: null,
|
||||
term,
|
||||
cursor: null,
|
||||
locale,
|
||||
timeZone,
|
||||
});
|
||||
|
||||
it.each([
|
||||
["labs", labPickerUrl, "sortDir"],
|
||||
["episodes", episodePickerUrl, "sortDir"],
|
||||
] as const)(
|
||||
"%s: a year is the year's instant window, newest first, with no q",
|
||||
(_name, build, sortKey) => {
|
||||
const sent = params(build(search("2019")));
|
||||
expect(sent.q).toBeUndefined();
|
||||
expect(sent.from).toBe("2019-01-01T00:00:00.000Z");
|
||||
expect(sent.to).toBe("2019-12-31T23:59:59.999Z");
|
||||
expect(sent[sortKey]).toBe("desc");
|
||||
},
|
||||
);
|
||||
|
||||
it("labs: a month in the person's language is that month", () => {
|
||||
const sent = params(labPickerUrl(search("März 2019", "de")));
|
||||
expect(sent.q).toBeUndefined();
|
||||
expect(sent.from).toBe("2019-03-01T00:00:00.000Z");
|
||||
expect(sent.to).toBe("2019-03-31T23:59:59.999Z");
|
||||
});
|
||||
|
||||
it("the window follows the person's timezone, DST included", () => {
|
||||
// Berlin: March 2019 starts at UTC+1 and ends at UTC+2.
|
||||
const sent = params(
|
||||
episodePickerUrl(search("03.2019", "de", "Europe/Berlin")),
|
||||
);
|
||||
expect(sent.from).toBe("2019-02-28T23:00:00.000Z");
|
||||
expect(sent.to).toBe("2019-03-31T21:59:59.999Z");
|
||||
});
|
||||
|
||||
it("documents: the day-granular window is the period's two calendar days", () => {
|
||||
const sent = params(documentPickerUrl(search("2019-02")));
|
||||
expect(sent.q).toBeUndefined();
|
||||
expect(sent.from).toBe("2019-02-01");
|
||||
expect(sent.to).toBe("2019-02-28");
|
||||
expect(sent.order).toBe("desc");
|
||||
});
|
||||
|
||||
it("encounters: the route without text search still gets the period", () => {
|
||||
const sent = params(encounterPickerUrl(search("Mar 2019")));
|
||||
expect(sent.q).toBeUndefined();
|
||||
expect(sent.from).toBe("2019-03-01T00:00:00.000Z");
|
||||
expect(sent.to).toBe("2019-03-31T23:59:59.999Z");
|
||||
});
|
||||
|
||||
it.each([labPickerUrl, episodePickerUrl, documentPickerUrl])(
|
||||
"a plain term stays a text search (%#)",
|
||||
(build) => {
|
||||
for (const term of ["LDL", "2019abc", "13.2019", "1850"]) {
|
||||
const sent = params(build(search(term)));
|
||||
expect(sent.q).toBe(term);
|
||||
expect(sent.from).toBeUndefined();
|
||||
expect(sent.to).toBeUndefined();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("a month name is read in the UI locale only", () => {
|
||||
// "März" is not an English month, so it stays text.
|
||||
expect(params(labPickerUrl(search("März 2019", "en"))).q).toBe("März 2019");
|
||||
});
|
||||
|
||||
it("the older and newer windows never read the term", () => {
|
||||
const older = params(
|
||||
labPickerUrl({ ...search("2019"), direction: "older", pivot }),
|
||||
);
|
||||
expect(older.to).toBe(pivot);
|
||||
expect(older.from).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -113,6 +113,8 @@ describe("fetchVaultPage", () => {
|
||||
pivot: "2026-05-17T23:59:59.999Z",
|
||||
term: "",
|
||||
cursor: "z",
|
||||
locale: "en",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
expect(page.items.map((d) => d.id)).toEqual(["a"]);
|
||||
expect(page.next).toBe("a");
|
||||
|
||||
@@ -53,6 +53,8 @@ import { QueryErrorRow } from "@/components/ui/query-error-row";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { formatPeriod, type PeriodQuery } from "./period-query";
|
||||
|
||||
export interface EntityLinkOption {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -110,6 +112,8 @@ export interface EntityLinkServerPaging {
|
||||
* here instead of being sent.
|
||||
*/
|
||||
filterLocally?: boolean;
|
||||
/** The term names a year or a month, and the list is that period. */
|
||||
period?: PeriodQuery | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,6 +131,7 @@ export function serverPagingFrom(pages: {
|
||||
loadOlder: () => void;
|
||||
loadNewer: () => void;
|
||||
filterLocally: boolean;
|
||||
period: PeriodQuery | null;
|
||||
}): EntityLinkServerPaging {
|
||||
return {
|
||||
term: pages.term,
|
||||
@@ -139,6 +144,7 @@ export function serverPagingFrom(pages: {
|
||||
onOlder: pages.loadOlder,
|
||||
onNewer: pages.loadNewer,
|
||||
filterLocally: pages.filterLocally,
|
||||
period: pages.period,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -278,7 +284,7 @@ export function EntityLinkPicker({
|
||||
*/
|
||||
knownOptions?: EntityLinkOption[];
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const { t, locale } = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [localTerm, setLocalTerm] = useState("");
|
||||
const term = server ? server.term : localTerm;
|
||||
@@ -308,7 +314,10 @@ export function EntityLinkPicker({
|
||||
// again here would drop a match on a field the option does not render.
|
||||
const groups = useMemo(() => {
|
||||
const visible =
|
||||
server && !server.filterLocally ? options : filterOptions(options, term);
|
||||
// A period is answered by the route's date window, never by the digits.
|
||||
server && (!server.filterLocally || server.period)
|
||||
? options
|
||||
: filterOptions(options, term);
|
||||
// Linked records the loaded pages do not hold stay reachable in the
|
||||
// sheet, on top, so they can be unticked where they are listed.
|
||||
const loaded = new Set(options.map((option) => option.id));
|
||||
@@ -486,6 +495,17 @@ export function EntityLinkPicker({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{server?.period ? (
|
||||
<p
|
||||
className="text-muted-foreground px-1 text-xs"
|
||||
data-slot={`${slot}-period`}
|
||||
>
|
||||
{t("links.picker.period.showing", {
|
||||
period: formatPeriod(server.period, locale),
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{server?.searchPending && groups.length === 0 ? (
|
||||
<div
|
||||
className="flex justify-center py-6"
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* A picker search term that names a calendar period: a year, or a month of a
|
||||
* year.
|
||||
*
|
||||
* A person looking for "the lab panel from March 2019" types the date, not an
|
||||
* analyte. The list routes match `q` against names and titles only, so "2019"
|
||||
* or "03.2019" found nothing, or only whatever happened to carry those digits
|
||||
* in its name. A term that parses here is sent as the route's own `from` /
|
||||
* `to` window instead, so the answer is every record in that period, however
|
||||
* far back it sits.
|
||||
*
|
||||
* Accepted, after folding case, accents and the umlaut spellings "ae", "oe",
|
||||
* "ue" (so "März", "Maerz" and "mär" agree):
|
||||
*
|
||||
* - a year: "2019" (Korean "2019년");
|
||||
* - a numeric month and year, either order, separated by ".", "/", "-" or a
|
||||
* space: "03.2019", "3.2019", "03/2019", "2019-03", "2019/03", "2019.03",
|
||||
* Korean "2019년 3월" / "2019. 3.";
|
||||
* - a month name and a year, either order, in the person's UI locale: the
|
||||
* full name, the short name, the genitive form where the language has one
|
||||
* (Polish "marca"), or any prefix of at least three letters that names one
|
||||
* month only ("sept", "paź"; "jui" is both juin and juillet, so it is not
|
||||
* a period). Spanish "de" may join the two ("marzo de 2019").
|
||||
*
|
||||
* The month names come from `Intl.DateTimeFormat` for the locale rather than a
|
||||
* table kept by hand, so they read the way the app's own dates are rendered.
|
||||
*
|
||||
* A year before {@link MIN_PERIOD_YEAR} or more than one year after the
|
||||
* current one is not a period ("1850" stays a text search), and neither is a
|
||||
* month outside 1 to 12 ("13.2019") or a term with anything else in it
|
||||
* ("2019abc", "LDL 2019").
|
||||
*
|
||||
* Pure: no provider, no clock unless the caller omits `now`.
|
||||
*/
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
/** The earliest year a period search accepts. */
|
||||
export const MIN_PERIOD_YEAR = 1900;
|
||||
|
||||
export interface PeriodQuery {
|
||||
year: number;
|
||||
/** 1 to 12, or null for the whole year. */
|
||||
month: number | null;
|
||||
/** First calendar day of the period, `YYYY-MM-DD`. */
|
||||
fromDay: string;
|
||||
/** Last calendar day of the period, `YYYY-MM-DD` (inclusive). */
|
||||
toDay: string;
|
||||
}
|
||||
|
||||
/** Words that may stand between a month name and its year. */
|
||||
const CONNECTORS: Record<string, readonly string[]> = {
|
||||
es: ["de", "del"],
|
||||
it: ["del"],
|
||||
};
|
||||
|
||||
const nameCache = new Map<string, ReadonlyArray<[string, number]>>();
|
||||
|
||||
/** Spell German umlauts the way a keyboard without them does. */
|
||||
function umlautSpelling(lower: string): string {
|
||||
return lower.replace(/ä/gu, "ae").replace(/ö/gu, "oe").replace(/ü/gu, "ue");
|
||||
}
|
||||
|
||||
/**
|
||||
* Every folded spelling of every month in `locale`, paired with its month
|
||||
* number: long, short and (where it differs) genitive, each also with its
|
||||
* umlauts spelled out.
|
||||
*/
|
||||
function monthNames(locale: string): ReadonlyArray<[string, number]> {
|
||||
const cached = nameCache.get(locale);
|
||||
if (cached) return cached;
|
||||
const names: Array<[string, number]> = [];
|
||||
const add = (raw: string, month: number) => {
|
||||
const lower = raw.toLowerCase().replace(/\./gu, "");
|
||||
for (const spelling of [lower, umlautSpelling(lower)]) {
|
||||
const folded = foldForMatch(spelling);
|
||||
if (folded && !names.some(([n, m]) => n === folded && m === month)) {
|
||||
names.push([folded, month]);
|
||||
}
|
||||
}
|
||||
};
|
||||
let long: Intl.DateTimeFormat;
|
||||
let short: Intl.DateTimeFormat;
|
||||
let genitive: Intl.DateTimeFormat;
|
||||
try {
|
||||
long = new Intl.DateTimeFormat(locale, { month: "long", timeZone: "UTC" });
|
||||
short = new Intl.DateTimeFormat(locale, {
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
genitive = new Intl.DateTimeFormat(locale, {
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
} catch {
|
||||
nameCache.set(locale, names);
|
||||
return names;
|
||||
}
|
||||
for (let month = 1; month <= 12; month += 1) {
|
||||
const day = new Date(Date.UTC(2019, month - 1, 15));
|
||||
add(long.format(day), month);
|
||||
add(short.format(day), month);
|
||||
const part = genitive
|
||||
.formatToParts(day)
|
||||
.find((p) => p.type === "month")?.value;
|
||||
if (part) add(part, month);
|
||||
}
|
||||
nameCache.set(locale, names);
|
||||
return names;
|
||||
}
|
||||
|
||||
/** The month a folded word names in `locale`, or null. */
|
||||
function monthFromName(word: string, locale: string): number | null {
|
||||
const names = monthNames(locale);
|
||||
const exact = names.find(([name]) => name === word);
|
||||
if (exact) return exact[1];
|
||||
if (word.length < 3 || !/^\p{L}+$/u.test(word)) return null;
|
||||
const months = new Set(
|
||||
names.filter(([name]) => name.startsWith(word)).map(([, month]) => month),
|
||||
);
|
||||
return months.size === 1 ? [...months][0] : null;
|
||||
}
|
||||
|
||||
function plausibleYear(word: string, now: Date): number | null {
|
||||
if (!/^\d{4}$/u.test(word)) return null;
|
||||
const year = Number(word);
|
||||
if (year < MIN_PERIOD_YEAR || year > now.getUTCFullYear() + 1) return null;
|
||||
return year;
|
||||
}
|
||||
|
||||
function numericMonth(word: string): number | null {
|
||||
if (!/^\d{1,2}$/u.test(word)) return null;
|
||||
const month = Number(word);
|
||||
return month >= 1 && month <= 12 ? month : null;
|
||||
}
|
||||
|
||||
function pad(value: number): string {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
function period(year: number, month: number | null): PeriodQuery {
|
||||
if (month === null) {
|
||||
return { year, month, fromDay: `${year}-01-01`, toDay: `${year}-12-31` };
|
||||
}
|
||||
const fromDay = `${year}-${pad(month)}-01`;
|
||||
const nextMonth =
|
||||
month === 12 ? `${year + 1}-01-01` : `${year}-${pad(month + 1)}-01`;
|
||||
return { year, month, fromDay, toDay: shiftDateKey(nextMonth, -1) };
|
||||
}
|
||||
|
||||
/** The base language of a locale tag: "de-AT" → "de". */
|
||||
function language(locale: string): string {
|
||||
return locale.toLowerCase().split(/[-_]/u)[0] ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The period `term` names in `locale`, or null when it is not one (and the
|
||||
* picker keeps its text search).
|
||||
*/
|
||||
export function parsePeriodQuery(
|
||||
term: string,
|
||||
locale: string,
|
||||
now: Date = new Date(),
|
||||
): PeriodQuery | null {
|
||||
const lang = language(locale);
|
||||
let text = term.toLowerCase();
|
||||
// Korean writes the units after the numbers: "2019년 3월".
|
||||
if (lang === "ko") {
|
||||
text = text.replace(/(\d)\s*년/gu, "$1 ").replace(/(\d)\s*월/gu, "$1 ");
|
||||
}
|
||||
const connectors = CONNECTORS[lang] ?? [];
|
||||
const words = foldForMatch(text.replace(/[.,]/gu, " "))
|
||||
.split(" ")
|
||||
.filter((word) => word.length > 0 && !connectors.includes(word));
|
||||
|
||||
if (words.length === 1) {
|
||||
const year = plausibleYear(words[0], now);
|
||||
return year === null ? null : period(year, null);
|
||||
}
|
||||
if (words.length !== 2) return null;
|
||||
|
||||
for (const [first, second] of [
|
||||
[words[0], words[1]],
|
||||
[words[1], words[0]],
|
||||
]) {
|
||||
const year = plausibleYear(second, now);
|
||||
if (year === null) continue;
|
||||
const month = numericMonth(first) ?? monthFromName(first, locale);
|
||||
if (month !== null) return period(year, month);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The period as the app names it in `locale`: "2019", "März 2019". */
|
||||
export function formatPeriod(value: PeriodQuery, locale: string): string {
|
||||
if (value.month === null) return String(value.year);
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
}).format(new Date(Date.UTC(value.year, value.month - 1, 15)));
|
||||
} catch {
|
||||
return `${pad(value.month)}.${value.year}`;
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,28 @@
|
||||
* `search` the term across the whole history. The cursor is the family's own:
|
||||
* an offset for the routes that page by offset, the last row's id for the
|
||||
* document route's keyset.
|
||||
*
|
||||
* A search term that names a year or a month ("2019", "03.2019", "März 2019",
|
||||
* see {@link parsePeriodQuery}) is not sent as `q`: it becomes the route's
|
||||
* own `from` / `to` window over that period, newest first, so the answer is
|
||||
* every record dated in it rather than the records whose name contains the
|
||||
* digits. The visit route, which has no text search at all, gets the same
|
||||
* window.
|
||||
*
|
||||
* The period is a calendar period as the person reads it. The routes over an
|
||||
* instant (lab draw, condition onset, visit) get the first instant of the
|
||||
* period's first day and the last instant of its last day in the person's
|
||||
* timezone, the zone every date in the picker is rendered in, so a visit at
|
||||
* 00:30 on 1 March is in March for the person who sees it dated 1 March. A
|
||||
* date-only lab reading is stored at noon UTC, which reads as its own date in
|
||||
* every zone from UTC-11 to UTC+11. The document route's window is already
|
||||
* day-granular and inclusive over a stored calendar date, so it gets the two
|
||||
* day keys as they are.
|
||||
*/
|
||||
import { startOfLocalDayKey } from "@/lib/tz/local-day";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
import { parsePeriodQuery, type PeriodQuery } from "./period-query";
|
||||
import {
|
||||
PICKER_PAGE_SIZE,
|
||||
afterPivot,
|
||||
@@ -22,6 +43,44 @@ function withParams(path: string, params: URLSearchParams): string {
|
||||
return `${path}?${params.toString()}`;
|
||||
}
|
||||
|
||||
/** The period a search request names, or null outside a period search. */
|
||||
export function requestPeriod(request: PickerPageRequest): PeriodQuery | null {
|
||||
if (request.direction !== "search") return null;
|
||||
return parsePeriodQuery(request.term, request.locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* The instant window of a period in `timeZone`: from the first instant of its
|
||||
* first day to the last millisecond before the day after its last, both
|
||||
* inclusive as the instant routes read them.
|
||||
*/
|
||||
export function periodInstants(
|
||||
period: PeriodQuery,
|
||||
timeZone: string,
|
||||
): { from: string; to: string } {
|
||||
const from = startOfLocalDayKey(period.fromDay, timeZone);
|
||||
const next = startOfLocalDayKey(shiftDateKey(period.toDay, 1), timeZone);
|
||||
return {
|
||||
from: from.toISOString(),
|
||||
to: new Date(next.getTime() - 1).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** `q`, or the period's instant window, for a search on an instant route. */
|
||||
function setInstantSearch(
|
||||
params: URLSearchParams,
|
||||
request: PickerPageRequest,
|
||||
): void {
|
||||
const period = requestPeriod(request);
|
||||
if (period) {
|
||||
const window = periodInstants(period, request.timeZone);
|
||||
params.set("from", window.from);
|
||||
params.set("to", window.to);
|
||||
} else {
|
||||
params.set("q", request.term);
|
||||
}
|
||||
}
|
||||
|
||||
/** `GET /api/labs` — offset paging, `from` / `to` on the draw instant. */
|
||||
export function labPickerUrl(request: PickerPageRequest): string {
|
||||
const params = new URLSearchParams({
|
||||
@@ -29,7 +88,7 @@ export function labPickerUrl(request: PickerPageRequest): string {
|
||||
offset: request.cursor ?? "0",
|
||||
sortDir: request.direction === "newer" ? "asc" : "desc",
|
||||
});
|
||||
if (request.direction === "search") params.set("q", request.term);
|
||||
if (request.direction === "search") setInstantSearch(params, request);
|
||||
else if (request.pivot !== null) {
|
||||
if (request.direction === "older") params.set("to", request.pivot);
|
||||
else params.set("from", afterPivot(request.pivot));
|
||||
@@ -45,7 +104,7 @@ export function episodePickerUrl(request: PickerPageRequest): string {
|
||||
offset: request.cursor ?? "0",
|
||||
sortDir: request.direction === "newer" ? "asc" : "desc",
|
||||
});
|
||||
if (request.direction === "search") params.set("q", request.term);
|
||||
if (request.direction === "search") setInstantSearch(params, request);
|
||||
else if (request.pivot !== null) {
|
||||
if (request.direction === "older") params.set("to", request.pivot);
|
||||
else params.set("from", afterPivot(request.pivot));
|
||||
@@ -65,7 +124,11 @@ export function documentPickerUrl(request: PickerPageRequest): string {
|
||||
limit: String(PICKER_PAGE_SIZE),
|
||||
});
|
||||
if (request.cursor) params.set("cursor", request.cursor);
|
||||
if (request.direction === "search") params.set("q", request.term);
|
||||
const period = requestPeriod(request);
|
||||
if (period) {
|
||||
params.set("from", period.fromDay);
|
||||
params.set("to", period.toDay);
|
||||
} else if (request.direction === "search") params.set("q", request.term);
|
||||
else if (request.pivot !== null) {
|
||||
if (request.direction === "older") {
|
||||
params.set("to", request.pivot.slice(0, 10));
|
||||
@@ -80,15 +143,20 @@ export function documentPickerUrl(request: PickerPageRequest): string {
|
||||
* `GET /api/encounters` — offset paging inside a window on the visit instant.
|
||||
* The route answers in two arms (upcoming soonest first, past newest first),
|
||||
* each paged by the same offset; the picker merges and orders them itself.
|
||||
* The visit route has no text search, so `search` reads the whole history
|
||||
* and the picker filters what it has loaded.
|
||||
* The visit route has no text search, so a plain term never reaches it (the
|
||||
* picker filters what it has loaded); a period search reads that period.
|
||||
*/
|
||||
export function encounterPickerUrl(request: PickerPageRequest): string {
|
||||
const params = new URLSearchParams({
|
||||
limit: String(PICKER_PAGE_SIZE),
|
||||
offset: request.cursor ?? "0",
|
||||
});
|
||||
if (request.direction !== "search" && request.pivot !== null) {
|
||||
const period = requestPeriod(request);
|
||||
if (period) {
|
||||
const window = periodInstants(period, request.timeZone);
|
||||
params.set("from", window.from);
|
||||
params.set("to", window.to);
|
||||
} else if (request.direction !== "search" && request.pivot !== null) {
|
||||
if (request.direction === "older") params.set("to", request.pivot);
|
||||
else params.set("from", afterPivot(request.pivot));
|
||||
}
|
||||
|
||||
@@ -22,8 +22,11 @@
|
||||
* paged further forward from there;
|
||||
*
|
||||
* and a typed term switches to `search`, which asks the list route itself
|
||||
* (`q`) so a match is found wherever it sits in the history. With no date
|
||||
* yet the picker opens on the newest records and pages back.
|
||||
* (`q`) so a match is found wherever it sits in the history. A term that names
|
||||
* a year or a month ("2019", "03.2019", "März 2019") searches that period
|
||||
* instead, through the route's date window, on every family including the
|
||||
* visit list that has no text search (`parsePeriodQuery`). With no date yet
|
||||
* the picker opens on the newest records and pages back.
|
||||
*
|
||||
* Every page comes from the family's own list route through `fetchPage`, so
|
||||
* paging, the filter and the ownership check stay server-side.
|
||||
@@ -33,6 +36,9 @@ import { useInfiniteQuery } from "@tanstack/react-query";
|
||||
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { ENCOUNTER_SUGGEST_WINDOW_DAYS } from "@/lib/encounters/suggest-window";
|
||||
import { useDisplayTimezone, useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import { parsePeriodQuery, type PeriodQuery } from "./period-query";
|
||||
|
||||
export type PickerDirection = "older" | "newer" | "search";
|
||||
|
||||
@@ -50,6 +56,10 @@ export interface PickerPageRequest {
|
||||
term: string;
|
||||
/** The family's own cursor (an offset or a row id), null for page one. */
|
||||
cursor: string | null;
|
||||
/** The UI locale, which names the months a period search understands. */
|
||||
locale: string;
|
||||
/** The person's timezone, where a period's days begin and end. */
|
||||
timeZone: string;
|
||||
}
|
||||
|
||||
/** Records per page, the same for every family. */
|
||||
@@ -106,17 +116,41 @@ export function useLinkPickerPages<T extends { id: string }>({
|
||||
*/
|
||||
serverSearch?: boolean;
|
||||
}) {
|
||||
const { locale } = useTranslations();
|
||||
const timeZone = useDisplayTimezone();
|
||||
const [rawTerm, setTerm] = useState("");
|
||||
const debounced = useDebouncedValue(rawTerm.trim(), SEARCH_DEBOUNCE_MS);
|
||||
const term = serverSearch ? debounced : "";
|
||||
// A period goes to the route as a date window, which every family's route
|
||||
// has, so it is searched on the server even where text is not.
|
||||
const period: PeriodQuery | null = useMemo(
|
||||
() => parsePeriodQuery(debounced, locale),
|
||||
[debounced, locale],
|
||||
);
|
||||
const typedPeriod = useMemo(
|
||||
() => parsePeriodQuery(rawTerm.trim(), locale) !== null,
|
||||
[rawTerm, locale],
|
||||
);
|
||||
const term = serverSearch || period !== null ? debounced : "";
|
||||
const searching = term.length > 0;
|
||||
// "März 2019" and "03.2019" are one request; the key says which period, in
|
||||
// which zone, rather than how it was typed.
|
||||
const searchKey = period
|
||||
? `period:${period.fromDay}..${period.toDay}@${timeZone}`
|
||||
: term;
|
||||
|
||||
const older = useInfiniteQuery({
|
||||
queryKey: queryKey("older", pivot, ""),
|
||||
enabled: enabled && !searching,
|
||||
initialPageParam: null as string | null,
|
||||
queryFn: ({ pageParam }) =>
|
||||
fetchPage({ direction: "older", pivot, term: "", cursor: pageParam }),
|
||||
fetchPage({
|
||||
direction: "older",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: pageParam,
|
||||
locale,
|
||||
timeZone,
|
||||
}),
|
||||
getNextPageParam: (last) => last.next ?? undefined,
|
||||
});
|
||||
|
||||
@@ -131,16 +165,30 @@ export function useLinkPickerPages<T extends { id: string }>({
|
||||
enabled: enabled && !searching && newerRequested,
|
||||
initialPageParam: null as string | null,
|
||||
queryFn: ({ pageParam }) =>
|
||||
fetchPage({ direction: "newer", pivot, term: "", cursor: pageParam }),
|
||||
fetchPage({
|
||||
direction: "newer",
|
||||
pivot,
|
||||
term: "",
|
||||
cursor: pageParam,
|
||||
locale,
|
||||
timeZone,
|
||||
}),
|
||||
getNextPageParam: (last) => last.next ?? undefined,
|
||||
});
|
||||
|
||||
const search = useInfiniteQuery({
|
||||
queryKey: queryKey("search", null, term),
|
||||
queryKey: queryKey("search", null, searchKey),
|
||||
enabled: enabled && searching,
|
||||
initialPageParam: null as string | null,
|
||||
queryFn: ({ pageParam }) =>
|
||||
fetchPage({ direction: "search", pivot: null, term, cursor: pageParam }),
|
||||
fetchPage({
|
||||
direction: "search",
|
||||
pivot: null,
|
||||
term,
|
||||
cursor: pageParam,
|
||||
locale,
|
||||
timeZone,
|
||||
}),
|
||||
getNextPageParam: (last) => last.next ?? undefined,
|
||||
});
|
||||
|
||||
@@ -171,10 +219,15 @@ export function useLinkPickerPages<T extends { id: string }>({
|
||||
setTerm,
|
||||
/** A search is in flight (typed, or its first page not back yet). */
|
||||
searchPending:
|
||||
serverSearch &&
|
||||
(serverSearch || typedPeriod || period !== null) &&
|
||||
(rawTerm.trim() !== term || (searching && search.isPending)),
|
||||
/** The picker filters the loaded options by the term itself. */
|
||||
filterLocally: !serverSearch,
|
||||
/**
|
||||
* The picker filters the loaded options by the term itself: a route
|
||||
* without text search, and a term that is not a period.
|
||||
*/
|
||||
filterLocally: !serverSearch && !typedPeriod,
|
||||
/** The period the list is showing, when the term names one. */
|
||||
period: searching ? period : null,
|
||||
hasOlder: searching ? search.hasNextPage : older.hasNextPage,
|
||||
// Unknown until asked: offered once for every dated record, then only
|
||||
// while the server reports another page.
|
||||
|
||||
@@ -34,8 +34,9 @@ import type {
|
||||
|
||||
/**
|
||||
* Structured lab results over the window, reduced to the latest reading per
|
||||
* analyte with a count, so the report is a concise panel rather than a raw
|
||||
* dump. Analyte keys fold case-insensitively.
|
||||
* marker with a count, so the report is a concise panel rather than a raw
|
||||
* dump. Readings group by their biomarker and carry its name; a legacy
|
||||
* unlinked reading groups by its own name, case-insensitively.
|
||||
*/
|
||||
export async function loadLabResults(
|
||||
userId: string,
|
||||
@@ -58,6 +59,8 @@ export async function loadLabResults(
|
||||
sourceReferenceText: true,
|
||||
sourceUnit: true,
|
||||
takenAt: true,
|
||||
biomarkerId: true,
|
||||
biomarker: { select: { name: true, panel: true } },
|
||||
},
|
||||
});
|
||||
const byAnalyte = new Map<
|
||||
@@ -65,7 +68,13 @@ export async function loadLabResults(
|
||||
NonNullable<DoctorReportData["labResults"]>[number]
|
||||
>();
|
||||
for (const r of rows) {
|
||||
const key = r.analyte.toLowerCase();
|
||||
// One line per marker: readings filed under one biomarker are one series
|
||||
// whatever each report printed (a merge keeps the printed `analyte` on
|
||||
// every reading), and the marker's own name heads it. A legacy unlinked
|
||||
// reading still groups by its name.
|
||||
const key = r.biomarkerId
|
||||
? `bm:${r.biomarkerId}`
|
||||
: `analyte:${r.analyte.toLowerCase()}`;
|
||||
const prev = byAnalyte.get(key);
|
||||
// The row already stamps the catalog band it was written under; the
|
||||
// reading's own report window, when present, is what the physician read
|
||||
@@ -77,8 +86,8 @@ export async function loadLabResults(
|
||||
r,
|
||||
);
|
||||
byAnalyte.set(key, {
|
||||
panel: r.panel,
|
||||
analyte: r.analyte,
|
||||
panel: r.biomarker?.panel ?? r.panel,
|
||||
analyte: r.biomarker?.name ?? r.analyte,
|
||||
value: r.value,
|
||||
valueText: r.valueText,
|
||||
unit: r.unit,
|
||||
|
||||
@@ -27,7 +27,11 @@ import { prisma } from "@/lib/db";
|
||||
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
|
||||
import { emitDataArrival } from "@/lib/arrivals/emit-shared";
|
||||
import { decryptFactData } from "@/lib/documents/store";
|
||||
import { resolveOrMintBiomarker } from "@/lib/labs/biomarker-store";
|
||||
import { rememberImportAlias } from "@/lib/labs/biomarker-aliases";
|
||||
import {
|
||||
resolveOrMintBiomarker,
|
||||
type MintedBiomarker,
|
||||
} from "@/lib/labs/biomarker-store";
|
||||
import { readingInMarkerUnit } from "@/lib/labs/reading-conversion";
|
||||
import {
|
||||
isUnreadableRange,
|
||||
@@ -67,9 +71,19 @@ function statedDateOrNow(date: string | null): Date {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — the marker the person picked for an OBSERVATION on the
|
||||
* review screen, and whether to remember the label as its alias.
|
||||
*/
|
||||
export interface ObservationChoice {
|
||||
biomarkerId?: string;
|
||||
rememberAlias?: boolean;
|
||||
}
|
||||
|
||||
async function commitObservation(
|
||||
userId: string,
|
||||
data: ObservationFactData,
|
||||
choice: ObservationChoice = {},
|
||||
): Promise<CommittedRecordRef> {
|
||||
const isQualitative = typeof data.value !== "number";
|
||||
// A numeric reading needs a unit so the catalog has something to mint with —
|
||||
@@ -121,13 +135,41 @@ async function commitObservation(
|
||||
});
|
||||
}
|
||||
|
||||
const biomarker = await resolveOrMintBiomarker(userId, {
|
||||
analyte: data.label,
|
||||
unit: isQualitative ? (data.unit ?? "") : (data.unit as string),
|
||||
referenceLow: isQualitative ? null : sourceLow,
|
||||
referenceHigh: isQualitative ? null : sourceHigh,
|
||||
panel: null,
|
||||
});
|
||||
// The marker the person chose wins; otherwise the label resolves through
|
||||
// the account's names, aliases and the catalog, or a marker is minted.
|
||||
let biomarker: MintedBiomarker;
|
||||
if (choice.biomarkerId) {
|
||||
const chosen = await prisma.biomarker.findFirst({
|
||||
where: { id: choice.biomarkerId, userId },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
unit: true,
|
||||
lowerBound: true,
|
||||
upperBound: true,
|
||||
panel: true,
|
||||
analyteKey: true,
|
||||
},
|
||||
});
|
||||
if (!chosen) {
|
||||
throw new FactCommitError(
|
||||
"observation.unknownBiomarker",
|
||||
"The chosen marker does not exist",
|
||||
);
|
||||
}
|
||||
if (choice.rememberAlias !== false) {
|
||||
await rememberImportAlias(prisma, userId, chosen, data.label);
|
||||
}
|
||||
biomarker = chosen;
|
||||
} else {
|
||||
biomarker = await resolveOrMintBiomarker(userId, {
|
||||
analyte: data.label,
|
||||
unit: isQualitative ? (data.unit ?? "") : (data.unit as string),
|
||||
referenceLow: isQualitative ? null : sourceLow,
|
||||
referenceHigh: isQualitative ? null : sourceHigh,
|
||||
panel: null,
|
||||
});
|
||||
}
|
||||
// A unit that differs from an EXISTING marker's is converted when the
|
||||
// marker's analyte is known and the registry has the pair (a document states
|
||||
// "6.1 mmol/L" against a marker stored in mg/dL), keeping what the document
|
||||
@@ -274,12 +316,13 @@ async function commitMedication(
|
||||
export async function commitApprovedFact(
|
||||
userId: string,
|
||||
fact: ExtractedFact,
|
||||
choice: ObservationChoice = {},
|
||||
): Promise<CommittedRecordRef> {
|
||||
// Decrypt the staged payload at confirm time to write it into the normal
|
||||
// structured store. Fail-closed: a bad key id throws and aborts the commit.
|
||||
const data = decryptFactData(fact.dataEncrypted);
|
||||
if (fact.factType === "OBSERVATION") {
|
||||
return commitObservation(userId, data as ObservationFactData);
|
||||
return commitObservation(userId, data as ObservationFactData, choice);
|
||||
}
|
||||
if (fact.factType === "CONDITION") {
|
||||
return commitCondition(userId, data as ConditionFactData);
|
||||
|
||||
@@ -16,7 +16,13 @@ import type {
|
||||
InboundDocument,
|
||||
InboundDocumentStatus,
|
||||
} from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { servingClassFor } from "@/lib/documents/upload-policy";
|
||||
import {
|
||||
loadMarkerIndex,
|
||||
matchForReview,
|
||||
type MarkerIndex,
|
||||
} from "@/lib/labs/biomarker-resolve";
|
||||
import {
|
||||
toDocumentSourceSystem,
|
||||
toIndexOutcome,
|
||||
@@ -32,6 +38,7 @@ import type {
|
||||
FactProvenance,
|
||||
InboundDocumentDetailDto,
|
||||
InboundDocumentDto,
|
||||
ObservationFactData,
|
||||
InboundDocumentKindValue,
|
||||
InboundFactType,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
@@ -254,19 +261,54 @@ export function serialiseDocument(
|
||||
};
|
||||
}
|
||||
|
||||
/** Map a persisted staged-fact row to the review DTO. */
|
||||
export function serialiseFact(fact: ExtractedFact): ExtractedFactDto {
|
||||
return {
|
||||
/**
|
||||
* Map a persisted staged-fact row to the review DTO.
|
||||
*
|
||||
* v1.43 (D1223) — with the account's `markerIndex`, a pending OBSERVATION
|
||||
* also says which marker its label resolves to (`biomarkerId`, `matchKind`)
|
||||
* or offers up to three (`suggestions`), the same resolution the confirm
|
||||
* applies. Without an index, or for any other fact, the fields are absent.
|
||||
*/
|
||||
export function serialiseFact(
|
||||
fact: ExtractedFact,
|
||||
markerIndex?: MarkerIndex | null,
|
||||
): ExtractedFactDto {
|
||||
const data = decryptFactData(fact.dataEncrypted);
|
||||
const dto: ExtractedFactDto = {
|
||||
id: fact.id,
|
||||
factType: fact.factType as InboundFactType,
|
||||
status: fact.status as ExtractedFactStatus,
|
||||
confidence: fact.confidence,
|
||||
needsReview: fact.needsReview,
|
||||
data: decryptFactData(fact.dataEncrypted),
|
||||
data,
|
||||
provenance: decryptFactProvenance(fact.provenanceEncrypted),
|
||||
committedRecordId: fact.committedRecordId,
|
||||
committedRecordType: fact.committedRecordType,
|
||||
};
|
||||
if (markerIndex && fact.factType === "OBSERVATION") {
|
||||
const observation = data as ObservationFactData;
|
||||
const isNumeric = typeof observation.value === "number";
|
||||
const { match, suggestions } = matchForReview(
|
||||
markerIndex,
|
||||
observation.label ?? "",
|
||||
isNumeric ? (observation.unit ?? null) : null,
|
||||
);
|
||||
dto.biomarkerId = match?.marker.id ?? null;
|
||||
dto.matchKind = match?.matchKind ?? null;
|
||||
dto.suggestions = suggestions;
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** The marker index a review needs, or null when no fact would use it. */
|
||||
export async function markerIndexForFacts(
|
||||
userId: string,
|
||||
facts: readonly Pick<ExtractedFact, "factType" | "status">[],
|
||||
): Promise<MarkerIndex | null> {
|
||||
const needed = facts.some(
|
||||
(f) => f.factType === "OBSERVATION" && f.status === "PENDING",
|
||||
);
|
||||
return needed ? loadMarkerIndex(prisma, userId) : null;
|
||||
}
|
||||
|
||||
/** Assemble the detail DTO (document + its staged facts + links). */
|
||||
@@ -279,6 +321,7 @@ export function serialiseDocumentDetail(
|
||||
hasThumbnail = false,
|
||||
encounterLinks: DocumentEncounterLinkDto[] = [],
|
||||
vaccinationLinks: DocumentVaccinationLinkDto[] | null = [],
|
||||
markerIndex: MarkerIndex | null = null,
|
||||
): InboundDocumentDetailDto {
|
||||
const pendingCount = facts.filter((f) => f.status === "PENDING").length;
|
||||
// `factCount` excludes REJECTED facts (a rejected fact is discarded, not part
|
||||
@@ -327,7 +370,7 @@ export function serialiseDocumentDetail(
|
||||
hasThumbnail,
|
||||
encounterLinks,
|
||||
),
|
||||
facts: facts.map(serialiseFact),
|
||||
facts: facts.map((fact) => serialiseFact(fact, markerIndex)),
|
||||
vaccinationLinks,
|
||||
summary,
|
||||
summaryGeneratedAt: doc.summaryGeneratedAt
|
||||
|
||||
@@ -73,6 +73,8 @@ function buildMockPrisma() {
|
||||
},
|
||||
]),
|
||||
},
|
||||
biomarkerAlias: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
biomarkerMerge: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
illnessEpisode: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
|
||||
@@ -160,6 +160,8 @@ function sourceClient() {
|
||||
// Records section: empty, exercised by its own suite.
|
||||
labResult: empty,
|
||||
biomarker: empty,
|
||||
biomarkerAlias: empty,
|
||||
biomarkerMerge: empty,
|
||||
illnessEpisode: empty,
|
||||
allergy: empty,
|
||||
familyHistoryEntry: empty,
|
||||
|
||||
@@ -576,6 +576,14 @@ export const TWO_ENDED_MODELS = [
|
||||
// questionnaire over every module decision taken in Settings since. It is
|
||||
// carried and asserted, not defaulted.
|
||||
"OnboardingRecord",
|
||||
// v1.43 (D1223) — a marker's other spellings ride on the marker as
|
||||
// `aliases[]`, and the merge ledger travels as its own list whose target is
|
||||
// resolved by id or by name like a lab result's marker. Without the aliases a
|
||||
// restored account is asked again at the next scan which marker each
|
||||
// spelling belongs to; without the ledger a link to a merged marker reads as
|
||||
// a plain 404 instead of leading to the marker it went into.
|
||||
"BiomarkerAlias",
|
||||
"BiomarkerMerge",
|
||||
] as const;
|
||||
|
||||
/** One model claimed to travel both ways. */
|
||||
@@ -614,10 +622,6 @@ export const STRUCTURALLY_UNATTRIBUTABLE: Readonly<Record<string, string>> = {
|
||||
export const COVERAGE_PENDING: Readonly<Record<string, string>> = {
|
||||
// v1.43 — the new tables are declared here with the schema and move to
|
||||
// TWO_ENDED_MODELS when their section writer and restore branch land.
|
||||
BiomarkerAlias:
|
||||
"Every other spelling a marker answers to: the names folded in by a merge, the choices made at a scan or a document import, the ones typed on the marker. Without them a restored account asks again at the next scan which marker each spelling belongs to.",
|
||||
BiomarkerMerge:
|
||||
"The ledger of which markers were merged into which. Without it a link or a cached screen that still names a merged marker reads as a plain 404 instead of being sent to the marker it went into.",
|
||||
MedicationIngredient:
|
||||
"What one tablet or capsule of a supplement contains. Without it a restored account's supplements stop counting toward the day's micronutrients, and the composition has to be typed in again from the label.",
|
||||
DawarichDay:
|
||||
|
||||
@@ -126,10 +126,38 @@ export interface BiomarkerBackupEntry {
|
||||
context: string | null;
|
||||
/** The catalogue key the marker's name and unit resolve to. */
|
||||
analyteKey?: string | null;
|
||||
/**
|
||||
* v1.43 (D1223) — the other spellings the marker answers to, with where
|
||||
* each came from. Absent on files written before them.
|
||||
*/
|
||||
aliases?: BiomarkerAliasBackupEntry[];
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface BiomarkerAliasBackupEntry {
|
||||
/** Present in canonical DR payloads. */
|
||||
id?: string;
|
||||
name: string;
|
||||
source: "MERGE" | "IMPORT_CHOICE" | "MANUAL";
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — one marker folded into another. The target travels by id
|
||||
* in a disaster-recovery file and by name in both, the way a lab result's
|
||||
* marker does; the source is gone, so its id and name are the record.
|
||||
*/
|
||||
export interface BiomarkerMergeBackupEntry {
|
||||
id?: string;
|
||||
targetBiomarkerId?: string;
|
||||
targetName: string;
|
||||
sourceBiomarkerId: string;
|
||||
sourceName: string;
|
||||
readingCount: number;
|
||||
mergedAt: string;
|
||||
}
|
||||
|
||||
export interface WorkoutBackupEntry {
|
||||
/** Present in canonical DR payloads for manual workouts without externalId. */
|
||||
id?: string;
|
||||
@@ -237,6 +265,7 @@ type CanonicalAllergy = AllergyDTO & {
|
||||
export interface RecordsBackupSection {
|
||||
labResults: LabResultBackupEntry[];
|
||||
biomarkers: BiomarkerBackupEntry[];
|
||||
biomarkerMerges: BiomarkerMergeBackupEntry[];
|
||||
illnessEpisodes: CanonicalIllnessEpisode[];
|
||||
allergies: CanonicalAllergy[];
|
||||
familyHistory: FamilyHistoryEntryDTO[];
|
||||
@@ -286,6 +315,8 @@ export async function buildRecordsBackupSection(
|
||||
PrismaClient,
|
||||
| "labResult"
|
||||
| "biomarker"
|
||||
| "biomarkerAlias"
|
||||
| "biomarkerMerge"
|
||||
| "illnessEpisode"
|
||||
| "allergy"
|
||||
| "familyHistoryEntry"
|
||||
@@ -351,6 +382,8 @@ export async function buildRecordsBackupSection(
|
||||
const [
|
||||
labResultRows,
|
||||
biomarkerRows,
|
||||
biomarkerAliasRows,
|
||||
biomarkerMergeRows,
|
||||
episodeRows,
|
||||
allergyRows,
|
||||
familyRows,
|
||||
@@ -366,6 +399,22 @@ export async function buildRecordsBackupSection(
|
||||
where: { userId },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.biomarkerAlias.findMany({
|
||||
where: { userId },
|
||||
orderBy: [{ biomarkerId: "asc" }, { nameFolded: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
biomarkerId: true,
|
||||
name: true,
|
||||
source: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.biomarkerMerge.findMany({
|
||||
where: { userId },
|
||||
orderBy: { mergedAt: "asc" },
|
||||
include: { target: { select: { name: true } } },
|
||||
}),
|
||||
prisma.illnessEpisode.findMany({
|
||||
where: disasterRecovery ? { userId } : { userId, deletedAt: null },
|
||||
orderBy: { onsetAt: "desc" },
|
||||
@@ -429,6 +478,32 @@ export async function buildRecordsBackupSection(
|
||||
biomarkerName: r.biomarker?.name ?? null,
|
||||
}));
|
||||
|
||||
const aliasesByMarker = new Map<string, BiomarkerAliasBackupEntry[]>();
|
||||
for (const alias of biomarkerAliasRows) {
|
||||
const list = aliasesByMarker.get(alias.biomarkerId) ?? [];
|
||||
list.push({
|
||||
name: alias.name,
|
||||
source: alias.source as BiomarkerAliasBackupEntry["source"],
|
||||
...(disasterRecovery
|
||||
? { id: alias.id, createdAt: alias.createdAt.toISOString() }
|
||||
: {}),
|
||||
});
|
||||
aliasesByMarker.set(alias.biomarkerId, list);
|
||||
}
|
||||
|
||||
const biomarkerMerges: BiomarkerMergeBackupEntry[] = biomarkerMergeRows.map(
|
||||
(m) => ({
|
||||
...(disasterRecovery
|
||||
? { id: m.id, targetBiomarkerId: m.targetBiomarkerId }
|
||||
: {}),
|
||||
targetName: m.target.name,
|
||||
sourceBiomarkerId: m.sourceBiomarkerId,
|
||||
sourceName: m.sourceName,
|
||||
readingCount: m.readingCount,
|
||||
mergedAt: m.mergedAt.toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
const biomarkers: BiomarkerBackupEntry[] = biomarkerRows.map((b) => ({
|
||||
...(disasterRecovery
|
||||
? {
|
||||
@@ -449,6 +524,7 @@ export async function buildRecordsBackupSection(
|
||||
decryptContextFromBytes,
|
||||
),
|
||||
analyteKey: b.analyteKey,
|
||||
aliases: aliasesByMarker.get(b.id) ?? [],
|
||||
}));
|
||||
|
||||
const illnessEpisodes: CanonicalIllnessEpisode[] = disasterRecovery
|
||||
@@ -598,6 +674,7 @@ export async function buildRecordsBackupSection(
|
||||
return {
|
||||
labResults,
|
||||
biomarkers,
|
||||
biomarkerMerges,
|
||||
illnessEpisodes,
|
||||
allergies,
|
||||
familyHistory,
|
||||
|
||||
@@ -72,6 +72,7 @@ import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
|
||||
import { encryptContextToBytes } from "@/lib/labs/biomarker-store";
|
||||
import { encryptNoteToBytes } from "@/lib/labs/store";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
import type { BackupMeasurement } from "@/lib/validations/backup";
|
||||
import {
|
||||
isCompatibleSchemaVersion,
|
||||
@@ -2076,6 +2077,76 @@ export async function restoreBackup(
|
||||
});
|
||||
biomarkerByName.set(biomarker.name, created.id);
|
||||
restoredBiomarkerIds.add(created.id);
|
||||
// v1.43 (D1223) — the other spellings, folded the way the resolver
|
||||
// reads them, so the next scan matches them again.
|
||||
const aliasRows = (biomarker.aliases ?? [])
|
||||
.map((alias) => ({
|
||||
id: alias.id,
|
||||
name: alias.name.trim().slice(0, 120),
|
||||
nameFolded: foldForMatch(alias.name).slice(0, 120),
|
||||
source: alias.source,
|
||||
createdAt: alias.createdAt,
|
||||
}))
|
||||
.filter(
|
||||
(alias) =>
|
||||
alias.nameFolded !== "" &&
|
||||
alias.nameFolded !== foldForMatch(biomarker.name),
|
||||
);
|
||||
if (aliasRows.length > 0) {
|
||||
await tx.biomarkerAlias.createMany({
|
||||
data: aliasRows.map((alias) => ({
|
||||
...(alias.id ? { id: alias.id } : {}),
|
||||
userId: ownerId,
|
||||
biomarkerId: created.id,
|
||||
name: alias.name,
|
||||
nameFolded: alias.nameFolded,
|
||||
source: alias.source,
|
||||
...(alias.createdAt
|
||||
? { createdAt: new Date(alias.createdAt) }
|
||||
: {}),
|
||||
})),
|
||||
// One spelling answers to one marker per account; a file that
|
||||
// names it twice keeps the first.
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// v1.43 (D1223) — the merge ledger, against the markers just written:
|
||||
// by id where the file carries one this restore kept, by name
|
||||
// otherwise. A row whose target the file does not carry has nothing
|
||||
// to point at and is left out (counted on the event).
|
||||
let unresolvedMerges = 0;
|
||||
const mergeRows = (payload.biomarkerMerges ?? []).flatMap((merge) => {
|
||||
const targetId =
|
||||
merge.targetBiomarkerId &&
|
||||
restoredBiomarkerIds.has(merge.targetBiomarkerId)
|
||||
? merge.targetBiomarkerId
|
||||
: biomarkerByName.get(merge.targetName);
|
||||
if (!targetId) {
|
||||
unresolvedMerges += 1;
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
...(merge.id ? { id: merge.id } : {}),
|
||||
userId: ownerId,
|
||||
targetBiomarkerId: targetId,
|
||||
sourceBiomarkerId: merge.sourceBiomarkerId,
|
||||
sourceName: merge.sourceName,
|
||||
readingCount: merge.readingCount,
|
||||
mergedAt: new Date(merge.mergedAt),
|
||||
},
|
||||
];
|
||||
});
|
||||
if (mergeRows.length > 0) {
|
||||
await tx.biomarkerMerge.createMany({ data: mergeRows });
|
||||
}
|
||||
if (unresolvedMerges > 0) {
|
||||
annotate({
|
||||
action: { name: "backup.restore.biomarkerMerge.unresolved" },
|
||||
meta: { count: unresolvedMerges },
|
||||
});
|
||||
}
|
||||
|
||||
// Collected for the staged facts further down: an approved fact's
|
||||
|
||||
@@ -35,9 +35,9 @@ export function labObservations(
|
||||
const observations: FhirObservation[] = [];
|
||||
|
||||
for (const lab of data.labResults ?? []) {
|
||||
// Forward-compat: when the DTO carries a resolved canonical analyte name,
|
||||
// thread it as the third arg so the catalog name wins over the free-text
|
||||
// `analyte`. Absent today.
|
||||
// `analyte` is the marker's own name (v1.43): readings of one biomarker
|
||||
// are one Observation whatever each report printed, so two spellings
|
||||
// merged into one marker never reach a receiver as two analytes.
|
||||
const coding = resolveLabCoding(lab.analyte, lab.unit);
|
||||
const text = lab.panel ? `${lab.analyte} (${lab.panel})` : lab.analyte;
|
||||
const code = coding
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
|
||||
import { catalogKeyForName, catalogNameIndex } from "../analyte-match";
|
||||
import { ANALYTE_ALIASES, LAB_NAME_ALIASES } from "../biomarker-catalog";
|
||||
import {
|
||||
addAliasToIndex,
|
||||
matchForReview,
|
||||
nameSimilarity,
|
||||
resolveInIndex,
|
||||
suggestInIndex,
|
||||
type IndexedMarker,
|
||||
type MarkerIndex,
|
||||
} from "../biomarker-resolve";
|
||||
|
||||
let seq = 0;
|
||||
function marker(
|
||||
name: string,
|
||||
unit: string,
|
||||
extra: Partial<IndexedMarker> = {},
|
||||
) {
|
||||
seq += 1;
|
||||
return {
|
||||
id: `bm-${seq}`,
|
||||
name,
|
||||
unit,
|
||||
lowerBound: null,
|
||||
upperBound: null,
|
||||
panel: null,
|
||||
analyteKey: null,
|
||||
hidden: false,
|
||||
createdAt: new Date(Date.UTC(2026, 0, seq)),
|
||||
...extra,
|
||||
} satisfies IndexedMarker;
|
||||
}
|
||||
|
||||
function index(
|
||||
markers: IndexedMarker[],
|
||||
aliases: Array<{ biomarkerId: string; name: string }> = [],
|
||||
): MarkerIndex {
|
||||
return {
|
||||
markers,
|
||||
aliases: aliases.map((a) => ({ ...a, nameFolded: foldForMatch(a.name) })),
|
||||
};
|
||||
}
|
||||
|
||||
describe("the catalog's shorthand (D1223)", () => {
|
||||
it.each([
|
||||
["Alk.P", "alkaline-phosphatase"],
|
||||
["Alk Phos", "alkaline-phosphatase"],
|
||||
["ALP", "alkaline-phosphatase"],
|
||||
["Alkalische Phosphatase (AP)", "alkaline-phosphatase"],
|
||||
["T.Bili", "bilirubin-total"],
|
||||
["T. Bili", "bilirubin-total"],
|
||||
["TBIL", "bilirubin-total"],
|
||||
["Bilirubin gesamt", "bilirubin-total"],
|
||||
["GPT", "alt"],
|
||||
["ALAT", "alt"],
|
||||
["AST(SGOT)", "ast"],
|
||||
["GOT", "ast"],
|
||||
["γ-GT", "ggt"],
|
||||
["Gamma-GT", "ggt"],
|
||||
["GGTP", "ggt"],
|
||||
["LDH", "ldh"],
|
||||
["CRP", "crp"],
|
||||
["hsCRP", "hs-crp"],
|
||||
["TSH basal", "tsh"],
|
||||
["fT3", "ft3"],
|
||||
["T4L", "ft4"],
|
||||
["HbA1c", "hba1c"],
|
||||
["eGFR", "egfr"],
|
||||
["Hb", "hemoglobin"],
|
||||
["Hkt", "hematocrit"],
|
||||
["MCV", "mcv"],
|
||||
["PLT", "platelets"],
|
||||
["Leuko", "wbc"],
|
||||
["Krea", "creatinine"],
|
||||
["25(OH)D", "vitamin-d"],
|
||||
["Ferr", "ferritin"],
|
||||
["B12", "vitamin-b12"],
|
||||
])("%s is %s", (name, key) => {
|
||||
expect(catalogKeyForName(name)).toBe(key);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Bilirubin (Total)", "bilirubin-total"],
|
||||
["Kreatinin (Serum)", "creatinine"],
|
||||
["GPT (ALT)", "alt"],
|
||||
])("%s, with its parenthetical, is %s", (name, key) => {
|
||||
expect(catalogKeyForName(name)).toBe(key);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["PCR"],
|
||||
["TG"],
|
||||
["T3"],
|
||||
["T4"],
|
||||
["Cr"],
|
||||
["Calcitriol"],
|
||||
["LDL-P"],
|
||||
["Calcium (ionisiert)"],
|
||||
["Glucose (urine)"],
|
||||
["GPT (AST)"],
|
||||
])("%s is no catalog name (ambiguous or another test)", (name) => {
|
||||
expect(catalogKeyForName(name)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the standard and the high-sensitivity CRP apart", () => {
|
||||
expect(catalogKeyForName("CRP")).not.toBe(catalogKeyForName("hs-CRP"));
|
||||
});
|
||||
|
||||
it("writes every name already folded", () => {
|
||||
for (const { key, names } of [...ANALYTE_ALIASES, ...LAB_NAME_ALIASES]) {
|
||||
for (const name of names) {
|
||||
expect(foldForMatch(name), `${key}: ${name}`).toBe(name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("has no name that two analytes claim", () => {
|
||||
expect(catalogNameIndex().ambiguous).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveInIndex", () => {
|
||||
it("resolves the marker's own name, case aside", () => {
|
||||
const ldl = marker("LDL", "mg/dL");
|
||||
expect(resolveInIndex(index([ldl]), "ldl")).toEqual({
|
||||
marker: ldl,
|
||||
matchKind: "name",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the exact spelling over a case variant", () => {
|
||||
const a = marker("ldl", "mg/dL");
|
||||
const b = marker("LDL", "mg/dL");
|
||||
expect(resolveInIndex(index([a, b]), "LDL")?.marker).toBe(b);
|
||||
});
|
||||
|
||||
it("resolves an alias of the account, folded", () => {
|
||||
const alp = marker("Alkaline Phosphatase", "U/L");
|
||||
const found = resolveInIndex(
|
||||
index([alp], [{ biomarkerId: alp.id, name: "Alk.P" }]),
|
||||
"ALK.P",
|
||||
);
|
||||
expect(found).toEqual({ marker: alp, matchKind: "alias" });
|
||||
});
|
||||
|
||||
it("resolves a catalog abbreviation to the account's marker of that analyte", () => {
|
||||
const alp = marker("Alkaline Phosphatase", "U/L");
|
||||
expect(resolveInIndex(index([alp]), "Alk.P", "U/L")).toEqual({
|
||||
marker: alp,
|
||||
matchKind: "catalog",
|
||||
});
|
||||
// The discussion's own pair: a marker named with a neutral qualifier.
|
||||
const bili = marker("Bilirubin (Total)", "mg/dL");
|
||||
expect(resolveInIndex(index([bili]), "T.Bili", "mg/dL")).toEqual({
|
||||
marker: bili,
|
||||
matchKind: "catalog",
|
||||
});
|
||||
});
|
||||
|
||||
it("recognises a marker by one of its aliases' catalog analyte", () => {
|
||||
const liver = marker("Leberwert 1", "U/L");
|
||||
const found = resolveInIndex(
|
||||
index([liver], [{ biomarkerId: liver.id, name: "ALT" }]),
|
||||
"GPT",
|
||||
"U/L",
|
||||
);
|
||||
expect(found).toEqual({ marker: liver, matchKind: "catalog" });
|
||||
});
|
||||
|
||||
it("converts across units in the catalog step where the registry can", () => {
|
||||
const glucose = marker("Glucose", "mg/dL", {
|
||||
analyteKey: "fasting-glucose",
|
||||
});
|
||||
expect(
|
||||
resolveInIndex(index([glucose]), "Blutzucker", "mmol/L")?.marker,
|
||||
).toBe(glucose);
|
||||
});
|
||||
|
||||
it("steps aside in the catalog step for a unit it cannot reconcile", () => {
|
||||
const alt = marker("ALT", "U/L");
|
||||
expect(resolveInIndex(index([alt]), "GPT", "µkat/L")).toBeNull();
|
||||
// A qualitative reading or none stated always fits.
|
||||
expect(resolveInIndex(index([alt]), "GPT", null)?.marker).toBe(alt);
|
||||
});
|
||||
|
||||
it("lets the name and the alias win regardless of the unit", () => {
|
||||
const alt = marker("ALT", "U/L");
|
||||
expect(resolveInIndex(index([alt]), "ALT", "µkat/L")?.matchKind).toBe(
|
||||
"name",
|
||||
);
|
||||
expect(
|
||||
resolveInIndex(
|
||||
index([alt], [{ biomarkerId: alt.id, name: "Leber ALT" }]),
|
||||
"Leber ALT",
|
||||
"µkat/L",
|
||||
)?.matchKind,
|
||||
).toBe("alias");
|
||||
});
|
||||
|
||||
it("prefers a visible marker over a hidden one in the catalog step", () => {
|
||||
const hidden = marker("ALT", "U/L", { hidden: true });
|
||||
const visible = marker("GPT (ALT)", "U/L");
|
||||
expect(
|
||||
resolveInIndex(index([hidden, visible]), "SGPT", "U/L")?.marker,
|
||||
).toBe(visible);
|
||||
});
|
||||
|
||||
it("resolves nothing for an unknown name", () => {
|
||||
expect(resolveInIndex(index([marker("ALT", "U/L")]), "Zinc")).toBeNull();
|
||||
expect(resolveInIndex(index([]), " ")).toBeNull();
|
||||
});
|
||||
|
||||
it("sees an alias added after the index was loaded", () => {
|
||||
const tsh = marker("TSH", "mIU/L");
|
||||
const idx = index([tsh]);
|
||||
addAliasToIndex(idx, tsh.id, "Thyreotropes Hormon");
|
||||
expect(resolveInIndex(idx, "thyreotropes hormon")?.matchKind).toBe("alias");
|
||||
});
|
||||
});
|
||||
|
||||
describe("suggestions", () => {
|
||||
it("offers the same analyte first when its unit kept it from matching", () => {
|
||||
const alt = marker("ALT", "U/L");
|
||||
const { match, suggestions } = matchForReview(
|
||||
index([alt, marker("AST", "U/L")]),
|
||||
"GPT",
|
||||
"µkat/L",
|
||||
);
|
||||
expect(match).toBeNull();
|
||||
expect(suggestions[0]).toEqual({
|
||||
biomarkerId: alt.id,
|
||||
name: "ALT",
|
||||
unit: "U/L",
|
||||
matchKind: "catalog",
|
||||
});
|
||||
});
|
||||
|
||||
it("offers similar names through the catalog's names for the marker", () => {
|
||||
const bili = marker("T.Bili", "mg/dL");
|
||||
const suggestions = suggestInIndex(index([bili]), "Bilirubin ges.");
|
||||
expect(suggestions).toEqual([
|
||||
{
|
||||
biomarkerId: bili.id,
|
||||
name: "T.Bili",
|
||||
unit: "mg/dL",
|
||||
matchKind: "similar",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers shorthand against a full name", () => {
|
||||
const alp = marker("Alkaline Phosphatase", "U/L");
|
||||
expect(suggestInIndex(index([alp]), "Alk. Phosph.")[0]?.biomarkerId).toBe(
|
||||
alp.id,
|
||||
);
|
||||
});
|
||||
|
||||
it("offers at most three and never a hidden marker", () => {
|
||||
const markers = [
|
||||
marker("Vitamin B1", "µg/L"),
|
||||
marker("Vitamin B2", "µg/L"),
|
||||
marker("Vitamin B6", "µg/L"),
|
||||
marker("Vitamin B9", "µg/L"),
|
||||
marker("Vitamin B3", "µg/L", { hidden: true }),
|
||||
];
|
||||
const suggestions = suggestInIndex(index(markers), "Vitamin B5");
|
||||
expect(suggestions).toHaveLength(3);
|
||||
expect(suggestions.map((s) => s.name)).not.toContain("Vitamin B3");
|
||||
});
|
||||
|
||||
it("offers nothing unrelated and nothing when the name matched", () => {
|
||||
const ldl = marker("LDL", "mg/dL");
|
||||
expect(suggestInIndex(index([ldl]), "Ferritin")).toEqual([]);
|
||||
expect(matchForReview(index([ldl]), "LDL").suggestions).toEqual([]);
|
||||
});
|
||||
|
||||
it("scores names", () => {
|
||||
expect(nameSimilarity("Ferritin", "ferritin")).toBe(1);
|
||||
expect(nameSimilarity("alk phos", "alkaline phosphatase")).toBe(0.8);
|
||||
expect(nameSimilarity("LDL", "Ferritin")).toBeLessThan(0.5);
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,24 @@
|
||||
/**
|
||||
* v1.18.1 — `resolveOrMintBiomarker`: the auto-link-on-write helper.
|
||||
* `resolveOrMintBiomarker`: the auto-link-on-write helper.
|
||||
*
|
||||
* Every free-text lab write resolves (or mints) a user-scoped Biomarker by
|
||||
* `(userId, lower(analyte))` so NO `LabResult` row ever persists unlinked.
|
||||
* Asserts: case-insensitive reuse, mint-on-miss from the reading's own
|
||||
* spelling, no silent rewrite of an existing marker, and the concurrent
|
||||
* Every free-text lab write resolves (or mints) a user-scoped Biomarker so NO
|
||||
* `LabResult` row ever persists unlinked. Since v1.43 the name resolves
|
||||
* through the account's markers and aliases (`resolveInIndex`), loaded in one
|
||||
* read. Asserts: case-insensitive reuse, alias reuse, mint-on-miss from the
|
||||
* reading's own spelling, no silent rewrite of an existing marker, a minted
|
||||
* marker found by the next row through a shared index, and the concurrent
|
||||
* unique-violation race adopting the winner.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const db = vi.hoisted(() => ({
|
||||
biomarker: { findFirst: vi.fn(), create: vi.fn() },
|
||||
biomarker: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn() },
|
||||
biomarkerAlias: { findMany: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({ prisma: db }));
|
||||
|
||||
import { loadMarkerIndex } from "@/lib/labs/biomarker-resolve";
|
||||
import { resolveOrMintBiomarker } from "@/lib/labs/biomarker-store";
|
||||
|
||||
const baseInput = {
|
||||
@@ -25,21 +29,32 @@ const baseInput = {
|
||||
panel: "lipids" as string | null,
|
||||
};
|
||||
|
||||
function marker(overrides: Record<string, unknown>) {
|
||||
return {
|
||||
id: "bm",
|
||||
name: "Marker",
|
||||
unit: "mg/dL",
|
||||
lowerBound: null,
|
||||
upperBound: null,
|
||||
panel: null,
|
||||
analyteKey: null,
|
||||
hidden: false,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
db.biomarker.findMany.mockResolvedValue([]);
|
||||
db.biomarkerAlias.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("resolveOrMintBiomarker", () => {
|
||||
it("reuses an existing marker (case-insensitive) without minting", async () => {
|
||||
db.biomarker.findFirst.mockResolvedValue({
|
||||
id: "bm_existing",
|
||||
name: "LDL Cholesterol",
|
||||
unit: "mg/dL",
|
||||
lowerBound: null,
|
||||
upperBound: 100,
|
||||
panel: "lipids",
|
||||
analyteKey: null,
|
||||
});
|
||||
db.biomarker.findMany.mockResolvedValue([
|
||||
marker({ id: "bm_existing", name: "LDL", upperBound: 100 }),
|
||||
]);
|
||||
|
||||
const out = await resolveOrMintBiomarker("u1", {
|
||||
...baseInput,
|
||||
@@ -51,23 +66,33 @@ describe("resolveOrMintBiomarker", () => {
|
||||
// values do NOT rewrite it.
|
||||
expect(out.upperBound).toBe(100);
|
||||
expect(db.biomarker.create).not.toHaveBeenCalled();
|
||||
// Match is case-insensitive on the catalog identity.
|
||||
const where = db.biomarker.findFirst.mock.calls[0][0].where;
|
||||
expect(where.name).toEqual({ equals: "ldl", mode: "insensitive" });
|
||||
expect(where.userId).toBe("u1");
|
||||
expect(db.biomarker.findMany.mock.calls[0][0].where).toEqual({
|
||||
userId: "u1",
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the marker an alias of the account names", async () => {
|
||||
db.biomarker.findMany.mockResolvedValue([
|
||||
marker({ id: "bm_alp", name: "Alkaline Phosphatase", unit: "U/L" }),
|
||||
]);
|
||||
db.biomarkerAlias.findMany.mockResolvedValue([
|
||||
{ biomarkerId: "bm_alp", name: "Alk.P", nameFolded: "alk.p" },
|
||||
]);
|
||||
|
||||
const out = await resolveOrMintBiomarker("u1", {
|
||||
...baseInput,
|
||||
analyte: "ALK.P",
|
||||
unit: "U/L",
|
||||
});
|
||||
|
||||
expect(out.id).toBe("bm_alp");
|
||||
expect(db.biomarker.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("mints a new marker from the reading when none exists", async () => {
|
||||
db.biomarker.findFirst.mockResolvedValue(null);
|
||||
db.biomarker.create.mockResolvedValue({
|
||||
id: "bm_new",
|
||||
name: "LDL",
|
||||
unit: "mg/dL",
|
||||
lowerBound: null,
|
||||
upperBound: 116,
|
||||
panel: "lipids",
|
||||
analyteKey: null,
|
||||
});
|
||||
db.biomarker.create.mockResolvedValue(
|
||||
marker({ id: "bm_new", name: "LDL", upperBound: 116, panel: "lipids" }),
|
||||
);
|
||||
|
||||
const out = await resolveOrMintBiomarker("u1", baseInput);
|
||||
|
||||
@@ -84,16 +109,9 @@ describe("resolveOrMintBiomarker", () => {
|
||||
});
|
||||
|
||||
it("trims the analyte before minting", async () => {
|
||||
db.biomarker.findFirst.mockResolvedValue(null);
|
||||
db.biomarker.create.mockResolvedValue({
|
||||
id: "bm_x",
|
||||
name: "Ferritin",
|
||||
unit: "ng/mL",
|
||||
lowerBound: 30,
|
||||
upperBound: 400,
|
||||
panel: null,
|
||||
analyteKey: null,
|
||||
});
|
||||
db.biomarker.create.mockResolvedValue(
|
||||
marker({ id: "bm_x", name: "Ferritin", unit: "ng/mL" }),
|
||||
);
|
||||
|
||||
await resolveOrMintBiomarker("u1", {
|
||||
analyte: " Ferritin ",
|
||||
@@ -106,17 +124,32 @@ describe("resolveOrMintBiomarker", () => {
|
||||
expect(db.biomarker.create.mock.calls[0][0].data.name).toBe("Ferritin");
|
||||
});
|
||||
|
||||
it("finds a marker minted for an earlier row through the shared index", async () => {
|
||||
db.biomarker.create.mockResolvedValue(
|
||||
marker({ id: "bm_tsh", name: "TSH", unit: "mIU/L" }),
|
||||
);
|
||||
const index = await loadMarkerIndex(db as never, "u1");
|
||||
const input = { ...baseInput, analyte: "TSH", unit: "mIU/L" };
|
||||
|
||||
const first = await resolveOrMintBiomarker("u1", input, { index });
|
||||
const second = await resolveOrMintBiomarker(
|
||||
"u1",
|
||||
{ ...input, analyte: "tsh" },
|
||||
{ index },
|
||||
);
|
||||
|
||||
expect(first.id).toBe("bm_tsh");
|
||||
expect(second.id).toBe("bm_tsh");
|
||||
expect(db.biomarker.create).toHaveBeenCalledTimes(1);
|
||||
expect(db.biomarker.findMany).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("adopts the race winner on a concurrent unique violation", async () => {
|
||||
// First lookup misses; create throws (the other writer won the unique
|
||||
// The index misses; create throws (the other writer won the unique
|
||||
// index); the re-lookup finds the winner.
|
||||
db.biomarker.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce({
|
||||
id: "bm_winner",
|
||||
name: "TSH",
|
||||
unit: "mIU/L",
|
||||
lowerBound: 0.4,
|
||||
upperBound: 4,
|
||||
panel: "thyroid",
|
||||
});
|
||||
db.biomarker.findFirst.mockResolvedValueOnce(
|
||||
marker({ id: "bm_winner", name: "TSH", unit: "mIU/L" }),
|
||||
);
|
||||
db.biomarker.create.mockRejectedValue(new Error("unique constraint"));
|
||||
|
||||
const out = await resolveOrMintBiomarker("u1", {
|
||||
@@ -128,7 +161,7 @@ describe("resolveOrMintBiomarker", () => {
|
||||
});
|
||||
|
||||
expect(out.id).toBe("bm_winner");
|
||||
expect(db.biomarker.findFirst).toHaveBeenCalledTimes(2);
|
||||
expect(db.biomarker.findFirst).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("throws when the create fails and no race winner exists", async () => {
|
||||
|
||||
@@ -22,7 +22,11 @@
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
import { localisedValues } from "@/lib/i18n/shared-resolve";
|
||||
|
||||
import { ANALYTE_ALIASES, BIOMARKER_CATALOG } from "./biomarker-catalog";
|
||||
import {
|
||||
ANALYTE_ALIASES,
|
||||
BIOMARKER_CATALOG,
|
||||
LAB_NAME_ALIASES,
|
||||
} from "./biomarker-catalog";
|
||||
import { analyteAcceptsUnit } from "./unit-conversion/convert";
|
||||
import { analyteConversionFor } from "./unit-conversion/registry";
|
||||
|
||||
@@ -77,7 +81,129 @@ export function matchAnalyteKey(input: {
|
||||
unit: string;
|
||||
}): string | null {
|
||||
cache ??= analyteNameIndex().index;
|
||||
const key = cache.get(foldForMatch(input.name));
|
||||
const key =
|
||||
cache.get(foldForMatch(input.name)) ??
|
||||
cache.get(foldWithoutDots(input.name));
|
||||
if (!key) return null;
|
||||
return analyteAcceptsUnit(key, input.unit) ? key : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fold with every full stop and comma read as a space as well: lab
|
||||
* shorthand is printed "Alk.P", "T.Bili", "Bilirubin, total", and the dot or
|
||||
* comma carries no meaning there. Applied to both sides, like the fold itself.
|
||||
*/
|
||||
export function foldWithoutDots(raw: string): string {
|
||||
return foldForMatch(raw).replace(/[.,]/gu, " ").replace(/\s+/gu, " ").trim();
|
||||
}
|
||||
|
||||
let catalogCache: ReadonlyMap<string, string> | null = null;
|
||||
let catalogNamesCache: ReadonlyMap<string, readonly string[]> | null = null;
|
||||
|
||||
/**
|
||||
* Which catalog analyte a NAME is, for telling two markers of one account
|
||||
* apart from two spellings of one marker (D1223). Unlike `analyteNameIndex`
|
||||
* this needs no conversion: "GPT" and "ALT" are one analyte whether or not
|
||||
* the registry can move it between units, so every seed, every alias in
|
||||
* `ANALYTE_ALIASES` and every name in `LAB_NAME_ALIASES` claims here, folded
|
||||
* with and without dots. A name two analytes claim matches neither.
|
||||
* Exported for the guard test.
|
||||
*/
|
||||
export function catalogNameIndex(): {
|
||||
index: ReadonlyMap<string, string>;
|
||||
ambiguous: readonly string[];
|
||||
} {
|
||||
const claims = new Map<string, Set<string>>();
|
||||
const claim = (folded: string, key: string) => {
|
||||
if (!folded) return;
|
||||
const keys = claims.get(folded) ?? new Set<string>();
|
||||
keys.add(key);
|
||||
claims.set(folded, keys);
|
||||
};
|
||||
const claimName = (name: string, key: string) => {
|
||||
claim(foldForMatch(name), key);
|
||||
claim(foldWithoutDots(name), key);
|
||||
};
|
||||
|
||||
for (const seed of BIOMARKER_CATALOG) {
|
||||
for (const name of localisedValues(`labs.catalog.${seed.slug}`)) {
|
||||
claimName(name, seed.slug);
|
||||
claim(withoutGloss(foldForMatch(name)), seed.slug);
|
||||
}
|
||||
}
|
||||
for (const { key, names } of [...ANALYTE_ALIASES, ...LAB_NAME_ALIASES]) {
|
||||
for (const name of names) claimName(name, key);
|
||||
}
|
||||
|
||||
const index = new Map<string, string>();
|
||||
const ambiguous: string[] = [];
|
||||
for (const [folded, keys] of claims) {
|
||||
if (keys.size === 1) index.set(folded, [...keys][0]);
|
||||
else ambiguous.push(folded);
|
||||
}
|
||||
return { index, ambiguous };
|
||||
}
|
||||
|
||||
/**
|
||||
* Qualifiers that may stand in parentheses after a name without making it a
|
||||
* different measurement: "Bilirubin (Total)", "Kreatinin (Serum)". Anything
|
||||
* else in parentheses names something else ("Calcium (ionisiert)", "Glucose
|
||||
* (urine)") and keeps the name unmatched.
|
||||
*/
|
||||
const NEUTRAL_GLOSSES = new Set([
|
||||
"total",
|
||||
"totale",
|
||||
"totales",
|
||||
"gesamt",
|
||||
"serum",
|
||||
"s",
|
||||
"plasma",
|
||||
"blood",
|
||||
"blut",
|
||||
"sang",
|
||||
"sangre",
|
||||
"sangue",
|
||||
"krew",
|
||||
]);
|
||||
|
||||
function lookupWhole(name: string): string | null {
|
||||
catalogCache ??= catalogNameIndex().index;
|
||||
return (
|
||||
catalogCache.get(foldForMatch(name)) ??
|
||||
catalogCache.get(foldWithoutDots(name)) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog analyte a name belongs to, or null. Whole names only, with one
|
||||
* allowance for a trailing parenthetical: it is read when it names the same
|
||||
* analyte as the rest ("GPT (ALT)") or is a neutral qualifier ("Bilirubin
|
||||
* (Total)"), and never otherwise.
|
||||
*/
|
||||
export function catalogKeyForName(name: string): string | null {
|
||||
const whole = lookupWhole(name);
|
||||
if (whole) return whole;
|
||||
const glossed = /^(.+?)\s*\(([^()]+)\)\s*$/u.exec(name.trim());
|
||||
if (!glossed) return null;
|
||||
const outer = lookupWhole(glossed[1]);
|
||||
if (!outer) return null;
|
||||
const gloss = glossed[2];
|
||||
if (NEUTRAL_GLOSSES.has(foldWithoutDots(gloss))) return outer;
|
||||
return lookupWhole(gloss) === outer ? outer : null;
|
||||
}
|
||||
|
||||
/** Every folded name the catalog knows for one analyte, for suggestions. */
|
||||
export function catalogNamesForKey(key: string): readonly string[] {
|
||||
if (!catalogNamesCache) {
|
||||
catalogCache ??= catalogNameIndex().index;
|
||||
const byKey = new Map<string, string[]>();
|
||||
for (const [folded, k] of catalogCache) {
|
||||
const list = byKey.get(k) ?? [];
|
||||
list.push(folded);
|
||||
byKey.set(k, list);
|
||||
}
|
||||
catalogNamesCache = byKey;
|
||||
}
|
||||
return catalogNamesCache.get(key) ?? [];
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* The other spellings of a marker (D1223), stored per account in
|
||||
* `biomarker_aliases`.
|
||||
*
|
||||
* `nameFolded` is `foldForMatch(name)` and unique per account, so one spelling
|
||||
* resolves to one marker. An alias equal to its own marker's name (folded) is
|
||||
* never stored: the name already resolves.
|
||||
*
|
||||
* Sources: `MERGE` (a merged marker's name), `IMPORT_CHOICE` (a name mapped to
|
||||
* a marker on a scan or document review), `MANUAL` (typed on the marker).
|
||||
*/
|
||||
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
|
||||
export type AliasSource = "MERGE" | "IMPORT_CHOICE" | "MANUAL";
|
||||
|
||||
type AliasClient = Pick<PrismaClient, "biomarkerAlias" | "biomarker">;
|
||||
type AliasTx = Prisma.TransactionClient;
|
||||
|
||||
/** Longest alias, matching the column. */
|
||||
export const BIOMARKER_ALIAS_MAX_LENGTH = 120;
|
||||
|
||||
/**
|
||||
* The aliases of each marker, sorted, without the marker's own name. One read
|
||||
* for the whole set, so a list of markers costs one query.
|
||||
*/
|
||||
export async function aliasNamesByMarker(
|
||||
client: Pick<PrismaClient, "biomarkerAlias">,
|
||||
userId: string,
|
||||
markers: ReadonlyArray<{ id: string; name: string }>,
|
||||
): Promise<Map<string, string[]>> {
|
||||
const out = new Map<string, string[]>();
|
||||
if (markers.length === 0) return out;
|
||||
const rows = await client.biomarkerAlias.findMany({
|
||||
where: { userId, biomarkerId: { in: markers.map((m) => m.id) } },
|
||||
select: { biomarkerId: true, name: true, nameFolded: true },
|
||||
});
|
||||
const ownFold = new Map(markers.map((m) => [m.id, foldForMatch(m.name)]));
|
||||
for (const row of rows) {
|
||||
if (row.nameFolded === ownFold.get(row.biomarkerId)) continue;
|
||||
const list = out.get(row.biomarkerId) ?? [];
|
||||
list.push(row.name);
|
||||
out.set(row.biomarkerId, list);
|
||||
}
|
||||
for (const list of out.values()) {
|
||||
list.sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What blocks an alias: another marker's name or another marker's alias. */
|
||||
export interface AliasConflict {
|
||||
alias: string;
|
||||
biomarkerId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first alias in `names` that another marker of the account already
|
||||
* answers to, by name or alias; null when none does.
|
||||
*/
|
||||
export async function findAliasConflict(
|
||||
client: AliasClient | AliasTx,
|
||||
userId: string,
|
||||
biomarkerId: string,
|
||||
names: readonly string[],
|
||||
): Promise<AliasConflict | null> {
|
||||
if (names.length === 0) return null;
|
||||
const folds = new Map(names.map((n) => [foldForMatch(n), n]));
|
||||
const [markers, aliases] = await Promise.all([
|
||||
client.biomarker.findMany({
|
||||
where: { userId, id: { not: biomarkerId } },
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
client.biomarkerAlias.findMany({
|
||||
where: {
|
||||
userId,
|
||||
biomarkerId: { not: biomarkerId },
|
||||
nameFolded: { in: [...folds.keys()] },
|
||||
},
|
||||
select: { biomarkerId: true, nameFolded: true },
|
||||
}),
|
||||
]);
|
||||
for (const marker of markers) {
|
||||
const hit = folds.get(foldForMatch(marker.name));
|
||||
if (hit !== undefined) return { alias: hit, biomarkerId: marker.id };
|
||||
}
|
||||
const alias = aliases[0];
|
||||
if (alias) {
|
||||
return {
|
||||
alias: folds.get(alias.nameFolded) ?? alias.nameFolded,
|
||||
biomarkerId: alias.biomarkerId,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make `names` the marker's aliases: what is listed stays (keeping where it
|
||||
* came from) or is added as `MANUAL`, what is not listed is removed. The list
|
||||
* is the whole set the marker answers to, as `aliases` on the marker reads it;
|
||||
* the caller has already checked it for conflicts.
|
||||
*/
|
||||
export async function replaceAliases(
|
||||
tx: AliasTx,
|
||||
userId: string,
|
||||
marker: { id: string; name: string },
|
||||
names: readonly string[],
|
||||
): Promise<void> {
|
||||
const ownFold = foldForMatch(marker.name);
|
||||
const wanted = new Map<string, string>();
|
||||
for (const raw of names) {
|
||||
const name = raw.trim();
|
||||
const folded = foldForMatch(name);
|
||||
if (!folded || folded === ownFold || wanted.has(folded)) continue;
|
||||
wanted.set(folded, name);
|
||||
}
|
||||
const existing = await tx.biomarkerAlias.findMany({
|
||||
where: { userId, biomarkerId: marker.id },
|
||||
select: { id: true, nameFolded: true },
|
||||
});
|
||||
const stale = existing
|
||||
.filter((row) => !wanted.has(row.nameFolded))
|
||||
.map((row) => row.id);
|
||||
if (stale.length > 0) {
|
||||
await tx.biomarkerAlias.deleteMany({
|
||||
where: { userId, id: { in: stale } },
|
||||
});
|
||||
}
|
||||
const kept = new Set(existing.map((row) => row.nameFolded));
|
||||
const fresh = [...wanted].filter(([folded]) => !kept.has(folded));
|
||||
if (fresh.length > 0) {
|
||||
await tx.biomarkerAlias.createMany({
|
||||
data: fresh.map(([nameFolded, name]) => ({
|
||||
userId,
|
||||
biomarkerId: marker.id,
|
||||
name: name.slice(0, BIOMARKER_ALIAS_MAX_LENGTH),
|
||||
nameFolded: nameFolded.slice(0, BIOMARKER_ALIAS_MAX_LENGTH),
|
||||
source: "MANUAL",
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remember a name the person mapped to a marker on a review screen, so the
|
||||
* next report with the same spelling resolves without asking. A spelling
|
||||
* already attached to another marker moves to this one: the choice is the
|
||||
* person's latest word on it. The marker's own name is not stored.
|
||||
* Returns whether an alias was written.
|
||||
*/
|
||||
export async function rememberImportAlias(
|
||||
client: Pick<PrismaClient, "biomarkerAlias">,
|
||||
userId: string,
|
||||
marker: { id: string; name: string },
|
||||
printedName: string,
|
||||
): Promise<boolean> {
|
||||
const name = printedName.trim().slice(0, BIOMARKER_ALIAS_MAX_LENGTH);
|
||||
const nameFolded = foldForMatch(name).slice(0, BIOMARKER_ALIAS_MAX_LENGTH);
|
||||
if (!nameFolded || nameFolded === foldForMatch(marker.name)) return false;
|
||||
await client.biomarkerAlias.upsert({
|
||||
where: { userId_nameFolded: { userId, nameFolded } },
|
||||
create: {
|
||||
userId,
|
||||
biomarkerId: marker.id,
|
||||
name,
|
||||
nameFolded,
|
||||
source: "IMPORT_CHOICE",
|
||||
},
|
||||
update: { biomarkerId: marker.id, name, source: "IMPORT_CHOICE" },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -217,6 +217,23 @@ export const BIOMARKER_CATALOG: readonly BiomarkerSeed[] = [
|
||||
lowerBound: null,
|
||||
upperBound: 55,
|
||||
},
|
||||
// v1.43 (D1223) — the two markers a report most often prints in shorthand
|
||||
// ("Alk.P", "T.Bili"). Adult reference windows per MedlinePlus: ALP 44-147
|
||||
// IU/L, total bilirubin 0.1-1.2 mg/dL. Editable defaults like every seed.
|
||||
{
|
||||
slug: "alkaline-phosphatase",
|
||||
panel: "liver",
|
||||
unit: "U/L",
|
||||
lowerBound: 44,
|
||||
upperBound: 147,
|
||||
},
|
||||
{
|
||||
slug: "bilirubin-total",
|
||||
panel: "liver",
|
||||
unit: "mg/dL",
|
||||
lowerBound: 0.1,
|
||||
upperBound: 1.2,
|
||||
},
|
||||
// Electrolytes
|
||||
{
|
||||
slug: "sodium",
|
||||
@@ -294,8 +311,8 @@ export const BIOMARKER_PANELS = [
|
||||
* Names are compared folded (lower case, no accents, hyphens and slashes as
|
||||
* spaces), so "Harnsäure" is written "harnsaure" here and "Nüchtern-Glukose"
|
||||
* needs no entry of its own. The registry-only keys (urea, blood urea
|
||||
* nitrogen, uric acid, total calcium, total bilirubin) have no seed, so their
|
||||
* names live only here.
|
||||
* nitrogen, uric acid, total calcium) have no seed, so their names live only
|
||||
* here; total bilirubin has had a seed since v1.43.
|
||||
*/
|
||||
export interface AnalyteAliases {
|
||||
/** The analyte key: a catalog slug, or a registry-only key. */
|
||||
@@ -336,6 +353,24 @@ export const ANALYTE_ALIASES: readonly AnalyteAliases[] = [
|
||||
"glycosylated hemoglobin",
|
||||
"glykohamoglobin",
|
||||
"hamoglobin a1c",
|
||||
// v1.43 (D1223) — MedlinePlus, Lab Tests Online (es, it, pl), Medics
|
||||
// Labor, CHU de Lille, IUCPQ / CHUM, Asan Medical Center.
|
||||
"hba1c",
|
||||
"glycohemoglobin",
|
||||
"glykohamoglobin a1c",
|
||||
"hemoglobina glicada",
|
||||
"hemoglobina glicosilada",
|
||||
"glicohemoglobina",
|
||||
"hemoglobine glyquee",
|
||||
"hb glyque",
|
||||
"glycohemoglobine",
|
||||
"hemoglobine glycosylee",
|
||||
"emoglobina a1c",
|
||||
"glicoemoglobina",
|
||||
"emoglobina glicosilata",
|
||||
"hemoglobina glikowana",
|
||||
"glikohemoglobina",
|
||||
"당화혈색소",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -351,8 +386,33 @@ export const ANALYTE_ALIASES: readonly AnalyteAliases[] = [
|
||||
"cholesterol calkowity",
|
||||
],
|
||||
},
|
||||
{ key: "ldl", names: ["ldl", "ldl c", "ldl chol", "ldl cholesterin"] },
|
||||
{ key: "hdl", names: ["hdl", "hdl c", "hdl chol", "hdl cholesterin"] },
|
||||
{
|
||||
key: "ldl",
|
||||
names: [
|
||||
"ldl",
|
||||
"ldl c",
|
||||
"ldl chol",
|
||||
"ldl cholesterin",
|
||||
// v1.43 — Labor Limbach, Medics Labor, gesundheit.gv.at, CHU de Lille,
|
||||
// the Korean national screening form.
|
||||
"ldl direkt",
|
||||
"ldlch",
|
||||
"cholesterol ldl",
|
||||
"저밀도 콜레스테롤",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "hdl",
|
||||
names: [
|
||||
"hdl",
|
||||
"hdl c",
|
||||
"hdl chol",
|
||||
"hdl cholesterin",
|
||||
"hdlch",
|
||||
"cholesterol hdl",
|
||||
"고밀도 콜레스테롤",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "creatinine",
|
||||
names: [
|
||||
@@ -360,6 +420,18 @@ export const ANALYTE_ALIASES: readonly AnalyteAliases[] = [
|
||||
"serumkreatinin",
|
||||
"kreatinin im serum",
|
||||
"creatinine serique",
|
||||
// v1.43 — Labor Limbach ("Krea/S", serum only: the urine "Krea/U" is a
|
||||
// different measurement and is not here), Medics Labor, Lab Tests
|
||||
// Online (es, it, pl), CHU de Lille, CHUM, the Korean screening form.
|
||||
"krea s",
|
||||
"krea",
|
||||
"crea",
|
||||
"creatinin",
|
||||
"kreatinin",
|
||||
"creatininemie",
|
||||
"creat",
|
||||
"creatinina sierica",
|
||||
"혈청 크레아티닌",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -371,6 +443,22 @@ export const ANALYTE_ALIASES: readonly AnalyteAliases[] = [
|
||||
"25 oh d",
|
||||
"calcidiol",
|
||||
"vitamin d 25 oh",
|
||||
// v1.43 — 25-OH only; calcitriol (1,25-(OH)2 D) is a different test and
|
||||
// stays out. MedlinePlus, Medics Labor, gesundheit.gv.at, Lab Tests
|
||||
// Online (es, it, pl), CHU de Lille, IUCPQ.
|
||||
"25(oh)d",
|
||||
"25 (oh)d",
|
||||
"calcifediol",
|
||||
"25 hydroxycholecalciferol",
|
||||
"vd25",
|
||||
"25 hidroxivitamina d",
|
||||
"25 (oh) vitamine d",
|
||||
"25 oh, vitamine d3",
|
||||
"25 oh vitamina d",
|
||||
"25 idrossi vitamina d",
|
||||
"25 hydroksy witamina d3",
|
||||
"kalcydiol",
|
||||
"25 hydroksykolekalciferol",
|
||||
],
|
||||
},
|
||||
{ key: "urea", names: ["urea", "harnstoff", "uree", "urea serum"] },
|
||||
@@ -422,6 +510,417 @@ export const ANALYTE_ALIASES: readonly AnalyteAliases[] = [
|
||||
"bilirrubina",
|
||||
"bilirubine",
|
||||
"bilirubina",
|
||||
// v1.43 (D1223) — "Alk.P" / "T.Bili" are how the reports in the
|
||||
// discussion print them; the rest are MedlinePlus, testing.com, Labor
|
||||
// Limbach, Medics Labor, Lab Tests Online (es, it), Dimedic (pl) and
|
||||
// Asan Medical Center. The bare "BIL" is left out: lower case it is the
|
||||
// urine dipstick field in German code lists.
|
||||
"t.bili",
|
||||
"t. bili",
|
||||
"tbil",
|
||||
"total serum bilirubin",
|
||||
"tsb",
|
||||
"bili",
|
||||
"totales bilirubin",
|
||||
"bilirrubina total",
|
||||
"bilirubina totale",
|
||||
"bilirubina całkowita",
|
||||
"총 빌리루빈",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* v1.43 (D1223) — other names for analytes, for recognising that two
|
||||
* spellings on two reports are one marker. Same shape and fold as
|
||||
* `ANALYTE_ALIASES`, and read together with it by `catalogNameIndex`, but
|
||||
* with no conversion attached: an analyte here may have no entry in the
|
||||
* unit-conversion registry ("GPT" is "ALT" whatever the unit), and the key may
|
||||
* be a catalog slug or a name-only key for an analyte with no seed (`ldh`,
|
||||
* `mcv`). Nothing here changes which unit conversion a marker gets.
|
||||
*
|
||||
* Every name is written folded (`foldForMatch`); a dot in shorthand is kept
|
||||
* ("alk.p") and also matched without it. Each name was checked against a
|
||||
* laboratory or clinical reference; a shorthand that names two analytes in
|
||||
* different places ("PCR", "AP" outside German reports, "Cr") is left out,
|
||||
* because a wrong automatic match moves a reading into the wrong history.
|
||||
*/
|
||||
export const LAB_NAME_ALIASES: readonly AnalyteAliases[] = [
|
||||
{
|
||||
key: "alkaline-phosphatase",
|
||||
names: [
|
||||
"alp",
|
||||
"alkp",
|
||||
"alk phos",
|
||||
"alk.p",
|
||||
"ap",
|
||||
"alk. phosphatase",
|
||||
"alkalische phosphatase",
|
||||
"fosfatasa alcalina",
|
||||
"pal",
|
||||
"phosphatases alcalines",
|
||||
"fosfatasi alcalina",
|
||||
"fosfataza alkaliczna",
|
||||
"fosfataza zasadowa",
|
||||
"알칼리인산분해효소",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "alt",
|
||||
names: [
|
||||
"alt",
|
||||
"sgpt",
|
||||
"gpt",
|
||||
"alanine transaminase",
|
||||
"alanine aminotransferase",
|
||||
"alat",
|
||||
"glutamat pyruvat transaminase",
|
||||
"alanina aminotransferasa",
|
||||
"transaminasa glutamico piruvico",
|
||||
"tgp",
|
||||
"alanina aminotransferasi",
|
||||
"aminotransferaza alaninowa",
|
||||
"alt(sgpt)",
|
||||
"혈청gpt",
|
||||
"알라닌아미노전달효소",
|
||||
"알라닌아미노전이효소",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "ast",
|
||||
names: [
|
||||
"ast",
|
||||
"sgot",
|
||||
"got",
|
||||
"aspartate transaminase",
|
||||
"aspartate aminotransferase",
|
||||
"asat",
|
||||
"glutamat oxalacetat transaminase",
|
||||
"aspartato aminotransferasa",
|
||||
"transaminasa glutamico oxalacetico",
|
||||
"tgo",
|
||||
"aspartato transaminasi",
|
||||
"aspat",
|
||||
"aminotransferaza asparaginianowa",
|
||||
"ast(sgot)",
|
||||
"혈청got",
|
||||
"아스파테이트아미노전달효소",
|
||||
"아스파테이트아미노전이효소",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "ggt",
|
||||
names: [
|
||||
"ggt",
|
||||
"ggtp",
|
||||
"gtp",
|
||||
"gamma gt",
|
||||
"γ gt",
|
||||
"γgt",
|
||||
"gamma glutamyltransferase",
|
||||
"gammaglutamyltransferase",
|
||||
"gamma glutamil transferasa",
|
||||
"gamma glutamylotranspeptydaza",
|
||||
"감마지티피(γgtp)",
|
||||
"γgtp",
|
||||
"감마지티피",
|
||||
"감마지티",
|
||||
"r gtp",
|
||||
"감마 gtp",
|
||||
"감마글루타밀전이효소",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "ldh",
|
||||
names: [
|
||||
"ldh",
|
||||
"ld",
|
||||
"lactate dehydrogenase",
|
||||
"lactic dehydrogenase",
|
||||
"lactatdehydrogenase",
|
||||
"laktatdehydrogenase",
|
||||
"lactato deshidrogenasa",
|
||||
"lactate deshydrogenase",
|
||||
"lattico deidrogenasi",
|
||||
"lattato deidrogenasi",
|
||||
"dehydrogenaza mleczanowa",
|
||||
"젖산탈수효소",
|
||||
],
|
||||
},
|
||||
{
|
||||
// The standard assay. "PCR" is left out: it is CRP on Spanish and
|
||||
// Italian reports and polymerase chain reaction everywhere else.
|
||||
key: "crp",
|
||||
names: [
|
||||
"crp",
|
||||
"c reactive protein",
|
||||
"c reaktives protein",
|
||||
"proteina c reactiva",
|
||||
"proteine c reactive",
|
||||
"proteina c reattiva",
|
||||
"białko c reaktywne",
|
||||
"c 반응성 단백",
|
||||
],
|
||||
},
|
||||
{
|
||||
// The high-sensitivity assay, kept apart from the standard one: the two
|
||||
// are read against different ranges, and a merge is the person's call.
|
||||
key: "hs-crp",
|
||||
names: [
|
||||
"hs crp",
|
||||
"hscrp",
|
||||
"high sensitivity crp",
|
||||
"cardiac crp",
|
||||
"crp hochsensitiv",
|
||||
"pcr ultrasensible",
|
||||
"pcr us",
|
||||
"proteina c reactiva ultrasensible",
|
||||
"crp ultrasensible",
|
||||
"crp hs",
|
||||
"hs pcr",
|
||||
"pcr ultrasensibile",
|
||||
"proteina c reattiva ultrasensibile",
|
||||
"crp wysoko czułe",
|
||||
"crp ultra czułe",
|
||||
"wysoko czułe białko c reaktywne",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "tsh",
|
||||
names: [
|
||||
"tsh",
|
||||
"thyrotropin",
|
||||
"thyroid stimulating hormone",
|
||||
"thyreotropin",
|
||||
"tsh basal",
|
||||
"tirotropina",
|
||||
"hormona estimulante del tiroides",
|
||||
"hormona tiroestimulante",
|
||||
"tsh us",
|
||||
"tsh ultra sensible",
|
||||
"thyrotropine",
|
||||
"tireotropina",
|
||||
"ormone tireotropo",
|
||||
"tyreotropina",
|
||||
"hormon tyreotropowy",
|
||||
"갑상선자극호르몬",
|
||||
],
|
||||
},
|
||||
{
|
||||
// Free T3 only: a bare "T3" is the total hormone.
|
||||
key: "ft3",
|
||||
names: [
|
||||
"ft3",
|
||||
"free t3",
|
||||
"free triiodothyronine",
|
||||
"t3 frei",
|
||||
"freies t3",
|
||||
"trijodthyronin frei",
|
||||
"t3 libre",
|
||||
"t3l",
|
||||
"triiodotironina libera",
|
||||
"wolna t3",
|
||||
],
|
||||
},
|
||||
{
|
||||
// Free T4 only: a bare "T4" is the total hormone.
|
||||
key: "ft4",
|
||||
names: [
|
||||
"ft4",
|
||||
"free t4",
|
||||
"free thyroxine",
|
||||
"t4 frei",
|
||||
"freies t4",
|
||||
"thyroxin frei",
|
||||
"t4l",
|
||||
"t4 libre",
|
||||
"tiroxina libre",
|
||||
"thyroxine libre",
|
||||
"tiroxina libera",
|
||||
"wolna t4",
|
||||
"유리 싸이록신",
|
||||
],
|
||||
},
|
||||
{
|
||||
// Estimates only: a bare "GFR" may be a measured rate, and a
|
||||
// Cockcroft-Gault clearance is a different quantity.
|
||||
key: "egfr",
|
||||
names: [
|
||||
"egfr",
|
||||
"estimated gfr",
|
||||
"cgfr",
|
||||
"egfr nach ckd epi formel",
|
||||
"ckdepi",
|
||||
"egfr nach mdrd formel",
|
||||
"tefg",
|
||||
"tfg calculada",
|
||||
"tasa estimada de filtrado glomerular",
|
||||
"fge",
|
||||
"dfg",
|
||||
"dfge",
|
||||
"szacowana filtracja kłebuszkowa",
|
||||
"신사구체여과율 (e gfr)",
|
||||
"e gfr",
|
||||
"신사구체여과율",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "hemoglobin",
|
||||
names: ["hb", "hgb", "hemogl", "hemoglobine", "혈색소"],
|
||||
},
|
||||
{
|
||||
key: "hematocrit",
|
||||
names: [
|
||||
"hct",
|
||||
"pcv",
|
||||
"crit",
|
||||
"packed cell volume",
|
||||
"hkt",
|
||||
"hto",
|
||||
"ht",
|
||||
"적혈구용적률",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "mcv",
|
||||
names: [
|
||||
"mcv",
|
||||
"mittleres zellvolumen",
|
||||
"vcm",
|
||||
"volumen corpuscular medio",
|
||||
"vgm",
|
||||
"volume globulaire moyen",
|
||||
"평균적혈구용적",
|
||||
],
|
||||
},
|
||||
{
|
||||
// "Hb/E" is Labor Limbach's code for MCH, not haemoglobin.
|
||||
key: "mch",
|
||||
names: ["mch", "hb e", "hcm", "tcmh", "tgmh", "평균적혈구혈색소량"],
|
||||
},
|
||||
{
|
||||
key: "mchc",
|
||||
names: [
|
||||
"mchc",
|
||||
"chcm",
|
||||
"ccmh",
|
||||
"cgmh",
|
||||
"평균적혈구 헤모글로빈농도",
|
||||
"평균 적혈구혈색소 농도",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "rbc",
|
||||
names: [
|
||||
"rbc",
|
||||
"rbc count",
|
||||
"erythrocyte count",
|
||||
"red count",
|
||||
"ery",
|
||||
"erythrozyten",
|
||||
"recuento de hematies",
|
||||
"recuento eritrocitario",
|
||||
"erythrocytes",
|
||||
"hematies",
|
||||
"liczba erytrocytow",
|
||||
"적혈구",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "wbc",
|
||||
names: [
|
||||
"wbc",
|
||||
"leukocyte count",
|
||||
"white cell count",
|
||||
"leuko",
|
||||
"leukozyten",
|
||||
"leuc",
|
||||
"leucocitos",
|
||||
"leucocytes",
|
||||
"liczba leukocytow",
|
||||
"백혈구",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "platelets",
|
||||
names: [
|
||||
"plt",
|
||||
"plt count",
|
||||
"thrombocyte count",
|
||||
"thromb",
|
||||
"thr",
|
||||
"thrombozyten",
|
||||
"plaq",
|
||||
"plaquetas",
|
||||
"plaquettes",
|
||||
"conta piastrinica",
|
||||
"liczba płytek krwi",
|
||||
"liczba trombocytow",
|
||||
"platelet",
|
||||
"혈소판",
|
||||
],
|
||||
},
|
||||
{
|
||||
// "TG" is left out: written "Tg" it is thyroglobulin, and the match
|
||||
// ignores case.
|
||||
key: "triglycerides",
|
||||
names: [
|
||||
"trig",
|
||||
"tgl",
|
||||
"trg",
|
||||
"triglyceride",
|
||||
"triglycerides",
|
||||
"trigliceridos",
|
||||
"trigliceridi",
|
||||
"triglicerydy",
|
||||
"중성지방",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "ferritin",
|
||||
names: [
|
||||
"ferritin",
|
||||
"serum ferritin",
|
||||
"ferr",
|
||||
"ferritina",
|
||||
"ferritine",
|
||||
"ferritina sierica",
|
||||
"ferrytyna",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "vitamin-b12",
|
||||
names: [
|
||||
"vitamin b12",
|
||||
"b12",
|
||||
"cobalamin",
|
||||
"cobalamina",
|
||||
"vitamine b12",
|
||||
"cyanocobalamine",
|
||||
"vb12",
|
||||
"vitamina b12",
|
||||
"witamina b12",
|
||||
"kobalamina",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "sodium",
|
||||
names: ["na", "na+", "natrium", "sodium", "sodio", "natremie", "소디움"],
|
||||
},
|
||||
{
|
||||
// A bare "K" only ever reaches a potassium marker whose unit the reading
|
||||
// fits (`resolveInIndex`), never vitamin K.
|
||||
key: "potassium",
|
||||
names: [
|
||||
"k",
|
||||
"k+",
|
||||
"kalium",
|
||||
"potassium",
|
||||
"potasio",
|
||||
"potassio",
|
||||
"potas",
|
||||
"kaliemie",
|
||||
"포타슘",
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* The `Biomarker` DTO, one shape for the list, the detail, the edit and the
|
||||
* merge result. The encrypted context bytes are never echoed: `hasContext`
|
||||
* flags them and `context` carries the plaintext. `aliases` are the other
|
||||
* spellings the marker answers to (v1.43), sorted, without its own name.
|
||||
*/
|
||||
import {
|
||||
decryptContextFromBytes,
|
||||
decryptContextSoft,
|
||||
} from "@/lib/labs/biomarker-store";
|
||||
|
||||
export interface BiomarkerDtoRow {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
lowerBound: number | null;
|
||||
upperBound: number | null;
|
||||
panel: string | null;
|
||||
analyteKey: string | null;
|
||||
hidden: boolean;
|
||||
contextEncrypted: Uint8Array | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* `soft` decrypts fail-soft (the list: one bad row must not 500 the catalog);
|
||||
* otherwise a decrypt failure throws so a key gap surfaces on the detail.
|
||||
*/
|
||||
export function serialiseBiomarker(
|
||||
row: BiomarkerDtoRow,
|
||||
aliases: readonly string[],
|
||||
options: { soft?: boolean } = {},
|
||||
) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
unit: row.unit,
|
||||
lowerBound: row.lowerBound,
|
||||
upperBound: row.upperBound,
|
||||
panel: row.panel,
|
||||
analyteKey: row.analyteKey,
|
||||
hasContext: row.contextEncrypted !== null,
|
||||
context: options.soft
|
||||
? decryptContextSoft(row.contextEncrypted)
|
||||
: row.contextEncrypted
|
||||
? decryptContextFromBytes(row.contextEncrypted)
|
||||
: null,
|
||||
hidden: row.hidden,
|
||||
aliases: [...aliases],
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export type BiomarkerDto = ReturnType<typeof serialiseBiomarker>;
|
||||
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* Merge markers into one (D1223): "Alk.P" and "Alkaline Phosphatase" become
|
||||
* one marker with one history.
|
||||
*
|
||||
* The plan and the write are one function, so a dry run answers exactly what
|
||||
* the merge would do: it reads the same rows, converts the same values and
|
||||
* returns the same numbers, and only the write step is skipped.
|
||||
*
|
||||
* What a merge does, in one transaction:
|
||||
* - every reading of every source moves to the target. A reading in a unit
|
||||
* other than the target's is converted with the target's analyte
|
||||
* (`convertLabValue`), together with the windows stamped on it; the value
|
||||
* and unit the report printed stay in `sourceValue` / `sourceUnit` (a
|
||||
* reading that was already converted keeps its original pair). The
|
||||
* reading's own `analyte` stays the name that was printed.
|
||||
* - a pair of units the registry cannot convert refuses the WHOLE merge;
|
||||
* nothing moves, not even the sources that would convert;
|
||||
* - medication efficacy targets follow their marker;
|
||||
* - each source's name and its aliases become aliases of the target
|
||||
* (`MERGE`), unless the target's name or another marker already answers
|
||||
* to that spelling;
|
||||
* - one `biomarker_merges` row per source, and the rows that already pointed
|
||||
* at a source now point at the target, so an id merged twice still finds
|
||||
* where it went;
|
||||
* - the sources are deleted.
|
||||
*
|
||||
* There is no undo. The ledger keeps what a later split would need to know
|
||||
* (which marker, which name, how many readings).
|
||||
*/
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
|
||||
import { matchAnalyteKey } from "./analyte-match";
|
||||
import {
|
||||
BIOMARKER_ALIAS_MAX_LENGTH,
|
||||
aliasNamesByMarker,
|
||||
} from "./biomarker-aliases";
|
||||
import { serialiseBiomarker, type BiomarkerDto } from "./biomarker-dto";
|
||||
import {
|
||||
convertLabRange,
|
||||
convertLabValue,
|
||||
type ConversionRefusal,
|
||||
} from "./unit-conversion/convert";
|
||||
import { sameLabUnit } from "./unit-normalise";
|
||||
|
||||
export type MergeConversion = "none" | "converted" | "refused";
|
||||
|
||||
export interface MergeSourceSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
readingCount: number;
|
||||
conversion: MergeConversion;
|
||||
refusal: ConversionRefusal | null;
|
||||
}
|
||||
|
||||
export interface BiomarkerMergeResult {
|
||||
dryRun: boolean;
|
||||
target: BiomarkerDto;
|
||||
sources: MergeSourceSummary[];
|
||||
movedReadings: number;
|
||||
convertedReadings: number;
|
||||
aliasesAdded: string[];
|
||||
mergeId: string | null;
|
||||
}
|
||||
|
||||
export type BiomarkerMergeOutcome =
|
||||
| { kind: "ok"; result: BiomarkerMergeResult }
|
||||
| { kind: "notFound"; ids: string[] }
|
||||
| {
|
||||
kind: "unitMismatch";
|
||||
sources: Array<{
|
||||
id: string;
|
||||
unit: string;
|
||||
targetUnit: string;
|
||||
reason: ConversionRefusal;
|
||||
}>;
|
||||
};
|
||||
|
||||
interface ReadingUpdate {
|
||||
id: string;
|
||||
value: number;
|
||||
unit: string;
|
||||
referenceLow: number | null;
|
||||
referenceHigh: number | null;
|
||||
sourceReferenceLow: number | null;
|
||||
sourceReferenceHigh: number | null;
|
||||
sourceValue: number;
|
||||
sourceUnit: string;
|
||||
}
|
||||
|
||||
/** Thrown inside the transaction to roll it back with the refusal. */
|
||||
class MergeRefused extends Error {
|
||||
constructor(readonly outcome: BiomarkerMergeOutcome) {
|
||||
super("merge refused");
|
||||
}
|
||||
}
|
||||
|
||||
export async function mergeBiomarkers(input: {
|
||||
userId: string;
|
||||
targetId: string;
|
||||
sourceIds: readonly string[];
|
||||
dryRun: boolean;
|
||||
}): Promise<BiomarkerMergeOutcome> {
|
||||
try {
|
||||
return await prisma.$transaction(
|
||||
(tx) => runMerge(tx, input),
|
||||
// A source with a long history updates row by row where it converts.
|
||||
{ timeout: 60_000, maxWait: 10_000 },
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof MergeRefused) return err.outcome;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function runMerge(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: {
|
||||
userId: string;
|
||||
targetId: string;
|
||||
sourceIds: readonly string[];
|
||||
dryRun: boolean;
|
||||
},
|
||||
): Promise<BiomarkerMergeOutcome> {
|
||||
const { userId, targetId, sourceIds, dryRun } = input;
|
||||
|
||||
const markers = await tx.biomarker.findMany({
|
||||
where: { userId, id: { in: [targetId, ...sourceIds] } },
|
||||
});
|
||||
const byId = new Map(markers.map((m) => [m.id, m]));
|
||||
const missing = [targetId, ...sourceIds].filter((id) => !byId.has(id));
|
||||
if (missing.length > 0) return { kind: "notFound", ids: missing };
|
||||
const target = byId.get(targetId)!;
|
||||
const sources = sourceIds.map((id) => byId.get(id)!);
|
||||
|
||||
// The target's analyte, derived the way every write path derives it, so a
|
||||
// stale stored key cannot pick the wrong factor.
|
||||
const analyteKey = matchAnalyteKey({ name: target.name, unit: target.unit });
|
||||
|
||||
const readings = await tx.labResult.findMany({
|
||||
where: { userId, biomarkerId: { in: [...sourceIds] } },
|
||||
select: {
|
||||
id: true,
|
||||
biomarkerId: true,
|
||||
value: true,
|
||||
unit: true,
|
||||
referenceLow: true,
|
||||
referenceHigh: true,
|
||||
sourceReferenceLow: true,
|
||||
sourceReferenceHigh: true,
|
||||
sourceValue: true,
|
||||
sourceUnit: true,
|
||||
deletedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const summaries: MergeSourceSummary[] = [];
|
||||
const updates: ReadingUpdate[] = [];
|
||||
let movedReadings = 0;
|
||||
// Counted like `readingCount`: the live readings a person sees. A tombstoned
|
||||
// reading moves and converts with them, so an undo brings it back right.
|
||||
let convertedLive = 0;
|
||||
for (const source of sources) {
|
||||
const own = readings.filter((r) => r.biomarkerId === source.id);
|
||||
let converted = 0;
|
||||
let refusal: ConversionRefusal | null = null;
|
||||
for (const reading of own) {
|
||||
// A qualitative reading, or one already in the target's unit, moves as
|
||||
// it is.
|
||||
if (reading.value === null || sameLabUnit(reading.unit, target.unit)) {
|
||||
continue;
|
||||
}
|
||||
const value = convertLabValue({
|
||||
analyteKey,
|
||||
value: reading.value,
|
||||
from: reading.unit,
|
||||
to: target.unit,
|
||||
});
|
||||
const stamped = convertLabRange({
|
||||
analyteKey,
|
||||
low: reading.referenceLow,
|
||||
high: reading.referenceHigh,
|
||||
from: reading.unit,
|
||||
to: target.unit,
|
||||
});
|
||||
const printed = convertLabRange({
|
||||
analyteKey,
|
||||
low: reading.sourceReferenceLow,
|
||||
high: reading.sourceReferenceHigh,
|
||||
from: reading.unit,
|
||||
to: target.unit,
|
||||
});
|
||||
if (!value.ok || !stamped.ok || !printed.ok) {
|
||||
refusal ??= !value.ok
|
||||
? value.reason
|
||||
: !stamped.ok
|
||||
? stamped.reason
|
||||
: !printed.ok
|
||||
? printed.reason
|
||||
: "unknown_unit";
|
||||
continue;
|
||||
}
|
||||
converted += 1;
|
||||
if (reading.deletedAt === null) convertedLive += 1;
|
||||
updates.push({
|
||||
id: reading.id,
|
||||
value: value.value,
|
||||
unit: target.unit,
|
||||
referenceLow: stamped.low,
|
||||
referenceHigh: stamped.high,
|
||||
sourceReferenceLow: printed.low,
|
||||
sourceReferenceHigh: printed.high,
|
||||
// A reading converted on its way in keeps what the report printed.
|
||||
sourceValue: reading.sourceValue ?? reading.value,
|
||||
sourceUnit: reading.sourceUnit ?? reading.unit.trim(),
|
||||
});
|
||||
}
|
||||
const live = own.filter((r) => r.deletedAt === null).length;
|
||||
movedReadings += live;
|
||||
summaries.push({
|
||||
id: source.id,
|
||||
name: source.name,
|
||||
unit: source.unit,
|
||||
readingCount: live,
|
||||
conversion: refusal ? "refused" : converted > 0 ? "converted" : "none",
|
||||
refusal,
|
||||
});
|
||||
}
|
||||
const convertedReadings = convertedLive;
|
||||
|
||||
// The spellings the target gains: each source's name and its aliases, once
|
||||
// each, except what the target's name already is or another marker (not a
|
||||
// source) already answers to.
|
||||
const sourceAliases = await tx.biomarkerAlias.findMany({
|
||||
where: { userId, biomarkerId: { in: [...sourceIds] } },
|
||||
select: { id: true, name: true, nameFolded: true },
|
||||
});
|
||||
const otherAliases = await tx.biomarkerAlias.findMany({
|
||||
where: { userId, biomarkerId: { notIn: [...sourceIds] } },
|
||||
select: { biomarkerId: true, nameFolded: true },
|
||||
});
|
||||
const blocked = new Set(
|
||||
otherAliases
|
||||
.filter((a) => a.biomarkerId !== targetId)
|
||||
.map((a) => a.nameFolded),
|
||||
);
|
||||
const targetAliasFolds = new Set(
|
||||
otherAliases
|
||||
.filter((a) => a.biomarkerId === targetId)
|
||||
.map((a) => a.nameFolded),
|
||||
);
|
||||
const otherMarkerFolds = new Set(
|
||||
(
|
||||
await tx.biomarker.findMany({
|
||||
where: { userId, id: { notIn: [targetId, ...sourceIds] } },
|
||||
select: { name: true },
|
||||
})
|
||||
).map((m) => foldForMatch(m.name)),
|
||||
);
|
||||
const targetFold = foldForMatch(target.name);
|
||||
const added = new Map<string, string>();
|
||||
const consider = (name: string) => {
|
||||
const folded = foldForMatch(name).slice(0, BIOMARKER_ALIAS_MAX_LENGTH);
|
||||
if (!folded || folded === targetFold) return;
|
||||
if (targetAliasFolds.has(folded) || added.has(folded)) return;
|
||||
if (blocked.has(folded) || otherMarkerFolds.has(folded)) return;
|
||||
added.set(folded, name.trim().slice(0, BIOMARKER_ALIAS_MAX_LENGTH));
|
||||
};
|
||||
for (const source of sources) consider(source.name);
|
||||
for (const alias of sourceAliases) consider(alias.name);
|
||||
const aliasesAdded = [...added.values()];
|
||||
|
||||
const refused = summaries.filter((s) => s.conversion === "refused");
|
||||
if (!dryRun && refused.length > 0) {
|
||||
throw new MergeRefused({
|
||||
kind: "unitMismatch",
|
||||
sources: refused.map((s) => ({
|
||||
id: s.id,
|
||||
unit: s.unit,
|
||||
targetUnit: target.unit,
|
||||
reason: s.refusal ?? "unknown_unit",
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
let mergeId: string | null = null;
|
||||
if (!dryRun) {
|
||||
for (const update of updates) {
|
||||
await tx.labResult.update({
|
||||
where: { id: update.id },
|
||||
data: {
|
||||
biomarkerId: targetId,
|
||||
value: update.value,
|
||||
unit: update.unit,
|
||||
referenceLow: update.referenceLow,
|
||||
referenceHigh: update.referenceHigh,
|
||||
sourceReferenceLow: update.sourceReferenceLow,
|
||||
sourceReferenceHigh: update.sourceReferenceHigh,
|
||||
sourceValue: update.sourceValue,
|
||||
sourceUnit: update.sourceUnit,
|
||||
},
|
||||
});
|
||||
}
|
||||
await tx.labResult.updateMany({
|
||||
where: { userId, biomarkerId: { in: [...sourceIds] } },
|
||||
data: { biomarkerId: targetId },
|
||||
});
|
||||
await tx.medicationEfficacyTarget.updateMany({
|
||||
where: { biomarkerId: { in: [...sourceIds] } },
|
||||
data: { biomarkerId: targetId },
|
||||
});
|
||||
// The sources' own alias rows go with the sources; the spellings that
|
||||
// survive are written again on the target below.
|
||||
await tx.biomarkerAlias.deleteMany({
|
||||
where: { userId, id: { in: sourceAliases.map((a) => a.id) } },
|
||||
});
|
||||
if (added.size > 0) {
|
||||
await tx.biomarkerAlias.createMany({
|
||||
data: [...added].map(([nameFolded, name]) => ({
|
||||
userId,
|
||||
biomarkerId: targetId,
|
||||
name,
|
||||
nameFolded,
|
||||
source: "MERGE",
|
||||
})),
|
||||
});
|
||||
}
|
||||
await tx.biomarkerMerge.updateMany({
|
||||
where: { userId, targetBiomarkerId: { in: [...sourceIds] } },
|
||||
data: { targetBiomarkerId: targetId },
|
||||
});
|
||||
const now = new Date();
|
||||
for (const summary of summaries) {
|
||||
const row = await tx.biomarkerMerge.create({
|
||||
data: {
|
||||
userId,
|
||||
targetBiomarkerId: targetId,
|
||||
sourceBiomarkerId: summary.id,
|
||||
sourceName: summary.name.slice(0, BIOMARKER_ALIAS_MAX_LENGTH),
|
||||
readingCount: summary.readingCount,
|
||||
mergedAt: now,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
mergeId ??= row.id;
|
||||
}
|
||||
await tx.biomarker.deleteMany({
|
||||
where: { userId, id: { in: [...sourceIds] } },
|
||||
});
|
||||
}
|
||||
|
||||
const after = dryRun
|
||||
? target
|
||||
: await tx.biomarker.findUniqueOrThrow({ where: { id: targetId } });
|
||||
const aliases = await aliasNamesByMarker(tx, userId, [after]);
|
||||
|
||||
return {
|
||||
kind: "ok",
|
||||
result: {
|
||||
dryRun,
|
||||
target: serialiseBiomarker(after, aliases.get(after.id) ?? []),
|
||||
sources: summaries,
|
||||
movedReadings,
|
||||
convertedReadings,
|
||||
aliasesAdded,
|
||||
mergeId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a merged marker went: the target of the newest merge that removed
|
||||
* `id`, or null. Chains resolve because a merge re-points the rows that named
|
||||
* its sources.
|
||||
*/
|
||||
export async function mergedInto(
|
||||
userId: string,
|
||||
id: string,
|
||||
): Promise<string | null> {
|
||||
const row = await prisma.biomarkerMerge.findFirst({
|
||||
where: { userId, sourceBiomarkerId: id },
|
||||
orderBy: { mergedAt: "desc" },
|
||||
select: { targetBiomarkerId: true },
|
||||
});
|
||||
return row?.targetBiomarkerId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
/**
|
||||
* Which of an account's markers a printed name belongs to (D1223).
|
||||
*
|
||||
* One lab writes "Alkaline Phosphatase", the next "Alk.P", and each spelling
|
||||
* used to become a marker of its own with half the history. Every path that
|
||||
* turns a name into a marker resolves it here, in one order:
|
||||
*
|
||||
* 1. `name` the marker's own name, case and spacing aside;
|
||||
* 2. `alias` a spelling the account attached to a marker (merged in,
|
||||
* chosen at an import, or typed on the marker), folded;
|
||||
* 3. `catalog` a name the catalog knows for the same analyte as a marker of
|
||||
* the account ("GPT" for a marker called "ALT"), when the
|
||||
* reading's unit is that marker's or converts to it;
|
||||
* 4. nothing the caller mints a marker, or the review offers suggestions.
|
||||
*
|
||||
* Steps 1 and 2 are the account's own decisions and win regardless of the
|
||||
* unit; a unit that does not fit is then refused by the write, exactly as it
|
||||
* is for a marker picked by hand. Step 3 is the app's guess, so it steps aside
|
||||
* for a unit it cannot reconcile and the reading keeps its own marker.
|
||||
*
|
||||
* The matching is pure over a {@link MarkerIndex} loaded once per request, so
|
||||
* the scan review, the commit and the document import cannot disagree about
|
||||
* the same name.
|
||||
*/
|
||||
import type { PrismaClient } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { foldForMatch } from "@/lib/i18n/fold-for-match";
|
||||
|
||||
import {
|
||||
catalogKeyForName,
|
||||
catalogNamesForKey,
|
||||
foldWithoutDots,
|
||||
} from "./analyte-match";
|
||||
import { convertLabValue } from "./unit-conversion/convert";
|
||||
import { sameLabUnit } from "./unit-normalise";
|
||||
|
||||
export type BiomarkerMatchKind = "name" | "alias" | "catalog";
|
||||
export type BiomarkerSuggestionKind = "catalog" | "similar";
|
||||
|
||||
/** Most suggestions a review row offers. */
|
||||
export const BIOMARKER_SUGGESTION_LIMIT = 3;
|
||||
|
||||
export interface IndexedMarker {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
lowerBound: number | null;
|
||||
upperBound: number | null;
|
||||
panel: string | null;
|
||||
analyteKey: string | null;
|
||||
hidden: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface IndexedAlias {
|
||||
biomarkerId: string;
|
||||
name: string;
|
||||
nameFolded: string;
|
||||
}
|
||||
|
||||
export interface MarkerIndex {
|
||||
markers: readonly IndexedMarker[];
|
||||
aliases: readonly IndexedAlias[];
|
||||
}
|
||||
|
||||
export interface MarkerMatch {
|
||||
marker: IndexedMarker;
|
||||
matchKind: BiomarkerMatchKind;
|
||||
}
|
||||
|
||||
export interface MarkerSuggestion {
|
||||
biomarkerId: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
matchKind: BiomarkerSuggestionKind;
|
||||
}
|
||||
|
||||
const MARKER_SELECT = {
|
||||
id: true,
|
||||
name: true,
|
||||
unit: true,
|
||||
lowerBound: true,
|
||||
upperBound: true,
|
||||
panel: true,
|
||||
analyteKey: true,
|
||||
hidden: true,
|
||||
createdAt: true,
|
||||
} as const;
|
||||
|
||||
/** Every marker and alias of the account, for {@link resolveInIndex}. */
|
||||
export async function loadMarkerIndex(
|
||||
client: Pick<PrismaClient, "biomarker" | "biomarkerAlias">,
|
||||
userId: string,
|
||||
): Promise<MarkerIndex> {
|
||||
const [markers, aliases] = await Promise.all([
|
||||
client.biomarker.findMany({
|
||||
where: { userId },
|
||||
select: MARKER_SELECT,
|
||||
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
||||
}),
|
||||
client.biomarkerAlias.findMany({
|
||||
where: { userId },
|
||||
select: { biomarkerId: true, name: true, nameFolded: true },
|
||||
}),
|
||||
]);
|
||||
return { markers, aliases };
|
||||
}
|
||||
|
||||
/** Add a marker minted after the index was loaded, so later rows see it. */
|
||||
export function addToIndex(index: MarkerIndex, marker: IndexedMarker): void {
|
||||
if (index.markers.some((m) => m.id === marker.id)) return;
|
||||
(index.markers as IndexedMarker[]).push(marker);
|
||||
}
|
||||
|
||||
/** Record an alias written after the index was loaded. */
|
||||
export function addAliasToIndex(
|
||||
index: MarkerIndex,
|
||||
biomarkerId: string,
|
||||
name: string,
|
||||
): void {
|
||||
const nameFolded = foldForMatch(name.trim());
|
||||
const list = index.aliases as IndexedAlias[];
|
||||
const at = list.findIndex((a) => a.nameFolded === nameFolded);
|
||||
const entry = { biomarkerId, name: name.trim(), nameFolded };
|
||||
if (at >= 0) list[at] = entry;
|
||||
else list.push(entry);
|
||||
}
|
||||
|
||||
/** Visible before hidden, then the oldest: the order a tie is broken in. */
|
||||
function preferred(candidates: IndexedMarker[]): IndexedMarker | null {
|
||||
if (candidates.length === 0) return null;
|
||||
const visible = candidates.filter((m) => !m.hidden);
|
||||
return (visible.length > 0 ? visible : candidates)[0] ?? null;
|
||||
}
|
||||
|
||||
/** The catalog analytes a marker answers to: through its name and its aliases. */
|
||||
function markerCatalogKeys(
|
||||
index: MarkerIndex,
|
||||
marker: IndexedMarker,
|
||||
): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
const own = catalogKeyForName(marker.name) ?? marker.analyteKey;
|
||||
if (own) keys.add(own);
|
||||
for (const alias of index.aliases) {
|
||||
if (alias.biomarkerId !== marker.id) continue;
|
||||
const key = catalogKeyForName(alias.name);
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a reading stated in `unit` can be stored under the marker: the same
|
||||
* unit, or one the conversion moves into it. No unit (a qualitative reading,
|
||||
* or none stated) always fits.
|
||||
*/
|
||||
export function unitFitsMarker(
|
||||
marker: Pick<IndexedMarker, "unit" | "analyteKey">,
|
||||
unit: string | null | undefined,
|
||||
analyteKey: string | null,
|
||||
): boolean {
|
||||
if (unit === null || unit === undefined || unit.trim() === "") return true;
|
||||
if (sameLabUnit(unit, marker.unit)) return true;
|
||||
return convertLabValue({
|
||||
analyteKey: marker.analyteKey ?? analyteKey,
|
||||
value: 1,
|
||||
from: unit,
|
||||
to: marker.unit,
|
||||
}).ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* The marker a printed name resolves to, and how; null when nothing does.
|
||||
* `unit` is the unit the reading states, used only by the catalog step.
|
||||
*/
|
||||
export function resolveInIndex(
|
||||
index: MarkerIndex,
|
||||
rawName: string,
|
||||
unit?: string | null,
|
||||
): MarkerMatch | null {
|
||||
const name = rawName.trim();
|
||||
if (!name) return null;
|
||||
|
||||
// 1. The marker's own name. An exact spelling wins over one that differs in
|
||||
// case, which wins over one that differs only in punctuation and spacing,
|
||||
// and that last one only when it names a single marker.
|
||||
const exact = index.markers.find((m) => m.name === name);
|
||||
if (exact) return { marker: exact, matchKind: "name" };
|
||||
const lower = name.toLowerCase();
|
||||
const caseless = preferred(
|
||||
index.markers.filter((m) => m.name.trim().toLowerCase() === lower),
|
||||
);
|
||||
if (caseless) return { marker: caseless, matchKind: "name" };
|
||||
const folded = foldForMatch(name);
|
||||
const byFold = index.markers.filter((m) => foldForMatch(m.name) === folded);
|
||||
if (byFold.length === 1) return { marker: byFold[0], matchKind: "name" };
|
||||
|
||||
// 2. An alias of the account.
|
||||
const alias = index.aliases.find((a) => a.nameFolded === folded);
|
||||
if (alias) {
|
||||
const marker = index.markers.find((m) => m.id === alias.biomarkerId);
|
||||
if (marker) return { marker, matchKind: "alias" };
|
||||
}
|
||||
|
||||
// 3. The catalog: a marker of the same analyte that can take the unit.
|
||||
const key = catalogKeyForName(name);
|
||||
if (key) {
|
||||
const candidates = index.markers.filter(
|
||||
(m) =>
|
||||
markerCatalogKeys(index, m).has(key) && unitFitsMarker(m, unit, key),
|
||||
);
|
||||
const marker = preferred(candidates);
|
||||
if (marker) return { marker, matchKind: "catalog" };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Folded name without dots, commas or parentheses, for the similarity. */
|
||||
function loose(raw: string): string {
|
||||
return foldWithoutDots(raw)
|
||||
.replace(/[()[\]]/gu, " ")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function bigrams(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < text.length - 1; i++) out.push(text.slice(i, i + 2));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Sørensen-Dice over character bigrams, 0..1. */
|
||||
export function diceSimilarity(a: string, b: string): number {
|
||||
const x = bigrams(a);
|
||||
const y = bigrams(b);
|
||||
if (x.length === 0 || y.length === 0) return a === b && a !== "" ? 1 : 0;
|
||||
const counts = new Map<string, number>();
|
||||
for (const g of y) counts.set(g, (counts.get(g) ?? 0) + 1);
|
||||
let shared = 0;
|
||||
for (const g of x) {
|
||||
const n = counts.get(g) ?? 0;
|
||||
if (n > 0) {
|
||||
shared += 1;
|
||||
counts.set(g, n - 1);
|
||||
}
|
||||
}
|
||||
return (2 * shared) / (x.length + y.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand against the full name: every word of the shorter is the start of
|
||||
* a word of the longer, in order ("alk phos" against "alkaline phosphatase").
|
||||
*/
|
||||
function abbreviates(short: string, long: string): boolean {
|
||||
const s = short.split(" ").filter(Boolean);
|
||||
const l = long.split(" ").filter(Boolean);
|
||||
if (s.length === 0 || s.length > l.length) return false;
|
||||
let j = 0;
|
||||
for (const word of s) {
|
||||
while (j < l.length && !l[j].startsWith(word)) j++;
|
||||
if (j === l.length) return false;
|
||||
j++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** How alike two names are, 0..1. */
|
||||
export function nameSimilarity(a: string, b: string): number {
|
||||
const x = loose(a);
|
||||
const y = loose(b);
|
||||
if (!x || !y) return 0;
|
||||
if (x === y) return 1;
|
||||
const [shorter, longer] = x.length <= y.length ? [x, y] : [y, x];
|
||||
const prefix = abbreviates(shorter, longer) ? 0.8 : 0;
|
||||
return Math.max(prefix, diceSimilarity(x, y));
|
||||
}
|
||||
|
||||
/** Below this a marker is not offered as similar. */
|
||||
export const SIMILARITY_FLOOR = 0.5;
|
||||
|
||||
/**
|
||||
* Up to three markers a review row offers for a name nothing resolved:
|
||||
* first the markers of the same catalog analyte (their unit kept the catalog
|
||||
* step from taking them), then the markers whose name, aliases or catalog
|
||||
* names are most alike. Hidden markers are not offered.
|
||||
*/
|
||||
export function suggestInIndex(
|
||||
index: MarkerIndex,
|
||||
rawName: string,
|
||||
limit = BIOMARKER_SUGGESTION_LIMIT,
|
||||
): MarkerSuggestion[] {
|
||||
const name = rawName.trim();
|
||||
if (!name) return [];
|
||||
const out: MarkerSuggestion[] = [];
|
||||
const taken = new Set<string>();
|
||||
const visible = index.markers.filter((m) => !m.hidden);
|
||||
|
||||
const key = catalogKeyForName(name);
|
||||
if (key) {
|
||||
for (const marker of visible) {
|
||||
if (out.length >= limit) break;
|
||||
if (!markerCatalogKeys(index, marker).has(key)) continue;
|
||||
out.push(toSuggestion(marker, "catalog"));
|
||||
taken.add(marker.id);
|
||||
}
|
||||
}
|
||||
|
||||
const scored: Array<{ marker: IndexedMarker; score: number }> = [];
|
||||
for (const marker of visible) {
|
||||
if (taken.has(marker.id)) continue;
|
||||
const names = [marker.name];
|
||||
for (const alias of index.aliases) {
|
||||
if (alias.biomarkerId === marker.id) names.push(alias.name);
|
||||
}
|
||||
for (const k of markerCatalogKeys(index, marker)) {
|
||||
names.push(...catalogNamesForKey(k));
|
||||
}
|
||||
let score = 0;
|
||||
for (const candidate of names) {
|
||||
score = Math.max(score, nameSimilarity(name, candidate));
|
||||
}
|
||||
if (score >= SIMILARITY_FLOOR) scored.push({ marker, score });
|
||||
}
|
||||
scored.sort(
|
||||
(a, b) => b.score - a.score || a.marker.name.localeCompare(b.marker.name),
|
||||
);
|
||||
for (const { marker } of scored) {
|
||||
if (out.length >= limit) break;
|
||||
out.push(toSuggestion(marker, "similar"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function toSuggestion(
|
||||
marker: IndexedMarker,
|
||||
matchKind: BiomarkerSuggestionKind,
|
||||
): MarkerSuggestion {
|
||||
return {
|
||||
biomarkerId: marker.id,
|
||||
name: marker.name,
|
||||
unit: marker.unit,
|
||||
matchKind,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolution and suggestions for one name, as the review rows carry them:
|
||||
* the matched marker and how, or none and up to three to choose from.
|
||||
*/
|
||||
export function matchForReview(
|
||||
index: MarkerIndex,
|
||||
name: string,
|
||||
unit?: string | null,
|
||||
): {
|
||||
match: MarkerMatch | null;
|
||||
suggestions: MarkerSuggestion[];
|
||||
} {
|
||||
const match = resolveInIndex(index, name, unit);
|
||||
return {
|
||||
match,
|
||||
suggestions: match ? [] : suggestInIndex(index, name),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The marker a name asked for on a read path (MCP `get_labs`, the
|
||||
* `healthlog://lab/{analyte}` resource) resolves to: its name, an alias or a
|
||||
* catalog abbreviation, with no unit to weigh. Null when nothing resolves;
|
||||
* the caller then keeps its own text match.
|
||||
*/
|
||||
export async function resolveMarkerForRead(
|
||||
userId: string,
|
||||
name: string,
|
||||
): Promise<{ id: string; name: string } | null> {
|
||||
const index = await loadMarkerIndex(prisma, userId);
|
||||
const match = resolveInIndex(index, name);
|
||||
return match ? { id: match.marker.id, name: match.marker.name } : null;
|
||||
}
|
||||
@@ -14,6 +14,13 @@ import { Buffer } from "node:buffer";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
|
||||
import {
|
||||
addToIndex,
|
||||
loadMarkerIndex,
|
||||
resolveInIndex,
|
||||
type IndexedMarker,
|
||||
type MarkerIndex,
|
||||
} from "@/lib/labs/biomarker-resolve";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
|
||||
/** Encrypt a UTF-8 context note into the `Bytes` payload the schema stores. */
|
||||
@@ -72,18 +79,19 @@ export interface MintedBiomarker {
|
||||
* v1.18.1 — resolve (or mint) the user-scoped Biomarker for a free-text lab
|
||||
* write so NO `LabResult` row ever persists unlinked.
|
||||
*
|
||||
* The catalog identity is `(userId, lower(analyte))`: a reading for "LDL",
|
||||
* "ldl", and "LDL " all resolve to one marker. An existing marker (hand-
|
||||
* defined or previously minted) is reused as-is — its unit / range are
|
||||
* authoritative and the incoming free-text unit / bounds are NOT allowed to
|
||||
* silently rewrite it. When no marker exists yet, one is minted from the
|
||||
* reading's own free-text spelling / unit / bounds. The `@@unique([userId,
|
||||
* name])` index is the structural backstop; a concurrent double-write
|
||||
* converges via the catch-and-refetch.
|
||||
* Since v1.43 (D1223) the name resolves through `resolveInIndex`: the
|
||||
* marker's own name (case aside), then an alias of the account, then a
|
||||
* catalog name for the same analyte as one of the account's markers ("GPT"
|
||||
* for "ALT") when the reading's unit fits that marker. An existing marker is
|
||||
* reused as-is: its unit / range are authoritative and the incoming free-text
|
||||
* unit / bounds are NOT allowed to silently rewrite it. When nothing resolves,
|
||||
* a marker is minted from the reading's own spelling / unit / bounds. The
|
||||
* `@@unique([userId, name])` index is the structural backstop; a concurrent
|
||||
* double-write converges via the catch-and-refetch.
|
||||
*
|
||||
* Turning the boot-time backfill into a pure historical migration: from
|
||||
* v1.18.1 on, every write goes through here, so the only unlinked rows that
|
||||
* can exist are pre-upgrade ones the backfill heals.
|
||||
* `index` lets a caller writing many rows load the account's markers once;
|
||||
* a marker minted here is added to it so a later row with the same name finds
|
||||
* it.
|
||||
*/
|
||||
export async function resolveOrMintBiomarker(
|
||||
userId: string,
|
||||
@@ -94,28 +102,15 @@ export async function resolveOrMintBiomarker(
|
||||
referenceHigh: number | null;
|
||||
panel: string | null;
|
||||
},
|
||||
options: { index?: MarkerIndex } = {},
|
||||
): Promise<MintedBiomarker> {
|
||||
const name = input.analyte.trim();
|
||||
const select = {
|
||||
id: true,
|
||||
name: true,
|
||||
unit: true,
|
||||
lowerBound: true,
|
||||
upperBound: true,
|
||||
panel: true,
|
||||
analyteKey: true,
|
||||
} as const;
|
||||
|
||||
// Case-insensitive match on the catalog identity. Postgres is the store;
|
||||
// `mode: "insensitive"` keeps "LDL" === "ldl" without a functional index.
|
||||
const existing = await prisma.biomarker.findFirst({
|
||||
where: { userId, name: { equals: name, mode: "insensitive" } },
|
||||
select,
|
||||
});
|
||||
if (existing) return existing;
|
||||
const index = options.index ?? (await loadMarkerIndex(prisma, userId));
|
||||
const hit = resolveInIndex(index, name, input.unit || null);
|
||||
if (hit) return toMinted(hit.marker);
|
||||
|
||||
try {
|
||||
return await prisma.biomarker.create({
|
||||
const created = await prisma.biomarker.create({
|
||||
data: {
|
||||
userId,
|
||||
name,
|
||||
@@ -125,15 +120,44 @@ export async function resolveOrMintBiomarker(
|
||||
panel: input.panel,
|
||||
analyteKey: matchAnalyteKey({ name, unit: input.unit }),
|
||||
},
|
||||
select,
|
||||
select: INDEXED_SELECT,
|
||||
});
|
||||
addToIndex(index, created);
|
||||
return toMinted(created);
|
||||
} catch {
|
||||
// A concurrent write minted the same `(userId, name)` first — adopt it.
|
||||
const raced = await prisma.biomarker.findFirst({
|
||||
where: { userId, name: { equals: name, mode: "insensitive" } },
|
||||
select,
|
||||
select: INDEXED_SELECT,
|
||||
});
|
||||
if (raced) return raced;
|
||||
if (raced) {
|
||||
addToIndex(index, raced);
|
||||
return toMinted(raced);
|
||||
}
|
||||
throw new Error("Failed to resolve biomarker for lab write");
|
||||
}
|
||||
}
|
||||
|
||||
const INDEXED_SELECT = {
|
||||
id: true,
|
||||
name: true,
|
||||
unit: true,
|
||||
lowerBound: true,
|
||||
upperBound: true,
|
||||
panel: true,
|
||||
analyteKey: true,
|
||||
hidden: true,
|
||||
createdAt: true,
|
||||
} as const;
|
||||
|
||||
function toMinted(marker: IndexedMarker): MintedBiomarker {
|
||||
return {
|
||||
id: marker.id,
|
||||
name: marker.name,
|
||||
unit: marker.unit,
|
||||
lowerBound: marker.lowerBound,
|
||||
upperBound: marker.upperBound,
|
||||
panel: marker.panel,
|
||||
analyteKey: marker.analyteKey,
|
||||
};
|
||||
}
|
||||
@@ -29,6 +29,11 @@ import {
|
||||
parseReferenceRange,
|
||||
} from "@/lib/labs/parse-reference-range";
|
||||
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
|
||||
import {
|
||||
loadMarkerIndex,
|
||||
matchForReview,
|
||||
type MarkerIndex,
|
||||
} from "@/lib/labs/biomarker-resolve";
|
||||
import { sameLabUnit } from "@/lib/labs/unit-normalise";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
@@ -138,16 +143,18 @@ export async function annotateRow(
|
||||
row: ExtractedRow,
|
||||
reportDate: string | null,
|
||||
tz: string,
|
||||
/** The account's markers and aliases, loaded once per extraction. */
|
||||
markerIndex?: MarkerIndex,
|
||||
): Promise<OcrExtractedRowDto> {
|
||||
const analyte = row.analyte.trim();
|
||||
const takenAt = normaliseDate(row.takenAt) ?? reportDate;
|
||||
const printed = parseReferenceRange(row.referenceText, row.unit);
|
||||
|
||||
// Biomarker match — case-insensitive on the catalog identity, presence-only.
|
||||
const existingBiomarker = await prisma.biomarker.findFirst({
|
||||
where: { userId, name: { equals: analyte, mode: "insensitive" } },
|
||||
select: { id: true, name: true, unit: true },
|
||||
});
|
||||
// v1.43 (D1223) — the marker this name resolves to (name, alias, catalog),
|
||||
// exactly as the commit resolves it, or up to three to choose from.
|
||||
const index = markerIndex ?? (await loadMarkerIndex(prisma, userId));
|
||||
const { match, suggestions } = matchForReview(index, analyte, row.unit);
|
||||
const existingBiomarker = match?.marker ?? null;
|
||||
// The analyte the marker is, so the review can say whether a row in another
|
||||
// unit converts. Derived from the name and unit exactly as the commit derives
|
||||
// it (a stored key is only that derivation, written down), so the review and
|
||||
@@ -171,7 +178,12 @@ export async function annotateRow(
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
analyte: { equals: analyte, mode: "insensitive" },
|
||||
// The printed name, or any reading already filed under the marker it
|
||||
// resolves to: an earlier report may have spelled it another way.
|
||||
OR: [
|
||||
{ analyte: { equals: analyte, mode: "insensitive" } },
|
||||
...(existingBiomarker ? [{ biomarkerId: existingBiomarker.id }] : []),
|
||||
],
|
||||
takenAt: labReadingDaySearchRange(takenAt),
|
||||
},
|
||||
select: {
|
||||
@@ -235,6 +247,9 @@ export async function annotateRow(
|
||||
markerUnit: existingBiomarker?.unit ?? null,
|
||||
markerAnalyteKey,
|
||||
duplicateOf,
|
||||
biomarkerId: existingBiomarker?.id ?? null,
|
||||
matchKind: match?.matchKind ?? null,
|
||||
suggestions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -322,11 +337,12 @@ export async function runOcrExtraction(
|
||||
// hearing about it. A count only: the string is the user's document.
|
||||
let unreadableRanges = 0;
|
||||
const tz = await resolveUserTimezone(args.userId);
|
||||
const markerIndex = await loadMarkerIndex(prisma, args.userId);
|
||||
for (const row of envelope.rows.slice(0, OCR_MAX_ROWS)) {
|
||||
if (isUnreadableRange(parseReferenceRange(row.referenceText, row.unit))) {
|
||||
unreadableRanges += 1;
|
||||
}
|
||||
rows.push(await annotateRow(args.userId, row, reportDate, tz));
|
||||
rows.push(await annotateRow(args.userId, row, reportDate, tz, markerIndex));
|
||||
}
|
||||
|
||||
annotate({
|
||||
@@ -337,6 +353,8 @@ export async function runOcrExtraction(
|
||||
rows: rows.length,
|
||||
duplicates: rows.filter((r) => r.duplicateOf !== null).length,
|
||||
newBiomarkers: rows.filter((r) => r.biomarkerMatch === "new").length,
|
||||
aliasMatches: rows.filter((r) => r.matchKind === "alias").length,
|
||||
catalogMatches: rows.filter((r) => r.matchKind === "catalog").length,
|
||||
unreadableRanges,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -51,6 +51,7 @@ vi.mock("@/lib/db", () => ({
|
||||
})),
|
||||
},
|
||||
labResult: { findMany: vi.fn(async () => [{ analyte: "LDL" }]) },
|
||||
biomarker: { findMany: vi.fn(async () => []) },
|
||||
encounter: {
|
||||
findMany: vi.fn(async () => [
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medication: { findMany: vi.fn(), findFirst: vi.fn() },
|
||||
labResult: { findMany: vi.fn() },
|
||||
biomarker: { findMany: vi.fn(async () => []) },
|
||||
// v1.30 (G1) — the nutrients pipeline.
|
||||
nutrientIntakeDay: {
|
||||
findMany: vi.fn(async () => []),
|
||||
@@ -13,6 +14,9 @@ vi.mock("@/lib/db", () => ({
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
vi.mock("@/lib/labs/biomarker-resolve", () => ({
|
||||
resolveMarkerForRead: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock("@/lib/ai/coach/tools/executor", () => ({
|
||||
executeCoachTool: vi.fn(),
|
||||
}));
|
||||
@@ -284,15 +288,25 @@ describe("argument completion (user-scoped, doubles as discovery)", () => {
|
||||
});
|
||||
|
||||
it("completes analytes from ONLY the user's own lab set", async () => {
|
||||
// One name per marker: the markers with readings, then the names of
|
||||
// readings filed under no marker (v1.43).
|
||||
vi.mocked(prisma.biomarker.findMany).mockResolvedValue([
|
||||
{ name: "LDL" },
|
||||
] as never);
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([
|
||||
{ analyte: "LDL" },
|
||||
{ analyte: "HDL" },
|
||||
{ analyte: "ldl" },
|
||||
] as never);
|
||||
const complete = template("lab").complete!.analyte;
|
||||
const result = await complete(CTX, "ld");
|
||||
expect(prisma.biomarker.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { userId: "user-1", results: { some: { deletedAt: null } } },
|
||||
}),
|
||||
);
|
||||
expect(prisma.labResult.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { userId: "user-1", deletedAt: null },
|
||||
where: { userId: "user-1", deletedAt: null, biomarkerId: null },
|
||||
distinct: ["analyte"],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -27,6 +27,11 @@ const { labResult, measurement, user } = vi.hoisted(() => ({
|
||||
// narrated sentence, which reads the stored preference.
|
||||
user: { findUnique: vi.fn(async () => ({ locale: "de" })) },
|
||||
}));
|
||||
// v1.43 — a lab name resolves to a marker through the account's names and
|
||||
// aliases; no marker resolves here, so the reads keep their text match.
|
||||
vi.mock("@/lib/labs/biomarker-resolve", () => ({
|
||||
resolveMarkerForRead: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock("@/lib/db", () => ({ prisma: { labResult, measurement, user } }));
|
||||
|
||||
import {
|
||||
|
||||
@@ -23,6 +23,11 @@ vi.mock("@/lib/mcp/record-search", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/mcp/record-search")>()),
|
||||
loadRecordCandidates: vi.fn(async () => []),
|
||||
}));
|
||||
// v1.43 — a lab name resolves to a marker through the account's names and
|
||||
// aliases; no marker resolves here, so the reads keep their text match.
|
||||
vi.mock("@/lib/labs/biomarker-resolve", () => ({
|
||||
resolveMarkerForRead: vi.fn(async () => null),
|
||||
}));
|
||||
// v1.22.0 — `search` reads the record directly via Prisma; stub it so the
|
||||
// registry-wide loops never reach a DB.
|
||||
vi.mock("@/lib/db", () => ({
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
* external-assistant boundary.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { resolveMarkerForRead } from "@/lib/labs/biomarker-resolve";
|
||||
import { fenceUserText } from "@/lib/ai/coach/data-fence";
|
||||
import { resolveMedicationCategories } from "@/lib/medication-category";
|
||||
import { dayKeyOfDate } from "@/lib/medications/course-window";
|
||||
@@ -397,13 +398,35 @@ async function completeMetric(
|
||||
async function userAnalytes(ctx: McpAuthContext): Promise<string[]> {
|
||||
// A switched-off labs module lists and completes nothing (v1.39.3).
|
||||
if (!(await isModuleEnabled(ctx.userId, "labs"))) return [];
|
||||
const rows = await prisma.labResult.findMany({
|
||||
where: { userId: ctx.userId, deletedAt: null },
|
||||
select: { analyte: true },
|
||||
distinct: ["analyte"],
|
||||
take: 200,
|
||||
});
|
||||
return rows.map((r) => r.analyte);
|
||||
// One name per marker (v1.43): readings filed under a biomarker list as the
|
||||
// marker's name, whatever each report printed, so two spellings merged into
|
||||
// one marker are one resource. A legacy unlinked reading keeps its own name.
|
||||
const [markers, unlinked] = await Promise.all([
|
||||
prisma.biomarker.findMany({
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
results: { some: { deletedAt: null } },
|
||||
},
|
||||
select: { name: true },
|
||||
orderBy: { name: "asc" },
|
||||
take: 200,
|
||||
}),
|
||||
prisma.labResult.findMany({
|
||||
where: { userId: ctx.userId, deletedAt: null, biomarkerId: null },
|
||||
select: { analyte: true },
|
||||
distinct: ["analyte"],
|
||||
take: 200,
|
||||
}),
|
||||
]);
|
||||
const names = new Map<string, string>();
|
||||
for (const name of [
|
||||
...markers.map((m) => m.name),
|
||||
...unlinked.map((r) => r.analyte),
|
||||
]) {
|
||||
const key = name.trim().toLowerCase();
|
||||
if (!names.has(key)) names.set(key, name);
|
||||
}
|
||||
return [...names.values()].slice(0, 200);
|
||||
}
|
||||
|
||||
async function completeAnalyte(
|
||||
@@ -514,7 +537,12 @@ export const MCP_RESOURCE_TEMPLATES: McpResourceTemplateDefinition[] = [
|
||||
if (!(await isModuleEnabled(ctx.userId, "labs"))) {
|
||||
return MODULE_DISABLED;
|
||||
}
|
||||
const analyte = decodeURIComponent(firstVar(variables.analyte));
|
||||
const asked = decodeURIComponent(firstVar(variables.analyte));
|
||||
// An alias or a catalog abbreviation reads as the marker's own name.
|
||||
const marker = asked.trim()
|
||||
? await resolveMarkerForRead(ctx.userId, asked)
|
||||
: null;
|
||||
const analyte = marker?.name ?? asked;
|
||||
const result = await executeCoachTool({
|
||||
userId: ctx.userId,
|
||||
name: "get_labs",
|
||||
|
||||
+27
-11
@@ -31,6 +31,7 @@
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { resolveMarkerForRead } from "@/lib/labs/biomarker-resolve";
|
||||
import { windowWeighting } from "@/lib/measurements/day-statistic";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { isModuleEnabled } from "@/lib/modules/gate";
|
||||
@@ -1400,18 +1401,33 @@ export async function getLabHistory(
|
||||
: LAB_HISTORY_MAX_LIMIT;
|
||||
const limit = Math.min(LAB_HISTORY_MAX_LIMIT, rawLimit);
|
||||
|
||||
// Match the analyte either on the LabResult's own `analyte` column or on the
|
||||
// linked Biomarker's canonical name. `take: limit + 1` peeks one row past the
|
||||
// page to decide whether a `nextCursor` is warranted. Field-by-field `where`.
|
||||
// A name that resolves to one marker (its name, an alias of the account, a
|
||||
// catalog abbreviation) reads that marker's whole series, merged spellings
|
||||
// included (v1.43). Anything else matches the analyte either on the
|
||||
// LabResult's own `analyte` column, on the linked Biomarker's canonical name
|
||||
// or on one of its aliases. `take: limit + 1` peeks one row past the page to
|
||||
// decide whether a `nextCursor` is warranted. Field-by-field `where`.
|
||||
const marker = await resolveMarkerForRead(userId, needle);
|
||||
const rows = await prisma.labResult.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
OR: [
|
||||
{ analyte: { contains: needle, mode: "insensitive" } },
|
||||
{ biomarker: { name: { contains: needle, mode: "insensitive" } } },
|
||||
],
|
||||
},
|
||||
where: marker
|
||||
? { userId, deletedAt: null, biomarkerId: marker.id }
|
||||
: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
OR: [
|
||||
{ analyte: { contains: needle, mode: "insensitive" } },
|
||||
{
|
||||
biomarker: { name: { contains: needle, mode: "insensitive" } },
|
||||
},
|
||||
{
|
||||
biomarker: {
|
||||
aliases: {
|
||||
some: { name: { contains: needle, mode: "insensitive" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { takenAt: "desc" },
|
||||
skip: offset,
|
||||
take: limit + 1,
|
||||
|
||||
+13
-4
@@ -20,6 +20,7 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { resolveMarkerForRead } from "@/lib/labs/biomarker-resolve";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getDayArgsSchema } from "@/lib/ai/coach/tools/definitions";
|
||||
import { readDayForTool } from "@/lib/ai/coach/tools/day-read";
|
||||
@@ -1510,10 +1511,18 @@ function readLabs(
|
||||
limit: LAB_HISTORY_MAX_LIMIT,
|
||||
});
|
||||
}
|
||||
// Default: latest reading per biomarker via the Coach labs read.
|
||||
return runCoachTool(ctx, "get_labs", {
|
||||
...(typeof args.analyte === "string" ? { analyte: args.analyte } : {}),
|
||||
});
|
||||
// Default: latest reading per biomarker via the Coach labs read. A name that
|
||||
// resolves to one of the user's markers (an alias or a catalog abbreviation
|
||||
// such as "GPT" for "ALT") is read as that marker's own name (v1.43).
|
||||
return (async () => {
|
||||
const asked = typeof args.analyte === "string" ? args.analyte : null;
|
||||
const marker = asked?.trim()
|
||||
? await resolveMarkerForRead(ctx.userId, asked)
|
||||
: null;
|
||||
return runCoachTool(ctx, "get_labs", {
|
||||
...(asked !== null ? { analyte: marker?.name ?? asked } : {}),
|
||||
});
|
||||
})();
|
||||
}
|
||||
|
||||
export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
|
||||
@@ -216,9 +216,11 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
|
||||
"insights.generate.scopeChanged",
|
||||
],
|
||||
labs: [
|
||||
"labs.biomarker.alias.taken",
|
||||
"labs.biomarker.create.invalid",
|
||||
"labs.biomarker.duplicate",
|
||||
"labs.biomarker.merge.invalid",
|
||||
"labs.biomarker.merge.unitMismatch",
|
||||
"labs.biomarker.notFound",
|
||||
"labs.biomarker.update.invalid",
|
||||
"labs.biomarker.update.referenceRangeInvalid",
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
errorEnvelope,
|
||||
idempotencyKeyParameter,
|
||||
idempotentWrite,
|
||||
notImplementedResponse,
|
||||
recordRefusal,
|
||||
recordWriteRateLimitResponse,
|
||||
stdResponses,
|
||||
@@ -89,6 +88,14 @@ const conflict = {
|
||||
},
|
||||
};
|
||||
|
||||
const updateConflict = {
|
||||
"409": {
|
||||
description:
|
||||
"`labs.biomarker.duplicate`: a rename collides with another of the caller's markers. `labs.biomarker.alias.taken` (v1.43): one of `aliases` is already the name or an alias of another marker; `meta.alias` names the spelling and `meta.biomarkerId` the marker that answers to it.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
};
|
||||
|
||||
const notFound = {
|
||||
"404": {
|
||||
description:
|
||||
@@ -184,7 +191,7 @@ export const biomarkerPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Labs"],
|
||||
summary: "Fetch a single biomarker",
|
||||
description:
|
||||
"Returns the biomarker including its decrypted `context`. Cross-user rows surface as 404.",
|
||||
"Returns the biomarker including its decrypted `context` and, since v1.43, its `aliases`. Cross-user rows surface as 404. A marker merged into another answers 404 with `meta.mergedInto`.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -204,7 +211,7 @@ export const biomarkerPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Labs"],
|
||||
summary: "Edit a biomarker",
|
||||
description:
|
||||
"Partial edit; omitted fields are untouched, an explicit null clears `context` / `panel` / a bound. Audits as `biomarker.update`. Since v1.40.0 a `unit` different from the stored one is refused with 422 `biomarkers.unit.locked` while any reading is linked to the marker (`meta.readingCount` carries how many): readers label every linked reading with the marker's unit, so a change would relabel stored numbers without converting them. Sending the current unit, or changing it on a marker with no readings, is accepted.",
|
||||
"Partial edit; omitted fields are untouched, an explicit null clears `context` / `panel` / a bound. Since v1.43 `aliases` (0..50, each 1..120 characters) replaces the marker's set of other spellings: listed spellings stay or are added, unlisted ones are removed; omitting the field leaves them as they are. Audits as `biomarker.update`. Since v1.40.0 a `unit` different from the stored one is refused with 422 `biomarkers.unit.locked` while any reading is linked to the marker (`meta.readingCount` carries how many): readers label every linked reading with the marker's unit, so a change would relabel stored numbers without converting them. Sending the current unit, or changing it on a marker with no readings, is accepted.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
requestBody: {
|
||||
required: true,
|
||||
@@ -220,7 +227,7 @@ export const biomarkerPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...conflict,
|
||||
...updateConflict,
|
||||
...notFound,
|
||||
...stdResponses,
|
||||
},
|
||||
@@ -263,8 +270,10 @@ export const biomarkerPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
responses: {
|
||||
...idempotentWrite(),
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The merge result (or the dry-run preview).",
|
||||
description:
|
||||
'The merge result, or the dry-run preview. A preview reports a source that cannot be converted with `conversion: "refused"` and its `refusal`; the same request without `dryRun` answers 422 `labs.biomarker.merge.unitMismatch`.',
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
@@ -276,8 +285,12 @@ export const biomarkerPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
...notFound,
|
||||
...stdResponses,
|
||||
"422": {
|
||||
description:
|
||||
"`labs.biomarker.merge.invalid`: a malformed body, or the target among the sources (Zod issues in `details.issues[]`). `labs.biomarker.merge.unitMismatch`: a source holds readings in a unit the registry cannot convert to the target's; `meta.sources` lists each `{ id, unit, targetUnit, reason }` with `reason` one of `unknown_analyte`, `unknown_unit`, `not_finite`. Nothing was moved.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...recordWriteRateLimitResponse,
|
||||
...notImplementedResponse,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -177,10 +177,12 @@ const commitResponse = z
|
||||
skipped: z.array(
|
||||
z.object({
|
||||
analyte: z.string(),
|
||||
reason: z.enum(["duplicate", "unit_mismatch"]).meta({
|
||||
description:
|
||||
"`duplicate`: the row matched a live reading at commit time. `unit_mismatch`: the row states a unit other than the one its marker is tracked in and the pair cannot be converted, so it was not written. A pair that can be converted is written in the marker's unit and reported with `converted: true`.",
|
||||
}),
|
||||
reason: z
|
||||
.enum(["duplicate", "unit_mismatch", "unknown_biomarker"])
|
||||
.meta({
|
||||
description:
|
||||
"`duplicate`: the row matched a live reading at commit time. `unit_mismatch`: the row states a unit other than the one its marker is tracked in and the pair cannot be converted, so it was not written. A pair that can be converted is written in the marker's unit and reported with `converted: true`. `unknown_biomarker` (v1.43): the row named a `biomarkerId` that is not one of the record's markers.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
outcome: z.enum(["empty", "failed", "partial", "success"]).meta({
|
||||
|
||||
@@ -179,6 +179,8 @@ export function recordActivityVerbLine(
|
||||
return t("recordSharing.activityVerb.biomarkerUpdate", { name });
|
||||
case "biomarker.delete":
|
||||
return t("recordSharing.activityVerb.biomarkerDelete", { name });
|
||||
case "labs.biomarker.merge":
|
||||
return t("recordSharing.activityVerb.biomarkerMerge", { name });
|
||||
|
||||
case "allergy.update":
|
||||
return t("recordSharing.activityVerb.allergyUpdate", { name });
|
||||
|
||||
@@ -1134,11 +1134,38 @@ const biomarkerBackupSchema = z
|
||||
// v1.42 (#1095) — the catalogue analyte the marker resolves to.
|
||||
analyteKey: z.string().nullable().optional(),
|
||||
context: z.string().nullable().optional(),
|
||||
// v1.43 (D1223) — the other spellings the marker answers to. Absent on
|
||||
// files written before them.
|
||||
aliases: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: z.string().min(1).optional(),
|
||||
name: z.string().min(1).max(120),
|
||||
source: z.enum(["MERGE", "IMPORT_CHOICE", "MANUAL"]),
|
||||
createdAt: isoDateTime.optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
)
|
||||
.optional(),
|
||||
createdAt: isoDateTime.optional(),
|
||||
updatedAt: isoDateTime.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// v1.43 (D1223) — the ledger of markers merged into others.
|
||||
const biomarkerMergeBackupSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).optional(),
|
||||
targetBiomarkerId: z.string().min(1).optional(),
|
||||
targetName: z.string().min(1),
|
||||
sourceBiomarkerId: z.string().min(1),
|
||||
sourceName: z.string().min(1).max(120),
|
||||
readingCount: z.number().int().min(0),
|
||||
mergedAt: isoDateTime,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const illnessSymptomBackupSchema = z
|
||||
.object({
|
||||
key: z.string().min(1),
|
||||
@@ -2101,6 +2128,8 @@ export const backupPayloadSchema = z
|
||||
// fields; portable exports retain the metadata-only subset.
|
||||
labResults: z.array(labResultBackupSchema).default([]),
|
||||
biomarkers: z.array(biomarkerBackupSchema).default([]),
|
||||
// Defaulted: a file written before v1.43 carries no key.
|
||||
biomarkerMerges: z.array(biomarkerMergeBackupSchema).default([]),
|
||||
illnessEpisodes: z.array(illnessEpisodeBackupSchema).default([]),
|
||||
// Defaulted: a file written before v1.40 carries no key.
|
||||
symptomDefinitions: z.array(symptomDefinitionBackupSchema).default([]),
|
||||
|
||||
@@ -75,6 +75,10 @@ export const updateBiomarkerSchema = z
|
||||
// v1.22 — hide / unhide a marker. An omitted key leaves visibility
|
||||
// untouched; `true` drops the marker from the active list + pickers.
|
||||
hidden: z.boolean().optional(),
|
||||
// v1.43 (D1223) — the other spellings this marker answers to, as a whole
|
||||
// set: what is listed stays or is added, what is not is removed. Omitted
|
||||
// leaves them untouched, so an older client's PUT keeps them.
|
||||
aliases: z.array(z.string().trim().min(1).max(120)).max(50).optional(),
|
||||
})
|
||||
.refine(
|
||||
(d) =>
|
||||
|
||||
@@ -340,6 +340,18 @@ export interface ExtractedFactDto {
|
||||
provenance: FactProvenance;
|
||||
committedRecordId: string | null;
|
||||
committedRecordType: string | null;
|
||||
/**
|
||||
* v1.43 (D1223), pending OBSERVATION facts only — the marker the label
|
||||
* resolves to and how, or up to three markers to choose from.
|
||||
*/
|
||||
biomarkerId?: string | null;
|
||||
matchKind?: "name" | "alias" | "catalog" | null;
|
||||
suggestions?: Array<{
|
||||
biomarkerId: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
matchKind: "catalog" | "similar";
|
||||
}>;
|
||||
}
|
||||
|
||||
/** One condition link on a document DTO (chip → `/illness/[id]`). */
|
||||
@@ -602,6 +614,15 @@ export const inboundConfirmSchema = z.object({
|
||||
z.object({
|
||||
factId: z.string().trim().min(1).max(40),
|
||||
action: z.enum(["approve", "reject"]),
|
||||
/**
|
||||
* v1.43 (D1223), OBSERVATION only — the marker the person chose for
|
||||
* the fact; the reading is filed under it whatever the label says.
|
||||
* An id that is not one of the record's markers fails the fact with
|
||||
* `observation.unknownBiomarker`.
|
||||
*/
|
||||
biomarkerId: z.string().trim().min(1).max(64).optional(),
|
||||
/** With `biomarkerId`: remember the label as an alias. Default true. */
|
||||
rememberAlias: z.boolean().optional(),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
|
||||
@@ -138,6 +138,19 @@ export interface OcrExtractedRowDto {
|
||||
*/
|
||||
markerAnalyteKey: string | null;
|
||||
duplicateOf: string | null;
|
||||
/**
|
||||
* v1.43 (D1223) — the marker the row was matched to automatically: by its
|
||||
* name, an alias of the account, or a catalog abbreviation. Null when none.
|
||||
*/
|
||||
biomarkerId: string | null;
|
||||
matchKind: "name" | "alias" | "catalog" | null;
|
||||
/** Up to three markers to choose from when nothing matched; else empty. */
|
||||
suggestions: Array<{
|
||||
biomarkerId: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
matchKind: "catalog" | "similar";
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface OcrExtractResponseDto {
|
||||
@@ -190,6 +203,18 @@ export const ocrCommitRowSchema = z
|
||||
.optional()
|
||||
.or(z.literal("").transform(() => undefined)),
|
||||
takenAt: takenAtField,
|
||||
/**
|
||||
* v1.43 (D1223) — the marker the person chose for this row on the review
|
||||
* screen. The row is written under it whatever `analyte` says; an id that
|
||||
* is not one of the record's markers skips the row (`unknown_biomarker`).
|
||||
*/
|
||||
biomarkerId: z.string().trim().min(1).max(64).optional(),
|
||||
/**
|
||||
* With `biomarkerId`: remember `analyte` as another spelling of that
|
||||
* marker, so the next report with the same name matches on its own.
|
||||
* Default true. Ignored when the name is the marker's own.
|
||||
*/
|
||||
rememberAlias: z.boolean().optional(),
|
||||
})
|
||||
// Numeric XOR qualitative: exactly one of value / valueText.
|
||||
.refine((d) => (d.value !== undefined) !== (d.valueText !== undefined), {
|
||||
@@ -246,11 +271,12 @@ export type OcrCommitInput = z.infer<typeof ocrCommitSchema>;
|
||||
/**
|
||||
* A row the commit route did not write. `duplicate`: it matched a live reading
|
||||
* at commit time. `unit_mismatch`: it states a unit other than the one its
|
||||
* marker is tracked in.
|
||||
* marker is tracked in. `unknown_biomarker`: the chosen `biomarkerId` is not
|
||||
* one of the record's markers.
|
||||
*/
|
||||
export interface OcrSkippedRowDto {
|
||||
analyte: string;
|
||||
reason: "duplicate" | "unit_mismatch";
|
||||
reason: "duplicate" | "unit_mismatch" | "unknown_biomarker";
|
||||
}
|
||||
|
||||
export interface OcrCommitResponseDto {
|
||||
|
||||
Reference in new issue
Block a user