release: v1.32.0 — hardening and scalability (#580)

* release: prepare v1.32.0

* test: stabilize water capture re-entry
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-07-22 04:14:15 +02:00
1 parent b01822be48
commit 62eb431d66
372 files changed
+25178 -8561

No files matched your search

@@ -0,0 +1,129 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
vi.mock("@tanstack/react-query", () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { username: "tester", timezone: "Europe/Berlin" },
}),
}));
vi.mock("@/components/ui/responsive-sheet", () => ({
ResponsiveSheet: ({
open,
children,
footer,
}: {
open: boolean;
children: React.ReactNode;
footer?: React.ReactNode;
}) =>
open ? (
<section>
{children}
{footer}
</section>
) : null,
}));
import {
LogIntakeDialog,
type LogIntakeMedication,
} from "../log-intake-dialog";
function medication(
id: string,
overrides: Partial<LogIntakeMedication> = {},
): LogIntakeMedication {
return {
id,
name: `Medication ${id}`,
dose: "5 mg",
active: true,
schedules: [],
lastTakenAt: null,
todayEventCount: 0,
nextDueAt: null,
nextDueOverdue: false,
...overrides,
};
}
function renderDialog(medications: LogIntakeMedication[]): string {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<LogIntakeDialog open onOpenChange={() => {}} medications={medications} />
</I18nProvider>,
);
}
function expectSelected(html: string, id: string): void {
expect(html).toMatch(
new RegExp(
`<option(?=[^>]*value="${id}")(?=[^>]*selected)[^>]*>|<option(?=[^>]*selected)(?=[^>]*value="${id}")[^>]*>`,
),
);
}
describe("<LogIntakeDialog> medication default", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-12T08:00:00.000Z"));
});
afterEach(() => {
vi.useRealTimers();
});
it("selects an overdue current-window medication ahead of array order", () => {
const html = renderDialog([
medication("first", { name: "Alpha" }),
medication("overdue", {
name: "Zulu",
schedules: [
{
windowStart: "08:00",
windowEnd: "09:00",
daysOfWeek: null,
label: null,
dose: null,
},
],
nextDueAt: "2026-05-12T06:00:00.000Z",
nextDueOverdue: true,
}),
]);
expectSelected(html, "overdue");
});
it("uses a stable alphabetical fallback instead of array order for future doses", () => {
const html = renderDialog([
medication("z", {
name: "Zolpidem",
schedules: [
{
windowStart: "08:00",
windowEnd: "11:00",
daysOfWeek: null,
label: null,
dose: null,
},
],
nextDueAt: "2099-05-13T07:00:00.000Z",
nextDueOverdue: false,
}),
medication("r", { name: "Ramipril" }),
]);
expectSelected(html, "r");
});
});
@@ -1,8 +1,44 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import type { ReactNode } from "react";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import en from "../../../../messages/en.json";
const errorCardCapture = vi.hoisted(() => ({
onRetry: undefined as (() => void) | undefined,
}));
type QueryErrorCardProps = {
title?: ReactNode;
description?: ReactNode;
onRetry?: () => void;
retryLabel?: string;
className?: string;
};
type QueryErrorCardModule = {
QueryErrorCard: (props: QueryErrorCardProps) => ReactNode;
};
vi.mock("@/components/ui/query-error-card", async () => {
// `vi.importActual` is required here so the wrapper can capture the retry
// callback while preserving the shared card's real accessible markup/copy.
const actual = await vi.importActual<QueryErrorCardModule>(
"@/components/ui/query-error-card",
);
return {
...actual,
QueryErrorCard: (props: QueryErrorCardProps) => {
errorCardCapture.onRetry = props.onRetry;
return actual.QueryErrorCard(props);
},
};
});
import { SideEffectsSection } from "@/components/medications/side-effects-section";
/**
@@ -32,6 +68,7 @@ function makeClient() {
// Synchronous resolution of seeded data is the test contract.
staleTime: Number.POSITIVE_INFINITY,
refetchOnMount: false,
retryOnMount: false,
},
},
});
@@ -49,7 +86,7 @@ function seedSideEffects(
notes: string | null;
}>,
) {
client.setQueryData(["medications", medId, "side-effects", "list"], {
client.setQueryData(queryKeys.medicationSideEffects(medId), {
items: rows,
meta: { total: rows.length },
});
@@ -69,6 +106,138 @@ function render(
beforeEach(() => {
vi.clearAllMocks();
errorCardCapture.onRetry = undefined;
});
afterEach(() => {
vi.unstubAllGlobals();
});
function emptySideEffectsResponse(): Response {
return new Response(
JSON.stringify({
data: { items: [], meta: { total: 0 } },
error: null,
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
}
async function executeSideEffectsQuery(
client: QueryClient,
medicationId: string,
): Promise<void> {
const queryKey = queryKeys.medicationSideEffects(medicationId);
const queryFn = client.getQueryCache().find({ queryKey, exact: true })
?.options.queryFn;
if (typeof queryFn !== "function") {
throw new Error("Side-effects query function was not registered");
}
try {
await client.fetchQuery({ queryKey, queryFn });
} catch {
// The settled error is the state under test.
}
}
async function waitForQueryStatus(
client: QueryClient,
medicationId: string,
status: "error" | "success",
): Promise<void> {
await vi.waitFor(() => {
expect(
client.getQueryState(queryKeys.medicationSideEffects(medicationId))
?.status,
).toBe(status);
});
}
describe("<SideEffectsSection> — failed reads", () => {
it.each([
{
failure: "HTTP",
response: () =>
Promise.resolve(
new Response(
JSON.stringify({ data: null, error: "service unavailable" }),
{
status: 503,
headers: { "Content-Type": "application/json" },
},
),
),
},
{
failure: "non-JSON",
response: () =>
Promise.resolve(
new Response("<html>not json</html>", {
status: 200,
headers: { "Content-Type": "text/html" },
}),
),
},
{
failure: "rejected",
response: () => Promise.reject(new TypeError("network unavailable")),
},
])(
"renders Retry instead of the empty state after a $failure failure",
async ({ response }) => {
const client = makeClient();
const fetchMock = vi.fn(response);
vi.stubGlobal("fetch", fetchMock);
render(<SideEffectsSection medicationId="med-failure" />, client);
await executeSideEffectsQuery(client, "med-failure");
await waitForQueryStatus(client, "med-failure", "error");
expect(fetchMock).toHaveBeenCalledTimes(1);
const html = render(
<SideEffectsSection medicationId="med-failure" />,
client,
);
expect(html).toContain('data-slot="query-error-card"');
expect(html).toContain('role="alert"');
expect(html).toContain(en.common.loadFailed);
expect(html).toContain(en.common.retry);
expect(html).not.toContain(en.medications.sideEffects.emptyState);
},
);
it("retries the failed query and renders the genuine empty response", async () => {
const client = makeClient();
const fetchMock = vi
.fn()
.mockRejectedValueOnce(new TypeError("network unavailable"))
.mockResolvedValueOnce(emptySideEffectsResponse());
vi.stubGlobal("fetch", fetchMock);
render(<SideEffectsSection medicationId="med-retry" />, client);
await executeSideEffectsQuery(client, "med-retry");
await waitForQueryStatus(client, "med-retry", "error");
const errorHtml = render(
<SideEffectsSection medicationId="med-retry" />,
client,
);
expect(errorHtml).toContain(en.common.retry);
expect(errorCardCapture.onRetry).toBeTypeOf("function");
errorCardCapture.onRetry?.();
await waitForQueryStatus(client, "med-retry", "success");
expect(fetchMock).toHaveBeenCalledTimes(2);
const recoveredHtml = render(
<SideEffectsSection medicationId="med-retry" />,
client,
);
expect(recoveredHtml).not.toContain('data-slot="query-error-card"');
expect(recoveredHtml).toContain(en.medications.sideEffects.emptyState);
});
});
describe("<SideEffectsSection> — surface render", () => {
@@ -34,6 +34,10 @@ import { Textarea } from "@/components/ui/textarea";
import { useTranslations } from "@/lib/i18n/context";
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
import { ApiError, apiPost } from "@/lib/api/api-fetch";
import {
MedicationIntakeImportError,
waitForMedicationIntakeImport,
} from "@/lib/medications/intake-import-poll";
export interface IntakeImportDialogProps {
medicationId: string | null;
@@ -104,11 +108,12 @@ export function IntakeImportDialog({
}
try {
const d = await apiPost<{
imported: number;
skippedDuplicates: number;
skippedInvalid: number;
const kickoff = await apiPost<{
jobId: string;
status: "queued";
statusUrl: string;
}>(`/api/medications/${medicationId}/intake/import`, data);
const d = await waitForMedicationIntakeImport(kickoff.statusUrl);
setResult(
t("medications.importResult", { imported: d.imported }) +
(d.skippedDuplicates > 0
@@ -121,6 +126,11 @@ export function IntakeImportDialog({
setResultType("success");
void invalidateKeys(queryClient, medicationDependentKeys);
} catch (err) {
if (err instanceof MedicationIntakeImportError) {
setResult(t("medications.importFailed"));
setResultType("error");
return;
}
if (!(err instanceof ApiError)) throw err;
setResult(err.message || t("medications.importFailed"));
setResultType("error");
@@ -32,22 +32,24 @@ import { DateTimeField } from "@/components/ui/date-time-field";
import { NativeSelect } from "@/components/ui/native-select";
import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
import { useAuth } from "@/hooks/use-auth";
import {
resolveMedicationSelectionId,
type DefaultMedicationOption,
} from "@/lib/medications/default-medication";
import type { ScheduleWindowInput } from "@/lib/medications/window-status";
import { formatDose } from "@/lib/medications/format-dose";
import {
runLogIntake,
runUndoIntake,
} from "@/components/medications/use-medication-intake";
interface LogIntakeSchedule {
windowStart: string;
interface LogIntakeSchedule extends ScheduleWindowInput {
label: string | null;
dose: string | null;
timesOfDay?: string[];
}
export interface LogIntakeMedication {
id: string;
name: string;
export interface LogIntakeMedication extends DefaultMedicationOption {
dose: string;
schedules: LogIntakeSchedule[];
}
@@ -115,11 +117,22 @@ export function LogIntakeDialog({
}: LogIntakeDialogProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const { user } = useAuth();
const userTz = user?.timezone || "Europe/Berlin";
const formId = useId();
const [medicationId, setMedicationId] = useState<string>(
() => medications[0]?.id ?? "",
const [medicationOverride, setMedicationOverride] = useState<string | null>(
null,
);
const [selectionNow] = useState(() => new Date());
const medicationId =
resolveMedicationSelectionId(
medications,
medicationOverride,
selectionNow,
undefined,
userTz,
) ?? "";
const [slot, setSlot] = useState<string>(NO_SLOT);
const [takenAt, setTakenAt] = useState<string>(() =>
toDateTimeLocal(new Date()),
@@ -156,7 +169,7 @@ export function LogIntakeDialog({
const dose = doseOverride ?? configuredDose;
function handleMedicationChange(id: string) {
setMedicationId(id);
setMedicationOverride(id);
// Reset the slot when switching medications — the prior slot may not
// exist on the new schedule. The dose override resets too so the new
// medication's configured dose flows through.
@@ -67,6 +67,17 @@ function render(
);
}
function actionMarkup(html: string, slot: string): string[] {
return (
html.match(
new RegExp(
`<button(?=[^>]*data-slot="${slot}")[^>]*>[\\s\\S]*?</button>`,
"g",
),
) ?? []
);
}
const MANUAL_ERA: ScheduleRevisionRow = {
id: "rev-manual",
validFrom: "2026-03-12T00:00:00.000Z",
@@ -142,6 +153,27 @@ describe("ScheduleHistoryTimeline", () => {
expect(html).toContain("Frühere Ären ausblenden");
});
it("uses non-overlapping 44px mobile era actions with compact icons", () => {
const client = makeClient();
seed(client, {
currentSince: "2026-06-01T00:00:00.000Z",
revisions: [MANUAL_ERA, ARCHIVED_ERA],
});
const html = render(client, { defaultExpanded: true });
const editButtons = actionMarkup(html, "zeitplan-history-edit");
const deleteButtons = actionMarkup(html, "zeitplan-history-delete");
expect(editButtons).toHaveLength(2);
expect(deleteButtons).toHaveLength(1);
for (const button of [...editButtons, ...deleteButtons]) {
expect(button).toContain("size-11");
expect(button).toContain("sm:size-8");
expect(button).toContain("size-4");
}
expect(editButtons[0]).toContain('aria-label="Ära bearbeiten"');
expect(deleteButtons[0]).toContain('aria-label="Ära löschen"');
expect(html).toContain('class="flex shrink-0 items-center"');
});
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: [] });
@@ -49,6 +49,7 @@ import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useTranslations } from "@/lib/i18n/context";
import { apiFetchRaw } from "@/lib/api/api-fetch";
import type { MedicationExtractionResult } from "@/lib/ai/coach/medication-extract-prompt";
@@ -135,7 +136,7 @@ export function NaturalLanguageExtractor({
abortRef.current = controller;
try {
const res = await fetch(endpoint, {
const res = await apiFetchRaw(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: trimmed, locale }),
@@ -225,7 +225,7 @@ export function ScheduleHistoryTimeline({
type="button"
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-foreground size-8"
className="text-muted-foreground hover:text-foreground size-11 sm:size-8"
aria-label={t(
"medications.detail.zeitplan.history.editAria",
)}
@@ -239,7 +239,7 @@ export function ScheduleHistoryTimeline({
type="button"
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive size-8"
className="text-muted-foreground hover:text-destructive size-11 sm:size-8"
aria-label={t(
"medications.detail.zeitplan.history.deleteAria",
)}
@@ -25,6 +25,7 @@ import { Download, Loader2, Upload } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
import { apiFetchRaw } from "@/lib/api/api-fetch";
export interface DataPortabilityRowProps {
medicationId: string;
@@ -33,7 +34,7 @@ export interface DataPortabilityRowProps {
}
async function downloadFromUrl(url: string, filename: string): Promise<void> {
const res = await fetch(url, { credentials: "include" });
const res = await apiFetchRaw(url, { credentials: "include" });
if (!res.ok) {
throw new Error(`Download failed (${res.status})`);
}
@@ -8,6 +8,7 @@ import { Loader2, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { QueryErrorCard } from "@/components/ui/query-error-card";
import {
AlertDialog,
AlertDialogAction,
@@ -42,7 +43,7 @@ import {
severityLikertLabel,
} from "@/lib/medications/side-effects/taxonomy";
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
import { apiDelete, apiPost } from "@/lib/api/api-fetch";
import { apiDelete, apiFetchEnvelope, apiPost } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
/**
@@ -128,19 +129,18 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
const listKey = queryKeys.medicationSideEffects(medicationId);
const { data, isLoading } = useQuery({
const { data, isLoading, isError, refetch } = useQuery({
queryKey: listKey,
queryFn: async () => {
// Last 30 days, newest-first.
const to = new Date();
const from = new Date(to.getTime() - 30 * 24 * 60 * 60 * 1000);
const url = `/api/medications/${medicationId}/side-effects?from=${encodeURIComponent(from.toISOString())}&to=${encodeURIComponent(to.toISOString())}&limit=100`;
const res = await fetch(url);
if (!res.ok) return { items: [] as SideEffectRow[], meta: { total: 0 } };
const json = (await res.json()) as {
data: { items: SideEffectRow[]; meta: { total: number } };
};
return json.data;
const { data: payload } = await apiFetchEnvelope<{
items: SideEffectRow[];
meta: { total: number };
}>(url);
return payload;
},
staleTime: 30 * 1000,
});
@@ -272,13 +272,17 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
</div>
)}
{!isLoading && items.length === 0 && (
{!isLoading && isError && (
<QueryErrorCard onRetry={() => void refetch()} />
)}
{!isLoading && !isError && items.length === 0 && (
<p className="text-muted-foreground py-1">
{t("medications.sideEffects.emptyState")}
</p>
)}
{!isLoading && items.length > 0 && (
{!isLoading && !isError && items.length > 0 && (
<div className="space-y-2">
<p className="text-muted-foreground text-xs tracking-wide uppercase">
{t("medications.sideEffects.recentTitle")}
@@ -47,6 +47,7 @@ import {
import { Button } from "@/components/ui/button";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { useTranslations } from "@/lib/i18n/context";
import { apiFetchRaw } from "@/lib/api/api-fetch";
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
import { NaturalLanguageExtractor } from "@/components/medications/scheduling/natural-language-extractor";
@@ -315,7 +316,7 @@ function WizardDialogShell({
: "/api/medications";
const method = mode === "edit" ? "PUT" : "POST";
const res = await fetch(url, {
const res = await apiFetchRaw(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),