perf(i18n,shell): ship one locale and stop blocking the first paint

The client bundle carries only the active locale — resolved on the
server and handed to the provider with no hydration flash, halving the
dashboard route to under a megabyte parsed (288 KiB gzip). The auth
shell renders the app chrome immediately instead of a spinner while the
session resolves in parallel, the widgets request folds into the
snapshot it duplicated, and insight pills prefetch their sub-pages —
a first visit to a sub-page lands in about ninety milliseconds instead
of nearly a second.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 02:19:27 +02:00
1 parent 9445d89b76
commit 3b480b9885
284 files changed
+6058 -5398

No files matched your search

@@ -58,7 +58,7 @@ describe("<AiQualitySection>", () => {
mockQueryState.isError = false;
const html = render(<AiQualitySection />);
// v1.4.33 IW7 — admin section renamed from "AI Quality" to
// "Insights Quality" per the Marc-Voice rule.
// "Insights Quality" per the project-voice rule.
expect(html).toContain("Insights Quality");
expect(html).toContain("No feedback yet");
});
@@ -35,8 +35,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -30,7 +30,7 @@ const sampleTokens = [
expiresAt: null,
createdAt: "2026-05-01T08:00:00Z",
revoked: false,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
@@ -54,8 +54,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -107,7 +107,7 @@ describe("ApiTokenOverviewSection — responsive", () => {
// All data points the desktop table shows must also appear in the
// mobile cards. Token name + username + a permission badge + the
// last-used/created labels are all present.
expect(html).toContain("marc"); // username
expect(html).toContain("testuser"); // username
expect(html).toContain("iOS app"); // token name
// F-19 (v1.4.19): the wildcard `*` permission renders as the
// human-readable "All" with a tooltip explaining the semantics,
@@ -4,7 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.19 A7 — `/admin/api-tokens` 4th-attempt scrollbar fix.
*
* the maintainer reported a "minimaler Scrollbar" still painting at the
* The maintainer reported a "minimaler Scrollbar" still painting at the
* bottom-right of the api-tokens page, even after the v1.4.18 phase
* A2 mobile-strip `no-scrollbar` fix. The remaining culprits are
* inside the section card itself: long token names, long usernames,
@@ -37,7 +37,7 @@ const sampleTokens = [
revoked: false,
user: {
id: "u1",
username: "marc-the-very-long-username-that-overflows",
username: "user-the-very-long-username-that-overflows",
},
},
];
@@ -62,8 +62,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -51,8 +51,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -35,7 +35,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "ADMIN" },
user: { id: "u1", username: "testuser", role: "ADMIN" },
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
@@ -108,7 +108,7 @@ describe("CoachFeedbackSection", () => {
expect(html).toContain('role="alert"');
});
// v1.4.25 W8 regression — Marc reported a layout shift on
// v1.4.25 W8 regression — the maintainer reported a layout shift on
// /admin/coach-feedback. Root cause was the title only rendering in the
// empty + data branches, so the section grew taller (loading → data)
// and snapped down. Lock the heading + outer-card structure across
@@ -64,8 +64,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -15,7 +15,7 @@ import { toCSV } from "@/lib/export";
* `createdAt` string, which Excel/LibreOffice misread once the `Z`
* suffix was stripped. This test pins:
*
* - The column order Marc requested:
* - The column order the maintainer requested:
* `timestamp → user → IP → location → provider → outcome` (email
* is absent from the audit-log API so it's intentionally skipped)
* followed by `action` + `details` for triage completeness.
@@ -80,7 +80,7 @@ function deterministicFormatter(iso: string): string {
}
describe("buildAuditLogCsvRecords", () => {
it("emits Marc's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
it("emits the maintainer's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
const entries: AuditCsvEntry[] = [
{
createdAt: "2026-05-11T09:05:00.000Z",
@@ -88,7 +88,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const [record] = buildAuditLogCsvRecords(
@@ -119,7 +119,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: null,
location: null,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -220,7 +220,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -234,12 +234,12 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
"Zeitpunkt,Benutzer,IP,Standort,Mobilfunkanbieter,Anbieter,Ergebnis,Aktion,Details",
);
expect(lines[1]).toBe(
'2026-05-11T09:05:00+00:00,marc,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
'2026-05-11T09:05:00+00:00,testuser,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
);
});
it("folds the GeoLite2 organisation string to the short DACH carrier label", () => {
// Marc's spec: the verbose MMDB org strings get a glanceable chip.
// The maintainer's spec: the verbose MMDB org strings get a glanceable chip.
// The CSV column carries the same folded text so a downstream
// spreadsheet matches what the admin overview screen renders.
const entries: AuditCsvEntry[] = [
@@ -251,7 +251,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Deutsche Telekom AG",
asn: 3320,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -261,7 +261,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Vodafone GmbH",
asn: 3209,
details: null,
user: { id: "u2", username: "marc" },
user: { id: "u2", username: "testuser" },
},
{
createdAt: "2026-05-11T09:07:00.000Z",
@@ -271,7 +271,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "1&1 Versatel GmbH",
asn: 8881,
details: null,
user: { id: "u3", username: "marc" },
user: { id: "u3", username: "testuser" },
},
{
createdAt: "2026-05-11T09:08:00.000Z",
@@ -281,7 +281,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Telefónica Germany GmbH & Co. OHG",
asn: 6805,
details: null,
user: { id: "u4", username: "marc" },
user: { id: "u4", username: "testuser" },
},
{
createdAt: "2026-05-11T09:09:00.000Z",
@@ -291,7 +291,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Google LLC",
asn: 15169,
details: null,
user: { id: "u5", username: "marc" },
user: { id: "u5", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -37,8 +37,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
timezone: "Europe/Berlin",
},
@@ -23,7 +23,7 @@ vi.mock("next/navigation", () => ({
const sampleEntries = [
{
id: "ev-1",
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
action: "auth.login.success",
ipAddress: "203.0.113.10",
location: "Berlin, DE",
@@ -55,8 +55,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
timezone: "Europe/Berlin",
},
@@ -55,7 +55,7 @@ describe("providerForAction", () => {
describe("iconForAuthProvider", () => {
it("maps each provider to the documented lucide glyph", () => {
// Marc's brief pinned the exact icon for each provider so the
// The maintainer's brief pinned the exact icon for each provider so the
// visual language stays consistent across the admin surface.
expect(iconForAuthProvider("password")).toBe(KeyRound);
expect(iconForAuthProvider("passkey")).toBe(Fingerprint);
@@ -30,8 +30,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -149,7 +149,7 @@ describe("admin sections — SSR smoke", () => {
it("<AiQualitySection> renders the empty-state when no summary exists", () => {
const html = render(<AiQualitySection />);
// v1.4.33 IW7 — section renamed from "AI Quality" to
// "Insights Quality" per the Marc-Voice rule (no "KI"/"AI" prefix
// "Insights Quality" per the project-voice rule (no "KI"/"AI" prefix
// in user-facing copy).
expect(html).toContain("Insights Quality");
expect(html).toContain("No feedback yet");
@@ -37,8 +37,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -74,8 +74,8 @@ describe("/admin overview composition", () => {
it("renders the welcome card with the admin's username", () => {
const html = render(<AdminOverviewPage />);
// `welcomeTitle` interpolates the username; the mocked auth hook
// returns "marc".
expect(html).toContain("Welcome, marc");
// returns "testuser".
expect(html).toContain("Welcome, testuser");
expect(html).toContain("admin-overview-welcome-heading");
});
@@ -41,8 +41,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -25,8 +25,8 @@ vi.mock("next/navigation", () => ({
const sampleUsers = [
{
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN" as const,
passkeyCount: 2,
createdAt: "2026-04-01T08:00:00Z",
@@ -57,8 +57,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
+6 -18
View File
@@ -8,6 +8,7 @@ import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { PasswordInput as SharedPasswordInput } from "@/components/ui/password-input";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
/**
* Re-export the canonical password input so admin sections have access to
@@ -228,9 +229,7 @@ export function useAdminSettings() {
return useQuery({
queryKey: queryKeys.adminSettings(),
queryFn: async () => {
const res = await fetch("/api/admin/settings");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminSettings;
return apiGet<AdminSettings>("/api/admin/settings");
},
});
}
@@ -240,14 +239,7 @@ export function useUpdateSettings() {
const { t } = useTranslations();
return useMutation({
mutationFn: async (data: Record<string, unknown>) => {
const res = await fetch("/api/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
await apiPut("/api/admin/settings", data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.adminSettings() });
@@ -423,7 +415,7 @@ export function carrierShortLabel(rawAsnOrg: string): string {
*
* Pulled out of the section component so the column order, header
* mapping, and provider/outcome derivation are reachable from a
* pure unit test without rendering the React tree. Marc's spec pins
* pure unit test without rendering the React tree. The maintainer's spec pins
* the column order at `timestamp → user → IP → location → provider
* → outcome` (email is absent from the audit-log API and would
* require schema/API changes that are out of scope). `action` and
@@ -526,9 +518,7 @@ export function useSystemStatus() {
return useQuery({
queryKey: queryKeys.adminStatus(),
queryFn: async () => {
const res = await fetch("/api/admin/status");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as SystemStatus;
return apiGet<SystemStatus>("/api/admin/status");
},
});
}
@@ -554,9 +544,7 @@ export function usePublicVersion() {
return useQuery({
queryKey: queryKeys.publicVersion(),
queryFn: async () => {
const res = await fetch("/api/version");
if (!res.ok) throw new Error("Failed to load version");
return (await res.json()).data as PublicVersion;
return apiGet<PublicVersion>("/api/version");
},
staleTime: 5 * 60_000,
});
+5 -9
View File
@@ -23,6 +23,7 @@ import { useQuery } from "@tanstack/react-query";
import { Sparkles, Loader2 } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { helpfulRateColour } from "./_shared";
interface FeedbackBucket {
@@ -42,11 +43,6 @@ interface FeedbackSummary {
buckets: FeedbackBucket[];
}
interface AiQualityResponse {
data: { summary: FeedbackSummary | null } | null;
error?: string | null;
}
const SEVERITY_TINT: Record<string, string> = {
info: "text-dracula-cyan",
suggestion: "text-dracula-purple",
@@ -61,10 +57,10 @@ export function AiQualitySection() {
const query = useQuery({
queryKey: queryKeys.adminAiQuality(),
queryFn: async () => {
const res = await fetch("/api/admin/ai-quality");
const json = (await res.json()) as AiQualityResponse;
if (!res.ok) throw new Error(json.error ?? "ai_quality_failed");
return json.data?.summary ?? null;
const data = await apiGet<{ summary: FeedbackSummary | null } | null>(
"/api/admin/ai-quality",
);
return data?.summary ?? null;
},
});
@@ -14,6 +14,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type ApiTokenInfo } from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
/**
* Wraps a string in `truncate` + tooltip so a long token name /
@@ -21,7 +22,7 @@ import { type ApiTokenInfo } from "./_shared";
*
* v1.4.19 phase A7 (4th attempt) — earlier fixes (column-hide,
* mobile card-list, mobile-strip `no-scrollbar`) cleared every
* scrollbar the maintainer reported except a residual painted bar he kept
* scrollbar the maintainer reported except a residual painted bar they kept
* seeing at the bottom-right. Production probe confirmed no
* remaining horizontal-overflow culprits, but the cards still
* carried `break-all` next to `truncate` (dead code; `white-space:
@@ -150,9 +151,7 @@ export function ApiTokenOverviewSection() {
const { data: tokens, isLoading } = useQuery({
queryKey: queryKeys.adminTokens(),
queryFn: async () => {
const res = await fetch("/api/admin/tokens");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as ApiTokenInfo[];
return apiGet<ApiTokenInfo[]>("/api/admin/tokens");
},
});
@@ -49,6 +49,7 @@ import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { WideEvent, LogLevel } from "@/lib/logging/types";
import { apiGet } from "@/lib/api/api-fetch";
type RangePreset = "15m" | "1h" | "6h" | "all";
@@ -103,9 +104,7 @@ export function AppLogPreviewSection() {
const { data, isLoading, refetch, isFetching } = useQuery({
queryKey: queryKeys.adminAppLogs(traceId, actionFilter, level, range),
queryFn: async () => {
const res = await fetch(`/api/admin/app-logs?${params.toString()}`);
if (!res.ok) throw new Error("Failed to load app logs");
return (await res.json()).data as AppLogsResponse;
return apiGet<AppLogsResponse>(`/api/admin/app-logs?${params.toString()}`);
},
refetchInterval: 30_000,
});
+4 -13
View File
@@ -6,7 +6,8 @@ import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { SettingsToggle, getApiErrorMessage } from "./_shared";
import { SettingsToggle } from "./_shared";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
/**
* v1.4.31 — operator-side panel for the six assistant feature
@@ -48,9 +49,7 @@ function useAssistantFlags() {
return useQuery({
queryKey: queryKeys.adminAssistantFlags(),
queryFn: async () => {
const res = await fetch("/api/admin/settings/assistant-flags");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AssistantFlagsResponse;
return apiGet<AssistantFlagsResponse>("/api/admin/settings/assistant-flags");
},
});
}
@@ -62,15 +61,7 @@ function useUpdateAssistantFlags() {
mutationFn: async (
patch: Partial<AssistantFlagsResponse["raw"]>,
): Promise<AssistantFlagsResponse> => {
const res = await fetch("/api/admin/settings/assistant-flags", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as AssistantFlagsResponse;
return apiPut<AssistantFlagsResponse>("/api/admin/settings/assistant-flags", patch);
},
onSuccess: (data) => {
client.setQueryData(
+15 -30
View File
@@ -44,6 +44,7 @@ import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { BackupRow, BackupsList } from "@/types/backups";
import { getApiErrorMessage } from "./_shared";
import { apiFetch, apiFetchRaw, apiGet, apiPost } from "@/lib/api/api-fetch";
/**
* Typed-confirmation dialog for restore. The destructive Restore button
@@ -175,19 +176,13 @@ export function BackupsSection() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminBackups(),
queryFn: async () => {
const res = await fetch("/api/admin/backups");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as BackupsList;
return apiGet<BackupsList>("/api/admin/backups");
},
});
const runBackup = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/backups/run", { method: "POST" });
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as { jobId: string | null };
return apiPost<{ jobId: string | null }>("/api/admin/backups/run");
},
onSuccess: () => {
toast.success(t("admin.section.backups.runEnqueued"));
@@ -219,14 +214,9 @@ export function BackupsSection() {
mutationFn: async (file: File) => {
const fd = new FormData();
fd.append("file", file);
const res = await fetch("/api/admin/backups/upload", {
method: "POST",
body: fd,
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as {
// apiFetch with a raw init: the multipart body must NOT be JSON
// re-encoded, so the verb helper (which JSON-stringifies) is out.
return apiFetch<{
id: string;
valid: true;
summary: {
@@ -237,7 +227,7 @@ export function BackupsSection() {
cycles?: number;
cycleDayLogs?: number;
};
};
}>("/api/admin/backups/upload", { method: "POST", body: fd });
},
onSuccess: (data) => {
const total =
@@ -280,18 +270,11 @@ export function BackupsSection() {
// destructive transaction. Include the row id so two different
// backups can both be restored independently in the same minute.
const idempotencyKey = `restore-${row.id}-${crypto.randomUUID()}`;
const res = await fetch(`/api/admin/backups/${row.id}/restore`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({ confirm: "RESTORE" }),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as { restored: true };
return apiPost<{ restored: true }>(
`/api/admin/backups/${row.id}/restore`,
{ confirm: "RESTORE" },
{ headers: { "Idempotency-Key": idempotencyKey } },
);
},
onSuccess: () => {
toast.success(t("admin.section.backups.restoreSuccess"));
@@ -312,7 +295,9 @@ export function BackupsSection() {
async function handleDownload(row: BackupRow) {
setDownloadingId(row.id);
try {
const res = await fetch(`/api/admin/backups/${row.id}/download`);
// apiFetchRaw: the download needs the raw Response for the blob +
// the Content-Disposition filename header.
const res = await apiFetchRaw(`/api/admin/backups/${row.id}/download`);
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
@@ -23,6 +23,7 @@ import { Loader2, Sparkles } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { helpfulRateColour } from "./_shared";
interface CoachFeedbackBucket {
@@ -41,11 +42,6 @@ interface FeedbackSummary {
coachBuckets?: CoachFeedbackBucket[];
}
interface CoachFeedbackResponse {
data: { summary: FeedbackSummary | null } | null;
error?: string | null;
}
export function CoachFeedbackSection() {
const { t } = useTranslations();
const fmt = useFormatters();
@@ -53,10 +49,10 @@ export function CoachFeedbackSection() {
const query = useQuery({
queryKey: queryKeys.adminCoachFeedback(),
queryFn: async () => {
const res = await fetch("/api/admin/ai-quality");
const json = (await res.json()) as CoachFeedbackResponse;
if (!res.ok) throw new Error(json.error ?? "coach_feedback_failed");
return json.data?.summary ?? null;
const data = await apiGet<{ summary: FeedbackSummary | null } | null>(
"/api/admin/ai-quality",
);
return data?.summary ?? null;
},
});
@@ -69,7 +65,7 @@ export function CoachFeedbackSection() {
// baseline stays at a constant Y-offset. Previously the loading branch
// returned a thin flex-row stub and the error branch a p-4 alert with
// NO heading, which made the entire section snap downward when the
// fetched data resolved — Marc reported the visible layout shift on
// fetched data resolved — the maintainer reported the visible layout shift on
// /admin/coach-feedback. Mirrors the canonical structure used by
// <SystemStatusSection> (header outside the fetch-state branch).
return (
+3 -9
View File
@@ -16,6 +16,7 @@ import {
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { apiDelete } from "@/lib/api/api-fetch";
export function DangerZoneSection() {
const { t } = useTranslations();
@@ -24,14 +25,7 @@ export function DangerZoneSection() {
const wipeAllData = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/data", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirm: "DELETE ALL" }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
return json.data as {
return apiDelete<{
measurements: number;
intakeEvents: number;
medications: number;
@@ -41,7 +35,7 @@ export function DangerZoneSection() {
notificationChannels: number;
pushSubscriptions: number;
telegramScheduledDeletions: number;
};
}>("/api/admin/data", { confirm: "DELETE ALL" });
},
onSuccess: (data) => {
queryClient.invalidateQueries();
@@ -38,9 +38,9 @@ import {
type FeedbackItem,
type FeedbackListResponse,
type FeedbackStatusType,
getApiErrorMessage,
useSystemStatus,
} from "./_shared";
import { apiDelete, apiGet, apiPatch, apiPost } from "@/lib/api/api-fetch";
export function FeedbackInboxSection() {
const { t } = useTranslations();
@@ -54,11 +54,7 @@ export function FeedbackInboxSection() {
const { data, isLoading } = useQuery({
queryKey: queryKeys.adminFeedback(activeStatus),
queryFn: async () => {
const res = await fetch(
`/api/admin/feedback?status=${activeStatus}&limit=100`,
);
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as FeedbackListResponse;
return apiGet<FeedbackListResponse>(`/api/admin/feedback?status=${activeStatus}&limit=100`);
},
});
@@ -259,12 +255,7 @@ function FeedbackDetailDialog({
status?: FeedbackStatusType;
adminNote?: string | null;
}) => {
const res = await fetch(`/api/admin/feedback/${item.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
await apiPatch(`/api/admin/feedback/${item.id}`, payload);
},
onSuccess: (_, vars) => {
onMutated();
@@ -281,10 +272,7 @@ function FeedbackDetailDialog({
const archive = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/admin/feedback/${item.id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
await apiDelete(`/api/admin/feedback/${item.id}`);
},
onSuccess: () => {
onMutated();
@@ -299,11 +287,7 @@ function FeedbackDetailDialog({
const publish = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/admin/feedback/${item.id}/github`, {
method: "POST",
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
return (await res.json()).data as { issueUrl: string };
return apiPost<{ issueUrl: string }>(`/api/admin/feedback/${item.id}/github`);
},
onSuccess: (data) => {
setIssueUrl(data.issueUrl);
+5 -9
View File
@@ -11,10 +11,10 @@ import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
SettingsToggle,
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function GlitchtipSection() {
const { t } = useTranslations();
@@ -35,14 +35,10 @@ export function GlitchtipSection() {
const testGlitchtip = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/monitoring/glitchtip-test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as { data?: { message?: string } };
return json.data?.message ?? t("admin.monitoringTestSuccess");
const data = await apiPost<{ message?: string } | undefined>(
"/api/admin/monitoring/glitchtip-test",
);
return data?.message ?? t("admin.monitoringTestSuccess");
},
onSuccess: (message) => {
toast.success(message);
+2 -3
View File
@@ -39,6 +39,7 @@ import { useMemo } from "react";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { Skeleton } from "@/components/ui/skeleton";
import { apiGet } from "@/lib/api/api-fetch";
interface HostMetricsApiSample {
capturedAt: string;
@@ -134,9 +135,7 @@ export function HostMetricsChart() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminHostMetrics("2h"),
queryFn: async () => {
const res = await fetch("/api/admin/host-metrics?since=2h");
if (!res.ok) throw new Error("Failed to load host metrics");
return (await res.json()).data as HostMetricsApiResponse;
return apiGet<HostMetricsApiResponse>("/api/admin/host-metrics?since=2h");
},
// 60s matches the sampler cadence — anything faster would just
// re-render the same data.
+20 -16
View File
@@ -79,6 +79,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { cn } from "@/lib/utils";
import { apiDelete, apiGet, apiPost } from "@/lib/api/api-fetch";
interface InviteRedemptionEntry {
id: string;
@@ -187,9 +188,7 @@ export function InviteTokensSection() {
const { data: invites, isError } = useQuery({
queryKey: queryKeys.adminInvites(),
queryFn: async () => {
const res = await fetch("/api/admin/invites");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminInvite[];
return apiGet<AdminInvite[]>("/api/admin/invites");
},
});
@@ -199,13 +198,10 @@ export function InviteTokensSection() {
expiresInDays: number;
maxUses: number;
}): Promise<MintedInvite> => {
const res = await fetch("/api/admin/invites", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()).data as Omit<MintedInvite, "qrDataUrl">;
const data = await apiPost<Omit<MintedInvite, "qrDataUrl">>(
"/api/admin/invites",
input,
);
// Lazy chunk: qrcode is only ever needed right here, at mint time.
const QRCode = (await import("qrcode")).default;
const qrDataUrl = await QRCode.toDataURL(data.url, {
@@ -226,10 +222,7 @@ export function InviteTokensSection() {
const revoke = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/admin/invites/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await apiDelete(`/api/admin/invites/${id}`);
},
onSuccess: () => {
toast.success(t("admin.invites.revokedToast"));
@@ -549,6 +542,16 @@ export function InviteTokensSection() {
{t("admin.invites.createDescription")}
</DialogDescription>
</DialogHeader>
{/* v1.16.4 — a real form so Enter in the max-uses field
submits; mirrors the intake-edit dialog convention. */}
<form
onSubmit={(e) => {
e.preventDefault();
if (create.isPending) return;
submitCreate();
}}
className="space-y-4"
>
<div className="space-y-5">
<fieldset>
<legend className="text-sm font-medium">
@@ -600,9 +603,9 @@ export function InviteTokensSection() {
</div>
<DialogFooter>
<Button
type="button"
type="submit"
disabled={create.isPending}
onClick={submitCreate}
aria-busy={create.isPending || undefined}
data-testid="admin-invites-submit-create"
>
{create.isPending ? (
@@ -616,6 +619,7 @@ export function InviteTokensSection() {
{t("admin.invites.createConfirm")}
</Button>
</DialogFooter>
</form>
</>
) : (
<>
@@ -36,6 +36,7 @@ import {
useAuthActionLabels,
useAuthProviderLabels,
} from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
type DateRangePreset = "all" | "24h" | "7d" | "30d";
type PerPageValue = 25 | 50 | 100;
@@ -130,9 +131,7 @@ export function LoginOverviewSection() {
if (filter === "failed") {
params.set("action", "auth.login.failed");
}
const res = await fetch(`/api/admin/audit-log?${params.toString()}`);
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AuditLogResponse;
return apiGet<AuditLogResponse>(`/api/admin/audit-log?${params.toString()}`);
},
});
@@ -140,9 +139,7 @@ export function LoginOverviewSection() {
const { data: actionsData } = useQuery({
queryKey: queryKeys.adminAuditActions(),
queryFn: async () => {
const res = await fetch("/api/admin/audit-log/actions");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as { actions: string[] };
return apiGet<{ actions: string[] }>("/api/admin/audit-log/actions");
},
staleTime: 5 * 60_000,
});
@@ -23,6 +23,7 @@ import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type AdminAuditEntry, useAuthActionLabels } from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
const PREVIEW_LIMIT = 10;
@@ -37,11 +38,7 @@ export function RecentAuditPreview() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminAuditOverview(),
queryFn: async () => {
const res = await fetch(
`/api/admin/audit-log?limit=${PREVIEW_LIMIT}&filter=auth`,
);
if (!res.ok) throw new Error("Failed to load audit log");
return (await res.json()).data as AuditLogResponse;
return apiGet<AuditLogResponse>(`/api/admin/audit-log?limit=${PREVIEW_LIMIT}&filter=auth`);
},
// Avoid hitting the DB on every page focus; the overview is the
// type of page admins keep open and re-render frequently.
+35 -50
View File
@@ -9,11 +9,8 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { useAdminSettings, useUpdateSettings } from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function RemindersSection() {
const { t } = useTranslations();
@@ -28,23 +25,17 @@ export function RemindersSection() {
const testNotification = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/notifications/test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as {
data?: {
message?: string;
results?: Array<{
channel: string;
success: boolean;
error?: string;
}>;
};
};
return json.data;
return apiPost<
| {
message?: string;
results?: Array<{
channel: string;
success: boolean;
error?: string;
}>;
}
| undefined
>("/api/admin/notifications/test");
},
onSuccess: (data) => {
const hasFailures = data?.results?.some((r) => !r.success);
@@ -65,35 +56,29 @@ export function RemindersSection() {
const reminderCheck = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/notifications/reminder-check", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as {
data?: {
message?: string;
medications?: Array<{
name: string;
dose: string;
user: string;
localTime: string;
dayOfWeek: string;
notificationsEnabled: boolean;
schedules: Array<{
window: string;
days: string;
status: string;
label: string;
notificationSent?: boolean;
return apiPost<
| {
message?: string;
medications?: Array<{
name: string;
dose: string;
user: string;
localTime: string;
dayOfWeek: string;
notificationsEnabled: boolean;
schedules: Array<{
window: string;
days: string;
status: string;
label: string;
notificationSent?: boolean;
}>;
eventsToday: number;
}>;
eventsToday: number;
}>;
notificationsSent?: number;
};
};
return json.data;
notificationsSent?: number;
}
| undefined
>("/api/admin/notifications/reminder-check");
},
onSuccess: (data) => {
toast.success(data?.message ?? t("admin.reminderCheckSuccess"));
+5 -9
View File
@@ -11,10 +11,10 @@ import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
SettingsToggle,
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function UmamiSection() {
const { t } = useTranslations();
@@ -38,14 +38,10 @@ export function UmamiSection() {
const testUmami = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/monitoring/umami-test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as { data?: { message?: string } };
return json.data?.message ?? t("admin.monitoringTestSuccess");
const data = await apiPost<{ message?: string } | undefined>(
"/api/admin/monitoring/umami-test",
);
return data?.message ?? t("admin.monitoringTestSuccess");
},
onSuccess: (message) => {
toast.success(message);
@@ -25,6 +25,7 @@ import { formatDate } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type AdminUser, PasswordInput } from "./_shared";
import { apiGet, apiPost, apiPut } from "@/lib/api/api-fetch";
/**
* Filter values for the v1.5 users sub-route. The User model does NOT
@@ -52,9 +53,7 @@ export function UserManagementSection() {
const { data: users } = useQuery({
queryKey: queryKeys.adminUsers(),
queryFn: async () => {
const res = await fetch("/api/admin/users");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminUser[];
return apiGet<AdminUser[]>("/api/admin/users");
},
});
@@ -73,13 +72,7 @@ export function UserManagementSection() {
id: string;
data: Record<string, unknown>;
}) => {
const res = await fetch(`/api/admin/users/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
await apiPut(`/api/admin/users/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.adminUsers() });
@@ -97,13 +90,7 @@ export function UserManagementSection() {
const resetPw = useMutation({
mutationFn: async ({ id, password }: { id: string; password: string }) => {
const res = await fetch(`/api/admin/users/${id}/reset-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
await apiPost(`/api/admin/users/${id}/reset-password`, { password });
},
onSuccess: () => {
setResetMsg(t("admin.passwordReset"));
@@ -116,12 +103,9 @@ export function UserManagementSection() {
const forceLogout = useMutation({
mutationFn: async ({ id }: { id: string }) => {
const res = await fetch(`/api/admin/users/${id}/force-logout`, {
method: "POST",
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
return json.data as { sessionsRevoked: number };
return apiPost<{ sessionsRevoked: number }>(
`/api/admin/users/${id}/force-logout`,
);
},
onSuccess: (result, vars) => {
const username =
@@ -421,7 +405,22 @@ export function UserManagementSection() {
<h3 className="mb-3 text-sm font-semibold">
{t("admin.editUserTitle", { name: editingUser.username })}
</h3>
<div className="space-y-3">
{/* v1.16.4 — a real form so Enter in the username / email
fields submits; mirrors the dialog convention. */}
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
if (updateUser.isPending) return;
updateUser.mutate({
id: editingUser.id,
data: {
username: editUsername,
email: editEmail || null,
},
});
}}
>
<div className="space-y-1">
<Label htmlFor="edit-username">{t("auth.username")}</Label>
<Input
@@ -448,17 +447,10 @@ export function UserManagementSection() {
</div>
<div className="flex gap-2">
<Button
type="submit"
size="sm"
disabled={updateUser.isPending}
onClick={() =>
updateUser.mutate({
id: editingUser.id,
data: {
username: editUsername,
email: editEmail || null,
},
})
}
aria-busy={updateUser.isPending || undefined}
>
{updateUser.isPending && (
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
@@ -466,6 +458,7 @@ export function UserManagementSection() {
{t("common.save")}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setEditingUser(null)}
@@ -478,7 +471,7 @@ export function UserManagementSection() {
</span>
)}
</div>
</div>
</form>
</div>
)}
@@ -21,6 +21,7 @@ import { useQuery } from "@tanstack/react-query";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiGet } from "@/lib/api/api-fetch";
import { StatusItem, usePublicVersion } from "./_shared";
type CheckUpdatesResult =
@@ -41,11 +42,13 @@ type CheckUpdatesResult =
| { status: "unknown"; current: string; reason: string };
async function fetchUpdateCheck(): Promise<CheckUpdatesResult> {
const res = await fetch("/api/version/check-updates");
if (!res.ok) {
return { status: "unknown", current: "", reason: `http_${res.status}` };
try {
return await apiGet<CheckUpdatesResult>("/api/version/check-updates");
} catch (err) {
const reason =
err instanceof ApiError ? `http_${err.status}` : "network_error";
return { status: "unknown", current: "", reason };
}
return (await res.json()).data as CheckUpdatesResult;
}
function shortSha(sha: string | null): string | null {
+2 -4
View File
@@ -26,6 +26,7 @@ import { createContext, useContext, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
export interface AppSettings {
/** Whether the admin has enabled in-app bug-report / feedback submission. */
@@ -60,10 +61,7 @@ export function AppSettingsProvider({ children }: { children: ReactNode }) {
queryKey: queryKeys.bugreportStatus(),
enabled: isAuthenticated,
queryFn: async () => {
const res = await fetch("/api/bugreport/status");
if (!res.ok) throw new Error("Failed to load bug-report status");
const json = (await res.json()) as { data: BugReportStatusPayload };
return json.data;
return apiGet<BugReportStatusPayload>("/api/bugreport/status");
},
staleTime: 5 * 60 * 1000,
});
@@ -1,5 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
// vi.doMock below invalidates the module registry, so the re-imported
// provider gets a fresh (unprimed) locale cache — pass the DE bundle
// explicitly instead of relying on the vitest.setup.ts seeding.
import deMessages from "../../../../messages/de.json";
/**
* Sparse-data render contract.
@@ -48,7 +52,7 @@ async function renderChart(data: unknown[]): Promise<string> {
const { HealthChart } = await import("../health-chart");
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<HealthChart types={["PULSE"]} title="Pulse" unit="bpm" />
</I18nProvider>,
);
@@ -1,5 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
// vi.doMock below invalidates the module registry, so the re-imported
// provider gets a fresh (unprimed) locale cache — pass the DE bundle
// explicitly instead of relying on the vitest.setup.ts seeding.
import deMessages from "../../../../messages/de.json";
/**
* v1.4.43 W11-M6 — chart empty-window state.
@@ -49,7 +53,7 @@ describe("<HealthChart> — empty-window state (W11-M6)", () => {
const { HealthChart } = await import("../health-chart");
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<HealthChart types={["PULSE"]} title="Pulse" unit="bpm" />
</I18nProvider>,
);
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
/**
* v1.4.18 — Default overlay state on chart wrappers.
*
* the maintainer rejected the always-on personal-baseline reference line that B1a
* The maintainer rejected the always-on personal-baseline reference line that B1a
* painted on every chart. The default surface for a new chart should be
* a clean line + axes + tooltip — no baseline, no target-zone shading,
* no trend line. Overlays are user-opt-in via the per-chart settings
@@ -1,5 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
// vi.doMock below invalidates the module registry, so the re-imported
// provider gets a fresh (unprimed) locale cache — pass the DE bundle
// explicitly instead of relying on the vitest.setup.ts seeding.
import deMessages from "../../../../messages/de.json";
/**
* v1.4.43 W2-CHART-GATE — medication-compliance empty-state copy split.
@@ -49,7 +53,7 @@ describe("<MedicationComplianceChart> — empty-state gate by raw count", () =>
);
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<MedicationComplianceChart />
</I18nProvider>,
);
@@ -80,7 +84,7 @@ describe("<MedicationComplianceChart> — empty-state gate by raw count", () =>
);
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<MedicationComplianceChart />
</I18nProvider>,
);
@@ -1,5 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
// vi.doMock below invalidates the module registry, so the re-imported
// provider gets a fresh (unprimed) locale cache — pass the DE bundle
// explicitly instead of relying on the vitest.setup.ts seeding.
import deMessages from "../../../../messages/de.json";
/**
* v1.4.43 W2-CHART-GATE — mood-chart empty-state copy split.
@@ -49,7 +53,7 @@ describe("<MoodChart> — empty-state gate by raw count", () => {
const { MoodChart } = await import("../mood-chart");
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<MoodChart />
</I18nProvider>,
);
@@ -81,7 +85,7 @@ describe("<MoodChart> — empty-state gate by raw count", () => {
const { MoodChart } = await import("../mood-chart");
const html = renderToStaticMarkup(
<I18nProvider initialLocale="de">
<I18nProvider initialLocale="de" initialMessages={deMessages}>
<MoodChart />
</I18nProvider>,
);
@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
/**
* v1.4.18 — MoodChart clean-line revert (gradient + emoji rolled back).
*
* the maintainer rejected B1a's coloured area fill below the chart line and the
* The maintainer rejected B1a's coloured area fill below the chart line and the
* smiley/emoji glyphs at every data point. The line stroke + Dracula
* tokens stay; the chart now paints a clean monotone line with simple
* Recharts dots.
@@ -67,7 +67,7 @@ describe("<MoodChart> v1.4.18 clean-line revert", () => {
});
it("does NOT render emoji glyphs at data points (source check)", async () => {
// the maintainer explicitly rejected smileys, especially in the mood chart.
// The maintainer explicitly rejected smileys, especially in the mood chart.
// Recharts does not paint <Line> dots during SSR (the dot callback
// only fires after first client render), so the emoji wouldn't
// surface in renderToStaticMarkup output anyway. Inspecting the
@@ -8,7 +8,7 @@ import { I18nProvider } from "@/lib/i18n/context";
/**
* v1.4.25 W20a — regression coverage for the dashboard top-tile polish.
*
* Marc-direktive 2026-05-14 named three issues with the 5-tile top row:
* Maintainer directive 2026-05-14 named three issues with the 5-tile top row:
*
* 1. Headings wrapped to two lines at narrow viewports (e.g. "Blood
* Pressure" on Pixel 5 / 393 px / 2-col grid). Locked the heading
@@ -23,7 +23,7 @@ import {
/**
* v1.4.18 — per-chart overlay-controls popover.
*
* the maintainer rolled back B1a's always-on chart overlays (gradient fills,
* The maintainer rolled back B1a's always-on chart overlays (gradient fills,
* personal-baseline reference line, target-zone shading) and asked for
* a per-chart switch surface instead. Each dashboard chart card mounts
* one of these in its top-right corner (a settings-cog dropdown) so the
+21 -12
View File
@@ -3,6 +3,7 @@
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import {
ResponsiveContainer,
ComposedChart,
@@ -707,13 +708,16 @@ export function HealthChart({
"days",
String(Math.max(1, Math.min(3650, Math.ceil(fetchWindow.windowDays)))),
);
const res = await fetch(`/api/measurements/series?${sleepParams}`);
if (!res.ok) return;
const json = await res.json();
const points = (json.data?.points ?? []) as Array<{
at: string;
value: number;
}>;
let points: Array<{ at: string; value: number }>;
try {
const data = await apiGet<{
points?: Array<{ at: string; value: number }>;
}>(`/api/measurements/series?${sleepParams}`);
points = data?.points ?? [];
} catch {
// Sleep overlay is additive — skip it on failure, as before.
return;
}
for (const point of points) {
const value = point.value * valueScale;
if (value == null || !Number.isFinite(value)) continue;
@@ -769,11 +773,16 @@ export function HealthChart({
typeParams.set("source", "rollup");
}
const res = await fetch(`/api/measurements?${typeParams}`);
if (!res.ok) return;
const json = await res.json();
const page = (json.data?.measurements ?? []) as MeasurementApiRow[];
let page: MeasurementApiRow[];
try {
const data = await apiGet<{ measurements?: MeasurementApiRow[] }>(
`/api/measurements?${typeParams}`,
);
page = data?.measurements ?? [];
} catch {
// Per-type fetch failure degrades that series only, as before.
return;
}
for (const measurement of page) {
// v1.7.0 — fold the display-time scale into the raw value at
@@ -61,6 +61,7 @@ import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import { useChartOverlayPrefs } from "@/hooks/use-chart-overlay-prefs";
import { useViewportWidth } from "@/hooks/use-viewport-width";
import { chooseTickInterval } from "@/lib/charts/x-axis-density";
import { apiGet } from "@/lib/api/api-fetch";
interface DailyCompliancePoint {
/** Berlin calendar day, "YYYY-MM-DD". */
@@ -244,12 +245,7 @@ export function MedicationComplianceChart({
const { data, isLoading } = useQuery({
queryKey: queryKeys.dashboardMedicationCompliance(days),
queryFn: async (): Promise<DailyCompliancePoint[]> => {
const res = await fetch(
`/api/medications/intake?scope=compliance&days=${days}`,
);
if (!res.ok) throw new Error("failed to fetch medication compliance");
const json = await res.json();
return json.data as DailyCompliancePoint[];
return apiGet<DailyCompliancePoint[]>(`/api/medications/intake?scope=compliance&days=${days}`);
},
enabled: isAuthenticated,
});
+2 -4
View File
@@ -40,6 +40,7 @@ import { useViewportWidth } from "@/hooks/use-viewport-width";
import { computeTickPositions } from "@/lib/charts/x-axis-density";
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
import { moodLabelKeyForScore } from "@/lib/mood/labels";
import { apiGet } from "@/lib/api/api-fetch";
// --- Types ---
@@ -348,10 +349,7 @@ export function MoodChart({
const { data, isLoading } = useQuery({
queryKey: queryKeys.moodAnalytics(),
queryFn: async (): Promise<MoodAnalyticsData> => {
const res = await fetch("/api/mood/analytics");
if (!res.ok) throw new Error("Failed to fetch mood analytics");
const json = await res.json();
return json.data as MoodAnalyticsData;
return apiGet<MoodAnalyticsData>("/api/mood/analytics");
},
enabled: isAuthenticated,
staleTime: 60_000,
+1 -1
View File
@@ -208,7 +208,7 @@ export function TrendCard({
to land at different heights when one tile had a one-line heading
and another had a two-line wrap). The arrow slot is always
present — when there is no signal yet, a muted "—" placeholder
renders so the value row keeps a deterministic width. Marc's
renders so the value row keeps a deterministic width. The maintainer's
ask: "rechts neben der Zahl … der Pfeil [ist], wie gerade der
Trend ist". */}
<div
+3 -11
View File
@@ -10,6 +10,7 @@ import {
type ComparisonBaseline,
type DashboardLayout,
} from "@/lib/dashboard-layout";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
/**
* v1.4.16 phase D reconcile (CRITICAL C3) — on-surface comparison
@@ -29,10 +30,7 @@ export function CompareToggle({ className }: { className?: string }) {
const { data: layoutData } = useQuery({
queryKey: queryKeys.dashboardWidgets(),
queryFn: async () => {
const res = await fetch("/api/dashboard/widgets");
if (!res.ok) throw new Error("failed");
const json = await res.json();
return json.data as DashboardLayout;
return apiGet<DashboardLayout>("/api/dashboard/widgets");
},
});
@@ -43,13 +41,7 @@ export function CompareToggle({ className }: { className?: string }) {
mutationFn: async (next: ComparisonBaseline) => {
if (!layout) throw new Error("layout-not-loaded");
const body: DashboardLayout = { ...layout, comparisonBaseline: next };
const res = await fetch("/api/dashboard/widgets", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error("save-failed");
return (await res.json()).data as DashboardLayout;
return apiPut<DashboardLayout>("/api/dashboard/widgets", body);
},
onMutate: async (next) => {
await queryClient.cancelQueries({
+41 -14
View File
@@ -369,33 +369,56 @@ export function LogDaySheet({
note,
symptoms,
};
if (rowId) {
// Editing an existing row → PATCH with explicit nulls so a deselected
// chip actually CLEARS (the POST merge can only add/keep — QA W-2).
await patchDay.mutateAsync({ id: rowId, patch: buildDayLogPatch(state) });
// v1.16.4 — catch so a rejected save doesn't escape as an unhandled
// rejection; the inline `logDay.isError || patchDay.isError` strip in the
// footer carries the visible failure signal and the sheet stays open.
try {
if (rowId) {
// Editing an existing row → PATCH with explicit nulls so a deselected
// chip actually CLEARS (the POST merge can only add/keep — QA W-2).
await patchDay.mutateAsync({
id: rowId,
patch: buildDayLogPatch(state),
});
} else {
await logDay.mutateAsync(buildDayLogInput(state, date));
}
onOpenChange(false);
return;
} catch {
/* surfaced via the inline isError strip */
}
await logDay.mutateAsync(buildDayLogInput(state, date));
onOpenChange(false);
}
// Period boundaries operate on the SELECTED date, so a forgotten day-1 can be
// corrected from the calendar retroactively (QA M3) — not today-only.
// v1.16.4 — the rejection is surfaced as a toast by the hook's onError;
// catching here keeps the sheet open without an unhandled rejection.
async function handleStartPeriod() {
await startPeriod.mutateAsync(date);
onOpenChange(false);
try {
await startPeriod.mutateAsync(date);
onOpenChange(false);
} catch {
/* toast shown by useStartPeriod onError */
}
}
async function handleEndPeriod() {
await endPeriod.mutateAsync(date);
onOpenChange(false);
try {
await endPeriod.mutateAsync(date);
onOpenChange(false);
} catch {
/* toast shown by useEndPeriod onError */
}
}
async function handleDelete() {
if (!rowId) return;
await deleteDay.mutateAsync(rowId);
onOpenChange(false);
try {
await deleteDay.mutateAsync(rowId);
onOpenChange(false);
} catch {
/* toast shown by useDeleteDayLog onError */
}
}
const busy =
@@ -757,7 +780,11 @@ function SymptomChip({
async function handleRemove() {
if (!custom) return;
onClear?.(custom.key);
await deleteCustom.mutateAsync(custom.key);
try {
await deleteCustom.mutateAsync(custom.key);
} catch {
/* toast shown by useDeleteCustomSymptom onError */
}
}
return (
+55 -82
View File
@@ -10,6 +10,16 @@
* log.
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
ApiError,
apiDelete,
apiGet,
apiPatch,
apiPost,
} from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
import {
cycleDependentKeys,
@@ -52,12 +62,6 @@ export interface CycleInsightsResponse {
symptomPatterns: SymptomPhaseRow[];
}
async function unwrap<T>(res: Response): Promise<T> {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
const json = await res.json();
return json.data as T;
}
/**
* The local-timezone `YYYY-MM-DD` for a Date (default: now). Cycle day-keys
* are tz-anchored on the server; the client must derive the key from the
@@ -81,9 +85,7 @@ export function useCycleDayLog(date: string | null) {
queryKey: queryKeys.cycleDayLog(date ?? ""),
enabled: date !== null,
queryFn: () =>
fetch(`/api/cycle/day-logs?date=${date}`).then((r) =>
unwrap<CycleDayLogDTO | null>(r),
),
apiGet<CycleDayLogDTO | null>(`/api/cycle/day-logs?date=${date}`),
staleTime: 30_000,
});
}
@@ -92,9 +94,7 @@ export function useCycleCalendar(from: string, to: string) {
return useQuery({
queryKey: queryKeys.cycleCalendar(from, to),
queryFn: () =>
fetch(`/api/cycle/calendar?from=${from}&to=${to}`).then((r) =>
unwrap<CalendarResponse>(r),
),
apiGet<CalendarResponse>(`/api/cycle/calendar?from=${from}&to=${to}`),
staleTime: 60_000,
});
}
@@ -103,9 +103,7 @@ export function useCycleHistory(limit = 24) {
return useQuery({
queryKey: queryKeys.cycleHistory(limit),
queryFn: () =>
fetch(`/api/cycle/cycles?limit=${limit}`).then((r) =>
unwrap<CycleHistoryResponse>(r),
),
apiGet<CycleHistoryResponse>(`/api/cycle/cycles?limit=${limit}`),
staleTime: 60_000,
});
}
@@ -126,9 +124,7 @@ export function useCustomSymptoms() {
return useQuery({
queryKey: queryKeys.cycleCustomSymptoms(),
queryFn: () =>
fetch("/api/cycle/symptoms/custom").then((r) =>
unwrap<{ symptoms: CustomSymptomDTO[] }>(r),
),
apiGet<{ symptoms: CustomSymptomDTO[] }>("/api/cycle/symptoms/custom"),
staleTime: 5 * 60_000,
});
}
@@ -152,22 +148,22 @@ export function useCreateCustomSymptom() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (input: { label: string; icon?: string | null }) => {
const res = await fetch("/api/cycle/symptoms/custom", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
try {
return await apiPost<CustomSymptomDTO>(
"/api/cycle/symptoms/custom",
input,
);
} catch (e) {
// Preserve the envelope errorCode so the UI can tell the cap hit
// (cycle.symptom.custom.limit) apart from a transient/validation error.
const errorCode = await res
.json()
.then((j) => (j?.meta?.errorCode as string | undefined) ?? null)
.catch(() => null);
throw new CustomSymptomError(errorCode, res.status);
if (e instanceof ApiError) {
throw new CustomSymptomError(
(e.meta?.errorCode as string | undefined) ?? null,
e.status,
);
}
throw e;
}
const json = await res.json();
return json.data as CustomSymptomDTO;
},
onSuccess: () =>
qc.invalidateQueries({ queryKey: queryKeys.cycleCustomSymptoms() }),
@@ -177,15 +173,17 @@ export function useCreateCustomSymptom() {
/** Soft-hide a custom symptom by its key (history-preserving). */
export function useDeleteCustomSymptom() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async (key: string) => {
const res = await fetch(
return apiDelete<{ key: string; purged: boolean }>(
`/api/cycle/symptoms/custom/${encodeURIComponent(key)}`,
{ method: "DELETE" },
);
return unwrap<{ key: string; purged: boolean }>(res);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
// v1.16.4 — a failed delete used to fail silently (the sheet clears the
// chip optimistically), so surface the rejection.
onError: () => toast.error(t("cycle.deleteError")),
});
}
@@ -193,7 +191,7 @@ export function useCycleProfile() {
return useQuery({
queryKey: queryKeys.cycleProfile(),
queryFn: () =>
fetch("/api/cycle/profile").then((r) => unwrap<CycleProfileDTO>(r)),
apiGet<CycleProfileDTO>("/api/cycle/profile"),
staleTime: 5 * 60_000,
});
}
@@ -207,9 +205,7 @@ export function useCycleInsights() {
return useQuery({
queryKey: queryKeys.cycleInsights(),
queryFn: () =>
fetch("/api/cycle/insights").then((r) =>
unwrap<CycleInsightsResponse>(r),
),
apiGet<CycleInsightsResponse>("/api/cycle/insights"),
staleTime: 5 * 60_000,
});
}
@@ -223,15 +219,9 @@ export function useLogDay() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (input: CycleDayLogInput) => {
const res = await fetch("/api/cycle/day-logs", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey(),
},
body: JSON.stringify(input),
return apiPost<unknown>("/api/cycle/day-logs", input, {
headers: { "Idempotency-Key": idempotencyKey() },
});
return unwrap<unknown>(res);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
});
@@ -269,12 +259,7 @@ export function usePatchDayLog() {
id: string;
patch: CycleDayLogPatch;
}) => {
const res = await fetch(`/api/cycle/day-logs/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
return unwrap<CycleDayLogDTO>(res);
return apiPatch<CycleDayLogDTO>(`/api/cycle/day-logs/${id}`, patch);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
});
@@ -282,56 +267,49 @@ export function usePatchDayLog() {
export function useStartPeriod() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async (date: string) => {
const res = await fetch("/api/cycle/period", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "start",
date,
loggedAt: new Date().toISOString(),
}),
return apiPost<unknown>("/api/cycle/period", {
action: "start",
date,
loggedAt: new Date().toISOString(),
});
return unwrap<unknown>(res);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
// v1.16.4 — period boundaries had no failure signal at all (the sheet
// simply stayed open); a toast names the rejection.
onError: () => toast.error(t("cycle.saveError")),
});
}
/** The one-tap "end period" boundary (`action:"end"`). */
export function useEndPeriod() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async (date: string) => {
const res = await fetch("/api/cycle/period", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "end",
date,
loggedAt: new Date().toISOString(),
}),
return apiPost<unknown>("/api/cycle/period", {
action: "end",
date,
loggedAt: new Date().toISOString(),
});
return unwrap<unknown>(res);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onError: () => toast.error(t("cycle.saveError")),
});
}
/** Soft-delete a logged day by its row id (the GET supplies the id). */
export function useDeleteDayLog() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/cycle/day-logs/${id}`, {
method: "DELETE",
});
if (!res.ok && res.status !== 204) {
throw new Error(`Request failed: ${res.status}`);
}
await apiDelete(`/api/cycle/day-logs/${id}`);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onError: () => toast.error(t("cycle.deleteError")),
});
}
@@ -351,12 +329,7 @@ export function useUpdateCyclePrefs() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (patch: CyclePrefsPatch) => {
const res = await fetch("/api/auth/me/cycle-prefs", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
return unwrap<CycleProfileDTO>(res);
return apiPatch<CycleProfileDTO>("/api/auth/me/cycle-prefs", patch);
},
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
@@ -6,7 +6,7 @@
* assertions below cover:
*
* 1. The pure `pickDefaultMedicationId` helper — the cool/easy
* default-selection logic Marc asked for ("auto-select when one is
* default-selection logic the maintainer asked for ("auto-select when one is
* due"). Tested across the four ranked branches: empty,
* single-active, due-now, alphabetical fallback.
* 2. The empty-state SSR markup — when the user has no active
@@ -183,7 +183,7 @@ describe("<MedicationIntakeQuickAdd> — SSR contract", () => {
const de = renderSSR(<MedicationIntakeQuickAdd />, "de");
expect(en).not.toContain("dashboard.medicationIntakeQuickAdd");
expect(de).not.toContain("dashboard.medicationIntakeQuickAdd");
// German locale ships Marc-Voice DE copy with umlauts (UTF-8
// German locale ships project-voice DE copy with umlauts (UTF-8
// end-to-end, never their HTML entity form).
expect(de).toContain("Medikamente angelegt");
});
@@ -28,11 +28,12 @@ import {
toBerlinDate,
type ScheduleWindowInput,
} from "@/lib/medications/window-status";
import { ApiError, apiGet, apiPost } from "@/lib/api/api-fetch";
/**
* v1.4.37 W7b — dashboard "Hinzufügen" → "Medikamenteneinnahme" quick-add.
*
* Marc's brief: the dashboard's top-right "Hinzufügen" menu logs
* The maintainer's brief: the dashboard's top-right "Hinzufügen" menu logs
* measurements and mood entries; add a medication-intake action so a
* dose can be logged in a few taps without leaving the dashboard.
*
@@ -157,10 +158,7 @@ export function MedicationIntakeQuickAdd({
const { data: medicationsRaw, isLoading: medicationsLoading } = useQuery({
queryKey: queryKeys.medications(),
queryFn: async () => {
const res = await fetch("/api/medications");
if (!res.ok) throw new Error("Failed to load medications");
const json = await res.json();
return json.data as MedicationOption[];
return apiGet<MedicationOption[]>("/api/medications");
},
// v1.4.38 — share the parent dashboard's medications cache.
// `queryKeys.medications()` resolves to `["medications"]` — the
@@ -241,27 +239,12 @@ export function MedicationIntakeQuickAdd({
const doseDeviates =
trimmedDose.length > 0 &&
trimmedDose !== (selectedMedication?.dose ?? "").trim();
const res = await fetch(`/api/medications/${medicationId}/intake`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
takenAt: timestamp,
skipped: false,
...(doseDeviates && { doseTaken: trimmedDose }),
}),
await apiPost(`/api/medications/${medicationId}/intake`, {
takenAt: timestamp,
skipped: false,
...(doseDeviates && { doseTaken: trimmedDose }),
});
const json = await res.json();
if (!res.ok) {
setError(
typeof json?.error === "string"
? json.error
: t("dashboard.medicationIntakeQuickAdd.saveError"),
);
setLoading(false);
return;
}
await invalidateKeys(queryClient, medicationDependentKeys);
// Fan-out to every inline compliance chart key (one per medication)
// so the detail-page tile refreshes when the user re-enters it.
@@ -271,8 +254,12 @@ export function MedicationIntakeQuickAdd({
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("dashboard.medicationIntakeQuickAdd.saveError"));
} catch (err) {
setError(
err instanceof ApiError && err.message
? err.message
: t("dashboard.medicationIntakeQuickAdd.saveError"),
);
} finally {
setLoading(false);
}
@@ -8,13 +8,13 @@
* 2. Practice / clinic name (optional, persisted between exports).
* 3. Which data sections appear in the PDF (per-user persisted toggles).
*
* Hide-when-empty (Marc 2026-05-14): a section's toggle is only shown
* Hide-when-empty (the maintainer 2026-05-14): a section's toggle is only shown
* when the selected date range actually has data for it — checking a box
* for an empty section would produce a silently-empty PDF page. The
* availability probe runs on every range change via
* `/api/doctor-report/availability`.
*
* Privacy default: mood is OFF by default per Marc — mental-health data
* Privacy default: mood is OFF by default per the maintainer — mental-health data
* is opt-in even within a single user's own surface. The API layer
* filters mood out of the report payload server-side when the toggle is
* off, so the data never leaves the DB row.
@@ -52,6 +52,7 @@ import {
type DoctorReportPrefs,
} from "@/lib/validations/doctor-report-prefs";
import { useTranslations } from "@/lib/i18n/context";
import { apiGet, apiPost, apiPut } from "@/lib/api/api-fetch";
const ONE_DAY_MS = 86_400_000;
const MAX_RANGE_DAYS = 730;
@@ -201,11 +202,12 @@ export function DoctorReportDialog({
useEffect(() => {
if (!open || prefsLoaded) return;
let cancelled = false;
fetch("/api/auth/me/doctor-report-prefs", { credentials: "include" })
.then((res) => (res.ok ? res.json() : null))
.then((json) => {
apiGet<Partial<DoctorReportPrefs> | null | undefined>(
"/api/auth/me/doctor-report-prefs",
{ credentials: "include" },
)
.then((incoming) => {
if (cancelled) return;
const incoming = json?.data;
if (incoming && typeof incoming === "object") {
setPrefs({ ...DEFAULT_DOCTOR_REPORT_PREFS, ...incoming });
}
@@ -236,18 +238,16 @@ export function DoctorReportDialog({
.then(() => {
if (cancelled) return null;
setAvailabilityLoading(true);
return fetch("/api/doctor-report/availability", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ startDate: startIso, endDate: endIso }),
});
return apiPost<SectionAvailability>(
"/api/doctor-report/availability",
{ startDate: startIso, endDate: endIso },
{ credentials: "include" },
);
})
.then(async (res) => {
if (cancelled || !res || !res.ok) return;
const json = (await res.json()) as { data: SectionAvailability };
.then((data) => {
if (cancelled || !data) return;
if (requestId !== availabilityRequestId.current) return;
setAvailability(json.data);
setAvailability(data);
})
.catch(() => {
// Best-effort — keep the previous availability snapshot.
@@ -320,11 +320,8 @@ export function DoctorReportDialog({
// way, so the user gets the PDF they asked for even if persistence
// failed (they'll just see the defaults next time).
try {
await fetch("/api/auth/me/doctor-report-prefs", {
method: "PUT",
headers: { "Content-Type": "application/json" },
await apiPut("/api/auth/me/doctor-report-prefs", next, {
credentials: "include",
body: JSON.stringify(next),
});
} catch {
// ignore
@@ -334,7 +334,7 @@ describe("<HealthScoreCard>", () => {
// (the provenance accordion) instead of clumping under the
// disclaimer. Pin both the grid switch and the `1fr` slack row so
// a future refactor can't silently revert to flex and re-introduce
// the "Karte hört bei der Trennlinie auf" Marc-reported bug.
// the "Karte hört bei der Trennlinie auf" maintainer-reported bug.
it("uses a 7-row grid on the inner column so slack distributes on the accordion row", () => {
const html = ssr(
<HealthScoreCard
@@ -50,7 +50,7 @@ describe("<CoachInput>", () => {
it("no longer renders a mic button (W5 removed the placeholder)", () => {
// v1.4.25 W5 — the mic icon used to be rendered + disabled with a
// "voice arrives with iOS" tooltip. Marc flagged it as a click-
// "voice arrives with iOS" tooltip. The maintainer flagged it as a click-
// trap: nothing happened on tap. The composer now drops the icon
// entirely; voice input remains a v1.5 iOS feature.
const html = render(
@@ -204,7 +204,7 @@ describe("<MessageThread>", () => {
/>,
);
// v1.4.33 IW7 — copy rewritten from "AI provider" to "Insights
// provider" per the Marc-Voice rule (no "KI"/"AI" prefix in
// provider" per the project-voice rule (no "KI"/"AI" prefix in
// user-facing strings).
expect(html).toContain("could not reach an Insights provider");
});
@@ -423,7 +423,7 @@ describe("<MessageThread>", () => {
useAuthMock.mockReturnValueOnce({
user: {
id: "u-1",
username: "marc",
username: "testuser",
role: "USER",
avatarUrl: "/api/user/avatar/u-1?v=1700000000000",
},
@@ -2,6 +2,7 @@
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import {
Bot,
ChevronRight,
@@ -14,6 +15,7 @@ import {
import { cn } from "@/lib/utils";
import { scrollBehaviorForUser } from "@/lib/motion";
import { useTranslations } from "@/lib/i18n/context";
import { ApiError, apiPost } from "@/lib/api/api-fetch";
import { stripChartTokens } from "@/lib/insights/chart-tokens";
import { useAuth } from "@/hooks/use-auth";
@@ -118,7 +120,7 @@ export function MessageThread({
// v1.4.27 F14 — the evidence disclosure used to honour an opt-in
// `coachPrefs.showEvidenceByDefault` flag that surfaced the raw
// measurement values unconditionally. The flag created an UX trap
// (Marc 2026-05-15: "literal metric values exposed under every
// (the maintainer 2026-05-15: "literal metric values exposed under every
// bubble") so the disclosure is now collapsed by default for every
// reply. The user expands by click; the pref is retired in the
// settings sheet so nothing flips it back on.
@@ -617,22 +619,25 @@ function CoachMessageFeedback({ messageId }: CoachMessageFeedbackProps) {
const submit = useMutation({
mutationFn: async (rating: "helpful" | "unhelpful") => {
const res = await fetch(
`/api/insights/chat/messages/${messageId}/feedback`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rating }),
},
);
// Treat 409 (already_rated) as a successful no-op so the user
// never sees an error toast for double-clicking the same chip.
if (!res.ok && res.status !== 409) {
throw new Error("coach-feedback.failed");
try {
await apiPost(`/api/insights/chat/messages/${messageId}/feedback`, {
rating,
});
} catch (err) {
// Treat 409 (already_rated) as a successful no-op so the user
// never sees an error toast for double-clicking the same chip.
if (!(err instanceof ApiError && err.status === 409)) {
throw err;
}
}
return rating;
},
onSuccess: (rating) => setSubmittedRating(rating),
// v1.16.4 — a failed rating used to fail silently; the chips stayed
// tappable with no signal that nothing was recorded.
onError: () => {
toast.error(t("insights.coach.feedbackError"));
},
});
if (submittedRating) {
@@ -19,6 +19,7 @@ import { BookmarkPlus, Check, Loader2, X } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import { apiPost } from "@/lib/api/api-fetch";
export interface SelfContextAdoptOfferProps {
/** The clarifying question the user just answered. */
@@ -39,13 +40,7 @@ export function SelfContextAdoptOffer({
const adopt = useMutation({
mutationFn: async () => {
const res = await fetch("/api/coach/about-me/adopt", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question, answer }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).data as { adopted: boolean };
return apiPost<{ adopted: boolean }>("/api/coach/about-me/adopt", { question, answer });
},
onSuccess: (data) => {
setSettled(data.adopted ? "adopted" : "duplicate");
@@ -17,10 +17,12 @@
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { MessageCircleQuestion, X } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { cn } from "@/lib/utils";
import { apiDelete, apiGet } from "@/lib/api/api-fetch";
export interface SelfContextChipsProps {
/** Insert the tapped question into the composer. */
@@ -39,9 +41,7 @@ export function SelfContextChips({
const { data } = useQuery({
queryKey: queryKeys.coachAboutMeQuestions(),
queryFn: async () => {
const res = await fetch("/api/coach/about-me/questions");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).data as { questions: string[] };
return apiGet<{ questions: string[] }>("/api/coach/about-me/questions");
},
staleTime: 60_000,
});
@@ -49,17 +49,16 @@ export function SelfContextChips({
const dismiss = useMutation({
mutationKey: queryKeys.coachAboutMeQuestions(),
mutationFn: async (question: string) => {
const res = await fetch("/api/coach/about-me/questions", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).data as { questions: string[] };
return apiDelete<{ questions: string[] }>("/api/coach/about-me/questions", { question });
},
onSuccess: (next) => {
queryClient.setQueryData(queryKeys.coachAboutMeQuestions(), next);
},
// v1.16.4 — a failed dismiss used to fail silently, leaving the chip
// in place with no signal that the request was rejected.
onError: () => {
toast.error(t("insights.coach.selfContextChipDismissError"));
},
});
const questions = data?.questions ?? [];
@@ -2,6 +2,7 @@
import { useState } from "react";
import { Eye, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import {
@@ -75,7 +76,12 @@ export function SourcesRail({ className }: SourcesRailProps) {
function persist(next: CoachPrefs, marker: CoachDataCluster | "window") {
setPending(marker);
save.mutate(next, { onSettled: () => setPending(null) });
save.mutate(next, {
onSettled: () => setPending(null),
// v1.16.4 — a failed save used to revert the switch silently once the
// spinner cleared; a toast names the rejection.
onError: () => toast.error(t("insights.coach.prefsSaveError")),
});
}
function toggleCluster(cluster: CoachDataCluster, next: boolean) {
@@ -11,6 +11,7 @@ import type {
CoachScope,
CoachStreamEvent,
} from "@/lib/ai/coach/types";
import { apiDelete, apiFetchRaw, apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.20 phase B2b — TanStack Query + SSE client for the AI Coach
@@ -34,14 +35,6 @@ const QUERY_KEYS = {
one: (id: string) => ["coachConversation", id] as const,
};
interface ConversationsApiResponse {
data: CoachConversationsPage;
}
interface ConversationApiResponse {
data: CoachConversationDetailDTO;
}
/**
* List of conversations for the rail. Cursor pagination is exposed via
* `loadMore` — the rail can call it when the user scrolls past the
@@ -52,12 +45,9 @@ export function useCoachConversations(enabled = true) {
const query = useQuery({
queryKey: QUERY_KEYS.list(),
queryFn: async (): Promise<CoachConversationsPage> => {
const res = await fetch("/api/insights/chat", {
return apiGet<CoachConversationsPage>("/api/insights/chat", {
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = (await res.json()) as ConversationsApiResponse;
return json.data;
},
enabled,
staleTime: 30 * 1000,
@@ -86,12 +76,9 @@ export function useCoachConversation(id: string | null) {
queryKey: ["coachConversation", id] as const,
queryFn: async (): Promise<CoachConversationDetailDTO> => {
if (!id) throw new Error("missing id");
const res = await fetch(`/api/insights/chat/${id}`, {
return apiGet<CoachConversationDetailDTO>(`/api/insights/chat/${id}`, {
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = (await res.json()) as ConversationApiResponse;
return json.data;
},
enabled: id !== null,
staleTime: 60 * 1000,
@@ -106,10 +93,7 @@ export function useDeleteCoachConversation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/insights/chat/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await apiDelete(`/api/insights/chat/${id}`);
return id;
},
onMutate: async (id: string) => {
@@ -210,7 +194,7 @@ export interface CoachStreamingMessage {
* `src/app/api/insights/chat/route.ts`), but the persisted twin only
* lands client-side after the SSE `done` frame triggers a
* `queryClient.invalidateQueries`. The earlier render order was
* "Thinking…" → user message → assistant reply, which Marc flagged in
* "Thinking…" → user message → assistant reply, which the maintainer flagged in
* the W5 polish brief; surfacing this optimistic bubble flips the
* order to user → "Thinking…" → assistant reply.
*
@@ -312,7 +296,7 @@ export function useSendCoachMessage(opts: UseSendCoachMessageOptions = {}) {
// the "Thinking…" placeholder paints. Without this the send hook
// only exposed the streaming assistant bubble, so the first
// thing the user saw was the placeholder followed by their own
// message landing on the next refetch — Marc flagged the
// message landing on the next refetch — the maintainer flagged the
// order as confusing on the suggested-prompt chips.
setOptimisticUser({
localId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
@@ -341,9 +325,11 @@ export function useSendCoachMessage(opts: UseSendCoachMessageOptions = {}) {
return;
}
// apiFetchRaw: the chat POST streams SSE — the envelope helpers
// would buffer and unwrap a body that never carries the envelope.
let response: Response;
try {
response = await fetch("/api/insights/chat", {
response = await apiFetchRaw("/api/insights/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -9,6 +9,7 @@ import type {
DerivedProvenance,
} from "@/lib/insights/derived/types";
import type { DerivedAssessment } from "@/lib/insights/derived/derived-assessment";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.10.0 — the single TanStack Query hook for the generic derived-metric
@@ -84,13 +85,7 @@ export function useDerivedMetric<T>(
try {
const params = new URLSearchParams({ metric });
if (type) params.set("type", type);
const res = await fetch(`/api/insights/derived?${params.toString()}`, {
signal: controller.signal,
});
if (!res.ok) {
throw new Error(`derived ${metric} request failed (${res.status})`);
}
return (await res.json()).data as DerivedMetricResponse<T>;
return apiGet<DerivedMetricResponse<T>>(`/api/insights/derived?${params.toString()}`, { signal: controller.signal });
} finally {
clearTimeout(timeoutHandle);
}
@@ -159,14 +154,7 @@ export function useDerivedBatch(
);
try {
const params = new URLSearchParams({ metrics: wireTokens.join(",") });
const res = await fetch(
`/api/insights/derived/batch?${params.toString()}`,
{ signal: controller.signal },
);
if (!res.ok) {
throw new Error(`derived batch request failed (${res.status})`);
}
return (await res.json()).data as DerivedBatchResponse;
return apiGet<DerivedBatchResponse>(`/api/insights/derived/batch?${params.toString()}`, { signal: controller.signal });
} finally {
clearTimeout(timeoutHandle);
}
@@ -271,7 +271,7 @@ export function HealthScoreCard({
accordion) instead of clumping under the disclaimer. The
score number stays anchored at the top, the disclaimer at
the bottom, and the card fills the row down to the
"Wirkt mein Medikament?" chip — closing Marc's "Karte hört
"Wirkt mein Medikament?" chip — closing the maintainer's "Karte hört
bei der Trennlinie auf" report against v1.4.36. */}
<div className="grid flex-1 grid-rows-[auto_auto_auto_auto_auto_1fr_auto] gap-3.5">
<div className="flex items-center justify-between gap-2">
+4 -11
View File
@@ -33,6 +33,7 @@ import {
type InsightsSectionConfig,
type InsightsSectionId,
} from "@/lib/insights-layout";
import { apiDelete, apiPut } from "@/lib/api/api-fetch";
/**
* v1.15.11 W3 — inline "Anpassen" edit mode for the customizable Insights
@@ -114,17 +115,11 @@ export function InsightsEditMode({
const saveMutation = useMutation({
mutationFn: async (next: InsightsLayout) => {
const res = await fetch("/api/insights/layout", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
return apiPut<InsightsLayout>("/api/insights/layout", {
version: 2,
sections: next.sections,
tiles: next.tiles,
}),
});
if (!res.ok) throw new Error("save failed");
return (await res.json()).data as InsightsLayout;
});
},
onSuccess: (saved) => {
// Optimistic-style settle: write the server-resolved layout into the
@@ -141,9 +136,7 @@ export function InsightsEditMode({
const resetMutation = useMutation({
mutationFn: async () => {
const res = await fetch("/api/insights/layout", { method: "DELETE" });
if (!res.ok) throw new Error("reset failed");
return (await res.json()).data as InsightsLayout;
return apiDelete<InsightsLayout>("/api/insights/layout");
},
onSuccess: (saved) => {
queryClient.setQueryData(queryKeys.insightsLayout(), saved);
@@ -14,6 +14,7 @@ import { useAnalyticsQuery } from "@/lib/queries/use-analytics-query";
import { useInsightsLayoutQuery } from "@/hooks/use-insights-layout";
import { queryKeys } from "@/lib/query-keys";
import type { InsightInputs } from "@/lib/insights/metric-availability";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.25 W4 — client shell for `src/app/insights/layout.tsx`.
@@ -81,10 +82,7 @@ export function InsightsLayoutShell({ children }: { children: ReactNode }) {
const comprehensiveQuery = useQuery({
queryKey: queryKeys.insightsComprehensive(),
queryFn: async () => {
const res = await fetch("/api/insights/comprehensive");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as ComprehensivePayload;
return apiGet<ComprehensivePayload>("/api/insights/comprehensive");
},
enabled: isAuthenticated,
});
+11 -1
View File
@@ -43,7 +43,7 @@ import {
* `usePathname()` decides the active pill, and the strip is mounted in
* `src/app/insights/layout.tsx` so it persists across navigation
* without re-rendering. The CoachDrawer is NOT mounted in this layout —
* the drawer lives in the mother page's body only (Marc directive
* the drawer lives in the mother page's body only (the maintainer directive
* 2026-05-11).
*
* Pills:
@@ -643,6 +643,13 @@ function InsightsTabStripImpl({
<Link
key={tab.href}
href={tab.href}
// Full route prefetch (RSC payload incl. the dynamic
// sub-page, not just the loading boundary) the moment
// the pill scrolls into view. The insights sub-pages
// are dynamic routes, so the default viewport prefetch
// only warms `loading.tsx`; the full prefetch removes
// the route-payload round-trip from the pill switch.
prefetch={true}
aria-current={isActive ? "page" : undefined}
data-slot="insights-tab-strip-pill"
data-active={isActive ? "true" : undefined}
@@ -713,6 +720,9 @@ function InsightsTabStripImpl({
<li key={child.href}>
<Link
href={child.href}
// Same full-prefetch contract as the flat
// pills — fires when the popover opens.
prefetch={true}
aria-current={isChildActive ? "page" : undefined}
data-slot="insights-tab-strip-group-item"
data-active={isChildActive ? "true" : undefined}
+2 -3
View File
@@ -14,6 +14,7 @@ import { useDisableCoach } from "@/hooks/use-disable-coach";
import { queryKeys } from "@/lib/query-keys";
import { useChartTooltipActive } from "./use-chart-tooltip-active";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.16.1 — the layout FAB is no longer a permanent launcher. It now
@@ -80,9 +81,7 @@ export function LayoutCoachFab() {
const { data: status } = useQuery({
queryKey: queryKeys.coachNudgeStatus(),
queryFn: async (): Promise<CoachNudgeStatus> => {
const res = await fetch("/api/insights/coach/nudge-status");
if (!res.ok) throw new Error("coach-nudge-status.failed");
return (await res.json()).data as CoachNudgeStatus;
return apiGet<CoachNudgeStatus>("/api/insights/coach/nudge-status");
},
enabled: coachAvailable,
staleTime: 5 * 60 * 1000,
@@ -12,6 +12,7 @@ import {
import { useAuth } from "@/hooks/use-auth";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { detectMeasurementDiversity } from "@/lib/insights/measurement-diversity";
/**
@@ -67,13 +68,15 @@ export function MeasurementDiversityNudge({
params.set("limit", String(WINDOW_SIZE));
params.set("sortBy", "measuredAt");
params.set("sortDir", "desc");
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) return [];
const json = await res.json();
const rows = (json.data?.measurements ?? []) as Array<{
measuredAt: string;
}>;
return rows.map((r) => r.measuredAt);
try {
const data = await apiGet<{
measurements?: Array<{ measuredAt: string }>;
}>(`/api/measurements?${params}`);
return (data?.measurements ?? []).map((r) => r.measuredAt);
} catch {
// Nudge is optional — degrade to "no data", as before.
return [];
}
},
enabled: isAuthenticated,
// The pattern shifts slowly — a 5-minute cache keeps the nudge calm
@@ -15,6 +15,7 @@ import { TargetStatusPill } from "@/components/targets/target-status-pill";
import { TileHeader } from "@/components/insights/tile-header";
import { useTargetAdjust } from "@/lib/insights/target-adjust-context";
import { getTargetSourceLink } from "@/lib/targets/source-link";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.8.0 → v1.8.5 — surface the per-metric target reference panel on each
@@ -133,10 +134,7 @@ export function MetricTargetSummary({ slug }: MetricTargetSummaryProps) {
const { data } = useQuery({
queryKey: queryKeys.insightsTargets(),
queryFn: async () => {
const res = await fetch("/api/insights/targets");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as TargetsResponse;
return apiGet<TargetsResponse>("/api/insights/targets");
},
enabled: isAuthenticated && (targetType != null || isGlucose),
});
@@ -95,6 +95,7 @@ import {
MoodFactorMetricCrosstab,
type MoodFactorMetricCrosstabRow,
} from "./mood-factor-metric-crosstab";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.8.5 — additional Mood Insights sections.
@@ -193,10 +194,7 @@ export function MoodInsightsSections({
const { data, isLoading } = useQuery({
queryKey: queryKeys.moodInsights(),
queryFn: async () => {
const res = await fetch("/api/mood/insights");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as MoodInsightsResponse;
return apiGet<MoodInsightsResponse>("/api/mood/insights");
},
enabled: isAuthenticated,
staleTime: 60_000,
@@ -7,6 +7,7 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TileHeader } from "@/components/insights/tile-header";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
import {
MoodNarrativeFeed,
@@ -44,11 +45,9 @@ export function MoodWhatStandsOut({
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.insightsCorrelations(),
queryFn: async () => {
const res = await fetch("/api/insights/correlations");
// 403 = operator disabled the surface; any non-OK degrades to nothing.
if (!res.ok) throw new Error("unavailable");
const json = await res.json();
return json.data as CorrelationDiscoveryResponse;
// 403 = operator disabled the surface; any rejection (ApiError)
// degrades to the card's isError → render-nothing path.
return apiGet<CorrelationDiscoveryResponse>("/api/insights/correlations");
},
enabled: isAuthenticated,
staleTime: 60_000,
@@ -13,6 +13,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.11.0 W3 — period-narrative card (Pillar P1).
@@ -59,11 +60,7 @@ interface PeriodNarrativeCardProps {
async function fetchNarrative(
period: NarrativePeriod,
): Promise<NarrativeResponse> {
const res = await fetch(`/api/insights/narrative?period=${period}`);
if (!res.ok) {
throw new Error(`narrative ${res.status}`);
}
return (await res.json()).data as NarrativeResponse;
return apiGet<NarrativeResponse>(`/api/insights/narrative?period=${period}`);
}
function ProvenanceDisclosure({
@@ -29,6 +29,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { apiGet } from "@/lib/api/api-fetch";
import type { MeasurementType } from "@/generated/prisma/client";
import { cn } from "@/lib/utils";
@@ -76,11 +77,15 @@ export function PersonalRecordBadge({
// `feedback_react_query_key_collision`).
queryKey: ["personal-records", "by-metric", metricType],
queryFn: async () => {
const res = await fetch(
`/api/personal-records?metricType=${encodeURIComponent(metricType)}`,
);
if (!res.ok) return [] as PersonalRecordRow[];
return ((await res.json()).data ?? []) as PersonalRecordRow[];
try {
const data = await apiGet<PersonalRecordRow[] | null>(
`/api/personal-records?metricType=${encodeURIComponent(metricType)}`,
);
return data ?? [];
} catch {
// The badge is decorative — degrade to "no records", as before.
return [] as PersonalRecordRow[];
}
},
// Per-tile data: stale-while-revalidate cadence matches the
// dashboard's existing trend queries. 5 minutes is enough to
@@ -33,6 +33,7 @@ import { ThumbsUp, ThumbsDown, Loader2, Check } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { useAuth } from "@/hooks/use-auth";
import type { RecommendationFeedbackRequest } from "@/lib/validations/recommendation-feedback";
import { ApiError, apiPost } from "@/lib/api/api-fetch";
// v1.4.16 phase D reconcile (simplify F5) — re-export the canonical
// types from the validation schema instead of hand-maintaining the
@@ -70,11 +71,6 @@ type FeedbackState =
const LOCAL_STORAGE_PREFIX = "healthlog-rec-feedback";
interface FeedbackEnvelope {
data: { id: string; createdAt: string } | null;
error?: string | null;
}
function localCacheKey(userId: string, recId: string, recText: string): string {
// recText is part of the key because the server-side dedup also
// includes it — a regeneration that rewrites the same id with new
@@ -152,24 +148,22 @@ export function RecommendationFeedback({
const mutation = useMutation({
mutationFn: async (helpful: boolean) => {
const res = await fetch("/api/insights/feedback", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
try {
await apiPost("/api/insights/feedback", {
recommendationId: recId,
recommendationText: recText,
recommendationSeverity: recSeverity,
metricSourceType,
metricSourceTimeRange,
helpful,
}),
});
const body = (await res.json()) as FeedbackEnvelope;
if (res.status === 409) {
return { duplicate: true, helpful } as const;
}
if (!res.ok) {
throw new Error(body.error ?? "feedback_failed");
});
} catch (err) {
// 409 = the server already holds a verdict for this rec — treat
// as the non-throwing duplicate outcome, exactly as before.
if (err instanceof ApiError && err.status === 409) {
return { duplicate: true, helpful } as const;
}
throw err;
}
return { duplicate: false, helpful } as const;
},
@@ -6,6 +6,7 @@ import type { LucideIcon } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import { SectionHeading } from "@/components/insights/section-heading";
@@ -90,10 +91,13 @@ export function RhythmEventsCard({
const { data, isLoading } = useQuery({
queryKey: queryKeys.insightsRhythmEvents(),
queryFn: async () => {
const res = await fetch("/api/insights/rhythm-events");
if (!res.ok) throw new Error(t("insights.rhythmEvents.loadError"));
const json = await res.json();
return json.data as RhythmEventsResponse;
try {
return await apiGet<RhythmEventsResponse>(
"/api/insights/rhythm-events",
);
} catch {
throw new Error(t("insights.rhythmEvents.loadError"));
}
},
enabled: enabled && isAuthenticated,
});
+1 -1
View File
@@ -15,7 +15,7 @@ import { useTranslations } from "@/lib/i18n/context";
import { STAGE_COLORS } from "./sleep-stage-stacked-bar";
/**
* v1.11.5 — last-night HYPNOGRAM (Marc directive: the phase-progression
* v1.11.5 — last-night HYPNOGRAM (the maintainer directive: the phase-progression
* view). Renders one night's stage timeline as a stepped depth track —
* Awake at the top, Deep at the base — over clock time, in the Dracula
* stage palette reused from `sleep-stage-stacked-bar.tsx` (no token
+3 -4
View File
@@ -18,6 +18,7 @@ import {
} from "./sleep-stage-stacked-bar";
import { SleepHypnogram, type SleepHypnogramSession } from "./sleep-hypnogram";
import { SleepDurationChart } from "./sleep-duration-chart";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.25 W4c — Sleep insights composition.
@@ -89,12 +90,10 @@ export function SleepOverview() {
const nightQuery = useQuery({
queryKey: queryKeys.sleepNight(),
queryFn: async () => {
const res = await fetch("/api/sleep/night");
if (!res.ok) throw new Error("Failed to fetch sleep night");
return (await res.json()).data as {
return apiGet<{
night: string | null;
main: SleepHypnogramSession | null;
};
}>("/api/sleep/night");
},
enabled: isAuthenticated && totalCount > 0,
staleTime: 60 * 1000,
@@ -20,7 +20,7 @@ import { useTranslations } from "@/lib/i18n/context";
/**
* v1.4.25 W4c → W3f — sleep-stage composition chart.
*
* Marc directive 2026-05-14: switch from "30-day average composition"
* The maintainer directive 2026-05-14: switch from "30-day average composition"
* to a per-night stacked column chart so the user sees nightly stage
* variation, not just a rolling average. Apple Health's sleep tab is
* the visual reference — one column per night, stacks for REM / Deep /
+6 -8
View File
@@ -19,6 +19,7 @@ import {
} from "@/lib/insights/trend-descriptor";
import { cn } from "@/lib/utils";
import { CONFIDENCE_BADGE_CLASS } from "./confidence-badge";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.20 phase B3 — single-sentence AI annotation rendered directly
@@ -276,10 +277,7 @@ export function TrendDescriptorCaption({
const moodQuery = useQuery({
queryKey: queryKeys.moodAnalytics(),
queryFn: async () => {
const res = await fetch("/api/mood/analytics");
if (!res.ok) throw new Error("Failed to fetch mood analytics");
const json = await res.json();
return json.data as { entries: MoodAnalyticsRow[] };
return apiGet<{ entries: MoodAnalyticsRow[] }>("/api/mood/analytics");
},
enabled: isAuthenticated && isMood,
staleTime: 60_000,
@@ -301,10 +299,10 @@ export function TrendDescriptorCaption({
aggregate: "daily",
source: "rollup",
});
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch measurement series");
const json = await res.json();
return (json.data?.measurements ?? []) as MeasurementApiRow[];
const data = await apiGet<{ measurements?: MeasurementApiRow[] }>(
`/api/measurements?${params}`,
);
return data?.measurements ?? [];
},
enabled: isAuthenticated && !isMood && primaryType.length > 0,
staleTime: 60_000,
@@ -10,6 +10,7 @@ import {
type TrendAnnotations,
} from "@/lib/ai/schema";
import { queryKeys } from "@/lib/query-keys";
import { apiFetchRaw } from "@/lib/api/api-fetch";
/**
* v1.4.16 phase D reconcile (CRITICAL C1 + C2) — shared TanStack Query
@@ -111,14 +112,17 @@ async function fetchAdvisor(
// and enqueues an out-of-band warm on a stale / missing cache — it
// never blocks the page-load path on the provider chain. Only the
// user-initiated regenerate (`force`) POSTs to generate inline.
// apiFetchRaw: this path branches on raw status codes (422 / 429 /
// 503 are expected, non-throwing surfaces) — the unwrap helpers
// would turn them into thrown ApiErrors.
res = options.force
? await fetch("/api/insights/generate", {
? await apiFetchRaw("/api/insights/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ force: true }),
signal: controller.signal,
})
: await fetch("/api/insights/generate", {
: await apiFetchRaw("/api/insights/generate", {
method: "GET",
signal: controller.signal,
});
@@ -15,8 +15,8 @@ vi.mock("next/navigation", () => ({
const mockUserRef = {
value: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "USER" as "USER" | "ADMIN",
avatarUrl: null,
cycleTrackingEnabled: false,
+30 -13
View File
@@ -113,17 +113,10 @@ export function AuthShell({
// previous `useEffect`-based redirect caused a brief dashboard flash
// for users with `onboardingCompletedAt === null`.
// Loading state
if (isLoading) {
return (
<div className="flex h-dvh items-center justify-center" role="status">
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
<span className="sr-only">{t("nav.loadingScreen")}</span>
</div>
);
}
// Public pages (login, register) — render without any nav
// Public pages (login, register) — render without any nav. Resolved
// BEFORE the auth-loading gate: a public page never needs the
// `/api/auth/me` round-trip to paint, so blocking it on `isLoading`
// only delayed the login form behind a spinner.
if (isPublicPage) {
// Long-form legal pages render edge-to-edge with their own chrome.
if (isStandalonePublicPage) {
@@ -143,8 +136,11 @@ export function AuthShell({
);
}
// Not authenticated, waiting for redirect
if (!isAuthenticated) {
// Admin pages stay behind the auth gate while `/api/auth/me` is in
// flight: the role is unknown until the payload lands, and mounting
// `/admin/*` children early would fire admin queries that 403 for a
// non-admin before the redirect effect can move them away.
if (isLoading && isAdminPage) {
return (
<div className="flex h-dvh items-center justify-center" role="status">
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
@@ -153,6 +149,27 @@ export function AuthShell({
);
}
// Auth RESOLVED as unauthenticated — hold a spinner while the
// redirect effect above replaces the route with /auth/login.
if (!isLoading && !isAuthenticated) {
return (
<div className="flex h-dvh items-center justify-center" role="status">
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
<span className="sr-only">{t("nav.loadingScreen")}</span>
</div>
);
}
// While `/api/auth/me` is still in flight the shell renders the full
// app chrome + children immediately (the chrome components own their
// null-user skeletons, pages own their data skeletons). This takes the
// auth round-trip off the first-paint critical path: page-level
// queries fire in parallel with `/api/auth/me` instead of behind it.
// `src/proxy.ts` has already refused cookie-less requests to
// protected routes, so the unauthenticated-flash window is limited to
// expired/invalid sessions — those resolve into the redirect branch
// above as soon as the 401 lands.
// Onboarding page — minimal shell, no sidebar/nav
if (isOnboardingPage) {
return (
-1
View File
@@ -9,7 +9,6 @@ import {
ChevronsRight,
Droplets,
Home,
Info,
Lightbulb,
LogOut,
Monitor,
@@ -46,7 +46,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -59,7 +59,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -39,7 +39,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -54,7 +54,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -43,7 +43,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -58,7 +58,7 @@ vi.mock("next/navigation", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
user: { id: "u1", username: "testuser", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
@@ -24,6 +24,7 @@ import { Loader2, MoreHorizontal, Plus, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { invalidateKeys, measurementDependentKeys } from "@/lib/query-keys";
import { ApiError, apiPost } from "@/lib/api/api-fetch";
import { MEASUREMENT_NOTES_MAX_LENGTH } from "@/lib/validations/measurement";
const MAX_COMMENT_LENGTH = MEASUREMENT_NOTES_MAX_LENGTH;
@@ -255,38 +256,16 @@ export function MeasurementForm({
});
}
const res = await fetch("/api/measurements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(batch),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
await apiPost("/api/measurements", batch);
} else {
// Single measurement
const res = await fetch("/api/measurements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type,
value: parseFloat(value),
measuredAt: timestamp,
notes: notes || undefined,
...(isGlucoseMode ? { glucoseContext } : {}),
}),
await apiPost("/api/measurements", {
type,
value: parseFloat(value),
measuredAt: timestamp,
notes: notes || undefined,
...(isGlucoseMode ? { glucoseContext } : {}),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
}
// Reset form
@@ -298,8 +277,12 @@ export function MeasurementForm({
await invalidateKeys(queryClient, measurementDependentKeys);
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("measurements.saveError"));
} catch (err) {
setError(
err instanceof ApiError && err.message
? err.message
: t("measurements.saveError"),
);
} finally {
setLoading(false);
}
@@ -48,7 +48,7 @@ import {
ChevronDown,
MoreHorizontal,
} from "lucide-react";
import { Fragment, useId, useState } from "react";
import { Fragment, useCallback, useId, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";
import { formatDateOrRelative, formatDateTime } from "@/lib/format";
@@ -80,6 +80,13 @@ import {
MEASUREMENT_TYPE_ICONS as TYPE_ICONS,
MEASUREMENT_TYPE_COLORS as TYPE_COLORS,
} from "./measurement-list-meta";
import {
ApiError,
apiDelete,
apiGet,
apiPost,
apiPut,
} from "@/lib/api/api-fetch";
/**
* v1.4.37 W7c — cumulative HK types whose list view collapses to one
@@ -425,26 +432,49 @@ export function MeasurementList({
params.set("limit", "366");
params.set("offset", "0");
}
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data as {
return apiGet<{
measurements: Measurement[];
meta: { total: number };
};
}>(`/api/measurements?${params}`);
},
enabled: isAuthenticated,
});
// v1.16.4 — deletes are soft (tombstones), so the success toast can
// carry a real Undo: it POSTs the ids to `/api/measurements/restore`,
// which clears `deletedAt` and re-fires the same dependent-key bundle.
// Mirrors the intake-Undo pattern in `use-medication-intake.ts`.
const restoreMeasurements = useCallback(
async (ids: string[]) => {
try {
await apiPost("/api/measurements/restore", { ids });
await invalidateKeys(queryClient, measurementDependentKeys);
toast.success(t("measurements.restoredToast"));
} catch {
toast.error(t("measurements.restoreError"));
}
},
[queryClient, t],
);
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/measurements/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Delete failed");
await apiDelete(`/api/measurements/${id}`);
},
onSuccess: () => {
onSuccess: (_data, id) => {
void invalidateKeys(queryClient, measurementDependentKeys);
toast.success(t("measurements.deletedToast"), {
action: {
label: t("common.undo"),
onClick: () => void restoreMeasurements([id]),
},
});
},
// v1.16.4 — a failed row delete used to fail silently (no onError
// handler); the edit-dialog path surfaced its own inline error but
// the row-level confirm had no feedback at all.
onError: () => {
toast.error(t("measurements.deleteError"));
},
});
@@ -454,20 +484,23 @@ export function MeasurementList({
// the dashboard / insights / chart caches stay in lockstep.
const bulkDeleteMutation = useMutation({
mutationFn: async (ids: string[]) => {
const res = await fetch("/api/measurements/bulk-delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids }),
});
if (!res.ok) throw new Error("Bulk delete failed");
const json = (await res.json()) as { data: { deleted: number } };
return json.data.deleted;
const data = await apiPost<{ deleted: number }>(
"/api/measurements/bulk-delete",
{ ids },
);
return data.deleted;
},
onSuccess: async (deleted) => {
onSuccess: async (deleted, ids) => {
await invalidateKeys(queryClient, measurementDependentKeys);
clearSelection();
toast.success(
t("measurements.bulkDeleteSuccess", { count: String(deleted) }),
{
action: {
label: t("common.undo"),
onClick: () => void restoreMeasurements(ids),
},
},
);
},
onError: () => {
@@ -517,35 +550,7 @@ export function MeasurementList({
measuredAt: string;
notes: string | null;
}) => {
const res = await fetch(`/api/measurements/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
value,
measuredAt,
notes,
}),
});
const json = (await res.json()) as {
error?: string;
meta?: { errorCode?: string };
};
if (!res.ok) {
// v1.4.28 FB-B1 — the PUT route now returns a 409 with
// `meta.errorCode === "measurement.duplicate_timestamp"` when
// the edit collides with an existing row's
// `(type, measuredAt, source, sleepStage)` tuple. Forward the
// code alongside the message so `onError` can pick the
// localised string.
const err = new Error(json.error ?? "Update failed") as Error & {
errorCode?: string;
status?: number;
};
err.errorCode = json.meta?.errorCode;
err.status = res.status;
throw err;
}
await apiPut(`/api/measurements/${id}`, { value, measuredAt, notes });
},
onSuccess: async () => {
await invalidateKeys(queryClient, measurementDependentKeys);
@@ -553,8 +558,15 @@ export function MeasurementList({
setEditError(null);
},
onError: (err) => {
const errWithCode = err as Error & { errorCode?: string };
if (errWithCode.errorCode === "measurement.duplicate_timestamp") {
// v1.4.28 FB-B1 — the PUT route returns a 409 with
// `meta.errorCode === "measurement.duplicate_timestamp"` when the
// edit collides with an existing row's
// `(type, measuredAt, source, sleepStage)` tuple. ApiError carries
// the envelope `meta`, so the localised string can be picked here.
if (
err instanceof ApiError &&
err.meta?.errorCode === "measurement.duplicate_timestamp"
) {
setEditError(t("measurements.duplicateTimestamp"));
return;
}
@@ -1430,10 +1442,7 @@ function DayDrillDown({
params.set("type", type);
params.set("dayKey", dayKey);
params.set("sortDir", "asc");
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch drill-down");
const json = await res.json();
return json.data as { measurements: Measurement[] };
return apiGet<{ measurements: Measurement[] }>(`/api/measurements?${params}`);
},
enabled: isAuthenticated,
// The drill-down is per-day — once fetched it rarely needs to
+15 -10
View File
@@ -49,6 +49,7 @@ import {
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import {
computeOneCompartment,
type DoseEvent,
@@ -127,10 +128,13 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
useQuery<Glp1DetailsResponse | null>({
queryKey: queryKeys.medicationGlp1Details(medication.id),
queryFn: async () => {
const res = await fetch(`/api/medications/${medication.id}/glp1`);
if (!res.ok) return null;
const json = await res.json();
return json.data as Glp1DetailsResponse;
try {
return await apiGet<Glp1DetailsResponse>(
`/api/medications/${medication.id}/glp1`,
);
} catch {
return null;
}
},
enabled: !!drugId,
staleTime: 60 * 1000,
@@ -139,12 +143,13 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
const { data: intakeEnvelope, isLoading: intakeLoading } = useQuery({
queryKey: queryKeys.medicationIntakeDrugLevelChart(medication.id),
queryFn: async () => {
const res = await fetch(
`/api/medications/${medication.id}/intake?limit=20&sortBy=takenAt&sortDir=desc`,
);
if (!res.ok) return null;
const json = await res.json();
return json.data as { events: IntakeEvent[] };
try {
return await apiGet<{ events: IntakeEvent[] }>(
`/api/medications/${medication.id}/intake?limit=20&sortBy=takenAt&sortDir=desc`,
);
} catch {
return null;
}
},
enabled: !!drugId,
staleTime: 60 * 1000,
@@ -23,7 +23,7 @@
* re-fetches the research-mode state and renders the toggle in
* the new state.
*
* Copy direction (Marc-Voice, English, no AI/phase/wave mentions):
* Copy direction (project-voice, English, no AI/phase/wave mentions):
* - "What this is" — single-paragraph framing: the chart is an
* estimate from EMA-published population PK.
* - "What this isn't" — explicit boundary: not a measurement, not
@@ -46,6 +46,7 @@ import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiPost } from "@/lib/api/api-fetch";
export interface ResearchModeAcknowledgmentDialogProps {
open: boolean;
@@ -77,18 +78,14 @@ export function ResearchModeAcknowledgmentDialog({
const mutation = useMutation({
mutationFn: async (version: string) => {
const res = await fetch("/api/auth/me/research-mode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ acknowledged: true, version }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
const code =
typeof json?.error === "string" ? json.error : `http-${res.status}`;
throw new Error(code);
}
return json?.data ?? null;
// ApiError.message carries the envelope `error` string verbatim, so
// the stale-version code below still matches on `err.message`.
return (
(await apiPost("/api/auth/me/research-mode", {
acknowledged: true,
version,
})) ?? null
);
},
onSuccess: () => {
setErrorMessage(null);
@@ -3,6 +3,7 @@
import { useId, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -31,6 +32,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";
/**
* v1.4.25 W19d — GLP-1 side-effect section for the medication detail
@@ -146,18 +148,10 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
// from the wire payload. The server derives it from the entry
// via `categoryForEntry`. Backwards-compatible with older
// clients during the cut window (route accepts both shapes).
const res = await fetch(`/api/medications/${medicationId}/side-effects`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as {
error?: string;
};
throw new Error(body.error ?? "Failed to log side effect");
}
return (await res.json()).data as SideEffectRow;
return apiPost<SideEffectRow>(
`/api/medications/${medicationId}/side-effects`,
payload,
);
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: listKey });
@@ -166,16 +160,17 @@ export function SideEffectsSection({ medicationId }: SideEffectsSectionProps) {
const deleteMutation = useMutation({
mutationFn: async (logId: string) => {
const res = await fetch(
`/api/medications/${medicationId}/side-effects/${logId}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Failed to delete entry");
await apiDelete(`/api/medications/${medicationId}/side-effects/${logId}`);
return true;
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: listKey });
},
// v1.16.4 — a failed delete used to fail silently, leaving the row
// in place with no signal that the request was rejected.
onError: () => {
toast.error(t("medications.sideEffects.deleteError"));
},
});
const items = data?.items ?? [];
@@ -145,7 +145,7 @@ describe("<ResearchModeAcknowledgmentDialog>", () => {
expect(html).toContain("Sources");
// Cited regulatory references must appear verbatim in the
// user-facing copy (Marc-Voice + research §11 + §12.4).
// user-facing copy (project-voice + research §11 + §12.4).
expect(html).toContain("2017/745");
expect(html).toContain("MDCG 2021-24");
// Peer-reviewed citation.
@@ -172,6 +172,8 @@ describe("<ResearchModeAcknowledgmentDialog>", () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { enabled: true } }),
// The apiFetch wrapper reads the envelope via `text()`.
text: async () => JSON.stringify({ data: { enabled: true } }),
});
vi.stubGlobal("fetch", fetchMock);
@@ -373,7 +373,7 @@ describe("streak-token parity — generic vs GLP-1 card", () => {
/**
* v1.15.18 — the ONE shared `<MedicationCardBody>` both cards render. These
* tests pin that the card surface is a CONSTANT neutral surface — dose status
* is never expressed as a background / border tint (Marc, recurring) — while
* is never expressed as a background / border tint (the maintainer, recurring) — while
* status is still surfaced via the discreet top line / pill, plus the
* structural identity that makes the two variants impossible to diverge.
*/
@@ -406,7 +406,7 @@ describe("medication card body — shared shell + dose-state presentation", () =
}
it("never tints the card surface when the dose is in its take-window", () => {
// Marc (recurring): the whole card washing green reads as "take it now"
// The maintainer (recurring): the whole card washing green reads as "take it now"
// and is a permanent removal. The take-window status survives ONLY as the
// discreet "Take now" pill, never as a card background / ring tint.
const html = renderBody("on_time_window");
@@ -148,7 +148,7 @@ describe("<IntakeHistoryListV2> — populated rows", () => {
});
it("renders the taken row with a green Check chip and the skipped row with an outline SkipForward chip", () => {
// v1.4.37 W3 — guards the regression Marc reported on 2026-05-17:
// v1.4.37 W3 — guards the regression the maintainer reported on 2026-05-17:
// before the fix, every row used the same secondary badge with the
// "Eingenommen" label regardless of skipped status. The chip must
// surface a distinct icon + label per branch and never label a
@@ -198,7 +198,7 @@ describe("<IntakeHistoryListV2> — populated rows", () => {
});
it("renders the skipped chip in German without leaking the Eingenommen label", () => {
// v1.4.37 W3 — UAT echo. Marc reported a German row labelled
// v1.4.37 W3 — UAT echo. The maintainer reported a German row labelled
// both "übersprungen" and "eingenommen". The fix means a
// skipped-only fixture renders "Übersprungen" exactly once and
// "Eingenommen" zero times.
@@ -108,6 +108,10 @@ describe("runRecordIntake — shared C1 failure toast + C2 Undo", () => {
vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ data: { id: "evt-99" } }),
// The apiFetch wrapper reads the envelope via `text()`.
text: vi
.fn()
.mockResolvedValue(JSON.stringify({ data: { id: "evt-99" } })),
}),
);
const undoIntake = vi.fn();
@@ -144,6 +148,7 @@ describe("runRecordIntake — shared C1 failure toast + C2 Undo", () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ data: { id: "evt-am" } }),
text: vi.fn().mockResolvedValue(JSON.stringify({ data: { id: "evt-am" } })),
});
vi.stubGlobal("fetch", fetchMock);
@@ -172,6 +177,7 @@ describe("runRecordIntake — shared C1 failure toast + C2 Undo", () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ data: { id: "evt" } }),
text: vi.fn().mockResolvedValue(JSON.stringify({ data: { id: "evt" } })),
});
vi.stubGlobal("fetch", fetchMock);
@@ -239,6 +245,7 @@ describe("runRecordIntake — shared C1 failure toast + C2 Undo", () => {
vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ data: {} }),
text: vi.fn().mockResolvedValue(JSON.stringify({ data: {} })),
}),
);
@@ -258,7 +265,11 @@ describe("runRecordIntake — shared C1 failure toast + C2 Undo", () => {
describe("runLogIntake — manual backdated intake from the Add choice", () => {
it("posts a backdated takenAt against the medication's intake route and returns true", async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: vi.fn() });
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn(),
text: vi.fn().mockResolvedValue(""),
});
vi.stubGlobal("fetch", fetchMock);
const queryClient = fakeQueryClient();
@@ -284,7 +295,11 @@ describe("runLogIntake — manual backdated intake from the Add choice", () => {
});
it("threads scheduledFor (the chosen slot) so the write routes through the canonical slot upsert", async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: vi.fn() });
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn(),
text: vi.fn().mockResolvedValue(""),
});
vi.stubGlobal("fetch", fetchMock);
await runLogIntake({
@@ -307,7 +322,11 @@ describe("runLogIntake — manual backdated intake from the Add choice", () => {
});
it("omits takenAt on a skipped log and shows the skipped toast", async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: vi.fn() });
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn(),
text: vi.fn().mockResolvedValue(""),
});
vi.stubGlobal("fetch", fetchMock);
await runLogIntake({
@@ -351,7 +370,10 @@ describe("runLogIntake — manual backdated intake from the Add choice", () => {
describe("runUndoIntake — shared soft-delete", () => {
it("reverts via DELETE and confirms on success", async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true });
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
text: vi.fn().mockResolvedValue(""),
});
vi.stubGlobal("fetch", fetchMock);
const queryClient = fakeQueryClient();
@@ -142,7 +142,7 @@ export function MedicationCardBody({
return (
<Card
// The card surface is a constant neutral surface — dose status is never
// expressed as a background / border tint (Marc, recurring): only the
// expressed as a background / border tint (the maintainer, recurring): only the
// discreet status line / pill below communicates take-now / overdue.
className={cn("h-full", active ? "" : "opacity-60")}
>
@@ -74,6 +74,7 @@ import { MedicationWizardDialog } from "@/components/medications/wizard/Medicati
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import type { MedicationPayload } from "@/components/medications/wizard/wizard-payload";
import type { ComplianceDisplay } from "@/lib/analytics/compliance";
@@ -280,13 +281,15 @@ export function MedicationDetailTabs({
const { data: compliance } = useQuery({
queryKey: queryKeys.medicationCompliance(id),
queryFn: async () => {
const res = await fetch(`/api/medications/${id}/compliance`);
if (!res.ok) return null;
return (await res.json()).data as {
compliance7?: { rate: number; streak: number };
compliance30?: { rate: number };
complianceDisplay?: ComplianceDisplay;
};
try {
return await apiGet<{
compliance7?: { rate: number; streak: number };
compliance30?: { rate: number };
complianceDisplay?: ComplianceDisplay;
}>(`/api/medications/${id}/compliance`);
} catch {
return null;
}
},
enabled: activeTab === "uebersicht",
staleTime: 30_000,
@@ -306,15 +309,17 @@ export function MedicationDetailTabs({
const { data: inventory } = useQuery({
queryKey: queryKeys.medicationInventory(id),
queryFn: async () => {
const res = await fetch(`/api/medications/${id}/inventory`);
if (!res.ok) return null;
return (await res.json()).data as {
items: Array<{
state: "ACTIVE" | "IN_USE" | "EXPIRED" | "USED_UP";
dosesTotal: number;
dosesRemaining: number;
}>;
} | null;
try {
return await apiGet<{
items: Array<{
state: "ACTIVE" | "IN_USE" | "EXPIRED" | "USED_UP";
dosesTotal: number;
dosesRemaining: number;
}>;
} | null>(`/api/medications/${id}/inventory`);
} catch {
return null;
}
},
enabled: activeTab === "uebersicht",
staleTime: 30_000,
@@ -787,12 +792,14 @@ function ComplianceGatedDangerZone({
offset: String(params.offset),
status: params.status,
});
const res = await fetch(
`/api/medications/${medicationId}/intake?${search.toString()}`,
);
if (!res.ok) return 0;
const json = await res.json();
return (json.data?.meta?.total ?? 0) as number;
try {
const data = await apiGet<{ meta?: { total?: number } }>(
`/api/medications/${medicationId}/intake?${search.toString()}`,
);
return data?.meta?.total ?? 0;
} catch {
return 0;
}
},
staleTime: 30_000,
});
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more