Merge branch 'fix/v1437-review' into release/v1.43.7

# Conflicts:
#	src/app/api/analytics/route.ts
This commit is contained in:
Marc-André Bombeck committed 2026-10-20 06:20:42 +02:00
commit 45c027aee2
217 files changed
+3636 -2127

No files matched your search

@@ -3,6 +3,8 @@ import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { ApiError } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
/**
* The strip sits above the chart on every metric sub-page. While its read is
@@ -37,4 +39,57 @@ describe("CoachReadStrip — placeholder while the read loads", () => {
expect(markup).toContain('data-state="loading"');
expect(markup).toContain('aria-busy="true"');
});
function renderFailed(error: Error) {
// `retryOnMount: false` keeps the seeded failure from being reset to a
// fresh load on render.
const client = new QueryClient({
defaultOptions: {
queries: { retry: false, enabled: false, retryOnMount: false },
},
});
client
.getQueryCache()
.build(client, { queryKey: queryKeys.insightsCoachRead("WEIGHT", "en") })
.setState({ status: "error", error, fetchStatus: "idle" });
return renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<CoachReadStrip metricType="WEIGHT" unit="kg" />
</I18nProvider>
</QueryClientProvider>,
);
}
/** The class list of the strip body, the element after the header. */
function bodyClass(markup: string): string | undefined {
return /data-slot="card-content" class="([^"]*)"/.exec(markup)?.[1];
}
it("holds the same frame and body height when the read fails", () => {
const loading = renderToStaticMarkup(
<QueryClientProvider
client={
new QueryClient({
defaultOptions: { queries: { retry: false, enabled: false } },
})
}
>
<I18nProvider initialLocale="en">
<CoachReadStrip metricType="WEIGHT" unit="kg" />
</I18nProvider>
</QueryClientProvider>,
);
const failed = renderFailed(new ApiError("Boom", 500));
expect(failed).toContain('data-slot="coach-read-strip"');
expect(failed).toContain('data-state="error"');
expect(failed).toContain('data-slot="coach-read-strip-error"');
expect(bodyClass(failed)).toBeDefined();
expect(bodyClass(failed)).toBe(bodyClass(loading));
expect(bodyClass(failed)).toContain("min-h-8");
});
it("draws nothing for a refused read", () => {
expect(renderFailed(new ApiError("Forbidden", 403))).toBe("");
});
});
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* A rhythm sub-score withheld for too few nights names the floor the server
* published (`rhythmMinNights`), not a number the sheet carries itself.
*/
const anatomy = vi.fn();
vi.mock("../score-anatomy-view", () => ({
ScoreAnatomyView: (props: Record<string, unknown>) => {
anatomy(props);
return null;
},
}));
vi.mock("@/components/insights/insight-status-card", () => ({
InsightStatusCard: () => null,
}));
vi.mock("../score-history", () => ({
ScoreHistoryChart: () => null,
ScoreTrendChartDynamic: () => null,
}));
vi.mock("@/lib/i18n/context", () => ({
useTranslations: () => ({
t: (key: string, vars?: Record<string, string | number>) =>
vars ? `${key}:${JSON.stringify(vars)}` : key,
}),
}));
vi.mock("../use-derived-metric", () => ({
useDerivedMetric: () => ({
isLoading: false,
data: {
status: "ok",
value: {
score: 70,
band: "yellow",
subScores: [
{ key: "consistency", value: null, weight: 0.2, gap: "few_nights" },
],
rhythmNights: 2,
rhythmMinNights: 5,
},
coverage: 1,
confidence: "high",
provenance: {},
},
}),
}));
import { CompositeScoreAnatomy } from "../composite-score-anatomy";
describe("sleep score sheet — the few-nights gap", () => {
it("names the published floor", () => {
renderToStaticMarkup(<CompositeScoreAnatomy metric="SLEEP_SCORE" />);
const props = anatomy.mock.calls.at(-1)![0] as {
contributors: Array<{ key: string; missingLabel?: string }>;
};
const consistency = props.contributors.find((c) => c.key === "consistency");
expect(consistency?.missingLabel).toContain('"count":2');
expect(consistency?.missingLabel).toContain('"needed":5');
});
});
@@ -10,8 +10,9 @@ import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { metricFractionDigits } from "@/lib/measurements/value-domain";
import { apiGet } from "@/lib/api/api-fetch";
import { readFailureKind } from "@/lib/api/read-failure";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { ReadFailureRow } from "@/components/ui/read-failure-row";
import { QueryErrorRow } from "@/components/ui/query-error-row";
import { Skeleton } from "@/components/ui/skeleton";
import { TileHeader } from "@/components/insights/tile-header";
import type { CoachReadStripData } from "@/lib/insights/derived/coach-read-shape";
@@ -60,6 +61,13 @@ export interface CoachReadStripProps {
valueScale?: number;
}
/**
* The strip's body holds the height of the error row's Retry button (32 px,
* 44 px on a touch screen) in every state, so the placeholder, a failure and
* a one-line read all stand the same height and the chart below never moves.
*/
const STRIP_BODY = "min-h-8 pointer-coarse:min-h-11";
export function CoachReadStrip({
metricType,
unit,
@@ -97,26 +105,19 @@ export function CoachReadStrip({
// baseline line degrades to the "learning" copy), so the placeholder only
// ever gives way to a card of its own height. A failed read gives way to a
// notice with a retry: dropping the strip read as "nothing to say about
// today", which is not what happened. The route is a manage-level read, so
// a viewer on a read-only share is refused it; that draws nothing, and a
// spent analytics budget says so without offering a retry.
// today", which is not what happened. The notice sits inside the same card
// shell as the placeholder, so a failure does not move the chart either.
// The route is a manage-level read, so a viewer on a read-only share is
// refused it; that draws nothing, and a spent analytics budget says so
// without offering a retry.
if (!mounted || !data) {
if (!isAuthenticated) return null;
if (isError) {
return (
<ReadFailureRow
error={error}
slot="coach-read-strip-error"
message={t("insights.coach.readStrip.loadError")}
onRetry={() => void refetch()}
/>
);
}
if (isError && readFailureKind(error) === "refused") return null;
return (
<Card
data-slot="coach-read-strip"
data-state="loading"
aria-busy="true"
data-state={isError ? "error" : "loading"}
aria-busy={isError ? undefined : "true"}
className="gap-2 py-3 md:py-4"
>
<CardHeader>
@@ -126,8 +127,18 @@ export function CoachReadStrip({
titleAs="h2"
/>
</CardHeader>
<CardContent>
<Skeleton className="h-5.5 w-3/4" />
<CardContent className={STRIP_BODY}>
{isError ? (
<QueryErrorRow
error={error}
slot="coach-read-strip-error"
message={t("insights.coach.readStrip.loadError")}
onRetry={() => void refetch()}
className="flex-row items-center justify-between rounded-none border-0 bg-transparent p-0"
/>
) : (
<Skeleton className="h-5.5 w-3/4" />
)}
</CardContent>
</Card>
);
@@ -236,12 +247,12 @@ export function CoachReadStrip({
<TileHeader
icon={Sparkles}
title={t("insights.coach.readStrip.label")}
// L3 — top-level section on every metric sub-page, sibling of the
// Top-level section on every metric sub-page, sibling of the
// already-`h2` stat strip directly under the page `h1`.
titleAs="h2"
/>
</CardHeader>
<CardContent>
<CardContent className={STRIP_BODY}>
<div className="min-w-0 space-y-1 text-sm leading-relaxed">
{baselineLine ? (
<p data-slot="coach-read-baseline" className="text-pretty">
@@ -186,6 +186,7 @@ export function CompositeScoreAnatomy({
return (
<div className={className}>
<QueryErrorRow
error={query.error}
slot="composite-anatomy-error"
onRetry={() => void query.refetch()}
/>
@@ -242,6 +243,7 @@ export function CompositeScoreAnatomy({
s.gap === "few_nights"
? t("insights.derived.composite.SLEEP_SCORE.gap.fewNights", {
count: v.rhythmNights ?? 0,
needed: v.rhythmMinNights,
})
: s.gap === "no_main_sleep"
? t("insights.derived.composite.SLEEP_SCORE.gap.noMainSleep")
@@ -891,6 +891,7 @@ export function VitalsDashboard({ batch, layout, className }: DashboardProps) {
subtitle={t("insights.derived.vitals.sectionSubtitle")}
/>
<QueryErrorRow
error={batch.error}
slot="vitals-dashboard-error"
retrySlot="vitals-dashboard-retry"
message={t("insights.derived.vitals.loadError")}