feat(medications): a sortable table view with an order you choose

The medications page gains a compact table beside the card view — one
row per medication with the same served-due status pill, next-intake
line, cadence-scaled adherence bars, dose-derived stock and the take
and skip actions the cards use, all from the payloads the cards
already read; the list response aggregates stock in the same round
trip. Columns sort tri-state with nulls last, the default order is
yours to arrange — the same drag dialog the dashboard and insights
use, applied to both views — and the chosen view and order persist
per user on their own settings column with field-scoped writes, so
toggling the view never touches the order. Inactive medications pin
to the end, the first column stays put under horizontal scroll, and
the loading skeleton follows the view you left.
This commit is contained in:
Marc-André Bombeck committed 2026-06-12 18:10:21 +02:00
1 parent d142a6ed31
commit e21dfd040e
31 files changed
+3382 -65

No files matched your search

@@ -0,0 +1,150 @@
/**
* v1.16.10 — toggle / reorder persistence wiring for the medications
* list presentation. Pins the PUT payload shape (field-scoped, version
* 1), the optimistic cache flip + rollback-on-failure for the view
* toggle, and the cache update on a saved order — without a React
* render, via the dependency-injected `run*` orchestration functions
* (the `use-medication-intake` testing convention).
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient } from "@tanstack/react-query";
vi.mock("@/lib/api/api-fetch", () => ({
apiGet: vi.fn(),
apiPut: vi.fn(),
}));
vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
import { apiPut } from "@/lib/api/api-fetch";
import { toast } from "sonner";
import {
runSetMedicationListView,
runSaveMedicationListOrder,
} from "@/lib/queries/use-medication-list-layout";
import { queryKeys } from "@/lib/query-keys";
import type { MedicationListLayout } from "@/lib/medication-list-layout";
const t = (key: string) => key;
function makeClient(): QueryClient {
return new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
});
}
beforeEach(() => {
vi.clearAllMocks();
});
describe("runSetMedicationListView", () => {
it("PUTs the field-scoped body and lands the server echo in the cache", async () => {
const queryClient = makeClient();
queryClient.setQueryData<MedicationListLayout>(
queryKeys.medicationListLayout(),
{ version: 1, view: "cards", order: ["med-a"] },
);
const saved: MedicationListLayout = {
version: 1,
view: "table",
order: ["med-a"],
};
vi.mocked(apiPut).mockResolvedValue(saved as never);
await runSetMedicationListView({ view: "table", queryClient, t });
// Field-scoped: only `view` rides the body — the server preserves
// the stored order (preserve-when-absent), so the client must not
// resend (and thereby race) it.
expect(apiPut).toHaveBeenCalledWith("/api/medications/layout", {
version: 1,
view: "table",
});
expect(
queryClient.getQueryData(queryKeys.medicationListLayout()),
).toEqual(saved);
expect(toast.error).not.toHaveBeenCalled();
});
it("flips the cache optimistically before the PUT resolves", async () => {
const queryClient = makeClient();
queryClient.setQueryData<MedicationListLayout>(
queryKeys.medicationListLayout(),
{ version: 1, view: "cards", order: [] },
);
let observedDuringFlight: MedicationListLayout | undefined;
vi.mocked(apiPut).mockImplementation((async () => {
observedDuringFlight = queryClient.getQueryData(
queryKeys.medicationListLayout(),
);
return { version: 1, view: "table", order: [] };
}) as never);
await runSetMedicationListView({ view: "table", queryClient, t });
expect(observedDuringFlight?.view).toBe("table");
});
it("rolls the cache back and surfaces a toast when the PUT fails", async () => {
const queryClient = makeClient();
const previous: MedicationListLayout = {
version: 1,
view: "cards",
order: ["med-a"],
};
queryClient.setQueryData(queryKeys.medicationListLayout(), previous);
vi.mocked(apiPut).mockRejectedValue(new Error("boom"));
await runSetMedicationListView({ view: "table", queryClient, t });
expect(
queryClient.getQueryData(queryKeys.medicationListLayout()),
).toEqual(previous);
expect(toast.error).toHaveBeenCalledWith("medications.viewSaveFailed");
});
});
describe("runSaveMedicationListOrder", () => {
it("PUTs the order-only body, caches the echo, and reports success", async () => {
const queryClient = makeClient();
const saved: MedicationListLayout = {
version: 1,
view: "table",
order: ["med-b", "med-a"],
};
vi.mocked(apiPut).mockResolvedValue(saved as never);
const ok = await runSaveMedicationListOrder({
order: ["med-b", "med-a"],
queryClient,
t,
});
expect(ok).toBe(true);
expect(apiPut).toHaveBeenCalledWith("/api/medications/layout", {
version: 1,
order: ["med-b", "med-a"],
});
expect(
queryClient.getQueryData(queryKeys.medicationListLayout()),
).toEqual(saved);
expect(toast.success).toHaveBeenCalledWith("medications.reorderSaved");
});
it("returns false and surfaces a toast when the PUT fails", async () => {
const queryClient = makeClient();
vi.mocked(apiPut).mockRejectedValue(new Error("boom"));
const ok = await runSaveMedicationListOrder({
order: ["med-a"],
queryClient,
t,
});
expect(ok).toBe(false);
expect(toast.error).toHaveBeenCalledWith(
"medications.reorderSaveFailed",
);
});
});
@@ -43,6 +43,19 @@ export interface MedicationComplianceSummaryEntry {
* lets the cards swap the skeleton for a quiet same-footprint fallback
* with a manual retry.
*/
/**
* The ONE fetcher behind the shared summary key. Both hooks below (and
* any future consumer) must ride this exact function so the key can
* never be registered with diverging fetch shapes.
*/
function fetchComplianceSummary(): Promise<
MedicationComplianceSummaryEntry[]
> {
return apiGet<MedicationComplianceSummaryEntry[]>(
"/api/medications/compliance",
);
}
export function useMedicationComplianceSummary(medicationId: string): {
data: MedicationComplianceSummaryEntry | null | undefined;
isError: boolean;
@@ -50,8 +63,7 @@ export function useMedicationComplianceSummary(medicationId: string): {
} {
const { data, isError, refetch } = useQuery({
queryKey: queryKeys.medicationComplianceSummary(),
queryFn: () =>
apiGet<MedicationComplianceSummaryEntry[]>("/api/medications/compliance"),
queryFn: fetchComplianceSummary,
// Dose actions invalidate the key explicitly through
// `medicationDependentKeys`; a shorter window would only re-fire the
// batch on every list visit. Matches the reminder-thresholds query
@@ -62,3 +74,20 @@ export function useMedicationComplianceSummary(medicationId: string): {
});
return { data, isError, refetch };
}
/**
* v1.16.10 — the whole batched array, for consumers that need every
* row at once (the table view's Therapietreue column sort). Same key,
* same fetcher, no `select` — the per-row hook and this one share one
* cache entry by construction.
*/
export function useMedicationComplianceSummaryAll(): {
data: MedicationComplianceSummaryEntry[] | undefined;
} {
const { data } = useQuery({
queryKey: queryKeys.medicationComplianceSummary(),
queryFn: fetchComplianceSummary,
staleTime: 5 * 60 * 1000,
});
return { data };
}
@@ -0,0 +1,116 @@
"use client";
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
import { useTranslations } from "@/lib/i18n/context";
import {
DEFAULT_MEDICATION_LIST_LAYOUT,
type MedicationListLayout,
type MedicationListView,
} from "@/lib/medication-list-layout";
type Translator = (
key: string,
params?: Record<string, string | number>,
) => string;
/**
* v1.16.10 — the /medications presentation preference (cards/table view
* + manual order), persisted per user through
* `GET`/`PUT /api/medications/layout`.
*
* The PUT is field-scoped: the server preserves whichever of `view` /
* `order` the body omits, so the two writers below each send only the
* field they own and can never wipe the other one.
*
* The orchestration lives in dependency-injected `run*` functions (the
* repo convention from `use-medication-intake.ts`) so the optimistic
* write + rollback contract is unit-testable without a React render.
*/
/**
* Flip the view optimistically (the toggle must feel instant), then
* persist. On failure the cache rolls back to the previous layout and
* a calm toast surfaces — the user is back on the view they came from.
*/
export async function runSetMedicationListView(deps: {
view: MedicationListView;
queryClient: QueryClient;
t: Translator;
}): Promise<void> {
const { view, queryClient, t } = deps;
const key = queryKeys.medicationListLayout();
const previous = queryClient.getQueryData<MedicationListLayout>(key);
queryClient.setQueryData<MedicationListLayout>(key, {
...(previous ?? DEFAULT_MEDICATION_LIST_LAYOUT),
view,
});
try {
const saved = await apiPut<MedicationListLayout>(
"/api/medications/layout",
{ version: 1, view },
);
if (saved) queryClient.setQueryData(key, saved);
} catch {
queryClient.setQueryData(key, previous);
toast.error(t("medications.viewSaveFailed"));
}
}
/**
* Persist a manual medication order (the reorder dialog's Save). Not
* optimistic — the dialog stays open until the PUT resolves, mirroring
* the dashboard layout section's explicit Save. Returns whether the
* save landed so the dialog knows to close.
*/
export async function runSaveMedicationListOrder(deps: {
order: string[];
queryClient: QueryClient;
t: Translator;
}): Promise<boolean> {
const { order, queryClient, t } = deps;
try {
const saved = await apiPut<MedicationListLayout>(
"/api/medications/layout",
{ version: 1, order },
);
if (saved) {
queryClient.setQueryData(queryKeys.medicationListLayout(), saved);
}
toast.success(t("medications.reorderSaved"));
return true;
} catch {
toast.error(t("medications.reorderSaveFailed"));
return false;
}
}
export function useMedicationListLayout(enabled: boolean = true): {
/** Resolved layout — defaults until the GET lands. */
layout: MedicationListLayout;
/** True while the preference GET is in flight (first load only). */
isLayoutLoading: boolean;
setView: (view: MedicationListView) => Promise<void>;
saveOrder: (order: string[]) => Promise<boolean>;
} {
const queryClient = useQueryClient();
const { t } = useTranslations();
const { data, isLoading } = useQuery({
queryKey: queryKeys.medicationListLayout(),
queryFn: () => apiGet<MedicationListLayout>("/api/medications/layout"),
staleTime: 5 * 60 * 1000,
enabled,
});
return {
layout: data ?? DEFAULT_MEDICATION_LIST_LAYOUT,
isLayoutLoading: enabled && isLoading,
setView: (view) => runSetMedicationListView({ view, queryClient, t }),
saveOrder: (order) =>
runSaveMedicationListOrder({ order, queryClient, t }),
};
}