chore(medications): drop the Bestand section from GLP-1 detail

Retire the entire inventory surface from the GLP-1 medication card:
the inline "pens left · weeks of supply" summary line, the disclosure
that wrapped the per-pen list, and the InventorySection component
file (no other consumer). The orphan i18n keys under
medications.inventory.* and the glp1Inventory* labels retire alongside
the help-text revision for glp1DosesPerUnitHelp. The iOS-consumed
Glp1InventoryDTO slot on /api/medications/[id]/glp1 stays byte-stable
in the response shape, and the server-side state-machine helpers
remain for that endpoint's computed weeksOfSupply.
This commit is contained in:
Marc-André Bombeck committed 2026-05-16 01:33:50 +02:00
1 parent 8c81af10d6
commit 8c8d6dc27f
10 files changed
+29 -779

No files matched your search

@@ -308,7 +308,11 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
expect(html).toContain("Abdomen, lower left");
});
it("renders the pen-inventory line when inventory data is present", () => {
it("no longer renders the pen-inventory line (retired v1.4.28)", () => {
// The maintainer retired the entire Bestand / inventory surface
// on the GLP-1 card in v1.4.28. The iOS-consumed Glp1InventoryDTO
// slot stays in the response shape, but the web card never paints
// the inline pens-remaining line or the low-stock badge any more.
const client = makeClient();
seedCompliance(client, med7p5.id);
seedGlp1Details(client, med7p5.id, {
@@ -325,14 +329,11 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
client,
);
// The inventory copy template is "{pens} pens left · ~{weeks} weeks of supply".
expect(html).toContain("2 pens left");
expect(html).toContain("8 weeks of supply");
// Low-stock badge omitted when lowStock=false.
expect(html).not.toContain("pens left");
expect(html).not.toContain("Low stock");
});
it("renders the low-stock badge when inventory.lowStock is true", () => {
it("does not render the low-stock badge even when inventory.lowStock is true (retired v1.4.28)", () => {
const client = makeClient();
seedCompliance(client, med7p5.id);
seedGlp1Details(client, med7p5.id, {
@@ -349,8 +350,8 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
client,
);
expect(html).toContain("1 pens left");
expect(html).toContain("Low stock");
expect(html).not.toContain("pens left");
expect(html).not.toContain("Low stock");
});
it("side-effect quick-log button hands off the medication object", () => {
@@ -26,16 +26,15 @@ import {
nextInjectionSite,
type InjectionSiteKey,
} from "@/lib/medications/injection-sites";
import { InventorySection } from "@/components/medications/inventory-section";
/**
* v1.4.25 W4d — GLP-1 medication card variant.
*
* Marc directive 2026-05-14: NO chart on the medication card. The card
* stays text-rich (drug name + current dose, last/next injection,
* injection-site rotation hint, pen inventory, side-effect quick-log).
* v1.4.28 retired the inline dose-history disclosure. Chart-only
* surfaces are the Dashboard tile + Insights /medikamente sub-page.
* injection-site rotation hint, side-effect quick-log). v1.4.28
* retired the inline dose-history disclosure and the inventory
* surface. Chart-only surfaces are the Dashboard tile + Insights
* /medikamente sub-page.
*
* Renders inside the standard medications grid alongside generic
* medication cards; visually mirrors `medication-card.tsx` so the page
@@ -219,8 +218,6 @@ export function Glp1MedicationCard({
.filter(Boolean) as InjectionSiteKey[],
);
const inventory = details?.inventory ?? null;
function lastInjectionLabel(): string | null {
if (!medication.lastTakenAt) return null;
const d = new Date(medication.lastTakenAt);
@@ -337,31 +334,11 @@ export function Glp1MedicationCard({
</div>
)}
{/* Inventory line — only when dosesPerUnit + at least one
inventory event recorded. Low-stock gets a warning badge. */}
{inventory && inventory.pensRemaining !== null && (
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">
{t("medications.glp1Inventory", {
pens: inventory.pensRemaining,
weeks: inventory.weeksOfSupply ?? "—",
})}
</span>
{inventory.lowStock && (
<Badge variant="destructive" className="text-[10px]">
{t("medications.glp1InventoryLow")}
</Badge>
)}
</div>
)}
{/* v1.4.25 W19b — per-pen / per-vial inventory disclosure.
Lazy-loads the inventory list on open; otherwise stays
collapsed so the card height matches generic cards. */}
<InventorySection
medicationId={medication.id}
defaultDosesPerUnit={medication.dosesPerUnit ?? null}
/>
{/* v1.4.28 — the "Bestand" (inventory) surface retired from
the GLP-1 card: both the inline pens-remaining summary line
and the per-pen disclosure are gone. The iOS-consumed
Glp1InventoryDTO slot on /api/medications/[id]/glp1 stays
in the response shape; only the web mounts are gone. */}
{/* Compliance bars — identical to the generic card so the page
grid stays harmonious. */}
@@ -1,549 +0,0 @@
"use client";
import { useId, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ChevronDown, Loader2, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import type { MedicationInventoryState } from "@/generated/prisma/client";
import {
DEFAULT_IN_USE_WINDOW_DAYS,
daysRemainingInUse,
} from "@/lib/medications/inventory/state-machine";
/**
* v1.4.25 W19b — Inventory disclosure for the GLP-1 medication card.
*
* Sits inline in the GLP-1 card as a collapsible section. Shows the
* active and recently-used pens, surfaces the 30-day in-use clock per
* pen, and offers an "Add new pen" dialog for `purchasedAt` +
* `printedExpiry` + `dosesTotal`. Per-pen actions are
* mark-as-in-use (manual override when an intake didn't auto-flip
* the state) and mark-as-used-up (terminal override when a pen is
* physically discarded).
*
* The UI deliberately reuses existing primitives — Card, Dialog,
* Input, Badge, Button — no new shadcn block.
*
* v1.4.25 W21 Fix-N
* - The local `InventoryState` string-union has been dropped in
* favour of the canonical `MedicationInventoryState` enum from
* the Prisma client.
* - The reimplemented client-side `daysRemainingInUse` has been
* replaced by the widened pure helper from the inventory
* state-machine module; one rule for the deadline math.
*/
interface InventoryItem {
id: string;
state: MedicationInventoryState;
dosesTotal: number;
dosesRemaining: number;
firstUseAt: string | null;
expiresAt: string | null;
printedExpiry: string | null;
purchasedAt: string | null;
notes: string | null;
createdAt: string;
}
interface InventorySectionProps {
medicationId: string;
/** Doses per pen — passed in so the dialog can pre-fill the input
* with the knowledge-layer value (e.g. 4 for a Mounjaro KwikPen). */
defaultDosesPerUnit: number | null;
}
export function InventorySection({
medicationId,
defaultDosesPerUnit,
}: InventorySectionProps) {
const { t } = useTranslations();
const fmt = useFormatters();
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [addOpen, setAddOpen] = useState(false);
// v1.4.27 B7 / L3 — explicit aria-controls between summary and disclosed
// panel for parity with the W8e Provenance accordion.
const panelId = useId();
const pastPanelId = useId();
// v1.4.27 MB3 — link the add-pen error message back to the doses-total
// input via aria-describedby so screen readers announce the failure
// when the form rejects an out-of-range value.
const formErrorId = useId();
// v1.4.27 R4 RC2 — portal target + stable form id wire the sticky
// Save / Cancel row into the `<ResponsiveSheet>` footer slot.
const formId = useId();
const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
const [dosesTotal, setDosesTotal] = useState<string>(
defaultDosesPerUnit ? String(defaultDosesPerUnit) : "",
);
const [printedExpiry, setPrintedExpiry] = useState<string>("");
const [purchasedAt, setPurchasedAt] = useState<string>("");
const [notes, setNotes] = useState<string>("");
const [formError, setFormError] = useState<string | null>(null);
const listKey = ["medications", medicationId, "inventory"] as const;
const { data, isLoading } = useQuery({
queryKey: listKey,
queryFn: async () => {
const res = await fetch(
`/api/medications/${medicationId}/inventory`,
);
if (!res.ok) return null;
const json = (await res.json()) as {
data: { items: InventoryItem[]; meta: { total: number } };
};
return json.data;
},
staleTime: 60 * 1000,
enabled: open,
});
const createMutation = useMutation({
mutationFn: async (payload: {
dosesTotal: number;
printedExpiry: string | null;
purchasedAt: string | null;
notes: string | null;
}) => {
const res = await fetch(
`/api/medications/${medicationId}/inventory`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
},
);
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as {
error?: string;
};
throw new Error(body.error ?? "Failed to add pen");
}
return (await res.json()).data as InventoryItem;
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: listKey });
},
});
const patchMutation = useMutation({
mutationFn: async (vars: {
itemId: string;
body: Record<string, unknown>;
}) => {
const res = await fetch(
`/api/medications/${medicationId}/inventory/${vars.itemId}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(vars.body),
},
);
if (!res.ok) throw new Error("Failed to update pen");
return (await res.json()).data as InventoryItem;
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: listKey });
},
});
const deleteMutation = useMutation({
mutationFn: async (itemId: string) => {
const res = await fetch(
`/api/medications/${medicationId}/inventory/${itemId}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Failed to delete pen");
return true;
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: listKey });
},
});
function resetAddForm() {
setDosesTotal(defaultDosesPerUnit ? String(defaultDosesPerUnit) : "");
setPrintedExpiry("");
setPurchasedAt("");
setNotes("");
setFormError(null);
}
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setFormError(null);
const dt = Number(dosesTotal);
if (!Number.isInteger(dt) || dt < 1 || dt > 100) {
setFormError(t("medications.inventory.errorDosesTotal"));
return;
}
createMutation.mutate(
{
dosesTotal: dt,
printedExpiry: printedExpiry ? new Date(printedExpiry).toISOString() : null,
purchasedAt: purchasedAt ? new Date(purchasedAt).toISOString() : null,
notes: notes.trim() ? notes.trim() : null,
},
{
onSuccess: () => {
resetAddForm();
setAddOpen(false);
},
onError: (err) => {
setFormError(err instanceof Error ? err.message : String(err));
},
},
);
}
const items = data?.items ?? [];
const liveItems = items.filter(
(i) => i.state === "ACTIVE" || i.state === "IN_USE",
);
const pastItems = items.filter(
(i) => i.state === "EXPIRED" || i.state === "USED_UP",
);
// Snapshot "now" once per render. The disclosure is opt-in (the
// user clicks to expand), so re-rendering on focus events should
// not cause the "days remaining" labels to flicker between values.
// eslint-disable-next-line react-hooks/purity -- intentional one-shot snapshot
const nowMs = useMemo(() => Date.now(), []);
function stateLabel(item: InventoryItem): string {
if (item.state === "ACTIVE") {
return t("medications.inventory.state.active");
}
if (item.state === "IN_USE") {
const d = daysRemainingInUse(
{ firstUseAt: item.firstUseAt },
nowMs,
DEFAULT_IN_USE_WINDOW_DAYS,
);
return t("medications.inventory.state.inUse", { days: d ?? 0 });
}
if (item.state === "EXPIRED") {
return t("medications.inventory.state.expired");
}
return t("medications.inventory.state.usedUp");
}
function badgeVariant(
state: MedicationInventoryState,
): "default" | "outline" | "secondary" | "destructive" {
if (state === "EXPIRED") return "destructive";
if (state === "USED_UP") return "secondary";
if (state === "IN_USE") return "default";
return "outline";
}
return (
<>
<details
className="border-border/60 rounded-md border text-xs"
open={open}
onToggle={(e) => setOpen((e.target as HTMLDetailsElement).open)}
>
<summary
className="text-foreground/85 flex cursor-pointer list-none items-center justify-between px-3 py-2 font-medium"
aria-controls={panelId}
aria-expanded={open}
>
<span>
{t("medications.inventory.title")}
{liveItems.length > 0 && (
<span className="text-muted-foreground ml-1.5 font-normal">
({liveItems.length})
</span>
)}
</span>
<ChevronDown
className={`h-3.5 w-3.5 transition-transform ${
open ? "rotate-180" : ""
}`}
/>
</summary>
<div
id={panelId}
className="border-border/60 space-y-3 border-t px-3 py-2.5"
>
{isLoading && (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
<span>{t("medications.inventory.loading")}</span>
</div>
)}
{!isLoading && liveItems.length === 0 && pastItems.length === 0 && (
<p className="text-muted-foreground">
{t("medications.inventory.empty")}
</p>
)}
{liveItems.length > 0 && (
<ul className="space-y-2">
{liveItems.map((item) => (
<li
key={item.id}
className="bg-muted/30 flex items-start justify-between gap-2 rounded-md px-2.5 py-2"
>
<div className="min-w-0 space-y-0.5">
<div className="flex flex-wrap items-center gap-1.5">
<Badge
variant={badgeVariant(item.state)}
className="text-[10px]"
>
{stateLabel(item)}
</Badge>
<span className="text-foreground/85 font-medium tabular-nums">
{item.dosesRemaining}/{item.dosesTotal}{" "}
{t("medications.inventory.dosesLabel")}
</span>
</div>
{item.printedExpiry && (
<p className="text-muted-foreground">
{t("medications.inventory.printedExpiry", {
date: fmt.dateShort(new Date(item.printedExpiry)),
})}
</p>
)}
{item.purchasedAt && (
<p className="text-muted-foreground">
{t("medications.inventory.purchasedAt", {
date: fmt.dateShort(new Date(item.purchasedAt)),
})}
</p>
)}
{item.notes && (
<p className="text-muted-foreground italic">
{item.notes}
</p>
)}
</div>
<div className="flex shrink-0 flex-col gap-1">
{item.state === "ACTIVE" && (
<Button
variant="outline"
className="min-h-11 px-3 text-xs"
onClick={() =>
patchMutation.mutate({
itemId: item.id,
body: { markAsFirstUseAt: new Date().toISOString() },
})
}
disabled={patchMutation.isPending}
>
{t("medications.inventory.markAsInUse")}
</Button>
)}
{(item.state === "ACTIVE" || item.state === "IN_USE") && (
<Button
variant="ghost"
className="min-h-11 px-3 text-xs"
onClick={() =>
patchMutation.mutate({
itemId: item.id,
body: { markAsUsedUp: true },
})
}
disabled={patchMutation.isPending}
>
{t("medications.inventory.markAsUsedUp")}
</Button>
)}
</div>
</li>
))}
</ul>
)}
{pastItems.length > 0 && (
<details className="border-border/40 rounded-md border">
<summary
className="text-muted-foreground cursor-pointer list-none px-2.5 py-1.5 font-medium"
aria-controls={pastPanelId}
>
{t("medications.inventory.pastTitle", {
count: pastItems.length,
})}
</summary>
<ul
id={pastPanelId}
className="border-border/40 space-y-1 border-t px-2.5 py-2"
>
{pastItems.map((item) => (
<li
key={item.id}
className="flex items-center justify-between gap-2"
>
<div className="flex flex-wrap items-center gap-1.5">
<Badge
variant={badgeVariant(item.state)}
className="text-[10px]"
>
{stateLabel(item)}
</Badge>
<span className="text-muted-foreground tabular-nums">
{item.dosesRemaining}/{item.dosesTotal}
</span>
{item.firstUseAt && (
<span className="text-muted-foreground">
·{" "}
{fmt.dateShort(new Date(item.firstUseAt))}
</span>
)}
</div>
<Button
variant="ghost"
size="icon"
className="size-11 shrink-0"
onClick={() => deleteMutation.mutate(item.id)}
disabled={deleteMutation.isPending}
aria-label={t("medications.inventory.delete")}
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
</details>
)}
<Button
size="sm"
variant="outline"
className="w-full"
onClick={() => setAddOpen(true)}
>
<Plus className="mr-1 h-3.5 w-3.5" />
{t("medications.inventory.addPen")}
</Button>
</div>
</details>
<ResponsiveSheet
open={addOpen}
onOpenChange={setAddOpen}
title={t("medications.inventory.addPenTitle")}
footer={<div ref={setFooterEl} className="flex w-full" />}
>
<form id={formId} onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="inv-doses-total">
{t("medications.inventory.fieldDosesTotal")}
</Label>
<Input
id="inv-doses-total"
type="number"
inputMode="numeric"
enterKeyHint="next"
min={1}
max={100}
step={1}
value={dosesTotal}
onChange={(e) => setDosesTotal(e.target.value)}
required
aria-required="true"
aria-invalid={!!formError || undefined}
aria-describedby={formError ? formErrorId : undefined}
/>
<p className="text-muted-foreground text-xs">
{t("medications.inventory.fieldDosesTotalHelp")}
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="inv-printed-expiry">
{t("medications.inventory.fieldPrintedExpiry")}
</Label>
<Input
id="inv-printed-expiry"
type="date"
enterKeyHint="next"
value={printedExpiry}
onChange={(e) => setPrintedExpiry(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="inv-purchased-at">
{t("medications.inventory.fieldPurchasedAt")}
</Label>
<Input
id="inv-purchased-at"
type="date"
enterKeyHint="next"
value={purchasedAt}
onChange={(e) => setPurchasedAt(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="inv-notes">
{t("medications.inventory.fieldNotes")}
</Label>
<textarea
id="inv-notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
maxLength={200}
rows={2}
enterKeyHint="done"
autoCapitalize="sentences"
className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
{formError && (
<p
id={formErrorId}
role="alert"
aria-live="polite"
className="text-destructive text-sm"
>
{formError}
</p>
)}
</form>
{footerEl
? createPortal(
<div className="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button
type="button"
variant="outline"
onClick={() => {
resetAddForm();
setAddOpen(false);
}}
>
{t("medications.inventory.cancel")}
</Button>
<Button
type="submit"
form={formId}
disabled={createMutation.isPending}
>
{createMutation.isPending && (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
)}
{t("medications.inventory.save")}
</Button>
</div>,
footerEl,
)
: null}
</ResponsiveSheet>
</>
);
}