diff --git a/messages/de.json b/messages/de.json index e6ce09d85..aa56088ab 100644 --- a/messages/de.json +++ b/messages/de.json @@ -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." } diff --git a/messages/en.json b/messages/en.json index 0d1c2030d..8f51cf488 100644 --- a/messages/en.json +++ b/messages/en.json @@ -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." } diff --git a/messages/es.json b/messages/es.json index d7c3ca060..87624a0d0 100644 --- a/messages/es.json +++ b/messages/es.json @@ -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." } diff --git a/messages/fr.json b/messages/fr.json index ac4f61a73..d910b843f 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -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." } diff --git a/messages/it.json b/messages/it.json index 2e29e239a..fbc65df37 100644 --- a/messages/it.json +++ b/messages/it.json @@ -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." } diff --git a/messages/pl.json b/messages/pl.json index 02f435542..4b6c3837c 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -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." } diff --git a/src/app/medications/page.tsx b/src/app/medications/page.tsx index 03ab9910f..3b1c9eeac 100644 --- a/src/app/medications/page.tsx +++ b/src/app/medications/page.tsx @@ -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, diff --git a/src/components/medications/wizard/MedicationWizardDialog.tsx b/src/components/medications/wizard/MedicationWizardDialog.tsx index 47b0a62cd..ca22c6150 100644 --- a/src/components/medications/wizard/MedicationWizardDialog.tsx +++ b/src/components/medications/wizard/MedicationWizardDialog.tsx @@ -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(1); const [payload, setPayload] = useState(() => mode === "edit" && initial ? hydrateWizardPayload(initial) : emptyWizardPayload(), ); + const [step, setStep] = useState(() => { + if (mode === "edit" && initial) { + const hydrated = hydrateWizardPayload(initial); + return landingStepForEdit(hydrated) as StepNumber; + } + return 1; + }); const [submitting, setSubmitting] = useState(false); const [submitError, setSubmitError] = useState(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({
+ {stepCaption && ( +

+ {stepCaption} +

+ )}

{stepTitle}

@@ -424,6 +476,9 @@ function WizardDialogShell({ mode={mode} initial={initial} submitError={submitError} + onEditSchedule={onEditSchedule} + onRemoveSchedule={onRemoveSchedule} + onAddSchedule={onAddSchedule} /> )}
diff --git a/src/components/medications/wizard/steps/Step8Summary.tsx b/src/components/medications/wizard/steps/Step8Summary.tsx index 0a8e2fd4b..b87236fa6 100644 --- a/src/components/medications/wizard/steps/Step8Summary.tsx +++ b/src/components/medications/wizard/steps/Step8Summary.tsx @@ -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 (
@@ -44,7 +64,76 @@ export function Step8Summary({

{t("medications.wizard.summary.title")}

-

{summary}

+

{topSummary}

+
+ +
+ {payload.schedules.map((draft, index) => { + const cardSummary = summariseScheduleDraft(draft, t); + return ( +
+

{cardSummary}

+
+ + +
+
+ ); + })} + + {!canRemove && ( +

+ {t("medications.wizard.compose.list.removeDisabled")} +

+ )} + + {payload.mode !== "oneShot" && ( + + )}
@@ -70,15 +159,6 @@ export function Step8Summary({ />
- {isMultiSchedule && ( -

- {t("medications.wizard.steps.step8.multiScheduleNote")} -

- )} - {submitError && (

= 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, @@ -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 { + 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,