chore(release): v1.4.25

Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites).

See CHANGELOG.md for the full per-section delta.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-14 23:49:32 +02:00
1 parent de0689e419
commit 17b8d8d2c2
528 files changed
+104033 -6524

No files matched your search

@@ -0,0 +1,191 @@
/**
* v1.4.25 W19c-Frontend — `<AdvancedSection>` Research Mode card tests.
*
* The card lives next to the danger-zone delete and drives three
* server interactions:
*
* GET /api/auth/me/research-mode on mount, via TanStack Query
* POST /api/auth/me/research-mode via the acknowledgment dialog
* DELETE /api/auth/me/research-mode directly when the user
* toggles OFF
*
* The toggle ON path opens the dialog; only the dialog's CTA fires
* the POST (so the user reads the disclaimer first). OFF fires
* DELETE directly. A version-mismatch banner renders above the
* toggle whenever `acknowledgedVersion !== currentDisclaimerVersion`
* even when `enabled === true`.
*
* The dialog itself is covered by
* `ResearchModeAcknowledgmentDialog.test.tsx`; we mock it down to a
* marker here so the toggle behaviour is the only contract under
* test.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
const queryResults: Record<string, unknown> = {};
function setQueryResult(keyJoined: string, data: unknown) {
queryResults[keyJoined] = data;
}
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
const key = (queryKey as Array<string | number>).join("/");
return {
data: queryResults[key],
isLoading: false,
};
},
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
useMutation: () => ({ mutate: vi.fn(), isPending: false }),
}));
// The acknowledgment dialog is exercised in its own spec; mock the
// import to a transparent marker so we can assert "the toggle ON path
// renders the dialog with the right props" without re-running the
// dialog tree.
vi.mock("@/components/medications/ResearchModeAcknowledgmentDialog", () => ({
ResearchModeAcknowledgmentDialog: ({
open,
currentDisclaimerVersion,
}: {
open: boolean;
currentDisclaimerVersion: string | null;
}) => (
<div
data-slot="mock-ack-dialog"
data-open={open ? "true" : "false"}
data-version={currentDisclaimerVersion ?? ""}
/>
),
}));
import { AdvancedSection } from "../advanced-section";
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
beforeEach(() => {
for (const k of Object.keys(queryResults)) delete queryResults[k];
});
describe("<AdvancedSection> → Research Mode card", () => {
it("renders the section title + subtitle + toggle in OFF state", () => {
setQueryResult("research-mode", {
enabled: false,
acknowledgedAt: null,
acknowledgedVersion: null,
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<AdvancedSection />);
expect(html).toContain('data-slot="settings-research-mode-card"');
expect(html).toContain("Research Mode");
expect(html).toContain("Show the estimated drug-level chart");
// OFF state status line.
expect(html).toContain("Disabled. The drug-level chart is hidden.");
// No re-prompt banner when versions already align (or the user has
// never acknowledged in the first place).
expect(html).not.toContain('data-slot="settings-research-mode-reprompt"');
// Switch is unchecked.
const switchTag = html.match(
/<button[^>]*data-slot="settings-research-mode-toggle"[^>]*>/,
)?.[0];
expect(switchTag).toBeDefined();
expect(switchTag).not.toMatch(/data-state="checked"/);
});
it("renders the acknowledged-on status when enabled + versions aligned", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T08:30:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<AdvancedSection />);
// Acknowledged-on copy carries the formatted date (the i18n
// template uses `{date}`; the formatter renders the day).
expect(html).toMatch(/Acknowledged on/);
// Banner stays hidden when versions match.
expect(html).not.toContain('data-slot="settings-research-mode-reprompt"');
// Switch is checked.
const switchTag = html.match(
/<button[^>]*data-slot="settings-research-mode-toggle"[^>]*>/,
)?.[0];
expect(switchTag).toMatch(/data-state="checked"/);
});
it("renders the re-prompt banner when versions diverge", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-04-01T00:00:00Z",
acknowledgedVersion: "2026-04-01.1",
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<AdvancedSection />);
expect(html).toContain('data-slot="settings-research-mode-reprompt"');
expect(html).toContain("Disclaimer updated");
expect(html).toContain(
'data-slot="settings-research-mode-reprompt-cta"',
);
expect(html).toContain("Re-acknowledge disclaimer");
// Status line reflects the stale state without claiming
// "acknowledged on …" — that copy would mis-represent that the
// chart is currently painting.
expect(html).not.toMatch(/Acknowledged on/);
expect(html).toContain(
"The disclaimer was updated. Re-acknowledge below to bring the chart back.",
);
// The toggle stays "on" — we surface the previous choice; the
// banner explains why the chart isn't painting.
const switchTag = html.match(
/<button[^>]*data-slot="settings-research-mode-toggle"[^>]*>/,
)?.[0];
expect(switchTag).toMatch(/data-state="checked"/);
});
it("forwards the current server-supplied version to the dialog", () => {
setQueryResult("research-mode", {
enabled: false,
acknowledgedAt: null,
acknowledgedVersion: null,
currentDisclaimerVersion: "2026-06-01.2",
});
const html = render(<AdvancedSection />);
// The dialog renders even when closed (its `open` prop is what
// controls visibility); the data-version attribute lets us verify
// the parent passes the live version string through.
expect(html).toContain('data-slot="mock-ack-dialog"');
expect(html).toMatch(/data-version="2026-06-01\.2"/);
expect(html).toMatch(/data-open="false"/);
});
it("renders German copy when locale='de'", () => {
setQueryResult("research-mode", {
enabled: false,
acknowledgedAt: null,
acknowledgedVersion: null,
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<AdvancedSection />, "de");
expect(html).toContain("Forschungsmodus");
expect(html).toContain("Geschätzte Wirkstoffkurve anzeigen");
expect(html).toContain("Deaktiviert");
});
});
@@ -35,7 +35,7 @@ function renderShell(props: {
}
describe("SETTINGS_SECTION_SLUGS", () => {
it("declares the ten sections agreed for v1.4.16", () => {
it("declares the eleven sections agreed for v1.4.25", () => {
// Order matters — `generateStaticParams()` and the sidebar derive their
// ordering from this constant, so a reorder is a behaviour change.
// v1.4.3 split the dashboard panel: layout stays under `dashboard`,
@@ -44,12 +44,17 @@ describe("SETTINGS_SECTION_SLUGS", () => {
// v1.4.16 phase B7 added the consolidated `export` section between
// `api` and `advanced` so every "give me my data out" path lives in
// one place.
// v1.4.25 W5e added `sources` between `thresholds` and `ai` so the
// per-metric-class source-priority surface lives next to the other
// analytics-shaping controls (thresholds → ranges; sources →
// canonical source per metric).
expect([...SETTINGS_SECTION_SLUGS]).toEqual([
"account",
"integrations",
"notifications",
"dashboard",
"thresholds",
"sources",
"ai",
"api",
"export",
+41 -11
View File
@@ -43,6 +43,7 @@ import { formatDate } from "@/lib/format";
import { locales, localeLabels, type Locale } from "@/lib/i18n/config";
import { useTranslations } from "@/lib/i18n/context";
import { describePasskeyError } from "@/lib/passkey-errors";
import { TimezonePicker } from "@/components/settings/timezone-picker";
interface PasskeyInfo {
id: string;
@@ -71,6 +72,7 @@ export function AccountSection() {
const [heightCm, setHeightCm] = useState("");
const [dateOfBirth, setDateOfBirth] = useState("");
const [gender, setGender] = useState<string>("");
const [timezone, setTimezone] = useState<string>("Europe/Berlin");
const [saving, setSaving] = useState(false);
const [saveMsg, setSaveMsg] = useState<string | null>(null);
const [saveMsgType, setSaveMsgType] = useState<"success" | "error" | null>(
@@ -132,6 +134,7 @@ export function AccountSection() {
: "",
);
setGender(user.gender ?? "");
setTimezone(user.timezone || "Europe/Berlin");
}
async function handleSaveProfile(e: React.FormEvent) {
@@ -140,23 +143,48 @@ export function AccountSection() {
setSaveMsg(null);
setSaveMsgType(null);
const res = await fetch("/api/auth/profile", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: email.trim() || null,
heightCm: heightCm ? parseFloat(heightCm) : null,
dateOfBirth: dateOfBirth || null,
gender: gender || null,
// The timezone is owned by a dedicated route (v1.4.25 W7) so the
// resolver cache can be invalidated without piping the flag
// through the bigger profile patch path. Run the two PUTs in
// parallel — they're independent.
const [profileRes, tzRes] = await Promise.all([
fetch("/api/auth/profile", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: email.trim() || null,
heightCm: heightCm ? parseFloat(heightCm) : null,
dateOfBirth: dateOfBirth || null,
gender: gender || null,
}),
}),
});
user && timezone && timezone !== user.timezone
? fetch("/api/auth/me/timezone", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ timezone }),
})
: Promise.resolve({ ok: true } as Response),
]);
if (res.ok) {
if (profileRes.ok && tzRes.ok) {
setSaveMsg(t("settings.profileSaved"));
setSaveMsgType("success");
await refetch();
} else if (!tzRes.ok) {
// The dedicated tz endpoint owns the IANA validation error
// text. Surface its message verbatim so the user sees
// "Not a valid IANA timezone." instead of the generic save
// failure copy.
try {
const json = (await (tzRes as Response).json()) as { error?: string };
setSaveMsg(json.error || t("settings.timezoneInvalid"));
} catch {
setSaveMsg(t("settings.timezoneInvalid"));
}
setSaveMsgType("error");
} else {
const json = await res.json();
const json = await profileRes.json();
setSaveMsg(json.error || t("settings.savingError"));
setSaveMsgType("error");
}
@@ -396,6 +424,8 @@ export function AccountSection() {
</div>
</div>
<TimezonePicker value={timezone} onChange={setTimezone} />
<div className="space-y-2">
<Label htmlFor="language-select">{t("settings.language")}</Label>
<select
+179 -2
View File
@@ -1,8 +1,8 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Loader2, Trash2 } from "lucide-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, BookOpenCheck, Loader2, Trash2 } from "lucide-react";
import {
AlertDialog,
@@ -16,7 +16,14 @@ import {
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { ResearchModeAcknowledgmentDialog } from "@/components/medications/ResearchModeAcknowledgmentDialog";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import {
type ResearchModeStatus,
researchModeGateState,
} from "@/lib/medications/research-mode-types";
/**
* Settings → Advanced.
@@ -26,6 +33,17 @@ import { useTranslations } from "@/lib/i18n/context";
* What stays here is the irreversible danger-zone — the "wipe all my
* data" surface that should never live next to a single-click export
* button.
*
* v1.4.25 W19c-Frontend adds the Research Mode toggle on this page.
* Research Mode and the data-reset are both opt-in / version-gated
* controls; they share a semantic shelf even though they touch
* different parts of the user record. Toggle ON opens the
* acknowledgment dialog (the user reads + confirms before the server
* stamps the version). Toggle OFF fires DELETE directly. A separate
* amber banner above the toggle catches the version-mismatch case
* (server bumped the disclaimer while the user was still
* acknowledged) and surfaces a Re-acknowledge CTA that re-opens the
* dialog.
*/
export function AdvancedSection() {
const { t } = useTranslations();
@@ -47,11 +65,170 @@ export function AdvancedSection() {
</p>
</header>
<ResearchModeCard />
<DataResetCard />
</section>
);
}
/**
* v1.4.25 W21 Fix-N (simp-H3) — pull the nested ternary that decided
* the toggle's caption out of the JSX. The four-way ladder (loading /
* enabled-open / enabled-stale / disabled) is dense to read inline,
* and the surface stays open to a fifth state ("never queried") when
* we wire the offline shell in v1.4.26.
*/
function researchModeStatusLabel(
status: ResearchModeStatus | null | undefined,
isLoading: boolean,
t: (key: string, params?: Record<string, string | number>) => string,
): string {
if (isLoading) return t("common.loading");
const gate = researchModeGateState(status);
if (gate === "off") return t("settings.researchMode.disabledStatus");
if (gate === "stale") return t("settings.researchMode.enabledStaleStatus");
return t("settings.researchMode.acknowledgedOn", {
date: status?.acknowledgedAt
? formatDateTime(status.acknowledgedAt)
: "—",
});
}
function ResearchModeCard() {
const { t } = useTranslations();
const queryClient = useQueryClient();
const [dialogOpen, setDialogOpen] = useState(false);
const [toggleBusy, setToggleBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const { data: status, isLoading } = useQuery<ResearchModeStatus | null>({
queryKey: ["research-mode"],
queryFn: async () => {
const res = await fetch("/api/auth/me/research-mode");
if (!res.ok) return null;
const json = await res.json();
return json.data as ResearchModeStatus;
},
staleTime: 60 * 1000,
});
const gateState = researchModeGateState(status);
const showRePrompt = gateState === "stale";
// The Switch's `checked` mirrors the server flag exactly — even when
// the version is stale we keep the toggle "on" so the user sees that
// their previous choice is preserved; the banner above the toggle
// explains why the chart isn't painting.
const switchChecked = !!status?.enabled;
async function handleToggle(next: boolean) {
if (toggleBusy) return;
setErrorMessage(null);
if (next) {
// Toggle ON → open the acknowledgment dialog. The dialog owns
// the POST; on success it invalidates the `research-mode` query
// and the toggle reflects the new state.
setDialogOpen(true);
return;
}
// Toggle OFF → fire DELETE directly.
setToggleBusy(true);
try {
const res = await fetch("/api/auth/me/research-mode", {
method: "DELETE",
});
if (!res.ok) {
setErrorMessage(t("settings.researchMode.disableError"));
return;
}
queryClient.invalidateQueries({ queryKey: ["research-mode"] });
} catch {
setErrorMessage(t("settings.researchMode.disableError"));
} finally {
setToggleBusy(false);
}
}
return (
<div
className="bg-card border-border rounded-xl border p-6"
data-slot="settings-research-mode-card"
>
<div className="flex items-center gap-2">
<BookOpenCheck className="text-dracula-purple h-5 w-5" />
<h2 className="text-lg font-semibold">
{t("settings.researchMode.sectionTitle")}
</h2>
</div>
<p className="text-muted-foreground mt-1 text-xs">
{t("settings.researchMode.subtitle")}
</p>
{showRePrompt && (
<div
role="alert"
data-slot="settings-research-mode-reprompt"
className="border-warning/40 bg-warning/10 mt-4 rounded-md border-l-4 px-3 py-2 text-sm"
>
<p className="text-foreground font-medium">
{t("settings.researchMode.rePromptTitle")}
</p>
<p className="text-muted-foreground mt-1 text-xs">
{t("settings.researchMode.rePromptBody")}
</p>
<Button
size="sm"
variant="outline"
className="mt-2"
onClick={() => setDialogOpen(true)}
data-slot="settings-research-mode-reprompt-cta"
>
{t("settings.researchMode.rePromptCta")}
</Button>
</div>
)}
<div className="mt-4 flex items-start justify-between gap-3">
<div className="space-y-0.5">
<p className="text-sm font-medium">
{t("settings.researchMode.toggleLabel")}
</p>
<p
className="text-muted-foreground text-xs"
data-slot="settings-research-mode-status"
>
{researchModeStatusLabel(status, isLoading, t)}
</p>
</div>
<Switch
checked={switchChecked}
disabled={isLoading || toggleBusy}
onCheckedChange={(next) => {
void handleToggle(next);
}}
aria-label={t("settings.researchMode.toggleLabel")}
data-slot="settings-research-mode-toggle"
/>
</div>
{errorMessage && (
<p
role="alert"
className="text-destructive mt-3 text-sm"
data-slot="settings-research-mode-error"
>
{errorMessage}
</p>
)}
<ResearchModeAcknowledgmentDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
currentDisclaimerVersion={status?.currentDisclaimerVersion ?? null}
/>
</div>
);
}
function DataResetCard() {
const { t } = useTranslations();
const queryClient = useQueryClient();
@@ -48,6 +48,8 @@ const WIDGET_LABEL_KEYS: Record<DashboardWidgetId, string> = {
// for the polished `<InsightsCardPreview>` (top severity-ordered AI
// recommendations + ring confidence meter + "View all" CTA).
insightsPreview: "dashboard.insightsPreview",
// v1.4.25 W8d — VO2 max secondary-metric tile (opt-in).
vo2Max: "dashboard.vo2Max",
};
export function DashboardLayoutSection({ id }: { id: string }) {
+9 -1
View File
@@ -105,6 +105,8 @@ interface ExportCardShellProps {
children?: React.ReactNode;
/** Footer slot — typically the "Download" button + status text. */
footer: React.ReactNode;
/** Extra grid-position classes applied to the outer card div. */
outerClassName?: string;
}
function ExportCardShell({
@@ -115,11 +117,12 @@ function ExportCardShell({
format,
children,
footer,
outerClassName,
}: ExportCardShellProps) {
return (
<div
data-testid={testId}
className="bg-card border-border flex h-full flex-col rounded-xl border p-5"
className={`bg-card border-border flex h-full flex-col rounded-xl border p-5${outerClassName ? ` ${outerClassName}` : ""}`}
>
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2">
@@ -180,6 +183,10 @@ function DoctorReportCard() {
startDate: payload.startDate,
endDate: payload.endDate,
practiceName: payload.practiceName,
// v1.4.25 W6c — per-section toggles. The aggregator drops
// disabled sections (mood is filtered server-side so the
// data never leaves the DB row).
sections: payload.sections,
}),
});
if (!res.ok) {
@@ -208,6 +215,7 @@ function DoctorReportCard() {
title={t("settings.sections.export.cards.doctorReport.title")}
description={t("settings.sections.export.cards.doctorReport.description")}
format="PDF"
outerClassName="md:col-span-2"
footer={
<Button
data-testid="export-action-doctor-report"
@@ -230,6 +230,12 @@ function WithingsCard({
lastSyncedAt?: string | null;
connectedAt?: string;
tokenExpired?: boolean;
// v1.4.25 W5d — reconnect banner conditional. `null` =
// legacy v1.4.24 connection without `user.activity`; the
// user needs to re-auth before steps / active energy /
// distance / floors ingest unlocks.
scope?: string | null;
hasActivityScope?: boolean;
};
},
enabled: isAuthenticated,
@@ -352,6 +358,32 @@ function WithingsCard({
<div className="mt-4 space-y-4">
{errorMessage && <IntegrationErrorMessage message={errorMessage} />}
{/* v1.4.25 W5d — Withings activity-scope reconnect banner.
Only paints when (a) the user has an active Withings
connection (so the credentials are already saved + a token
exists) AND (b) the persisted scope is missing
`user.activity`. Reconnecting takes the user through the
standard /api/withings/connect → Withings → callback flow;
the callback persists the upgraded scope and the banner
vanishes on the next status poll. */}
{status?.connected && status?.hasActivityScope === false && (
<a
href="/api/withings/connect"
data-testid="withings-reconnect-banner"
className="border-warning/30 bg-warning/10 text-warning-foreground hover:bg-warning/20 block rounded-md border px-3 py-2 text-sm transition-colors"
>
<span className="font-medium">
{t("settings.integrations.withings.reconnect.banner.title")}
</span>
<span className="text-muted-foreground block text-xs">
{t("settings.integrations.withings.reconnect.banner.body")}
</span>
<span className="text-primary mt-1 inline-block text-xs font-medium">
{t("settings.integrations.withings.reconnect.banner.action")}
{" →"}
</span>
</a>
)}
<div className="space-y-3">
<h3 className="text-sm font-medium">
{t("settings.withingsCredentials")}
@@ -21,6 +21,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
AlertCircle,
Bell,
CheckCircle2,
Clock,
Loader2,
@@ -123,9 +124,12 @@ export function NotificationStatusCard() {
className="bg-card border-border rounded-xl border p-6"
data-testid="notification-status-empty"
>
<h2 className="text-lg font-semibold">
{t("settings.notificationStatus.title")}
</h2>
<div className="flex items-center gap-2">
<Bell className="text-primary h-5 w-5" />
<h2 className="text-lg font-semibold">
{t("settings.notificationStatus.title")}
</h2>
</div>
<p className="text-muted-foreground mt-1 text-sm">
{t("settings.notificationStatus.emptyDescription")}
</p>
@@ -136,9 +140,12 @@ export function NotificationStatusCard() {
return (
<div className="bg-card border-border rounded-xl border p-6">
<header className="mb-4">
<h2 className="text-lg font-semibold">
{t("settings.notificationStatus.title")}
</h2>
<div className="flex items-center gap-2">
<Bell className="text-primary h-5 w-5" />
<h2 className="text-lg font-semibold">
{t("settings.notificationStatus.title")}
</h2>
</div>
<p className="text-muted-foreground text-xs">
{t("settings.notificationStatus.description")}
</p>
@@ -16,6 +16,7 @@ import {
Download,
Info,
KeyRound,
Layers,
LayoutDashboard,
Link2,
Settings2,
@@ -35,6 +36,7 @@ const SLUG_ICON: Record<SettingsSectionSlug, LucideIcon> = {
notifications: Bell,
dashboard: LayoutDashboard,
thresholds: SlidersHorizontal,
sources: Layers,
ai: Sparkles,
api: KeyRound,
export: Download,
+1
View File
@@ -12,6 +12,7 @@ export const SETTINGS_SECTION_SLUGS = [
"notifications",
"dashboard",
"thresholds",
"sources",
"ai",
"api",
"export",
+16 -2
View File
@@ -22,6 +22,7 @@ import {
Download,
Info,
KeyRound,
Layers,
LayoutDashboard,
Link2,
Settings2,
@@ -86,6 +87,11 @@ export const SETTINGS_SECTIONS: readonly SettingsSection[] = [
titleKey: "settings.sections.thresholds.title",
icon: SlidersHorizontal,
},
{
slug: "sources",
titleKey: "settings.sections.sources.title",
icon: Layers,
},
{ slug: "ai", titleKey: "settings.sections.ai.title", icon: Sparkles },
{ slug: "api", titleKey: "settings.sections.api.title", icon: KeyRound },
{
@@ -129,8 +135,13 @@ export function SettingsShell({ active, children }: SettingsShellProps) {
const { t } = useTranslations();
const activeSlug = deriveActiveSlug(pathname, active);
// v1.4.25 W8 — AuthShell wraps the page in `px-4 py-6 md:px-6`
// already, so this inner shell only carries the wider max-width.
// Previously the duplicate `px-4 py-6 md:px-6 md:py-8` here was
// producing visibly more top/bottom whitespace on Settings/Admin
// pages than on Dashboard/Insights/Measurements.
return (
<div className="mx-auto w-full max-w-screen-xl px-4 py-6 md:px-6 md:py-8">
<div className="mx-auto w-full max-w-screen-xl">
{/* Mobile section strip — horizontal scroll, hidden on md+.
`no-scrollbar` (defined in `globals.css`) suppresses the
painted scrollbar; the horizontal swipe + keyboard arrow
@@ -152,7 +163,10 @@ export function SettingsShell({ active, children }: SettingsShellProps) {
href={`/settings/${section.slug}`}
aria-current={isActive ? "page" : undefined}
className={cn(
"flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors",
// v1.4.25 W8 — chip strip is the primary mobile-settings
// navigation surface. Pad to WCAG 2.5.5 44 px so the
// chips can be tapped without zoom on a Pixel-5.
"flex min-h-11 items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors",
isActive
? "border-primary/40 bg-primary/10 text-primary"
: "border-border text-foreground hover:bg-accent",
+566
View File
@@ -0,0 +1,566 @@
"use client";
/**
* v1.4.25 W5e — Settings → Sources.
*
* Per-metric-class source priority. When more than one ingest source
* records the same metric for the same day, the analytics aggregator
* picks ONE canonical source per day (for cumulative metrics like
* steps / sleep duration) or surfaces a "preferred" source (for point
* measurements like weight / BP). Non-picked rows stay in the DB as an
* audit trail.
*
* Today (v1.4.25) only WITHINGS + MANUAL coexist; the cumulative-metric
* aggregator no-ops because no user has two ingest paths reporting the
* same daily total. The UI lands now so v1.5's Apple Health passthrough
* drops onto a known foundation — every user's preferences carry
* straight into iOS-era analytics without an extra migration step.
*
* v1.4.25 W8c — two-axis extension. The same screen now hosts three
* vertically-stacked sections (Marc no-split directive):
* 1. Global default ladder per metric class (existing).
* 2. Per-metric override expander — collapsed by default; an
* explicit knob for power users (the global ladder already lives
* above and most users never open this).
* 3. Device-type override expander — collapsed by default; one
* global ladder ("watch beats phone beats scale") with optional
* per-metric overrides.
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import {
ArrowDown,
ArrowUp,
ChevronDown,
Layers,
Loader2,
RotateCcw,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import {
DEFAULT_DEVICE_TYPE_PRIORITY,
DEFAULT_SOURCE_PRIORITY,
type DeviceType,
type DeviceTypePriority,
type MetricPriority,
SOURCE_PRIORITY_METRIC_KEYS,
type SourcePriorityMetricKey,
} from "@/lib/validations/source-priority";
/**
* Resolved shape returned by `GET /api/auth/me/source-priority`. Mirrors
* `parseSourcePriority()`'s return: every metric ladder is defaulted,
* the two-axis containers are present (possibly empty).
*/
interface ResolvedPriority extends Required<MetricPriority> {
metricPriority: Required<MetricPriority>;
deviceTypePriority: DeviceTypePriority;
}
const METRIC_LABEL_KEYS: Record<SourcePriorityMetricKey, string> = {
steps: "settings.sections.sources.metrics.steps",
activeEnergy: "settings.sections.sources.metrics.activeEnergy",
walkingRunningDistance:
"settings.sections.sources.metrics.walkingRunningDistance",
flightsClimbed: "settings.sections.sources.metrics.flightsClimbed",
sleep: "settings.sections.sources.metrics.sleep",
weight: "settings.sections.sources.metrics.weight",
bloodPressure: "settings.sections.sources.metrics.bloodPressure",
pulse: "settings.sections.sources.metrics.pulse",
bodyFat: "settings.sections.sources.metrics.bodyFat",
bodyTemperature: "settings.sections.sources.metrics.bodyTemperature",
spo2: "settings.sections.sources.metrics.spo2",
hrv: "settings.sections.sources.metrics.hrv",
restingHeartRate: "settings.sections.sources.metrics.restingHeartRate",
vo2Max: "settings.sections.sources.metrics.vo2Max",
};
const SOURCE_LABEL_KEYS: Record<string, string> = {
WITHINGS: "settings.sections.sources.sourceLabels.WITHINGS",
APPLE_HEALTH: "settings.sections.sources.sourceLabels.APPLE_HEALTH",
MANUAL: "settings.sections.sources.sourceLabels.MANUAL",
IMPORT: "settings.sections.sources.sourceLabels.IMPORT",
};
const DEVICE_TYPE_LABEL_KEYS: Record<DeviceType, string> = {
watch: "settings.sections.sources.deviceLabels.watch",
band: "settings.sections.sources.deviceLabels.band",
ring: "settings.sections.sources.deviceLabels.ring",
phone: "settings.sections.sources.deviceLabels.phone",
scale: "settings.sections.sources.deviceLabels.scale",
other: "settings.sections.sources.deviceLabels.other",
unknown: "settings.sections.sources.deviceLabels.unknown",
};
export function SourcesSection() {
const { t } = useTranslations();
const queryClient = useQueryClient();
const { data: remote, isLoading } = useQuery({
queryKey: queryKeys.sourcePriority(),
queryFn: async () => {
const res = await fetch("/api/auth/me/source-priority");
if (!res.ok) throw new Error("failed");
const json = await res.json();
return json.data as ResolvedPriority;
},
});
// Local draft state — same pattern as `<DashboardLayoutSection>`. The
// user reorders sources via the up/down arrows; nothing hits the
// network until they click Save.
const [draft, setDraft] = useState<ResolvedPriority | null>(null);
const priority = draft ?? remote ?? null;
const [showPerMetric, setShowPerMetric] = useState(false);
const [showDeviceType, setShowDeviceType] = useState(false);
const saveMutation = useMutation({
mutationFn: async (next: ResolvedPriority) => {
// PUT the W8c-canonical shape: nested `metricPriority` +
// `deviceTypePriority` together. The server's
// `parseSourcePriority` echoes the resolved shape back so the
// optimistic update is just a `setQueryData`.
const body = {
metricPriority: next.metricPriority,
deviceTypePriority: next.deviceTypePriority,
};
const res = await fetch("/api/auth/me/source-priority", {
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 ResolvedPriority;
},
onSuccess: (saved) => {
queryClient.setQueryData(queryKeys.sourcePriority(), saved);
// The analytics aggregator folds source priority into per-day
// canonical-row picks — flush its cache so the charts re-paint
// with the new picker on the next mount.
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
setDraft(null);
toast.success(t("settings.sections.sources.saveSuccess"));
},
onError: () => toast.error(t("settings.sections.sources.saveError")),
});
const resetMutation = useMutation({
mutationFn: async () => {
// Sending the empty W8c shape clears every per-user override; the
// server's `parseSourcePriority` then returns the constant
// defaults verbatim. Keeps the wire payload tiny.
const res = await fetch("/api/auth/me/source-priority", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
if (!res.ok) throw new Error("reset failed");
return (await res.json()).data as ResolvedPriority;
},
onSuccess: (saved) => {
queryClient.setQueryData(queryKeys.sourcePriority(), saved);
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
setDraft(null);
toast.success(t("settings.sections.sources.resetSuccess"));
},
});
/**
* Shared adjacent-swap for both ladder buckets. Returns a copy of
* `list` with `index` and `index+delta` swapped, or `null` when the
* target index falls outside the array. The helper deliberately stays
* generic (typed via `T`) so both the source ladder (string[]) and
* the device-type ladder (DeviceType[]) share one implementation —
* the previous moveSource + moveDeviceType pair drifted apart twice
* during W8c before they were re-aligned.
*/
function reorderLadder<T>(
list: readonly T[],
index: number,
delta: -1 | 1,
): T[] | null {
const targetIdx = index + delta;
if (targetIdx < 0 || targetIdx >= list.length) return null;
const next = [...list];
[next[index], next[targetIdx]] = [next[targetIdx], next[index]];
return next;
}
function moveSource(
metric: SourcePriorityMetricKey,
index: number,
delta: -1 | 1,
) {
if (!priority) return;
const current =
priority.metricPriority[metric] ?? DEFAULT_SOURCE_PRIORITY[metric];
const list = reorderLadder(current, index, delta);
if (!list) return;
const nextMetric = { ...priority.metricPriority, [metric]: list };
setDraft({
...priority,
...nextMetric,
metricPriority: nextMetric,
});
}
function moveDeviceType(
/** `null` for the global ladder, MeasurementType-enum string otherwise. */
bucket: string | null,
index: number,
delta: -1 | 1,
) {
if (!priority) return;
const key = bucket ?? "default";
const current =
priority.deviceTypePriority[key] ?? DEFAULT_DEVICE_TYPE_PRIORITY;
const list = reorderLadder(current, index, delta);
if (!list) return;
const nextDevicePriority: DeviceTypePriority = {
...priority.deviceTypePriority,
[key]: list,
};
setDraft({ ...priority, deviceTypePriority: nextDevicePriority });
}
function resetMetricToDefault(metric: SourcePriorityMetricKey) {
if (!priority) return;
const nextMetric: Required<MetricPriority> = {
...priority.metricPriority,
[metric]: [...DEFAULT_SOURCE_PRIORITY[metric]],
};
setDraft({
...priority,
...nextMetric,
metricPriority: nextMetric,
});
}
function resetDeviceTypeAxis() {
if (!priority) return;
setDraft({ ...priority, deviceTypePriority: {} });
}
const dirty = draft !== null && priority !== null;
// The per-metric expander shows every metric whose ladder has been
// overridden, plus a hint when none has. Counter lives next to the
// expander label so the section "asks" for attention proportional
// to its setting.
const overriddenMetrics = useMemo(() => {
if (!priority) return [] as SourcePriorityMetricKey[];
return SOURCE_PRIORITY_METRIC_KEYS.filter((metric) => {
const list = priority.metricPriority[metric];
const defaultList = DEFAULT_SOURCE_PRIORITY[metric];
if (!list || list.length !== defaultList.length) return true;
return list.some((s, i) => s !== defaultList[i]);
});
}, [priority]);
// Count distinct overrides the user has set on the device-type axis.
// `default` counts as one if present; every per-metric override
// (`WEIGHT`, `ACTIVITY_STEPS`, …) counts as one more. The number drives
// the expander label so the section is self-explanatory at a glance.
const deviceTypeOverrideCount = useMemo(() => {
if (!priority) return 0;
return Object.keys(priority.deviceTypePriority).length;
}, [priority]);
return (
<section
aria-labelledby="settings-section-sources-title"
className="space-y-6"
>
<header className="space-y-1">
<h1
id="settings-section-sources-title"
className="text-2xl font-semibold tracking-tight"
>
{t("settings.sections.sources.title")}
</h1>
<p className="text-muted-foreground text-sm">
{t("settings.sections.sources.description")}
</p>
</header>
<div className="bg-card border-border space-y-4 rounded-xl border p-6">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
<div className="flex items-center gap-2">
<Layers className="text-primary h-5 w-5" />
<h2 className="text-lg font-semibold">
{t("settings.sections.sources.cardTitle")}
</h2>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => resetMutation.mutate()}
disabled={resetMutation.isPending || saveMutation.isPending}
className="self-end sm:self-auto"
>
<RotateCcw className="mr-2 h-3.5 w-3.5" />
{t("settings.sections.sources.resetDefaults")}
</Button>
</div>
<p className="text-muted-foreground text-xs">
{t("settings.sections.sources.help")}
</p>
{isLoading || !priority ? (
<div className="text-muted-foreground flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{t("common.loading")}
</div>
) : (
<div className="space-y-3">
{SOURCE_PRIORITY_METRIC_KEYS.map((metric) => {
const list =
priority.metricPriority[metric] ??
DEFAULT_SOURCE_PRIORITY[metric];
return (
<div
key={metric}
className="border-border bg-background/30 space-y-2 rounded-md border p-3"
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium">
{t(METRIC_LABEL_KEYS[metric])}
</span>
</div>
<ul className="space-y-1">
{list.map((source, index) => (
<li
key={`${metric}-${source}-${index}`}
className="border-border bg-card flex items-center gap-2 rounded-md border px-2 py-1.5"
>
<span className="text-muted-foreground w-5 text-xs font-medium tabular-nums">
{index + 1}.
</span>
<span className="flex-1 text-sm">
{t(SOURCE_LABEL_KEYS[source] ?? source)}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11"
onClick={() => moveSource(metric, index, -1)}
disabled={index === 0 || saveMutation.isPending}
aria-label={t("settings.sections.sources.moveUp")}
>
<ArrowUp className="h-3.5 w-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11"
onClick={() => moveSource(metric, index, 1)}
disabled={
index === list.length - 1 || saveMutation.isPending
}
aria-label={t("settings.sections.sources.moveDown")}
>
<ArrowDown className="h-3.5 w-3.5" />
</Button>
</li>
))}
</ul>
</div>
);
})}
</div>
)}
{/* ── v1.4.25 W8c — per-metric override expander ──
Collapsed by default. The global ladder above already
covers every metric; this section lets a power user reset
a single metric back to the constant default in one click. */}
{priority && (
<div className="border-border space-y-2 border-t pt-4">
<button
type="button"
onClick={() => setShowPerMetric((prev) => !prev)}
aria-expanded={showPerMetric}
aria-controls="sources-per-metric-panel"
className="text-foreground hover:text-primary flex items-center gap-2 text-sm font-medium transition-colors"
>
<ChevronDown
className={`h-4 w-4 transition-transform ${
showPerMetric ? "rotate-180" : ""
}`}
/>
{t("settings.sections.sources.perMetricToggle", {
count: overriddenMetrics.length,
})}
</button>
{showPerMetric && (
<div
id="sources-per-metric-panel"
role="region"
className="bg-background/30 border-border space-y-3 rounded-md border p-3"
>
<p className="text-muted-foreground text-xs">
{t("settings.sections.sources.perMetricHelp")}
</p>
{overriddenMetrics.length === 0 ? (
<p className="text-muted-foreground text-xs italic">
{t("settings.sections.sources.perMetricEmpty")}
</p>
) : (
<ul className="space-y-2">
{overriddenMetrics.map((metric) => (
<li
key={metric}
className="border-border bg-card flex items-center justify-between gap-3 rounded-md border px-3 py-2"
>
<span className="text-sm">
{t(METRIC_LABEL_KEYS[metric])}
</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => resetMetricToDefault(metric)}
disabled={saveMutation.isPending}
>
{t("settings.sections.sources.resetMetric")}
</Button>
</li>
))}
</ul>
)}
</div>
)}
</div>
)}
{/* ── v1.4.25 W8c — device-type override expander ──
One global ladder ("watch beats phone beats scale"). When
multiple device-types stream the same source's metric
(Apple Watch + iPhone → APPLE_HEALTH steps), the higher-
ranked device-type wins. Collapsed by default. */}
{priority && (
<div className="border-border space-y-2 border-t pt-4">
<button
type="button"
onClick={() => setShowDeviceType((prev) => !prev)}
aria-expanded={showDeviceType}
aria-controls="sources-device-type-panel"
className="text-foreground hover:text-primary flex items-center gap-2 text-sm font-medium transition-colors"
>
<ChevronDown
className={`h-4 w-4 transition-transform ${
showDeviceType ? "rotate-180" : ""
}`}
/>
{t("settings.sections.sources.deviceTypeToggle", {
count: deviceTypeOverrideCount,
})}
</button>
{showDeviceType && (
<div
id="sources-device-type-panel"
role="region"
className="bg-background/30 border-border space-y-3 rounded-md border p-3"
>
<p className="text-muted-foreground text-xs">
{t("settings.sections.sources.deviceTypeHelp")}
</p>
<div className="flex items-center justify-between">
<span className="text-sm font-medium">
{t("settings.sections.sources.deviceTypeDefault")}
</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={resetDeviceTypeAxis}
disabled={saveMutation.isPending}
>
<RotateCcw className="mr-1 h-3 w-3" />
{t("settings.sections.sources.resetDeviceTypes")}
</Button>
</div>
<ul className="space-y-1">
{(
priority.deviceTypePriority.default ??
DEFAULT_DEVICE_TYPE_PRIORITY
).map((deviceType, index, list) => (
<li
key={`device-default-${deviceType}-${index}`}
className="border-border bg-card flex items-center gap-2 rounded-md border px-2 py-1.5"
>
<span className="text-muted-foreground w-5 text-xs font-medium tabular-nums">
{index + 1}.
</span>
<span className="flex-1 text-sm">
{t(DEVICE_TYPE_LABEL_KEYS[deviceType])}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11"
onClick={() =>
moveDeviceType(null, index, -1)
}
disabled={index === 0 || saveMutation.isPending}
aria-label={t("settings.sections.sources.moveUp")}
>
<ArrowUp className="h-3.5 w-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11"
onClick={() => moveDeviceType(null, index, 1)}
disabled={
index === list.length - 1 || saveMutation.isPending
}
aria-label={t("settings.sections.sources.moveDown")}
>
<ArrowDown className="h-3.5 w-3.5" />
</Button>
</li>
))}
</ul>
</div>
)}
</div>
)}
{dirty && priority && (
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
<Button
type="button"
variant="ghost"
onClick={() => setDraft(null)}
disabled={saveMutation.isPending}
>
{t("common.cancel")}
</Button>
<Button
type="button"
onClick={() => saveMutation.mutate(priority)}
disabled={saveMutation.isPending}
>
{saveMutation.isPending && (
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
)}
{t("common.save")}
</Button>
</div>
)}
</div>
</section>
);
}
+123
View File
@@ -0,0 +1,123 @@
"use client";
/**
* Per-user timezone picker (v1.4.25 W7).
*
* Renders a native `<select>` over `Intl.supportedValuesOf('timeZone')`
* plus a "use my browser zone" button. The control is uncontrolled
* w.r.t. its parent — the parent passes in `value` + `onChange`, but
* the parent owns the network round-trip so this component stays
* synchronous + presentational. The save POSTs
* `PUT /api/auth/me/timezone` in the parent form's submit handler.
*
* Fallback: on older engines without `Intl.supportedValuesOf` we
* render a free-text input. Every modern browser back to mid-2022
* (Chrome 99 / Safari 15.4 / Firefox 99) ships the API; the fallback
* is defensive only.
*/
import { useMemo, useState } from "react";
import { Compass } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
detectBrowserTimezone,
listSupportedTimezones,
} from "@/lib/tz/format";
import { useTranslations } from "@/lib/i18n/context";
const NATIVE_SELECT_CLASS =
"border-input bg-background text-foreground ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border px-3 py-1 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none";
export interface TimezonePickerProps {
/** The user's current stored timezone. */
value: string;
/** Called when the user picks (or types) a new zone. */
onChange: (next: string) => void;
/** Render-only id for the label association. */
id?: string;
/** Optional override of the hint copy under the picker. */
hint?: string;
}
export function TimezonePicker({
value,
onChange,
id = "timezone",
hint,
}: TimezonePickerProps) {
const { t } = useTranslations();
// `listSupportedTimezones()` is engine-side; memoise so the list
// isn't reconstructed on every render.
const zones = useMemo(() => listSupportedTimezones(), []);
const [detected] = useState(() => detectBrowserTimezone());
const handleUseBrowserTz = () => {
if (detected) onChange(detected);
};
const labelHint = hint ?? t("settings.timezoneHint");
if (zones.length === 0) {
// Older engine — free-text fallback.
return (
<div className="space-y-2">
<Label htmlFor={id}>{t("settings.timezone")}</Label>
<Input
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="Europe/Berlin"
autoComplete="off"
/>
<p className="text-muted-foreground text-xs">{labelHint}</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleUseBrowserTz}
>
<Compass className="mr-2 h-4 w-4" />
{t("settings.timezoneDetect", { tz: detected })}
</Button>
</div>
);
}
return (
<div className="space-y-2">
<Label htmlFor={id}>{t("settings.timezone")}</Label>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<select
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${NATIVE_SELECT_CLASS} sm:max-w-sm`}
>
{/* Preserve the stored value even if the runtime's IANA
list changed across engines or tzdata rolls. */}
{!zones.includes(value) && value.length > 0 && (
<option value={value}>{value}</option>
)}
{zones.map((zone) => (
<option key={zone} value={zone}>
{zone}
</option>
))}
</select>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleUseBrowserTz}
className="sm:w-auto"
>
<Compass className="mr-2 h-4 w-4" />
{t("settings.timezoneDetect", { tz: detected })}
</Button>
</div>
<p className="text-muted-foreground text-xs">{labelHint}</p>
</div>
);
}