feat(medications): add optional ATC + RxNorm codes to the medication row

Add two nullable, additive columns to `Medication` (`atc_code`,
`rxnorm_code`) so a user or clinician can assert a drug-classification
code that the health-record FHIR export emits on the medication concept.
Codes are taken verbatim, never machine-guessed: a wrong code is a
clinical-safety problem, an absent one is merely a (conformant)
text-only concept.

- Migration 0103 — additive, nullable, no backfill. Pre-existing rows
  read NULL, which the exporter already treats as "no code".
- Validate on write — ATC `^[A-Z]\d{2}[A-Z]{2}\d{2}$`, RxCUI `^\d+$`;
  422 on a malformed value. Wired field-by-field through the create +
  update routes (no mass assignment); `null` clears a code on update.
- Surface both codes in the medication advanced-settings sheet's Data
  group with a self-saving input, and echo them on the GET/POST/PUT
  response shape. OpenAPI regenerated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 2e0051d42826fa3f043c32e78a34dab7c8050165)
This commit is contained in:
Marc-André Bombeck committed 2026-06-02 16:45:23 +02:00
1 parent eff7b42348
commit 0a8c6e307c
18 files changed
+476

No files matched your search

@@ -54,6 +54,7 @@ vi.mock("@/components/medications/sections/notifications-section", () => ({
vi.mock("@/components/medications/sections/settings-section", () => ({
GraceRow: () => <div data-slot="mock-grace" />,
DrugCodingRow: () => <div data-slot="mock-drug-coding" />,
PhasesRow: ({
onRequestPhaseSheet,
}: {
@@ -41,6 +41,7 @@ import { ApiTokensRow } from "@/components/medications/sections/api-tokens-row";
import { DataPortabilityRow } from "@/components/medications/sections/data-portability-row";
import { NotificationsBody } from "@/components/medications/sections/notifications-section";
import {
DrugCodingRow,
GraceRow,
PhasesRow,
} from "@/components/medications/sections/settings-section";
@@ -62,6 +63,9 @@ export interface AdvancedSettingsSheetProps {
notificationsEnabled: boolean;
reminderGraceMinutes: number | null;
intakeCount: number;
/** v1.9.0 — optional drug-classification codes for the FHIR export. */
atcCode?: string | null;
rxNormCode?: string | null;
/**
* Sibling-swap the phase sheet: the parent closes this sheet and
* opens `<PhaseConfigSheet>` so the two never stack (G-1 §5).
@@ -86,6 +90,8 @@ export function AdvancedSettingsSheet({
notificationsEnabled,
reminderGraceMinutes,
intakeCount,
atcCode,
rxNormCode,
onRequestPhaseSheet,
onOpenImport,
}: AdvancedSettingsSheetProps) {
@@ -177,6 +183,13 @@ export function AdvancedSettingsSheet({
medicationName={medicationName}
/>
</div>
<div className="py-3">
<DrugCodingRow
medicationId={medicationId}
atcCode={atcCode}
rxNormCode={rxNormCode}
/>
</div>
</SettingsGroup>
{/* DANGER ZONE — purge + delete. Set off by the destructive-
@@ -131,6 +131,111 @@ export function GraceRow({
);
}
/**
* v1.9.0 — optional drug-classification codes (ATC / RxNorm) row.
* Self-saves via `PUT /api/medications/[id]` with the two top-level
* `atcCode` / `rxNormCode` fields. The codes are user/clinician-asserted
* and surface on the FHIR health-record export's
* `medicationCodeableConcept` (ATC primary, RxNorm secondary); the app
* never machine-guesses a code. An empty input clears the stored code.
*/
export function DrugCodingRow({
medicationId,
atcCode,
rxNormCode,
}: {
medicationId: string;
atcCode?: string | null;
rxNormCode?: string | null;
}) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const [atcValue, setAtcValue] = useState(atcCode ?? "");
const [rxValue, setRxValue] = useState(rxNormCode ?? "");
const [busy, setBusy] = useState(false);
async function save() {
if (busy) return;
setBusy(true);
try {
// Empty input clears the column (null); a non-empty value is sent
// verbatim for the server to validate (422 on a malformed code).
const res = await fetch(`/api/medications/${medicationId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
atcCode: atcValue.trim() === "" ? null : atcValue.trim(),
rxNormCode: rxValue.trim() === "" ? null : rxValue.trim(),
}),
});
if (!res.ok) {
toast.error(t("medications.detail.settings.codes.failed"));
return;
}
await invalidateKeys(queryClient, medicationDependentKeys);
toast.success(t("medications.detail.settings.codes.saved"));
} catch {
toast.error(t("medications.detail.settings.codes.failed"));
} finally {
setBusy(false);
}
}
return (
<div className="space-y-2" data-slot="medication-detail-drug-coding-row">
<Label className="text-foreground text-sm font-medium">
{t("medications.detail.settings.codes.label")}
</Label>
<p className="text-muted-foreground text-xs">
{t("medications.detail.settings.codes.note")}
</p>
<div className="flex flex-wrap items-end gap-3">
<div className="space-y-1">
<Label
htmlFor="medication-detail-atc-input"
className="text-muted-foreground text-xs"
>
{t("medications.detail.settings.codes.atcLabel")}
</Label>
<Input
id="medication-detail-atc-input"
value={atcValue}
onChange={(e) => setAtcValue(e.target.value.toUpperCase())}
placeholder="A10BX10"
className="w-32"
/>
</div>
<div className="space-y-1">
<Label
htmlFor="medication-detail-rxnorm-input"
className="text-muted-foreground text-xs"
>
{t("medications.detail.settings.codes.rxNormLabel")}
</Label>
<Input
id="medication-detail-rxnorm-input"
inputMode="numeric"
value={rxValue}
onChange={(e) => setRxValue(e.target.value)}
placeholder="2601723"
className="w-32"
/>
</div>
<Button
variant="outline"
size="sm"
onClick={() => void save()}
disabled={busy}
aria-busy={busy || undefined}
className="min-h-11 sm:min-h-9"
>
{t("common.save")}
</Button>
</div>
</div>
);
}
/**
* v1.7.0 — phases / course-window row. GLP-1 only; the button mounts
* once a course window is set, otherwise an italic hint. When