feat(meds): compose-mode for the modal wizard

A medication can now hold multiple parallel schedules, each with its
own cadence and times. Steps 5-7 of the wizard become per-schedule;
Step 8 lists every configured schedule with edit and remove actions
and surfaces a "Weiteren Zeitplan hinzufügen" card at the bottom.
The hydrator reads every schedule on edit and lands the user
directly on the list view when more than one is present.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.7 committed 2026-05-28 19:52:39 +02:00
1 parent 320970c97d
commit 8578924f14
10 files changed
+567 -104

No files matched your search

+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ende: {date}",
"noEndDate": "Kein Enddatum"
},
"compose": {
"scheduleIndex": "Zeitplan {n} von {total}",
"list": {
"add": "Weiteren Zeitplan hinzufügen",
"edit": "Bearbeiten",
"remove": "Entfernen",
"removeDisabled": "Mindestens ein Zeitplan ist erforderlich.",
"empty": "Noch kein Zeitplan."
}
},
"errors": {
"submitFailed": "Medikament konnte nicht gespeichert werden — bitte erneut versuchen."
}
+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ends: {date}",
"noEndDate": "No end date"
},
"compose": {
"scheduleIndex": "Schedule {n} of {total}",
"list": {
"add": "Add another schedule",
"edit": "Edit",
"remove": "Remove",
"removeDisabled": "At least one schedule is required.",
"empty": "No schedule yet."
}
},
"errors": {
"submitFailed": "Could not save the medication — please retry."
}
+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ends: {date}",
"noEndDate": "No end date"
},
"compose": {
"scheduleIndex": "Schedule {n} of {total}",
"list": {
"add": "Add another schedule",
"edit": "Edit",
"remove": "Remove",
"removeDisabled": "At least one schedule is required.",
"empty": "No schedule yet."
}
},
"errors": {
"submitFailed": "Could not save the medication — please retry."
}
+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ends: {date}",
"noEndDate": "No end date"
},
"compose": {
"scheduleIndex": "Schedule {n} of {total}",
"list": {
"add": "Add another schedule",
"edit": "Edit",
"remove": "Remove",
"removeDisabled": "At least one schedule is required.",
"empty": "No schedule yet."
}
},
"errors": {
"submitFailed": "Could not save the medication — please retry."
}
+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ends: {date}",
"noEndDate": "No end date"
},
"compose": {
"scheduleIndex": "Schedule {n} of {total}",
"list": {
"add": "Add another schedule",
"edit": "Edit",
"remove": "Remove",
"removeDisabled": "At least one schedule is required.",
"empty": "No schedule yet."
}
},
"errors": {
"submitFailed": "Could not save the medication — please retry."
}
+10
View File
@@ -899,6 +899,16 @@
"endsOn": "Ends: {date}",
"noEndDate": "No end date"
},
"compose": {
"scheduleIndex": "Schedule {n} of {total}",
"list": {
"add": "Add another schedule",
"edit": "Edit",
"remove": "Remove",
"removeDisabled": "At least one schedule is required.",
"empty": "No schedule yet."
}
},
"errors": {
"submitFailed": "Could not save the medication — please retry."
}
+1
View File
@@ -328,6 +328,7 @@ function medicationToPayload(med: Medication): MedicationPayload {
endsOn: med.endsOn ? new Date(med.endsOn) : null,
oneShot: med.oneShot ?? false,
schedules: med.schedules.map((s) => ({
id: s.id,
windowStart: s.windowStart,
windowEnd: s.windowEnd,
label: s.label ?? null,
@@ -58,11 +58,16 @@ import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
import { NaturalLanguageExtractor } from "@/components/medications/scheduling/NaturalLanguageExtractor";
import {
addSchedule,
buildCreateBody,
commitActiveDraft,
emptyWizardPayload,
hydrateWizardPayload,
landingStepForEdit,
type MedicationPayload,
progressIndices,
removeSchedule,
setActiveSchedule,
type WizardPayload,
} from "./wizard-payload";
import { Step1Name } from "./steps/Step1Name";
@@ -121,12 +126,18 @@ function WizardDialogShell({
const router = useRouter();
const queryClient = useQueryClient();
const [step, setStep] = useState<StepNumber>(1);
const [payload, setPayload] = useState<WizardPayload>(() =>
mode === "edit" && initial
? hydrateWizardPayload(initial)
: emptyWizardPayload(),
);
const [step, setStep] = useState<StepNumber>(() => {
if (mode === "edit" && initial) {
const hydrated = hydrateWizardPayload(initial);
return landingStepForEdit(hydrated) as StepNumber;
}
return 1;
});
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [nlOpen, setNlOpen] = useState(false);
@@ -177,6 +188,13 @@ function WizardDialogShell({
// step in the path, which is the one-shot summary at step 8.
const forward = list.find((n) => n > step);
if (forward !== undefined) {
// Crossing into Step 8 commits the active per-schedule draft so
// the schedule-list view renders the user's just-edited cadence
// and times. Step transitions inside Steps 5-7 keep the flat
// mirror as the source of truth.
if (forward === 8) {
setPayload((prev) => commitActiveDraft(prev));
}
setStep(forward as StepNumber);
}
}, [canContinue, payload.mode, payload.cadence.kind, step]);
@@ -205,6 +223,32 @@ function WizardDialogShell({
target?.focus({ preventScroll: true });
}, [step]);
/**
* Step 8 actions — every schedule-list mutation routes through the
* pure helpers so the flat mirror stays in sync.
*/
const onEditSchedule = useCallback((index: number) => {
setPayload((prev) => setActiveSchedule(prev, index));
setStep(5);
}, []);
const onRemoveSchedule = useCallback((index: number) => {
setPayload((prev) => removeSchedule(prev, index));
}, []);
const onAddSchedule = useCallback(() => {
setPayload((prev) => addSchedule(prev));
setStep(5);
}, []);
const stepCaption =
payload.schedules.length > 1 && step >= 5 && step <= 7
? t("medications.wizard.compose.scheduleIndex", {
n: payload.activeScheduleIndex + 1,
total: payload.schedules.length,
})
: null;
const onSubmit = useCallback(async () => {
setSubmitting(true);
setSubmitError(null);
@@ -377,6 +421,14 @@ function WizardDialogShell({
<Icon className="text-primary h-6 w-6" />
</div>
<div className="min-w-0 space-y-1">
{stepCaption && (
<p
className="text-muted-foreground text-xs"
data-slot="wizard-schedule-caption"
>
{stepCaption}
</p>
)}
<h2 className="text-foreground text-base font-medium leading-tight">
{stepTitle}
</h2>
@@ -424,6 +476,9 @@ function WizardDialogShell({
mode={mode}
initial={initial}
submitError={submitError}
onEditSchedule={onEditSchedule}
onRemoveSchedule={onRemoveSchedule}
onAddSchedule={onAddSchedule}
/>
)}
</div>
@@ -1,5 +1,8 @@
"use client";
import { Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
@@ -7,6 +10,7 @@ import { useTranslations } from "@/lib/i18n/context";
import {
type MedicationPayload,
summariseCadence,
summariseScheduleDraft,
type WizardPayload,
} from "../wizard-payload";
@@ -16,24 +20,40 @@ export interface Step8SummaryProps {
mode: "create" | "edit";
initial?: MedicationPayload;
submitError: string | null;
/** Jump to Step 5 with the schedule at `index` as the active draft. */
onEditSchedule: (index: number) => void;
/** Remove the schedule at `index` from the list. */
onRemoveSchedule: (index: number) => void;
/** Append a fresh schedule and jump to Step 5 of the new entry. */
onAddSchedule: () => void;
}
/**
* v1.5.4 — Step 8: schedule list + reminders + summary.
*
* Compose-mode lands here. Every entry in `payload.schedules` renders
* as a small card with a plain-language summary, a "Bearbeiten" link
* back into Step 5 of that schedule, and a "Entfernen" button. The
* "+ Weiteren Zeitplan hinzufügen" card at the bottom of the list
* appends a fresh empty draft. The medication-level reminders toggle
* stays at the bottom.
*
* The first summary block at the top keeps the v1.5.4 single-schedule
* shape so single-schedule paths read identically to before. The
* per-schedule cards underneath only render when more than one
* schedule exists.
*/
export function Step8Summary({
payload,
applyPartial,
mode,
initial,
submitError,
onEditSchedule,
onRemoveSchedule,
onAddSchedule,
}: Step8SummaryProps) {
const { t } = useTranslations();
const summary = summariseCadence(payload, t);
// v1.5.4 ships single-schedule editing only. A medication that
// already carries multiple schedules surfaces a note pointing at
// the legacy detail form; the multi-schedule compose-mode lands in
// v1.5.5 per the design hand-off (D-1 §10 deferred bullet 2).
const isMultiSchedule =
mode === "edit" && (initial?.schedules.length ?? 0) > 1;
const topSummary = summariseCadence(payload, t);
const canRemove = payload.schedules.length > 1;
return (
<div className="space-y-4" data-slot="wizard-step8">
@@ -44,7 +64,76 @@ export function Step8Summary({
<p className="mb-1 font-medium">
{t("medications.wizard.summary.title")}
</p>
<p>{summary}</p>
<p>{topSummary}</p>
</div>
<div className="space-y-2" data-slot="wizard-schedule-list">
{payload.schedules.map((draft, index) => {
const cardSummary = summariseScheduleDraft(draft, t);
return (
<div
key={index}
className="border-border/70 rounded-md border p-3"
data-slot="wizard-schedule-card"
data-index={index}
>
<p className="text-sm">{cardSummary}</p>
<div className="mt-2 flex items-center gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 px-2 text-xs"
onClick={() => onEditSchedule(index)}
data-slot="wizard-schedule-edit"
data-index={index}
>
{t("medications.wizard.compose.list.edit")}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-destructive h-8 gap-1 px-2 text-xs"
onClick={() => onRemoveSchedule(index)}
disabled={!canRemove}
data-slot="wizard-schedule-remove"
data-index={index}
aria-label={t("medications.wizard.compose.list.remove")}
>
<Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
{t("medications.wizard.compose.list.remove")}
</Button>
</div>
</div>
);
})}
{!canRemove && (
<p
className="text-muted-foreground text-xs"
data-slot="wizard-schedule-remove-disabled-hint"
>
{t("medications.wizard.compose.list.removeDisabled")}
</p>
)}
{payload.mode !== "oneShot" && (
<button
type="button"
onClick={onAddSchedule}
data-slot="wizard-schedule-add"
className={[
"border-border/70 hover:bg-muted/40 focus-visible:ring-ring",
"flex w-full items-center justify-center gap-2 rounded-md border border-dashed",
"p-3 text-sm font-medium transition-colors",
"focus-visible:outline-none focus-visible:ring-2",
].join(" ")}
>
<Plus className="h-4 w-4" aria-hidden="true" />
{t("medications.wizard.compose.list.add")}
</button>
)}
</div>
<div className="flex items-start justify-between gap-3">
@@ -70,15 +159,6 @@ export function Step8Summary({
/>
</div>
{isMultiSchedule && (
<p
className="text-muted-foreground border-border/70 rounded-md border border-dashed p-3 text-xs"
data-slot="wizard-multi-schedule-note"
>
{t("medications.wizard.steps.step8.multiScheduleNote")}
</p>
)}
{submitError && (
<p
className="text-destructive text-sm"
@@ -2,22 +2,23 @@
* v1.5.4 — Medication wizard payload + pure helpers.
*
* The wizard is a popup that drives the same eight-step decision in
* Marc's "one question per breath" cadence. The pure helpers here
* a "one question per breath" cadence. The pure helpers here
* (state machine, validation gate, request body builder, summary
* formatter) carry the test surface; the dialog and step components
* compose them.
*
* Step encoding:
* 1. Name
* 2. Treatment class / clinical category
* 3. Dose
* 4. Course window
* 5. Cadence
* 6. Sub-cadence detail (conditional)
* 7. Times of day
* 8. Reminders + summary
* 1. Name (medication-global)
* 2. Treatment class / clinical category (medication-global)
* 3. Dose (medication-global)
* 4. Course window (medication-global)
* 5. Cadence (per-schedule)
* 6. Sub-cadence detail (per-schedule, conditional)
* 7. Times of day (per-schedule)
* 8. Schedule list + reminders + summary (medication-global)
*
* The visible step counter follows the path the user actually walks:
* The visible step counter follows the path the user actually walks
* for the ACTIVE schedule:
*
* ONE_SHOT_PATH = [1, 2, 3, 4, 8] — 5 steps
* DAILY_PATH = [1, 2, 3, 4, 5, 7, 8] — 7 steps
@@ -27,6 +28,14 @@
* radio picks `recurring`. The cadence kind drives the path between
* daily (skips Step 6) and the calendar-anchored / rolling shapes.
*
* Compose-mode: a medication can hold N parallel schedules. Steps 5-7
* mutate the schedule at `activeScheduleIndex`; Step 8 surfaces the
* full list with add / edit / remove actions. The flat
* `(mode, cadence, subControls, timesOfDay)` fields on the payload
* mirror the active draft so the step components stay
* single-schedule-aware. The list-mutating helpers below keep that
* mirror in sync.
*
* Each row in Step 2 maps to a `(treatmentClass, category)` pair that
* the request body carries. GLP-1-Injektion is the only row that picks
* `treatmentClass = "GLP1"`; every other row inherits `GENERIC` and
@@ -149,28 +158,56 @@ export function rowFromTreatment(
}
// ────────────────────────────────────────────────────────────────────
// Wizard payload
// Wizard payload + per-schedule draft
// ────────────────────────────────────────────────────────────────────
/**
* One schedule under construction inside the wizard. A medication can
* hold N parallel drafts (e.g. short-acting insulin to meals + a
* long-acting evening dose on the same medication). The `id` is
* present on edit hydrate so the round-trip preserves identity for
* the API layer; create drafts leave it undefined.
*/
export interface ScheduleDraft {
id?: string;
mode: "oneShot" | "recurring" | null;
cadence: CadenceValue;
subControls: CadenceSubControls;
timesOfDay: string[];
}
/**
* The wizard's working state. The cadence + sub-controls mirror the
* picker primitives; the treatment row collapses Step 2's
* `(treatmentClass, category)` decision into a single value the
* mapping table re-expands at submit time.
*
* Steps 1-4 + 8 are medication-global. Steps 5-7 edit the schedule
* at `activeScheduleIndex`. The flat `(mode, cadence, subControls,
* timesOfDay)` fields mirror the active draft so the step components
* stay single-schedule-aware; the list-mutating helpers below keep
* the mirror in sync.
*/
export interface WizardPayload {
name: string;
doseAmount: string;
doseUnit: string;
treatmentRow: WizardTreatmentRow | null;
/** Set in Step 5. */
/** Set in Step 5 — mirrors `schedules[activeScheduleIndex].mode`. */
mode: "oneShot" | "recurring" | null;
/** Mirrors `schedules[activeScheduleIndex].cadence`. */
cadence: CadenceValue;
/** Mirrors `schedules[activeScheduleIndex].subControls`. */
subControls: CadenceSubControls;
/** Mirrors `schedules[activeScheduleIndex].timesOfDay`. */
timesOfDay: string[];
startsOn: Date | null;
endsOn: Date | null;
notificationsEnabled: boolean;
/** Every parallel schedule under construction. Always >= 1 entry. */
schedules: ScheduleDraft[];
/** Which schedule Steps 5-7 currently edit. */
activeScheduleIndex: number;
}
const TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
@@ -182,20 +219,124 @@ function todayUtc(): Date {
);
}
/** Default draft for a fresh schedule slot. */
export function emptyScheduleDraft(): ScheduleDraft {
return {
mode: null,
cadence: encodeCadence("daily", DEFAULT_SUB_CONTROLS),
subControls: { ...DEFAULT_SUB_CONTROLS },
timesOfDay: ["08:00"],
};
}
/** Sensible defaults for a fresh wizard. */
export function emptyWizardPayload(): WizardPayload {
const draft = emptyScheduleDraft();
return {
name: "",
doseAmount: "",
doseUnit: "mg",
treatmentRow: null,
mode: null,
cadence: encodeCadence("daily", DEFAULT_SUB_CONTROLS),
subControls: { ...DEFAULT_SUB_CONTROLS },
timesOfDay: ["08:00"],
mode: draft.mode,
cadence: draft.cadence,
subControls: draft.subControls,
timesOfDay: draft.timesOfDay,
startsOn: todayUtc(),
endsOn: null,
notificationsEnabled: true,
schedules: [draft],
activeScheduleIndex: 0,
};
}
// ────────────────────────────────────────────────────────────────────
// Active-draft mirror helpers
// ────────────────────────────────────────────────────────────────────
/**
* Project the flat per-schedule fields onto the schedule slot at
* `activeScheduleIndex`. Pure — returns a new payload with the
* updated schedules array.
*/
export function commitActiveDraft(payload: WizardPayload): WizardPayload {
const idx = payload.activeScheduleIndex;
if (idx < 0 || idx >= payload.schedules.length) return payload;
const current = payload.schedules[idx];
const next: ScheduleDraft = {
...current,
mode: payload.mode,
cadence: payload.cadence,
subControls: payload.subControls,
timesOfDay: payload.timesOfDay,
};
const schedules = payload.schedules.slice();
schedules[idx] = next;
return { ...payload, schedules };
}
/**
* Pull the schedule slot at `index` onto the flat mirror fields and
* set `activeScheduleIndex`. Used when Step 8 routes the user into a
* Bearbeiten action.
*/
export function setActiveSchedule(
payload: WizardPayload,
index: number,
): WizardPayload {
if (index < 0 || index >= payload.schedules.length) return payload;
const draft = payload.schedules[index];
return {
...payload,
activeScheduleIndex: index,
mode: draft.mode,
cadence: draft.cadence,
subControls: draft.subControls,
timesOfDay: draft.timesOfDay,
};
}
/**
* Append a fresh empty schedule to the list, commit the currently
* active draft so its in-flight edits are not lost, and land the
* active pointer on the new slot.
*/
export function addSchedule(payload: WizardPayload): WizardPayload {
const committed = commitActiveDraft(payload);
const draft = emptyScheduleDraft();
const schedules = [...committed.schedules, draft];
return {
...committed,
schedules,
activeScheduleIndex: schedules.length - 1,
mode: draft.mode,
cadence: draft.cadence,
subControls: draft.subControls,
timesOfDay: draft.timesOfDay,
};
}
/**
* Remove the schedule at `index`. Refuses when only one schedule
* remains — a medication must carry at least one. The active pointer
* clamps into the new list bounds and the flat mirror re-syncs.
*/
export function removeSchedule(
payload: WizardPayload,
index: number,
): WizardPayload {
if (payload.schedules.length <= 1) return payload;
if (index < 0 || index >= payload.schedules.length) return payload;
const schedules = payload.schedules.filter((_, i) => i !== index);
const nextIndex = Math.min(payload.activeScheduleIndex, schedules.length - 1);
const draft = schedules[nextIndex];
return {
...payload,
schedules,
activeScheduleIndex: nextIndex,
mode: draft.mode,
cadence: draft.cadence,
subControls: draft.subControls,
timesOfDay: draft.timesOfDay,
};
}
@@ -307,6 +448,7 @@ export interface CreateMedicationBody {
endsOn?: string;
oneShot: boolean;
schedules: Array<{
id?: string;
windowStart: string;
windowEnd: string;
timesOfDay: string[];
@@ -347,6 +489,45 @@ function addOneHour(hhmm: string): string {
return `${String(next).padStart(2, "0")}:${mm}`;
}
/**
* Encode a single `ScheduleDraft` into the request-body schedule
* entry. Mirrors the legacy bridge so each schedule dual-writes
* `(daysOfWeek, intervalWeeks, rrule, rollingIntervalDays,
* timesOfDay)` correctly. The `oneShotMedication` flag suppresses
* recurrence on every schedule — the route enforces the
* one-schedule-per-one-shot invariant on top.
*/
export function encodeScheduleDraft(
draft: ScheduleDraft,
oneShotMedication: boolean,
): CreateMedicationBody["schedules"][number] {
const isOneShot = oneShotMedication || draft.mode === "oneShot";
const times = sortTimes(
isOneShot ? draft.timesOfDay.slice(0, 1) : draft.timesOfDay,
);
const [windowStart, windowEnd] = deriveWindow(times);
const legacyPair = legacyPairFromCadence(draft.cadence, draft.subControls);
const out: CreateMedicationBody["schedules"][number] = {
windowStart,
windowEnd,
timesOfDay: times,
};
if (draft.id) out.id = draft.id;
if (!isOneShot) {
if (draft.cadence.rrule !== null) {
out.rrule = draft.cadence.rrule;
} else if (draft.cadence.rollingIntervalDays !== null) {
out.rollingIntervalDays = draft.cadence.rollingIntervalDays;
}
if (legacyPair.daysOfWeek.length > 0) {
out.daysOfWeek = legacyPair.daysOfWeek;
}
out.intervalWeeks = legacyPair.intervalWeeks;
}
return out;
}
/**
* Map a wizard payload onto the `POST /api/medications` body. The
* route still requires the legacy `windowStart` / `windowEnd` pair for
@@ -354,59 +535,47 @@ function addOneHour(hhmm: string): string {
*
* The treatment row drives both `treatmentClass` and `category` through
* the mapping table. The route writes `category` to the side-table.
*
* Compose-mode: every entry in `payload.schedules` lands in the body's
* `schedules` array. The active draft is committed first so any
* in-flight edits flow into the encoded entry.
*
* For one-shot medications the wizard collapses to a single schedule;
* recurrence fields are suppressed across the board and the route
* normalises `endsOn` to equal `startsOn`.
*/
export function buildCreateBody(payload: WizardPayload): CreateMedicationBody {
const dose = composeDose(payload.doseAmount, payload.doseUnit);
const times = sortTimes(
payload.mode === "oneShot"
? payload.timesOfDay.slice(0, 1)
: payload.timesOfDay,
);
const [windowStart, windowEnd] = deriveWindow(times);
const isOneShot = payload.mode === "oneShot";
const committed = commitActiveDraft(payload);
const dose = composeDose(committed.doseAmount, committed.doseUnit);
const mapping =
payload.treatmentRow !== null
? WIZARD_TREATMENT_MAPPING[payload.treatmentRow]
committed.treatmentRow !== null
? WIZARD_TREATMENT_MAPPING[committed.treatmentRow]
: WIZARD_TREATMENT_MAPPING.other;
// Legacy dual-write pair so the route's `serializeScheduleRecurrence`
// sees a consistent shape — mirrors the edit-form bridge.
const legacyPair = legacyPairFromCadence(payload.cadence, payload.subControls);
const schedule: CreateMedicationBody["schedules"][number] = {
windowStart,
windowEnd,
timesOfDay: times,
};
if (!isOneShot) {
if (payload.cadence.rrule !== null) {
schedule.rrule = payload.cadence.rrule;
} else if (payload.cadence.rollingIntervalDays !== null) {
schedule.rollingIntervalDays = payload.cadence.rollingIntervalDays;
}
if (legacyPair.daysOfWeek.length > 0) {
schedule.daysOfWeek = legacyPair.daysOfWeek;
}
schedule.intervalWeeks = legacyPair.intervalWeeks;
}
// A one-shot medication carries exactly one schedule with no
// recurrence. We honour the active draft (it carries the times the
// user picked); the route enforces the one-schedule invariant.
const isOneShot = committed.mode === "oneShot";
const draftsToEmit = isOneShot
? [committed.schedules[committed.activeScheduleIndex] ?? committed.schedules[0]]
: committed.schedules;
const body: CreateMedicationBody = {
name: payload.name.trim(),
name: committed.name.trim(),
dose,
category: mapping.category,
treatmentClass: mapping.treatmentClass,
notificationsEnabled: payload.notificationsEnabled,
notificationsEnabled: committed.notificationsEnabled,
oneShot: isOneShot,
schedules: [schedule],
schedules: draftsToEmit.map((draft) => encodeScheduleDraft(draft, isOneShot)),
};
if (payload.startsOn) {
body.startsOn = dateToIsoString(payload.startsOn);
if (committed.startsOn) {
body.startsOn = dateToIsoString(committed.startsOn);
}
if (isOneShot && payload.startsOn) {
body.endsOn = dateToIsoString(payload.startsOn);
} else if (payload.endsOn) {
body.endsOn = dateToIsoString(payload.endsOn);
if (isOneShot && committed.startsOn) {
body.endsOn = dateToIsoString(committed.startsOn);
} else if (committed.endsOn) {
body.endsOn = dateToIsoString(committed.endsOn);
}
return body;
}
@@ -415,19 +584,23 @@ export function buildCreateBody(payload: WizardPayload): CreateMedicationBody {
// summariseCadence — plain-language Step 8 line
// ────────────────────────────────────────────────────────────────────
function summaryKeyForCadence(payload: WizardPayload): string {
if (payload.mode === "oneShot") return "oneShot";
switch (payload.cadence.kind) {
function summaryKeyForDraft(
mode: WizardPayload["mode"],
cadence: CadenceValue,
sub: CadenceSubControls,
): string {
if (mode === "oneShot") return "oneShot";
switch (cadence.kind) {
case "daily":
return "daily";
case "weekdays":
return "weekdays";
case "everyNWeeks":
return payload.subControls.intervalWeeks === 2 ? "biweekly" : "everyNWeeks";
return sub.intervalWeeks === 2 ? "biweekly" : "everyNWeeks";
case "monthly":
return "monthly";
case "everyNMonths":
return payload.subControls.intervalMonths === 3 ? "quarterly" : "everyNMonths";
return sub.intervalMonths === 3 ? "quarterly" : "everyNMonths";
case "yearly":
return "yearly";
case "rolling":
@@ -437,6 +610,10 @@ function summaryKeyForCadence(payload: WizardPayload): string {
}
}
function summaryKeyForCadence(payload: WizardPayload): string {
return summaryKeyForDraft(payload.mode, payload.cadence, payload.subControls);
}
function weekdaysDetail(
tokens: readonly string[],
t: (key: string, params?: Record<string, string | number>) => string,
@@ -519,6 +696,54 @@ export function summariseCadence(
.join(" · ");
}
/**
* Per-schedule summary the Step 8 list cards render. Skips the
* course-window phrases (those are medication-global and only need to
* render once on the summary block at the top of Step 8).
*/
export function summariseScheduleDraft(
draft: ScheduleDraft,
t: (key: string, params?: Record<string, string | number>) => string,
): string {
const cadenceKey = summaryKeyForDraft(
draft.mode,
draft.cadence,
draft.subControls,
);
const cadencePhrase = t(
`medications.wizard.summary.cadence.${cadenceKey}`,
{
n:
draft.cadence.kind === "everyNWeeks"
? draft.subControls.intervalWeeks
: draft.cadence.kind === "rolling"
? (draft.cadence.rollingIntervalDays ?? 0)
: 0,
},
);
let cadenceDetail = "";
if (draft.mode !== "oneShot") {
if (
draft.cadence.kind === "weekdays" ||
draft.cadence.kind === "everyNWeeks"
) {
cadenceDetail = weekdaysDetail(draft.subControls.weekdays, t);
} else if (draft.cadence.kind === "monthly") {
cadenceDetail = t("medications.wizard.summary.dayOfMonthDetail", {
day: draft.subControls.dayOfMonth,
});
}
}
const cadenceLine = cadencePhrase + cadenceDetail;
const timesPhrase =
draft.mode !== "oneShot" && draft.timesOfDay.length > 0
? t("medications.wizard.summary.times", {
times: sortTimes(draft.timesOfDay).join(", "),
})
: "";
return [cadenceLine, timesPhrase].filter(Boolean).join(" · ");
}
// ────────────────────────────────────────────────────────────────────
// Hydration — edit-path payload from an existing medication
// ────────────────────────────────────────────────────────────────────
@@ -540,6 +765,7 @@ export interface MedicationPayload {
endsOn: Date | null;
oneShot: boolean;
schedules: Array<{
id?: string;
windowStart: string;
windowEnd: string;
label?: string | null;
@@ -563,30 +789,59 @@ function parseDoseExpression(input: string): { amount: string; unit: string } {
return { amount, unit };
}
interface MedicationScheduleSnapshot {
id?: string;
windowStart: string;
windowEnd: string;
daysOfWeek?: number[];
intervalWeeks?: number;
timesOfDay?: string[];
rrule?: string | null;
rollingIntervalDays?: number | null;
}
function hydrateScheduleDraft(
schedule: MedicationScheduleSnapshot,
oneShot: boolean,
): ScheduleDraft {
const cadence = deriveCadenceFromSchedule(schedule, oneShot);
const times =
schedule.timesOfDay && schedule.timesOfDay.length > 0
? [...schedule.timesOfDay]
: schedule.windowStart
? [schedule.windowStart]
: ["08:00"];
const draft: ScheduleDraft = {
mode: oneShot ? "oneShot" : "recurring",
cadence: cadence.value,
subControls: cadence.subControls,
timesOfDay: times,
};
if (schedule.id) draft.id = schedule.id;
return draft;
}
/**
* Hydrate a `WizardPayload` from a medication snapshot. The legacy
* bridge (`inferCadenceFromLegacy`) infers a cadence from the
* `(daysOfWeek, intervalWeeks)` pair when the v1.5 `rrule` /
* `rollingIntervalDays` fields are absent. The first schedule wins
* (multi-schedule edit support lands in v1.5.5 — until then the
* dialog surfaces a "Mehrere Zeitpläne" link that routes back to the
* legacy flat form).
* Hydrate a `WizardPayload` from a medication snapshot. Every schedule
* on the snapshot lands as its own `ScheduleDraft` so compose-mode
* surfaces the full list on the edit path. The flat mirror points at
* the first draft so the step components stay coherent.
*
* The legacy bridge (`inferCadenceFromLegacy`) infers a cadence from
* the `(daysOfWeek, intervalWeeks)` pair when the v1.5 `rrule` /
* `rollingIntervalDays` fields are absent.
*/
export function hydrateWizardPayload(initial: MedicationPayload): WizardPayload {
const base = emptyWizardPayload();
const parsedDose = parseDoseExpression(initial.dose ?? "");
const firstSchedule = initial.schedules[0];
const cadence = firstSchedule
? deriveCadenceFromSchedule(firstSchedule, initial.oneShot)
: { value: base.cadence, subControls: base.subControls };
const times =
firstSchedule?.timesOfDay && firstSchedule.timesOfDay.length > 0
? [...firstSchedule.timesOfDay]
: firstSchedule?.windowStart
? [firstSchedule.windowStart]
: base.timesOfDay;
const drafts: ScheduleDraft[] =
initial.schedules.length > 0
? initial.schedules.map((schedule) =>
hydrateScheduleDraft(schedule, initial.oneShot),
)
: [emptyScheduleDraft()];
const first = drafts[0];
return {
...base,
@@ -594,16 +849,28 @@ export function hydrateWizardPayload(initial: MedicationPayload): WizardPayload
doseAmount: parsedDose.amount,
doseUnit: parsedDose.unit || base.doseUnit,
treatmentRow: rowFromTreatment(initial.treatmentClass, initial.category),
mode: initial.oneShot ? "oneShot" : "recurring",
cadence: cadence.value,
subControls: cadence.subControls,
timesOfDay: times,
mode: first.mode,
cadence: first.cadence,
subControls: first.subControls,
timesOfDay: first.timesOfDay,
startsOn: initial.startsOn ?? base.startsOn,
endsOn: initial.endsOn,
notificationsEnabled: initial.notificationsEnabled ?? true,
schedules: drafts,
activeScheduleIndex: 0,
};
}
/**
* Decision the dialog uses to pick the landing step on edit-hydrate.
* Multi-schedule medications open on the list view so the user sees
* every parallel schedule immediately; single-schedule edits keep the
* Step 1 entry to preserve muscle memory.
*/
export function landingStepForEdit(payload: WizardPayload): number {
return payload.schedules.length > 1 ? 8 : 1;
}
function deriveCadenceFromSchedule(
schedule: MedicationPayload["schedules"][number],
oneShot: boolean,