mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
feat(medications,admin): the schedule's history is visible and invites count their uses
The schedule tab shows its eras as a collapsible timeline — current plan since its date, predecessors with their times and span — and a past era can be added manually for old history, with validation against overlaps and the live plan. Invite creation chooses one to fifty uses and the redemption list scrolls.
This commit is contained in:
1 parent
a62e00cfcd
commit
5639da4333
11 files changed
+1847
No files matched your search
@@ -50,6 +50,7 @@ import { MedicationDetailSection } from "@/components/medications/medication-det
|
||||
import { MedicationComplianceBars } from "@/components/medications/card-parts/medication-compliance-bars";
|
||||
import { DoseHistoryLedger } from "@/components/medications/dose-history-ledger";
|
||||
import { ScheduleTimesEditor } from "@/components/medications/scheduling/ScheduleTimesEditor";
|
||||
import { ScheduleHistoryTimeline } from "@/components/medications/scheduling/schedule-history-timeline";
|
||||
import type { DoseWindowEntry } from "@/components/medications/scheduling/dose-window";
|
||||
import { IntakeImportDialog } from "@/components/medications/intake-import-dialog";
|
||||
import { InventorySection } from "@/components/medications/sections/inventory-section";
|
||||
@@ -536,6 +537,24 @@ export function MedicationDetailTabs({
|
||||
</p>
|
||||
</div>
|
||||
</MedicationDetailSection>
|
||||
|
||||
{/* PLANHISTORIE — archived schedule eras (v1.16.3 effective
|
||||
dating) as a quiet collapsible timeline, plus the manual
|
||||
pre-tracking-era flow. Read-only for write-path archives. */}
|
||||
<MedicationDetailSection
|
||||
titleId="medication-zeitplan-history-heading"
|
||||
title={t("medications.detail.zeitplan.history.title")}
|
||||
dataSlot="medication-zeitplan-history"
|
||||
>
|
||||
<ScheduleHistoryTimeline
|
||||
medicationId={id}
|
||||
currentTimes={medication.schedules.flatMap((s) =>
|
||||
s.timesOfDay && s.timesOfDay.length > 0
|
||||
? s.timesOfDay
|
||||
: [s.windowStart],
|
||||
)}
|
||||
/>
|
||||
</MedicationDetailSection>
|
||||
</TabsContent>
|
||||
|
||||
{/* BESTAND — inventory readout + register / correct flows. */}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* v1.16.5 — schedule-history timeline SSR smoke tests.
|
||||
*
|
||||
* Project convention: `renderToStaticMarkup` + assertions against the
|
||||
* SSR string, react-query data seeded via `setQueryData` so `useQuery`
|
||||
* resolves synchronously (no `@testing-library/react` installed).
|
||||
* Interactive branches (toggle click, dialog submit, delete confirm)
|
||||
* are covered by the route tests + the `defaultExpanded` render path
|
||||
* here; the contracts pinned:
|
||||
*
|
||||
* 1. Live plan row: deduped/sorted times + "current since" line.
|
||||
* 2. Collapsed default: era rows absent, toggle carries the count.
|
||||
* 3. Expanded: each era renders times + date range; MANUAL eras get
|
||||
* the chip + delete affordance, ARCHIVED eras get neither.
|
||||
* 4. No revisions: no toggle, the add-era CTA still renders.
|
||||
* 5. `eraTimes` dedupes/sorts across entries and drops non-arrays.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import {
|
||||
ScheduleHistoryTimeline,
|
||||
eraTimes,
|
||||
type ScheduleRevisionRow,
|
||||
} from "@/components/medications/scheduling/schedule-history-timeline";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
const MED_ID = "med-1";
|
||||
|
||||
function makeClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
refetchOnMount: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function seed(
|
||||
client: QueryClient,
|
||||
data: { currentSince: string; revisions: ScheduleRevisionRow[] },
|
||||
) {
|
||||
client.setQueryData(queryKeys.medicationScheduleRevisions(MED_ID), data);
|
||||
}
|
||||
|
||||
function render(
|
||||
client: QueryClient,
|
||||
props?: Partial<Parameters<typeof ScheduleHistoryTimeline>[0]>,
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="de">
|
||||
<QueryClientProvider client={client}>
|
||||
<ScheduleHistoryTimeline
|
||||
medicationId={MED_ID}
|
||||
currentTimes={["20:00", "08:00", "08:00"]}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const MANUAL_ERA: ScheduleRevisionRow = {
|
||||
id: "rev-manual",
|
||||
validFrom: "2026-03-12T00:00:00.000Z",
|
||||
validUntil: "2026-06-01T00:00:00.000Z",
|
||||
source: "MANUAL",
|
||||
entries: [
|
||||
{
|
||||
timesOfDay: ["07:00", "19:00"],
|
||||
label: null,
|
||||
dose: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const ARCHIVED_ERA: ScheduleRevisionRow = {
|
||||
id: "rev-archived",
|
||||
validFrom: "2026-01-10T00:00:00.000Z",
|
||||
validUntil: "2026-03-12T00:00:00.000Z",
|
||||
source: "ARCHIVED",
|
||||
entries: [
|
||||
{
|
||||
timesOfDay: ["09:00"],
|
||||
label: "Morgens",
|
||||
dose: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("ScheduleHistoryTimeline", () => {
|
||||
it("renders the live plan with deduped, sorted times and the since line", () => {
|
||||
const client = makeClient();
|
||||
seed(client, { currentSince: "2026-06-01T00:00:00.000Z", revisions: [] });
|
||||
const html = render(client);
|
||||
expect(html).toContain("08:00 / 20:00");
|
||||
expect(html).toContain("Aktueller Plan seit");
|
||||
expect(html).toContain("01.06.2026");
|
||||
});
|
||||
|
||||
it("collapses predecessor eras by default and counts them in the toggle", () => {
|
||||
const client = makeClient();
|
||||
seed(client, {
|
||||
currentSince: "2026-06-01T00:00:00.000Z",
|
||||
revisions: [MANUAL_ERA, ARCHIVED_ERA],
|
||||
});
|
||||
const html = render(client);
|
||||
expect(html).toContain("2 frühere Ären anzeigen");
|
||||
expect(html).not.toContain("07:00 / 19:00");
|
||||
expect(html).not.toContain("zeitplan-history-era");
|
||||
});
|
||||
|
||||
it("expanded: era rows carry times, range, and MANUAL-only affordances", () => {
|
||||
const client = makeClient();
|
||||
seed(client, {
|
||||
currentSince: "2026-06-01T00:00:00.000Z",
|
||||
revisions: [MANUAL_ERA, ARCHIVED_ERA],
|
||||
});
|
||||
const html = render(client, { defaultExpanded: true });
|
||||
expect(html).toContain("07:00 / 19:00");
|
||||
expect(html).toContain("12.03.2026");
|
||||
expect(html).toContain("01.06.2026");
|
||||
expect(html).toContain("Manuell ergänzt");
|
||||
expect(html).toContain("Ära löschen");
|
||||
// Exactly ONE manual chip + ONE delete button — the archived era
|
||||
// renders read-only.
|
||||
expect(html.match(/zeitplan-history-manual-chip/g)).toHaveLength(1);
|
||||
expect(html.match(/zeitplan-history-delete/g)).toHaveLength(1);
|
||||
expect(html).toContain("Frühere Ären ausblenden");
|
||||
});
|
||||
|
||||
it("renders the add-era CTA without a toggle when no era exists", () => {
|
||||
const client = makeClient();
|
||||
seed(client, { currentSince: "2026-06-01T00:00:00.000Z", revisions: [] });
|
||||
const html = render(client);
|
||||
expect(html).toContain("Frühere Ära ergänzen");
|
||||
expect(html).not.toContain("zeitplan-history-toggle");
|
||||
});
|
||||
});
|
||||
|
||||
describe("eraTimes", () => {
|
||||
it("dedupes and sorts across entries", () => {
|
||||
expect(
|
||||
eraTimes([
|
||||
{
|
||||
timesOfDay: ["19:00", "07:00"],
|
||||
label: null,
|
||||
dose: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
},
|
||||
{
|
||||
timesOfDay: ["07:00", "12:00"],
|
||||
label: null,
|
||||
dose: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
},
|
||||
]),
|
||||
).toEqual(["07:00", "12:00", "19:00"]);
|
||||
});
|
||||
|
||||
it("tolerates a non-array timesOfDay", () => {
|
||||
expect(
|
||||
eraTimes([
|
||||
{
|
||||
timesOfDay: undefined as unknown as string[],
|
||||
label: null,
|
||||
dose: null,
|
||||
scheduleType: "PRN",
|
||||
},
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,530 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* v1.16.5 — Zeitplan-tab schedule-history timeline.
|
||||
*
|
||||
* The ledger and compliance tallies have minted past days against
|
||||
* archived schedule eras since v1.16.3; this is the missing management
|
||||
* surface. A quiet vertical timeline under the times editor:
|
||||
*
|
||||
* - the live plan as the accent node ("Aktueller Plan seit {Datum}",
|
||||
* with its times when the parent passes them),
|
||||
* - predecessor eras collapsed behind a count toggle — each row reads
|
||||
* "07:00 / 19:00 · 12.03.2026 – 01.06.2026", read-only,
|
||||
* - a "Frühere Ära ergänzen" flow for pre-tracking history: the
|
||||
* dialog collects daily times (the existing `TimesOfDayChips`
|
||||
* idiom) plus a Von/Bis date pair and POSTs a MANUAL revision,
|
||||
* - MANUAL eras carry a tinted chip and a delete affordance
|
||||
* (confirmed via AlertDialog); write-path archives are immutable
|
||||
* and render without one.
|
||||
*
|
||||
* The "Bis" date is the day the NEXT plan took over (exclusive bound) —
|
||||
* the dialog copy says so, and adjacency with the live plan is the
|
||||
* common case. Dates convert to instants at the browser's local
|
||||
* midnight, matching the user's wall clock like every schedule input.
|
||||
*/
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ChevronDown, History, Loader2, Plus, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { DateInput } from "@/components/ui/date-input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { TimesOfDayChips } from "@/components/medications/scheduling/TimesOfDayChips";
|
||||
import { apiDelete, apiGet, apiPost } from "@/lib/api/api-fetch";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface RevisionEntrySummary {
|
||||
timesOfDay: string[];
|
||||
label: string | null;
|
||||
dose: string | null;
|
||||
scheduleType: string;
|
||||
}
|
||||
|
||||
export interface ScheduleRevisionRow {
|
||||
id: string;
|
||||
validFrom: string;
|
||||
validUntil: string;
|
||||
source: "ARCHIVED" | "MANUAL";
|
||||
entries: RevisionEntrySummary[];
|
||||
}
|
||||
|
||||
interface ScheduleRevisionsResponse {
|
||||
currentSince: string;
|
||||
revisions: ScheduleRevisionRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dose-time readout of one era: the union of its entries' times,
|
||||
* deduped + sorted ("07:00 / 19:00"). PRN-only eras have no times —
|
||||
* the caller renders its own placeholder for an empty result.
|
||||
*/
|
||||
export function eraTimes(entries: RevisionEntrySummary[]): string[] {
|
||||
const all = entries.flatMap((e) =>
|
||||
Array.isArray(e.timesOfDay) ? e.timesOfDay : [],
|
||||
);
|
||||
return [...new Set(all)].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
export function ScheduleHistoryTimeline({
|
||||
medicationId,
|
||||
currentTimes,
|
||||
defaultExpanded = false,
|
||||
}: {
|
||||
medicationId: string;
|
||||
/** Live-plan dose times the parent already holds (deduped here). */
|
||||
currentTimes: string[];
|
||||
/** Start with the predecessor eras unfolded (default collapsed). */
|
||||
defaultExpanded?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const queryClient = useQueryClient();
|
||||
const [expanded, setExpanded] = useState(defaultExpanded);
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ScheduleRevisionRow | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const { data, isError } = useQuery({
|
||||
queryKey: queryKeys.medicationScheduleRevisions(medicationId),
|
||||
queryFn: async () =>
|
||||
apiGet<ScheduleRevisionsResponse>(
|
||||
`/api/medications/${medicationId}/schedule-revisions`,
|
||||
),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
const liveTimes = useMemo(
|
||||
() => [...new Set(currentTimes)].sort((a, b) => a.localeCompare(b)),
|
||||
[currentTimes],
|
||||
);
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: async (revisionId: string) => {
|
||||
await apiDelete(
|
||||
`/api/medications/${medicationId}/schedule-revisions/${revisionId}`,
|
||||
);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t("medications.detail.zeitplan.history.deletedToast"));
|
||||
// An era delete re-segments history — the ledger, compliance, and
|
||||
// cadence reads under this medication's prefix all go stale.
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.medicationDetail(medicationId),
|
||||
});
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("medications.detail.zeitplan.history.deleteError"));
|
||||
},
|
||||
});
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-sm" data-slot="zeitplan-history">
|
||||
{t("medications.detail.zeitplan.history.loadError")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (!data) return null;
|
||||
|
||||
const revisions = data.revisions;
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-slot="zeitplan-history">
|
||||
<ol className="space-y-0">
|
||||
{/* Live plan — the accent node. */}
|
||||
<TimelineRow
|
||||
dotClassName="bg-dracula-green"
|
||||
railVisible={expanded && revisions.length > 0}
|
||||
dataSlot="zeitplan-history-current"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-foreground text-sm font-medium tabular-nums">
|
||||
{liveTimes.length > 0
|
||||
? liveTimes.join(" / ")
|
||||
: t("medications.detail.zeitplan.history.noTimes")}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("medications.detail.zeitplan.history.currentSince", {
|
||||
date: fmt.date(data.currentSince),
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</TimelineRow>
|
||||
|
||||
{/* Predecessor eras — newest first, only when expanded. */}
|
||||
{expanded &&
|
||||
revisions.map((revision, idx) => {
|
||||
const times = eraTimes(revision.entries);
|
||||
return (
|
||||
<TimelineRow
|
||||
key={revision.id}
|
||||
dotClassName="bg-muted-foreground/50"
|
||||
railVisible={idx < revisions.length - 1}
|
||||
dataSlot="zeitplan-history-era"
|
||||
>
|
||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-foreground text-sm tabular-nums">
|
||||
{times.length > 0
|
||||
? times.join(" / ")
|
||||
: t("medications.detail.zeitplan.history.noTimes")}
|
||||
{revision.source === "MANUAL" && (
|
||||
<span
|
||||
className="border-dracula-purple/30 bg-dracula-purple/10 text-dracula-purple ml-2 inline-flex rounded-full border px-2 py-px align-middle text-[11px] font-medium"
|
||||
data-slot="zeitplan-history-manual-chip"
|
||||
>
|
||||
{t("medications.detail.zeitplan.history.manualChip")}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs tabular-nums">
|
||||
{fmt.date(revision.validFrom)}
|
||||
{" – "}
|
||||
{fmt.date(revision.validUntil)}
|
||||
</p>
|
||||
</div>
|
||||
{revision.source === "MANUAL" && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-dracula-red size-8 shrink-0"
|
||||
aria-label={t(
|
||||
"medications.detail.zeitplan.history.deleteAria",
|
||||
)}
|
||||
disabled={remove.isPending}
|
||||
onClick={() => setDeleteTarget(revision)}
|
||||
data-slot="zeitplan-history-delete"
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</TimelineRow>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{revisions.length > 0 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
aria-expanded={expanded}
|
||||
data-slot="zeitplan-history-toggle"
|
||||
>
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
{expanded
|
||||
? t("medications.detail.zeitplan.history.hideEras")
|
||||
: revisions.length === 1
|
||||
? t("medications.detail.zeitplan.history.showErasOne")
|
||||
: t("medications.detail.zeitplan.history.showErasOther", {
|
||||
count: revisions.length,
|
||||
})}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setAddOpen(true)}
|
||||
data-slot="zeitplan-history-add"
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{t("medications.detail.zeitplan.history.addEra")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<AddEraDialog
|
||||
medicationId={medicationId}
|
||||
open={addOpen}
|
||||
onOpenChange={setAddOpen}
|
||||
onCreated={() => setExpanded(true)}
|
||||
/>
|
||||
|
||||
<AlertDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null);
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("medications.detail.zeitplan.history.deleteConfirmTitle")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("medications.detail.zeitplan.history.deleteConfirmBody")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("medications.detail.zeitplan.history.cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
if (deleteTarget) remove.mutate(deleteTarget.id);
|
||||
setDeleteTarget(null);
|
||||
}}
|
||||
>
|
||||
{t("medications.detail.zeitplan.history.deleteConfirmAction")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One timeline node: dot + optional rail segment down to the next row.
|
||||
* The rail is a plain absolutely-positioned line (not `border-l` on the
|
||||
* list) so the last row never paints a dangling tail.
|
||||
*/
|
||||
function TimelineRow({
|
||||
dotClassName,
|
||||
railVisible,
|
||||
dataSlot,
|
||||
children,
|
||||
}: {
|
||||
dotClassName: string;
|
||||
railVisible: boolean;
|
||||
dataSlot: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<li className="relative pb-4 pl-5 last:pb-0" data-slot={dataSlot}>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"absolute top-1.5 left-0 size-2 rounded-full",
|
||||
dotClassName,
|
||||
)}
|
||||
/>
|
||||
{railVisible && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="bg-border/70 absolute top-4 bottom-0 left-[3.5px] w-px"
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Frühere Ära ergänzen" — collects daily dose times + the Von/Bis date
|
||||
* pair and POSTs a MANUAL schedule revision. Client-side guards mirror
|
||||
* the server validation (times present, Von before Bis); the server
|
||||
* stays authoritative for overlap / before-current-plan and its message
|
||||
* surfaces through the error toast.
|
||||
*/
|
||||
function AddEraDialog({
|
||||
medicationId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: {
|
||||
medicationId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreated: () => void;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [times, setTimes] = useState<string[]>([]);
|
||||
const [fromDate, setFromDate] = useState("");
|
||||
const [untilDate, setUntilDate] = useState("");
|
||||
const [validationKey, setValidationKey] = useState<
|
||||
"timesMissing" | "rangeMissing" | "rangeOrder" | null
|
||||
>(null);
|
||||
|
||||
function reset() {
|
||||
setTimes([]);
|
||||
setFromDate("");
|
||||
setUntilDate("");
|
||||
setValidationKey(null);
|
||||
}
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: async (input: {
|
||||
validFrom: string;
|
||||
validUntil: string;
|
||||
timesOfDay: string[];
|
||||
}) =>
|
||||
apiPost<ScheduleRevisionRow>(
|
||||
`/api/medications/${medicationId}/schedule-revisions`,
|
||||
input,
|
||||
),
|
||||
onSuccess: () => {
|
||||
toast.success(t("medications.detail.zeitplan.history.createdToast"));
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.medicationDetail(medicationId),
|
||||
});
|
||||
onOpenChange(false);
|
||||
reset();
|
||||
onCreated();
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("medications.detail.zeitplan.history.createError"));
|
||||
},
|
||||
});
|
||||
|
||||
function submit() {
|
||||
if (times.length === 0) {
|
||||
setValidationKey("timesMissing");
|
||||
return;
|
||||
}
|
||||
if (!fromDate || !untilDate) {
|
||||
setValidationKey("rangeMissing");
|
||||
return;
|
||||
}
|
||||
// Local-midnight instants: the era bounds follow the user's wall
|
||||
// clock, the same way every schedule time input does.
|
||||
const from = new Date(`${fromDate}T00:00:00`);
|
||||
const until = new Date(`${untilDate}T00:00:00`);
|
||||
if (from.getTime() >= until.getTime()) {
|
||||
setValidationKey("rangeOrder");
|
||||
return;
|
||||
}
|
||||
setValidationKey(null);
|
||||
create.mutate({
|
||||
validFrom: from.toISOString(),
|
||||
validUntil: until.toISOString(),
|
||||
timesOfDay: times,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
onOpenChange(next);
|
||||
if (!next) reset();
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t("medications.detail.zeitplan.history.addEraTitle")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("medications.detail.zeitplan.history.addEraDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (create.isPending) return;
|
||||
submit();
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-sm font-medium">
|
||||
{t("medications.detail.zeitplan.history.timesLabel")}
|
||||
</p>
|
||||
<TimesOfDayChips value={times} onChange={setTimes} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="zeitplan-history-from">
|
||||
{t("medications.detail.zeitplan.history.fromLabel")}
|
||||
</Label>
|
||||
<DateInput
|
||||
id="zeitplan-history-from"
|
||||
value={fromDate}
|
||||
onChange={(e) => setFromDate(e.target.value)}
|
||||
data-slot="zeitplan-history-from"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="zeitplan-history-until">
|
||||
{t("medications.detail.zeitplan.history.untilLabel")}
|
||||
</Label>
|
||||
<DateInput
|
||||
id="zeitplan-history-until"
|
||||
value={untilDate}
|
||||
onChange={(e) => setUntilDate(e.target.value)}
|
||||
data-slot="zeitplan-history-until"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("medications.detail.zeitplan.history.untilHint")}
|
||||
</p>
|
||||
{validationKey !== null && (
|
||||
<p
|
||||
className="text-dracula-red text-sm"
|
||||
role="alert"
|
||||
data-slot="zeitplan-history-validation"
|
||||
>
|
||||
{validationKey === "timesMissing" &&
|
||||
t("medications.detail.zeitplan.history.validationTimes")}
|
||||
{validationKey === "rangeMissing" &&
|
||||
t("medications.detail.zeitplan.history.validationRangeMissing")}
|
||||
{validationKey === "rangeOrder" &&
|
||||
t("medications.detail.zeitplan.history.validationRangeOrder")}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{t("medications.detail.zeitplan.history.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={create.isPending}
|
||||
aria-busy={create.isPending || undefined}
|
||||
data-slot="zeitplan-history-submit"
|
||||
>
|
||||
{create.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<History className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
{t("medications.detail.zeitplan.history.submit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user