diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a0a6ab71..33e719fca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and document chat streams are left uncompressed, so their text still arrives as it is written. +### Fixed + +- A lab marker created from a text result, such as "negative" on a scanned report or a CSV row without a unit, can be edited again. It opens with "No unit" ticked, a rename saves without touching the unit, and the unit can be set while the marker holds only text results. The unit stays locked once numbers are stored under it, and writing the same unit another way (`mg/dl` for `mg/dL`) no longer counts as a change. (#1393) + ### Security - The container image moves to Node 22.23.5, a security release with fixes diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index aede67992..a1bda5378 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -17803,9 +17803,11 @@ paths: 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." + `biomarkers.unit.locked` while a numeric reading is linked to the marker, a deleted one included + (`meta.readingCount` carries how many): readers label every linked number with the marker's unit, so a change + would relabel stored numbers without converting them. Sending the current unit or another spelling of it + (`mg/dl` for `mg/dL`), or changing it on a marker whose readings are all text or that has none, is accepted. A + marker minted from a text result has an empty unit, so any unit may be set on it." parameters: - in: path name: id @@ -78491,11 +78493,13 @@ components: type: string unit: type: string - description: 'The unit the value is in, free-form as the report prints it (e.g. `mg/dL`). `"1"`, the UCUM unity, means + description: "The unit the value is in, free-form as the report prints it (e.g. `mg/dL`). `\"1\"`, the UCUM unity, means the value has no unit: a ratio or an index such as INR or cholesterol/HDL. It is an explicit choice and a - unit of its own: it matches only `"1"`, so a reading without a unit is refused under a marker kept in a real - unit and the other way round. Clients show nothing beside such a value. An empty unit on a numeric value is - never read as `"1"` and stays refused.' + unit of its own: it matches only `\"1\"`, so a reading without a unit is refused under a marker kept in a + real unit and the other way round. Clients show nothing beside such a value. An empty unit on a numeric + value is never read as `\"1\"` and stays refused. On a marker, an empty unit means none has been chosen yet: + the marker was minted from a text result, and its first numeric reading gives it that reading's unit. It is + not the unity: it holds no number, so a `PUT` may set any unit on it." lowerBound: type: - number @@ -78595,11 +78599,13 @@ components: type: string unit: type: string - description: 'The unit the value is in, free-form as the report prints it (e.g. `mg/dL`). `"1"`, the UCUM unity, means + description: "The unit the value is in, free-form as the report prints it (e.g. `mg/dL`). `\"1\"`, the UCUM unity, means the value has no unit: a ratio or an index such as INR or cholesterol/HDL. It is an explicit choice and a - unit of its own: it matches only `"1"`, so a reading without a unit is refused under a marker kept in a real - unit and the other way round. Clients show nothing beside such a value. An empty unit on a numeric value is - never read as `"1"` and stays refused.' + unit of its own: it matches only `\"1\"`, so a reading without a unit is refused under a marker kept in a + real unit and the other way round. Clients show nothing beside such a value. An empty unit on a numeric + value is never read as `\"1\"` and stays refused. On a marker, an empty unit means none has been chosen yet: + the marker was minted from a text result, and its first numeric reading gives it that reading's unit. It is + not the unity: it holds no number, so a `PUT` may set any unit on it." lowerBound: type: - number diff --git a/messages/en.json b/messages/en.json index de6c5d6a6..bc4d11216 100644 --- a/messages/en.json +++ b/messages/en.json @@ -10466,7 +10466,7 @@ "namePlaceholder": "e.g. LDL cholesterol", "unit": "Unit", "unitPlaceholder": "e.g. mg/dL", - "unitLockedHint": "Once this marker has readings, its unit stays as it is. The stored values would otherwise be shown in a new unit without being converted.", + "unitLockedHint": "Once this marker holds numeric readings, its unit stays as it is. The stored values would otherwise be shown in a new unit without being converted.", "panel": "Panel", "panelPlaceholder": "e.g. Lipids", "panelHint": "Pick a suggestion or type your own. Catalog panels are recognised in every language.", diff --git a/src/app/api/biomarkers/[id]/route.ts b/src/app/api/biomarkers/[id]/route.ts index 864071182..09fc6f6e4 100644 --- a/src/app/api/biomarkers/[id]/route.ts +++ b/src/app/api/biomarkers/[id]/route.ts @@ -24,6 +24,7 @@ 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 { sameLabUnit } from "@/lib/labs/unit-normalise"; import { annotate } from "@/lib/logging/context"; import { computeLabTrend } from "@/lib/labs/lab-trend"; @@ -160,14 +161,20 @@ export const PUT = apiHandler( } } - // A marker's unit labels every reading linked to it: readers resolve the + // A marker's unit labels every number linked to it: readers resolve the // unit from the marker, and the stored numbers are in the old unit. A - // change while readings exist would relabel history without converting a - // single value, so it is refused. Tombstoned readings count too, since an - // undo brings them back under the new label. - if (d.unit !== undefined && d.unit !== existing.unit) { + // change while numeric readings exist would relabel history without + // converting a single value, so it is refused. Tombstoned readings count + // too, since an undo brings them back under the new label. + // + // Only a real change is one: another spelling of the same unit relabels + // nothing. And only numbers lock it: a text result ("negative") carries + // no value the unit could misstate. That is what frees a marker minted + // from a text result, whose empty unit nothing has chosen yet (#1393); + // its first number would have set the unit the same way. + if (d.unit !== undefined && !sameLabUnit(d.unit, existing.unit)) { const readingCount = await prisma.labResult.count({ - where: { userId: user.id, biomarkerId: id }, + where: { userId: user.id, biomarkerId: id, value: { not: null } }, }); if (readingCount > 0) { annotate({ diff --git a/src/components/labs/__tests__/biomarker-form-body.test.ts b/src/components/labs/__tests__/biomarker-form-body.test.ts index 8b71aefad..55b1823bc 100644 --- a/src/components/labs/__tests__/biomarker-form-body.test.ts +++ b/src/components/labs/__tests__/biomarker-form-body.test.ts @@ -38,6 +38,7 @@ describe("buildBiomarkerBody", () => { it("sends null for every field an edit emptied", () => { expect( buildBiomarkerBody(empty, { + unit: "mmol/L", lowerBound: 10, upperBound: 0, panel: "Lipids", @@ -56,6 +57,7 @@ describe("buildBiomarkerBody", () => { it("leaves a field out that was empty when the edit began", () => { expect( buildBiomarkerBody(empty, { + unit: "mmol/L", lowerBound: null, upperBound: null, panel: null, @@ -64,3 +66,51 @@ describe("buildBiomarkerBody", () => { ).toEqual({ name: "LDL", unit: "mg/dL" }); }); }); + +describe("buildBiomarkerBody: the unit on an edit", () => { + const initial = { + lowerBound: null, + upperBound: null, + panel: null, + context: null, + }; + + it("leaves an unchanged unit out, so a rename never touches it", () => { + expect( + buildBiomarkerBody( + { ...empty, name: "LDL-C" }, + { ...initial, unit: "mg/dL" }, + ), + ).toEqual({ name: "LDL-C" }); + }); + + it("leaves the unit out when only the whitespace around it moved", () => { + expect( + buildBiomarkerBody( + { ...empty, unit: " mg/dL " }, + { ...initial, unit: "mg/dL" }, + ), + ).toEqual({ name: "LDL" }); + }); + + it("reads a marker minted from a text result and the ticked box as the same no unit", () => { + expect( + buildBiomarkerBody( + { ...empty, name: "Urine protein", unit: "1" }, + { ...initial, unit: "" }, + ), + ).toEqual({ name: "Urine protein" }); + }); + + it("sends a unit the edit changed", () => { + expect( + buildBiomarkerBody({ ...empty, unit: "mg/dL" }, { ...initial, unit: "" }), + ).toEqual({ name: "LDL", unit: "mg/dL" }); + expect( + buildBiomarkerBody( + { ...empty, unit: "1" }, + { ...initial, unit: "mg/dL" }, + ), + ).toEqual({ name: "LDL", unit: "1" }); + }); +}); diff --git a/src/components/labs/__tests__/biomarker-form.test.tsx b/src/components/labs/__tests__/biomarker-form.test.tsx index 1eb91a737..eb4e70497 100644 --- a/src/components/labs/__tests__/biomarker-form.test.tsx +++ b/src/components/labs/__tests__/biomarker-form.test.tsx @@ -91,6 +91,32 @@ describe(" unit lock", () => { }); }); +describe(" a marker without a unit", () => { + function noneBox(html: string): string { + const box = html.match(/]*role="checkbox"[^>]*>/)?.[0]; + if (!box) throw new Error("no checkbox rendered"); + return box; + } + + it("opens a marker minted from a text result with No unit ticked", () => { + // A text result ("negative") mints its marker with an empty unit. The + // editor read that as a unit still to be typed and refused every save. + const html = render(); + expect(noneBox(html)).toContain('aria-checked="true"'); + expect(html).not.toMatch(/]*id="biomarker-unit"[^>]*required/); + }); + + it("opens a marker kept in the unity with No unit ticked", () => { + const html = render(); + expect(noneBox(html)).toContain('aria-checked="true"'); + }); + + it("opens a marker with a real unit with the box clear", () => { + const html = render(); + expect(noneBox(html)).toContain('aria-checked="false"'); + }); +}); + describe(" panel suggestions", () => { it("suggests every catalog panel and the person's own panels", () => { const html = render(, ["Annual check"]); diff --git a/src/components/labs/biomarker-form-body.ts b/src/components/labs/biomarker-form-body.ts index fa3203921..cc177b6df 100644 --- a/src/components/labs/biomarker-form-body.ts +++ b/src/components/labs/biomarker-form-body.ts @@ -8,8 +8,17 @@ * none is cleared, which an omitted key never did. Only a field that held a * value when the form opened can be emptied, so a context the list could not * decrypt (shown empty) is never wiped by saving another field. + * + * An edit sends the unit only when it changed. A marker with readings refuses + * a unit change, so a unit sent back unchanged could only trip that check, and + * did on a marker minted from a text result: its empty unit opens as "no unit", + * which the box states as the unity, and a rename then read as a unit change. + * The empty unit and the unity are the same "no unit" here; saving leaves the + * empty one as it is, so the marker still takes the unit of its first number. */ +import { DIMENSIONLESS_UNIT, markerHasNoUnit } from "@/lib/labs/dimensionless"; + export interface BiomarkerFormFields { name: string; unit: string; @@ -20,6 +29,7 @@ export interface BiomarkerFormFields { } export interface BiomarkerFormInitial { + unit: string; lowerBound: number | null; upperBound: number | null; panel: string | null; @@ -28,7 +38,7 @@ export interface BiomarkerFormInitial { export type BiomarkerBody = { name: string; - unit: string; + unit?: string; lowerBound?: number | null; upperBound?: number | null; panel?: string | null; @@ -41,10 +51,9 @@ export function buildBiomarkerBody( ): BiomarkerBody { const panel = fields.panel.trim(); const context = fields.context.trim(); - const body: BiomarkerBody = { - name: fields.name.trim(), - unit: fields.unit.trim(), - }; + const unit = fields.unit.trim(); + const body: BiomarkerBody = { name: fields.name.trim() }; + if (!initial || !sameFormUnit(unit, initial.unit)) body.unit = unit; if (fields.lower !== null) body.lowerBound = fields.lower; else if (initial?.lowerBound != null) body.lowerBound = null; if (fields.upper !== null) body.upperBound = fields.upper; @@ -55,3 +64,18 @@ export function buildBiomarkerBody( else if (initial?.context) body.context = null; return body; } + +/** + * The unit an edit opens with. A marker minted from a text result has an + * empty unit, none chosen yet; it opens as "no unit", like the unity, rather + * than as a unit still to be typed. + */ +export function formUnit(stored: string): string { + return markerHasNoUnit(stored) ? DIMENSIONLESS_UNIT : stored; +} + +/** Whether the unit the form holds is the one the marker opened with. */ +function sameFormUnit(unit: string, initial: string): boolean { + if (unit === initial.trim()) return true; + return markerHasNoUnit(unit) && markerHasNoUnit(initial); +} diff --git a/src/components/labs/biomarker-form.tsx b/src/components/labs/biomarker-form.tsx index 7a7d07c8e..2ef112342 100644 --- a/src/components/labs/biomarker-form.tsx +++ b/src/components/labs/biomarker-form.tsx @@ -26,7 +26,7 @@ import { } from "@/lib/labs/biomarker-catalog"; import { useTranslations } from "@/lib/i18n/context"; -import { buildBiomarkerBody } from "./biomarker-form-body"; +import { buildBiomarkerBody, formUnit } from "./biomarker-form-body"; import { BiomarkerPanelField } from "./biomarker-panel-field"; import { LabUnitInput } from "./lab-unit-input"; import type { BiomarkerDto } from "./types"; @@ -76,7 +76,7 @@ export function BiomarkerForm({ const unitHintId = `${formId}-unit-hint`; const [name, setName] = useState(existing?.name ?? ""); - const [unit, setUnit] = useState(existing?.unit ?? ""); + const [unit, setUnit] = useState(existing ? formUnit(existing.unit) : ""); const [lower, setLower] = useState( existing?.lowerBound != null ? String(existing.lowerBound) : "", ); diff --git a/src/lib/labs/dimensionless.ts b/src/lib/labs/dimensionless.ts index 91a7d413a..de4381864 100644 --- a/src/lib/labs/dimensionless.ts +++ b/src/lib/labs/dimensionless.ts @@ -12,6 +12,15 @@ * other way round. Only the display differs: nobody wants "3.6 1", so the * helpers below render the unity as nothing beside a value. * + * A marker's unit has one more state: empty. A marker minted from a text + * result ("negative", "SEE NOTE") has no unit because nothing has chosen one + * yet, and the first numeric reading gives it its unit, the unity included + * (`adoptFirstNumericUnit` in `./reading-conversion.ts`). Empty is therefore + * not a second spelling of `"1"`: the unity refuses a reading in mg/dL, an + * empty unit takes it. Both hold no number in a unit, so the editor shows + * both as "no unit" (`markerHasNoUnit`), and the unit lock, which guards the + * numbers stored under a unit, never fires on either while they hold none. + * * Pure and dependency-free. */ @@ -23,6 +32,17 @@ export function isDimensionlessUnit(unit: string | null | undefined): boolean { return typeof unit === "string" && unit.trim() === DIMENSIONLESS_UNIT; } +/** + * Whether a marker's unit reads as "no unit" in the editor: the unity, or the + * empty unit of a marker no number has given a unit yet. + */ +export function markerHasNoUnit(unit: string | null | undefined): boolean { + return ( + typeof unit === "string" && + (unit.trim() === "" || unit.trim() === DIMENSIONLESS_UNIT) + ); +} + /** The unit as it reads beside a value: trimmed, and empty for the unity. */ export function labUnitText(unit: string | null | undefined): string { if (typeof unit !== "string") return ""; @@ -54,3 +74,6 @@ export function labUnitLabel( /** How the API contract describes a lab unit field. */ export const LAB_UNIT_DESCRIPTION = 'The unit the value is in, free-form as the report prints it (e.g. `mg/dL`). `"1"`, the UCUM unity, means the value has no unit: a ratio or an index such as INR or cholesterol/HDL. It is an explicit choice and a unit of its own: it matches only `"1"`, so a reading without a unit is refused under a marker kept in a real unit and the other way round. Clients show nothing beside such a value. An empty unit on a numeric value is never read as `"1"` and stays refused.'; + +/** How the API contract describes a marker's stored unit. */ +export const BIOMARKER_UNIT_DESCRIPTION = `${LAB_UNIT_DESCRIPTION} On a marker, an empty unit means none has been chosen yet: the marker was minted from a text result, and its first numeric reading gives it that reading's unit. It is not the unity: it holds no number, so a \`PUT\` may set any unit on it.`; diff --git a/src/lib/openapi/routes/biomarkers.ts b/src/lib/openapi/routes/biomarkers.ts index 47a464fe2..c2180f811 100644 --- a/src/lib/openapi/routes/biomarkers.ts +++ b/src/lib/openapi/routes/biomarkers.ts @@ -14,7 +14,7 @@ import type { ZodOpenApiObject } from "zod-openapi"; import { z } from "zod/v4"; -import { LAB_UNIT_DESCRIPTION } from "@/lib/labs/dimensionless"; +import { BIOMARKER_UNIT_DESCRIPTION } from "@/lib/labs/dimensionless"; import { dateKeySchema } from "@/lib/day/date-key-schema"; import { labSeriesQuerySchema, @@ -62,7 +62,7 @@ const biomarkerRow = z .object({ id: z.string(), name: z.string(), - unit: z.string().describe(LAB_UNIT_DESCRIPTION), + unit: z.string().describe(BIOMARKER_UNIT_DESCRIPTION), lowerBound: z.number().nullable(), upperBound: z.number().nullable(), panel: z.string().nullable(), @@ -318,7 +318,7 @@ export const biomarkerPaths: NonNullable = { tags: ["Labs"], summary: "Edit a biomarker", description: - "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.", + "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 a numeric reading is linked to the marker, a deleted one included (`meta.readingCount` carries how many): readers label every linked number with the marker's unit, so a change would relabel stored numbers without converting them. Sending the current unit or another spelling of it (`mg/dl` for `mg/dL`), or changing it on a marker whose readings are all text or that has none, is accepted. A marker minted from a text result has an empty unit, so any unit may be set on it.", requestParams: { path: z.object({ id: z.string() }) }, requestBody: { required: true, diff --git a/tests/integration/biomarker-detail.test.ts b/tests/integration/biomarker-detail.test.ts index b9c408396..22537e7fc 100644 --- a/tests/integration/biomarker-detail.test.ts +++ b/tests/integration/biomarker-detail.test.ts @@ -216,6 +216,127 @@ describe("PUT /api/biomarkers/{id} — unit lock (real Postgres)", () => { }); }); +/** + * #1393 — a marker minted from a text result ("negative", "SEE NOTE") has an + * empty unit: none has been chosen yet, and the first numeric reading gives + * it one. The lock guards numbers stored in a unit, so it never fires on such + * a marker, and a rename or a spelling of the same unit never trips it. + */ +async function seedTextMarker(name: string) { + const prisma = getPrismaClient(); + const marker = await prisma.biomarker.create({ + data: { userId: USER_ID, name, unit: "" }, + }); + await prisma.labResult.create({ + data: { + userId: USER_ID, + biomarkerId: marker.id, + analyte: name, + unit: "", + valueText: "negative", + takenAt: new Date("2026-06-20T08:00:00.000Z"), + }, + }); + return marker; +} + +describe("PUT /api/biomarkers/{id} — a marker without a unit (#1393)", () => { + it("renames a marker minted from a text result and keeps its empty unit", async () => { + const { PUT } = await import("@/app/api/biomarkers/[id]/route"); + const marker = await seedTextMarker("Urine protein"); + + const res = await PUT( + putReq(marker.id, { name: "Protein (urine)" }), + params(marker.id), + ); + + expect(res.status).toBe(200); + const row = await getPrismaClient().biomarker.findUniqueOrThrow({ + where: { id: marker.id }, + }); + expect(row.name).toBe("Protein (urine)"); + expect(row.unit).toBe(""); + }); + + it("lets a text-only marker take the unity, since no number is stored in its unit", async () => { + const { PUT } = await import("@/app/api/biomarkers/[id]/route"); + const marker = await seedTextMarker("Nitrite"); + + const res = await PUT( + putReq(marker.id, { name: "Nitrite (urine)", unit: "1" }), + params(marker.id), + ); + + expect(res.status).toBe(200); + const row = await getPrismaClient().biomarker.findUniqueOrThrow({ + where: { id: marker.id }, + }); + expect(row.name).toBe("Nitrite (urine)"); + expect(row.unit).toBe("1"); + }); + + it("lets a text-only marker take a real unit", async () => { + const { PUT } = await import("@/app/api/biomarkers/[id]/route"); + const marker = await seedTextMarker("Glucose (urine)"); + + const res = await PUT( + putReq(marker.id, { unit: "mg/dL" }), + params(marker.id), + ); + + expect(res.status).toBe(200); + const row = await getPrismaClient().biomarker.findUniqueOrThrow({ + where: { id: marker.id }, + }); + expect(row.unit).toBe("mg/dL"); + }); + + it("accepts another spelling of the stored unit while numbers are linked", async () => { + const { PUT } = await import("@/app/api/biomarkers/[id]/route"); + const marker = await seedMarkerWithReadings(USER_ID, "Cholesterol"); + + const res = await PUT( + putReq(marker.id, { name: "Total cholesterol", unit: "mg/dl" }), + params(marker.id), + ); + + expect(res.status).toBe(200); + const row = await getPrismaClient().biomarker.findUniqueOrThrow({ + where: { id: marker.id }, + }); + expect(row.name).toBe("Total cholesterol"); + }); + + it("still locks a real change and counts only the numeric readings", async () => { + const { PUT } = await import("@/app/api/biomarkers/[id]/route"); + const prisma = getPrismaClient(); + const marker = await seedMarkerWithReadings(USER_ID, "Albumin"); + await prisma.labResult.create({ + data: { + userId: USER_ID, + biomarkerId: marker.id, + analyte: "Albumin", + unit: "", + valueText: "SEE NOTE", + takenAt: new Date("2026-04-20T08:00:00.000Z"), + }, + }); + + const res = await PUT(putReq(marker.id, { unit: "1" }), params(marker.id)); + + expect(res.status).toBe(422); + const body = await res.json(); + expect(body.meta).toMatchObject({ + errorCode: "biomarkers.unit.locked", + readingCount: 2, + }); + const row = await prisma.biomarker.findUniqueOrThrow({ + where: { id: marker.id }, + }); + expect(row.unit).toBe("mg/dL"); + }); +}); + describe("DELETE /api/biomarkers/{id} (real Postgres)", () => { it("drops the marker together with its readings", async () => { const { DELETE } = await import("@/app/api/biomarkers/[id]/route");