fix(medications): page the side-effect list and name every GLP-1 medication in the timeline

This commit is contained in:
Marc-André Bombeck committed 2026-10-15 15:05:51 +02:00
1 parent 53e60f43f1
commit 7c905249fb
13 files changed
+228 -33

No files matched your search

@@ -87,8 +87,14 @@ function seedSideEffects(
}>,
) {
client.setQueryData(queryKeys.medicationSideEffects(medId), {
items: rows,
meta: { total: rows.length },
pages: [
{
items: rows,
meta: { total: rows.length },
from: "2026-01-01T00:00:00.000Z",
},
],
pageParams: [null],
});
}
@@ -131,13 +137,24 @@ async function executeSideEffectsQuery(
medicationId: string,
): Promise<void> {
const queryKey = queryKeys.medicationSideEffects(medicationId);
const queryFn = client.getQueryCache().find({ queryKey, exact: true })
?.options.queryFn;
if (typeof queryFn !== "function") {
const options = client.getQueryCache().find({ queryKey, exact: true })
?.options as
| {
queryFn?: unknown;
initialPageParam?: unknown;
getNextPageParam?: unknown;
}
| undefined;
if (typeof options?.queryFn !== "function") {
throw new Error("Side-effects query function was not registered");
}
try {
await client.fetchQuery({ queryKey, queryFn });
await client.fetchInfiniteQuery({
queryKey,
queryFn: options.queryFn as never,
initialPageParam: options.initialPageParam as never,
getNextPageParam: options.getNextPageParam as never,
});
} catch {
// The settled error is the state under test.
}
@@ -420,3 +437,88 @@ describe("<SideEffectsSection> — timeline rows", () => {
expect(html).toContain("Mittel");
});
});
describe("<SideEffectsSection> — paging", () => {
function sideEffectsResponse(
items: Array<{ id: string; occurredAt: string }>,
): Response {
return new Response(
JSON.stringify({
data: {
items: items.map((row) => ({
...row,
category: "GI",
entry: "NAUSEA",
severity: 2,
notes: null,
})),
meta: { total: items.length },
},
error: null,
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
it("offers a next page after a full one and asks for the entries before it", async () => {
const base = Date.parse("2026-05-20T12:00:00.000Z");
const firstPage = Array.from({ length: 50 }, (_, i) => ({
id: `se-${i}`,
occurredAt: new Date(base - i * 60_000).toISOString(),
}));
const oldest = firstPage[firstPage.length - 1];
const fetchMock = vi
.fn()
.mockResolvedValueOnce(sideEffectsResponse(firstPage))
// The boundary entry comes back once more and is shown once.
.mockResolvedValueOnce(
sideEffectsResponse([
oldest,
{ id: "se-older", occurredAt: "2026-05-01T08:00:00.000Z" },
]),
);
vi.stubGlobal("fetch", fetchMock);
const client = makeClient();
render(<SideEffectsSection medicationId="med-paged" />, client);
await executeSideEffectsQuery(client, "med-paged");
await waitForQueryStatus(client, "med-paged", "success");
const firstHtml = render(
<SideEffectsSection medicationId="med-paged" />,
client,
);
expect(firstHtml).toContain(en.medications.sideEffects.loadMore);
await client
.getQueryCache()
.find({
queryKey: queryKeys.medicationSideEffects("med-paged"),
exact: true,
})
?.fetch(undefined, { meta: { fetchMore: { direction: "forward" } } });
const secondUrl = new URL(
String(fetchMock.mock.calls[1]?.[0]),
"http://localhost",
);
expect(secondUrl.searchParams.get("to")).toBe(
new Date(Date.parse(oldest.occurredAt) + 1).toISOString(),
);
const firstUrl = new URL(
String(fetchMock.mock.calls[0]?.[0]),
"http://localhost",
);
expect(secondUrl.searchParams.get("from")).toBe(
firstUrl.searchParams.get("from"),
);
const secondHtml = render(
<SideEffectsSection medicationId="med-paged" />,
client,
);
// 50 + 1 new, the repeated boundary entry dropped; a short page ends it.
expect(secondHtml).toContain("(51)");
expect(secondHtml).not.toContain(en.medications.sideEffects.loadMore);
});
});
@@ -3,7 +3,11 @@
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
import { useId, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
useInfiniteQuery,
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { toast } from "sonner";
import { Loader2, Plus, Trash2 } from "lucide-react";
@@ -110,6 +114,16 @@ function entryI18nKey(entry: MedicationSideEffectEntry): string {
.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
}
/** Entries per page of the side-effect list. */
const SIDE_EFFECTS_PAGE_SIZE = 50;
interface SideEffectPageParam {
/** The window start, fixed when the first page loaded. */
from: string;
/** Exclusive upper bound: just after the oldest entry already shown. */
to: string;
}
export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
const { t } = useTranslations();
const { canWriteDomain, canManageDomain } = useRecordCapabilities();
@@ -133,18 +147,40 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
const listKey = queryKeys.medicationSideEffects(medicationId);
const { data, isLoading, isError, refetch } = useQuery({
// The last 30 days, newest first, one page at a time. The window is fixed
// when the first page loads; each further page asks for the entries before
// the oldest one shown (`to` is exclusive, so the boundary instant is
// re-asked one millisecond later and the overlap is dropped by id).
const {
data,
isLoading,
isError,
refetch,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
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`;
initialPageParam: null as SideEffectPageParam | null,
queryFn: async ({ pageParam }) => {
const to = pageParam ? new Date(pageParam.to) : new Date();
const from = pageParam
? new Date(pageParam.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=${SIDE_EFFECTS_PAGE_SIZE}`;
const { data: payload } = await apiFetchEnvelope<{
items: SideEffectRow[];
meta: { total: number };
}>(url);
return payload;
return { ...payload, from: from.toISOString() };
},
getNextPageParam: (lastPage): SideEffectPageParam | undefined => {
if (lastPage.items.length < SIDE_EFFECTS_PAGE_SIZE) return undefined;
const oldest = lastPage.items[lastPage.items.length - 1];
return {
from: lastPage.from,
to: new Date(Date.parse(oldest.occurredAt) + 1).toISOString(),
};
},
staleTime: 30 * 1000,
});
@@ -184,7 +220,18 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
},
});
const items = data?.items ?? [];
const items = useMemo(() => {
const seen = new Set<string>();
const out: SideEffectRow[] = [];
for (const page of data?.pages ?? []) {
for (const row of page.items) {
if (seen.has(row.id)) continue;
seen.add(row.id);
out.push(row);
}
}
return out;
}, [data]);
const filteredEntries = useMemo(
() => entriesByCategory(category),
@@ -363,6 +410,20 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
</li>
))}
</ul>
{hasNextPage ? (
<div className="flex justify-center">
<Button
variant="outline"
size="sm"
disabled={isFetchingNextPage}
onClick={() => void fetchNextPage()}
>
{isFetchingNextPage
? t("common.loading")
: t("medications.sideEffects.loadMore")}
</Button>
</div>
) : null}
</div>
)}