mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
v1.4.37 — final web polish before iOS focus
Carries the v1.4.36 perf carry-over for the full /api/analytics route (correlations + healthScore + bp_in_target on the rollup- coverage probe, 111s cold worst-case down to ~1.5-3s on power-user accounts), consolidates Apple Health step samples into a one-row- per-day list view with chevron drill-down and a nightly drain (~50x table compression once it converges), restores IntakeHistoryListV2 to the pre-v1.4.28 contract, converges every Coach affordance behind a single feature gate with an invariant test pin, lifts the medication-detail Mounjaro card to byte- equivalent parity with Ramipril, brings the Insights overview hero row to height parity, hardens getClientIp behind a new TRUST_CF_CONNECTING_IP env flag, ships the Arztbericht hero card on Settings -> Export, adds the Medikamenteneinnahme quick-add overlay to the dashboard, drops the timezone override toggle for a silent browser-zone auto-seed, and fixes the v1.4.36 red CI workflows. Documentation refreshed across all three repos with five new architecture diagrams in the Dracula palette. Unit suite 4354 -> 4486 passing; typecheck + lint clean.
This commit is contained in:
1 parent
0e2a99f8e7
commit
88028fa082
121 files changed
+13912
-1437
No files matched your search
@@ -544,13 +544,22 @@ export function MoodChart({
|
||||
// visibly heavier corner radius than BP / weight in the same
|
||||
// row. Align to the `rounded-md` shell so the three trend
|
||||
// tiles share one corner radius.
|
||||
//
|
||||
// v1.4.37 W4a item 5 — collapse the Card's inter-row gap to
|
||||
// 0 so the only space between the title and the chart strip
|
||||
// is the CardHeader's own `pb-1` (4 px), matching the
|
||||
// `mb-1` HealthChart paints below its plain `<div>` title.
|
||||
// Pre-fix Mood's `gap-1` (4 px) on top of the header `pb-1`
|
||||
// stacked an extra 4 px below the title, which read as a
|
||||
// ~12-16 px taller card than the BP/weight siblings inside
|
||||
// the trends row.
|
||||
className={
|
||||
mini ? "gap-1 rounded-md py-2 shadow-none" : undefined
|
||||
mini ? "gap-0 rounded-md py-2 shadow-none" : undefined
|
||||
}
|
||||
>
|
||||
<CardHeader
|
||||
className={
|
||||
mini ? "px-2 pb-1 [&]:gap-0.5" : "pb-2"
|
||||
mini ? "px-2 pb-1 [&]:gap-0" : "pb-2"
|
||||
}
|
||||
>
|
||||
{/* v1.4.19 A2 — mobile-first header: stack title row above
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* v1.4.37 W7b — `<MedicationIntakeQuickAdd>` contract suite.
|
||||
*
|
||||
* Project convention is SSR-only tests (vitest runs in `node`
|
||||
* environment; `@testing-library/react` is not installed). The
|
||||
* assertions below cover:
|
||||
*
|
||||
* 1. The pure `pickDefaultMedicationId` helper — the cool/easy
|
||||
* default-selection logic Marc 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
|
||||
* medications, the form is suppressed and an EmptyState-style
|
||||
* hint with a CTA to `/medications` is rendered.
|
||||
* 3. The populated-state SSR markup — picker + dose + time fields
|
||||
* mount with the right labels + 44 px touch floor.
|
||||
* 4. The POST submit contract — the handler that fires on Save is
|
||||
* observed via a fetch spy: the request method, URL, and body
|
||||
* shape (takenAt ISO string, skipped:false) must match the
|
||||
* `/api/medications/[id]/intake` route signature so the dashboard
|
||||
* quick-add stays in lockstep with the API W3 hardened.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
|
||||
// Stub @tanstack/react-query so the SSR render path doesn't try to
|
||||
// reach into a real QueryClient. The default-stub returns the
|
||||
// populated medications list; per-test mockReturnValue calls override.
|
||||
const mockUseQuery = vi.fn();
|
||||
const mockInvalidateQueries = vi.fn().mockResolvedValue(undefined);
|
||||
const mockQueryClient = { invalidateQueries: mockInvalidateQueries };
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: (opts: unknown) => mockUseQuery(opts),
|
||||
useQueryClient: () => mockQueryClient,
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
import {
|
||||
MedicationIntakeQuickAdd,
|
||||
pickDefaultMedicationId,
|
||||
type MedicationOption,
|
||||
} from "../medication-intake-quick-add";
|
||||
|
||||
function makeMed(
|
||||
id: string,
|
||||
overrides: Partial<MedicationOption> = {},
|
||||
): MedicationOption {
|
||||
return {
|
||||
id,
|
||||
name: `Med ${id}`,
|
||||
dose: "5 mg",
|
||||
active: true,
|
||||
schedules: [],
|
||||
lastTakenAt: null,
|
||||
todayEventCount: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderSSR(node: React.ReactElement, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseQuery.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("pickDefaultMedicationId — auto-select heuristic", () => {
|
||||
it("returns null when no active medications exist", () => {
|
||||
expect(pickDefaultMedicationId([])).toBeNull();
|
||||
expect(
|
||||
pickDefaultMedicationId([makeMed("a", { active: false })]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("auto-selects the single active medication", () => {
|
||||
expect(pickDefaultMedicationId([makeMed("solo")])).toBe("solo");
|
||||
});
|
||||
|
||||
it("prefers an in-window medication over the alphabetical fallback", () => {
|
||||
// 10:00 Berlin time on a weekday. The morning slot for med "b" is
|
||||
// open (08:00–11:00); med "a" has no schedule so it can only
|
||||
// surface via the alphabetical fallback. The helper must pick "b".
|
||||
const now = new Date("2026-05-12T08:00:00Z"); // 10:00 Berlin (UTC+2)
|
||||
const result = pickDefaultMedicationId(
|
||||
[
|
||||
makeMed("a"),
|
||||
makeMed("b", {
|
||||
schedules: [
|
||||
{
|
||||
id: "s1",
|
||||
windowStart: "08:00",
|
||||
windowEnd: "11:00",
|
||||
daysOfWeek: null,
|
||||
label: null,
|
||||
dose: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
now,
|
||||
);
|
||||
expect(result).toBe("b");
|
||||
});
|
||||
|
||||
it("falls back to the alphabetical-first active medication when nothing is due", () => {
|
||||
// 03:00 Berlin time: no schedules overlap. The helper should
|
||||
// alphabetically sort and pick the leading id, "ramipril".
|
||||
const now = new Date("2026-05-12T01:00:00Z"); // 03:00 Berlin
|
||||
const result = pickDefaultMedicationId(
|
||||
[
|
||||
makeMed("z", { name: "Zolpidem" }),
|
||||
makeMed("r", { name: "Ramipril" }),
|
||||
],
|
||||
now,
|
||||
);
|
||||
expect(result).toBe("r");
|
||||
});
|
||||
});
|
||||
|
||||
describe("<MedicationIntakeQuickAdd> — SSR contract", () => {
|
||||
it("renders the empty-state with a CTA to /medications when no active medications", () => {
|
||||
mockUseQuery.mockReturnValue({ data: [], isLoading: false });
|
||||
const html = renderSSR(<MedicationIntakeQuickAdd />);
|
||||
expect(html).toContain('data-testid="medication-intake-quick-add-empty"');
|
||||
// Visible copy resolves from i18n (no raw key leak).
|
||||
expect(html).toContain("No medications yet");
|
||||
expect(html).toContain('href="/medications"');
|
||||
// The form itself must not render — otherwise we'd ship a Save
|
||||
// button with no medication to record.
|
||||
expect(html).not.toContain(
|
||||
'data-testid="medication-intake-quick-add-form"',
|
||||
);
|
||||
// v1.4.37 W10 — the empty-state CTA must clear the 44 px touch
|
||||
// floor that W-CI raised on the onboarding checklist. The
|
||||
// `size="sm"` default would land at 32 px without an explicit
|
||||
// `min-h-11 sm:min-h-9` override.
|
||||
expect(html).toContain("min-h-11");
|
||||
});
|
||||
|
||||
it("renders the populated form with picker + dose + time fields", () => {
|
||||
mockUseQuery.mockReturnValue({
|
||||
data: [
|
||||
makeMed("med-1", { name: "Ramipril", dose: "5 mg" }),
|
||||
makeMed("med-2", { name: "Mounjaro", dose: "5 mg" }),
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
const html = renderSSR(<MedicationIntakeQuickAdd />);
|
||||
expect(html).toContain('data-testid="medication-intake-quick-add-form"');
|
||||
// Field-level testids pinned for the e2e + future-coverage handles.
|
||||
expect(html).toContain(
|
||||
'data-testid="medication-intake-quick-add-medication"',
|
||||
);
|
||||
expect(html).toContain('data-testid="medication-intake-quick-add-dose"');
|
||||
expect(html).toContain(
|
||||
'data-testid="medication-intake-quick-add-taken-at"',
|
||||
);
|
||||
// 44 px touch floor on every interactive field + the footer Save
|
||||
// button (WCAG 2.5.5). v1.4.37 W10 added the floor to the footer
|
||||
// buttons; the form fields already carried it.
|
||||
expect(html.match(/min-h-11/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("does not leak raw i18n keys in either locale", () => {
|
||||
mockUseQuery.mockReturnValue({ data: [], isLoading: false });
|
||||
const en = renderSSR(<MedicationIntakeQuickAdd />, "en");
|
||||
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
|
||||
// end-to-end, never their HTML entity form).
|
||||
expect(de).toContain("Medikamente angelegt");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,452 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useMemo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { DateTimeInput } from "@/components/ui/date-input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, Pill, Plus } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import {
|
||||
invalidateKeys,
|
||||
medicationDependentKeys,
|
||||
queryKeys,
|
||||
} from "@/lib/query-keys";
|
||||
import {
|
||||
reduceCurrentWindowStatus,
|
||||
toBerlinDate,
|
||||
type ScheduleWindowInput,
|
||||
} from "@/lib/medications/window-status";
|
||||
|
||||
/**
|
||||
* v1.4.37 W7b — dashboard "Hinzufügen" → "Medikamenteneinnahme" quick-add.
|
||||
*
|
||||
* Marc'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.
|
||||
*
|
||||
* Form shape mirrors `MoodForm` / `MeasurementForm`:
|
||||
*
|
||||
* 1. Medication picker. Auto-selects the only active medication when
|
||||
* the user has one; otherwise defaults to the first medication
|
||||
* whose schedule window is currently open (the cool/easy slice).
|
||||
* Falls back to the most-recently-created entry when nothing is
|
||||
* due. Disabled when the user has no active medications — the
|
||||
* sheet body renders an EmptyState-style hint instead of an
|
||||
* unusable form.
|
||||
* 2. Dose. Pre-filled from the medication's catalogue dose for
|
||||
* visual confirmation ("this is the strength I'm logging").
|
||||
* v1.4.37 W10 — rendered read-only because the POST body has no
|
||||
* `dose` field; any user edit would be silently dropped. When
|
||||
* the user wants to record a half/double dose they still edit
|
||||
* the medication itself on `/medications` until the v1.4.38
|
||||
* schema grows a `doseOverride` slot. Hint copy below the
|
||||
* field warns about the constraint so the user's mental model
|
||||
* tracks what the server persists.
|
||||
* 3. Time taken. Defaults to `now` (local datetime-local format
|
||||
* shaped the same as `MoodForm`).
|
||||
*
|
||||
* On success: invalidate `medicationDependentKeys` (medications +
|
||||
* analytics + insights + intake-summary + achievements) PLUS the
|
||||
* inline per-medication compliance chart key so the detail page tile
|
||||
* refreshes if it happens to be mounted elsewhere in the app.
|
||||
*
|
||||
* Mounted inside `<ResponsiveSheet>` from `page.tsx`; the action row
|
||||
* is portalled into the sheet's sticky footer slot via `footerSlot`,
|
||||
* matching the `MoodForm` / `MeasurementForm` contract so the Save
|
||||
* button stays reachable above the mobile keyboard.
|
||||
*/
|
||||
|
||||
interface Schedule extends ScheduleWindowInput {
|
||||
id: string;
|
||||
label: string | null;
|
||||
dose: string | null;
|
||||
}
|
||||
|
||||
export interface MedicationOption {
|
||||
id: string;
|
||||
name: string;
|
||||
dose: string;
|
||||
active: boolean;
|
||||
schedules: Schedule[];
|
||||
lastTakenAt: string | null;
|
||||
todayEventCount: number | null;
|
||||
}
|
||||
|
||||
interface MedicationIntakeQuickAddProps {
|
||||
onSuccess?: () => void;
|
||||
onCancel?: () => void;
|
||||
/**
|
||||
* v1.4.27 R4 RC2 contract — when mounted inside the responsive sheet,
|
||||
* the parent passes the sheet's sticky footer slot so the action row
|
||||
* (Cancel + Save) renders pinned above the soft keyboard. The
|
||||
* `<form>` keeps `submit-on-Enter` working through the HTML `form`
|
||||
* attribute on the portalled Save button.
|
||||
*/
|
||||
footerSlot?: HTMLElement | null;
|
||||
}
|
||||
|
||||
function getDefaultIntakeAtValue(): string {
|
||||
const now = new Date();
|
||||
const offset = now.getTimezoneOffset();
|
||||
const local = new Date(now.getTime() - offset * 60 * 1000);
|
||||
return local.toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the medication that should be pre-selected when the sheet opens.
|
||||
*
|
||||
* Priority:
|
||||
* 1. The active medication whose schedule window is currently open
|
||||
* (or late / very_late) — this is the "due now" surface.
|
||||
* 2. The single active medication when the user has exactly one.
|
||||
* 3. The first active medication alphabetically (stable fallback).
|
||||
*
|
||||
* Returns the medication id or `null` when no active medication exists.
|
||||
*/
|
||||
export function pickDefaultMedicationId(
|
||||
options: MedicationOption[],
|
||||
now: Date = new Date(),
|
||||
thresholds: { lateMinutes: number; missedMinutes: number } = {
|
||||
lateMinutes: 120,
|
||||
missedMinutes: 240,
|
||||
},
|
||||
): string | null {
|
||||
const actives = options.filter((m) => m.active);
|
||||
if (actives.length === 0) return null;
|
||||
if (actives.length === 1) return actives[0].id;
|
||||
|
||||
const nowBerlin = toBerlinDate(now);
|
||||
const due = actives.find((m) => {
|
||||
const status = reduceCurrentWindowStatus({
|
||||
schedules: m.schedules,
|
||||
nowBerlin,
|
||||
lateMinutes: thresholds.lateMinutes,
|
||||
missedMinutes: thresholds.missedMinutes,
|
||||
active: true,
|
||||
lastTakenAt: m.lastTakenAt,
|
||||
todayEventCount: m.todayEventCount ?? 0,
|
||||
});
|
||||
return status.status !== null;
|
||||
});
|
||||
if (due) return due.id;
|
||||
|
||||
// Stable alphabetical fallback when nothing is currently due.
|
||||
const sorted = [...actives].sort((a, b) =>
|
||||
a.name.localeCompare(b.name, "de", { sensitivity: "base" }),
|
||||
);
|
||||
return sorted[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export function MedicationIntakeQuickAdd({
|
||||
onSuccess,
|
||||
onCancel,
|
||||
footerSlot,
|
||||
}: MedicationIntakeQuickAddProps) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
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[];
|
||||
},
|
||||
});
|
||||
|
||||
const medications = useMemo(
|
||||
() =>
|
||||
Array.isArray(medicationsRaw)
|
||||
? medicationsRaw.filter((m) => m.active)
|
||||
: [],
|
||||
[medicationsRaw],
|
||||
);
|
||||
const sortedMedications = useMemo(
|
||||
() =>
|
||||
[...medications].sort((a, b) =>
|
||||
a.name.localeCompare(b.name, "de", { sensitivity: "base" }),
|
||||
),
|
||||
[medications],
|
||||
);
|
||||
|
||||
// User-driven medication override; `null` means "use the auto-pick".
|
||||
// Derived selection prefers the override, falls back to the heuristic
|
||||
// so a freshly-mounted sheet shows the cool/easy default without any
|
||||
// effect-driven setState.
|
||||
const [medicationOverride, setMedicationOverride] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
// v1.4.37 W10 — the dose field is informational only. The intake
|
||||
// POST body has no `dose` slot, so any user edit would be silently
|
||||
// dropped on submit. Until the v1.4.38 schema grows a `doseOverride`
|
||||
// field, render the input as read-only so the user's mental model
|
||||
// tracks what the server actually persists. The state holder is
|
||||
// kept (as `null`) so the medication-switch handler still resets
|
||||
// the slot cleanly if the schema ever grows the field.
|
||||
const [doseOverride, setDoseOverride] = useState<string | null>(null);
|
||||
const [takenAt, setTakenAt] = useState<string>(getDefaultIntakeAtValue);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const errorId = useId();
|
||||
const errorDescriptor = error ? errorId : undefined;
|
||||
const formId = useId();
|
||||
|
||||
const defaultMedicationId = useMemo(
|
||||
() => pickDefaultMedicationId(medications),
|
||||
[medications],
|
||||
);
|
||||
const medicationId = medicationOverride ?? defaultMedicationId ?? "";
|
||||
const selectedMedication = medications.find((m) => m.id === medicationId);
|
||||
const dose = doseOverride ?? selectedMedication?.dose ?? "";
|
||||
|
||||
function handleMedicationChange(value: string) {
|
||||
setMedicationOverride(value);
|
||||
// Reset the dose override when the medication changes so the new
|
||||
// default flows through on the next render. The dose field is
|
||||
// currently read-only (see v1.4.37 W10 note above), but the reset
|
||||
// stays in place so the slot is ready to switch back to editable
|
||||
// when the v1.4.38 doseOverride schema lands.
|
||||
setDoseOverride(null);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!medicationId || loading) return;
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const timestamp = new Date(takenAt).toISOString();
|
||||
const res = await fetch(`/api/medications/${medicationId}/intake`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
takenAt: timestamp,
|
||||
skipped: false,
|
||||
}),
|
||||
});
|
||||
|
||||
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.
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ["compliance-chart-inline"],
|
||||
});
|
||||
|
||||
toast.success(t("common.saved"));
|
||||
onSuccess?.();
|
||||
} catch {
|
||||
setError(t("dashboard.medicationIntakeQuickAdd.saveError"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const footerNode = (
|
||||
<div className="flex w-full items-center justify-end gap-2">
|
||||
{onCancel && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
disabled={loading}
|
||||
className="min-h-11 sm:min-h-9"
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
form={formId}
|
||||
disabled={loading || !medicationId || medications.length === 0}
|
||||
className="min-h-11 sm:min-h-9"
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Empty-state branch: the user has no active medications. Render a
|
||||
// hint + CTA into the body so the user has a single tap into the
|
||||
// medication-creation surface. The form itself is suppressed so we
|
||||
// don't ship an unusable Save button.
|
||||
if (!medicationsLoading && medications.length === 0) {
|
||||
const emptyFooter = (
|
||||
<div className="flex w-full items-center justify-end gap-2">
|
||||
{onCancel && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
className="min-h-11 sm:min-h-9"
|
||||
>
|
||||
{t("common.close")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
data-testid="medication-intake-quick-add-empty"
|
||||
className="flex flex-col items-center gap-3 py-4 text-center"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<Pill className="text-muted-foreground h-6 w-6" aria-hidden="true" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
{t("dashboard.medicationIntakeQuickAdd.emptyTitle")}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("dashboard.medicationIntakeQuickAdd.emptyDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
>
|
||||
<Link href="/medications">
|
||||
{t("dashboard.medicationIntakeQuickAdd.emptyCta")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
{footerSlot ? createPortal(emptyFooter, footerSlot) : emptyFooter}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
id={formId}
|
||||
onSubmit={handleSubmit}
|
||||
className="space-y-4"
|
||||
data-testid="medication-intake-quick-add-form"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="medication-intake-medication">
|
||||
{t("dashboard.medicationIntakeQuickAdd.medicationLabel")}
|
||||
</Label>
|
||||
<Select
|
||||
value={medicationId}
|
||||
onValueChange={handleMedicationChange}
|
||||
disabled={medicationsLoading || medications.length === 0}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="medication-intake-medication"
|
||||
data-testid="medication-intake-quick-add-medication"
|
||||
className="min-h-11"
|
||||
>
|
||||
<SelectValue
|
||||
placeholder={t(
|
||||
"dashboard.medicationIntakeQuickAdd.medicationPlaceholder",
|
||||
)}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sortedMedications.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id}>
|
||||
<span className="flex items-center gap-2">
|
||||
<Pill
|
||||
className="text-muted-foreground h-4 w-4"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{m.name}</span>
|
||||
{m.dose ? (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({m.dose})
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="medication-intake-dose">
|
||||
{t("dashboard.medicationIntakeQuickAdd.doseLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
id="medication-intake-dose"
|
||||
data-testid="medication-intake-quick-add-dose"
|
||||
value={dose}
|
||||
readOnly
|
||||
aria-readonly="true"
|
||||
tabIndex={-1}
|
||||
placeholder={
|
||||
selectedMedication?.dose ??
|
||||
t("dashboard.medicationIntakeQuickAdd.dosePlaceholder")
|
||||
}
|
||||
autoComplete="off"
|
||||
className="min-h-11 bg-muted/40"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("dashboard.medicationIntakeQuickAdd.doseHint")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="medication-intake-taken-at">
|
||||
{t("dashboard.medicationIntakeQuickAdd.timeLabel")}
|
||||
</Label>
|
||||
<DateTimeInput
|
||||
id="medication-intake-taken-at"
|
||||
data-testid="medication-intake-quick-add-taken-at"
|
||||
value={takenAt}
|
||||
onChange={(e) => setTakenAt(e.target.value)}
|
||||
required
|
||||
aria-required="true"
|
||||
aria-invalid={!!error || undefined}
|
||||
aria-describedby={errorDescriptor}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
id={errorId}
|
||||
role="alert"
|
||||
aria-live="assertive"
|
||||
className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{footerSlot ? createPortal(footerNode, footerSlot) : footerNode}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -328,6 +328,36 @@ describe("<HealthScoreCard>", () => {
|
||||
expect(disclaimerOpen?.[0]).toContain("mt-auto");
|
||||
});
|
||||
|
||||
// v1.4.37 W4a item 1 — the inner column switched from `flex
|
||||
// flex-col gap-3` to a 7-row grid so the slack collects on row 6
|
||||
// (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.
|
||||
it("uses a 7-row grid on the inner column so slack distributes on the accordion row", () => {
|
||||
const html = ssr(
|
||||
<HealthScoreCard
|
||||
score={86}
|
||||
band="green"
|
||||
components={baseComponents}
|
||||
delta={null}
|
||||
/>,
|
||||
);
|
||||
// The inner column lives directly after the card wrapper. Match
|
||||
// the first <div> that opens after the wrapper and assert the
|
||||
// grid + grid-rows-[...1fr...] contract.
|
||||
const innerColumn = html.match(
|
||||
/<div[^>]*data-slot="health-score-card"[^>]*>\s*(?:<!--[\s\S]*?-->\s*)?<div([^>]*)>/,
|
||||
);
|
||||
expect(innerColumn).not.toBeNull();
|
||||
const innerAttrs = innerColumn?.[1] ?? "";
|
||||
expect(innerAttrs).toContain("grid");
|
||||
expect(innerAttrs).toContain("flex-1");
|
||||
expect(innerAttrs).toContain(
|
||||
"grid-rows-[auto_auto_auto_auto_auto_1fr_auto]",
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes the progressbar role + ARIA values for screen readers", () => {
|
||||
const html = ssr(
|
||||
<HealthScoreCard
|
||||
|
||||
@@ -89,4 +89,22 @@ describe("<InsightStatusCard>", () => {
|
||||
const html = render(<InsightStatusCard {...baseProps} text={null} />);
|
||||
expect(html).toContain("No analysis yet.");
|
||||
});
|
||||
|
||||
it("renders the structured skeleton (v1.4.37) when loading instead of a centred spinner", () => {
|
||||
const html = render(
|
||||
<InsightStatusCard {...baseProps} text={null} loading />,
|
||||
);
|
||||
// The skeleton mounts the same icon dot, title bar, prose lines,
|
||||
// and footer that the loaded card paints so the loading state
|
||||
// previews the final geometry instead of pinning the card to a
|
||||
// single centred spinner row. The aria-busy + sr-only label
|
||||
// preserve the accessible "loading" semantics for assistive
|
||||
// tech.
|
||||
expect(html).toContain('aria-busy="true"');
|
||||
expect(html).toContain('data-testid="insight-status-card-loading"');
|
||||
expect(html).toContain("Loading");
|
||||
// The classic Loader2 + visible "common.loading" copy retired so
|
||||
// we do not double-paint the announcement.
|
||||
expect(html).not.toContain("animate-spin");
|
||||
});
|
||||
});
|
||||
@@ -256,7 +256,16 @@ export function HealthScoreCard({
|
||||
"flex h-full flex-col",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-1 flex-col gap-3">
|
||||
{/* v1.4.37 W4a item 1 — swap the inner column from `flex
|
||||
flex-col` to a 7-row grid so the recovered vertical slack
|
||||
(when the parent hero-row stretches the card past the
|
||||
natural content height) collects on row 6 (the provenance
|
||||
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
|
||||
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">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<p
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Sparkles } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { formatRelativeTime } from "@/lib/i18n/relative-time";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { SuggestedPrompts } from "./suggested-prompts";
|
||||
import {
|
||||
@@ -118,6 +119,14 @@ export function HeroStrip({
|
||||
healthScore,
|
||||
}: HeroStripProps) {
|
||||
const { t } = useTranslations();
|
||||
// v1.4.37 W5 — operator-level Coach gate. When the global Coach flag
|
||||
// is off every Coach affordance must vanish from this band (the
|
||||
// action-row button, the suggested-prompts chip strip, and the
|
||||
// HealthScoreCard's `onAskCoach` prop). The button and chips both
|
||||
// open the Coach drawer, so leaving them visible while the drawer
|
||||
// mount is suppressed would surface dead controls.
|
||||
const flags = useFeatureFlags();
|
||||
const coachEnabled = flags.coach;
|
||||
const greetingKey = resolveGreetingKey(now ?? new Date());
|
||||
const greetingBase = t(greetingKey);
|
||||
const greeting = userName ? `${greetingBase}, ${userName}` : greetingBase;
|
||||
@@ -207,45 +216,61 @@ export function HeroStrip({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* B2b wires this into the Coach drawer. The button is
|
||||
enabled whenever the parent supplies an `onAskCoach`
|
||||
handler; older parents that haven't adopted B2b yet
|
||||
still get the disabled "Coming soon" affordance so the
|
||||
hero doesn't break. v1.4.28 retired the weekly-report
|
||||
button, leaving Coach as the only hero-row action. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onAskCoach ? () => onAskCoach() : undefined}
|
||||
disabled={!onAskCoach}
|
||||
title={onAskCoach ? undefined : comingSoon}
|
||||
data-slot="insights-hero-strip-action-coach"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
<span>{t("insights.heroActionAskCoach")}</span>
|
||||
</Button>
|
||||
{/*
|
||||
* v1.4.25 W3 — the regenerate button moved to the new
|
||||
* `<InsightsTabStrip>` (icon-only RefreshCw, sticky next
|
||||
* to the pill nav) so the user can re-run the analysis
|
||||
* without scrolling back to the hero band.
|
||||
*/}
|
||||
</div>
|
||||
{/*
|
||||
* v1.4.37 W5 — the action row only carries the Coach button
|
||||
* today (v1.4.28 retired the weekly-report affordance). When
|
||||
* the operator turns the global Coach flag off the whole row
|
||||
* disappears rather than collapsing to an empty flex shell.
|
||||
*/}
|
||||
{coachEnabled && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* B2b wires this into the Coach drawer. The button is
|
||||
enabled whenever the parent supplies an `onAskCoach`
|
||||
handler; older parents that haven't adopted B2b yet
|
||||
still get the disabled "Coming soon" affordance so the
|
||||
hero doesn't break. v1.4.28 retired the weekly-report
|
||||
button, leaving Coach as the only hero-row action. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onAskCoach ? () => onAskCoach() : undefined}
|
||||
disabled={!onAskCoach}
|
||||
title={onAskCoach ? undefined : comingSoon}
|
||||
data-slot="insights-hero-strip-action-coach"
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
<span>{t("insights.heroActionAskCoach")}</span>
|
||||
</Button>
|
||||
{/*
|
||||
* v1.4.25 W3 — the regenerate button moved to the new
|
||||
* `<InsightsTabStrip>` (icon-only RefreshCw, sticky next
|
||||
* to the pill nav) so the user can re-run the analysis
|
||||
* without scrolling back to the hero band.
|
||||
*/}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
data-slot="insights-hero-strip-prompts"
|
||||
className="border-border/50 border-t pt-4"
|
||||
>
|
||||
{/*
|
||||
* v1.4.20 phase B2b — chip clicks open the Coach drawer
|
||||
* with the localised prompt pre-filled in the composer.
|
||||
* The parent owns drawer state so the chip strip stays
|
||||
* presentational.
|
||||
*/}
|
||||
<SuggestedPrompts onPick={onPickPrompt ?? (() => undefined)} />
|
||||
</div>
|
||||
{coachEnabled && (
|
||||
<div
|
||||
data-slot="insights-hero-strip-prompts"
|
||||
className="border-border/50 border-t pt-4"
|
||||
>
|
||||
{/*
|
||||
* v1.4.20 phase B2b — chip clicks open the Coach drawer
|
||||
* with the localised prompt pre-filled in the composer.
|
||||
* The parent owns drawer state so the chip strip stays
|
||||
* presentational.
|
||||
*
|
||||
* v1.4.37 W5 — the strip is a Coach-only affordance
|
||||
* (every chip seeds a Coach turn), so it is gated on the
|
||||
* same flag as the action-row button above. Without the
|
||||
* gate the chips would still paint while the drawer is
|
||||
* suppressed, leaving inert controls in the band.
|
||||
*/}
|
||||
<SuggestedPrompts onPick={onPickPrompt ?? (() => undefined)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{healthScore && (
|
||||
@@ -255,7 +280,14 @@ export function HeroStrip({
|
||||
components={healthScore.components}
|
||||
delta={healthScore.delta}
|
||||
onAskCoach={
|
||||
onAskCoach ? (prefill: string) => onAskCoach(prefill) : undefined
|
||||
// v1.4.37 W5 — short-circuit the prop drilling even
|
||||
// though `HealthScoreCard` retired its inline button in
|
||||
// v1.4.27. A future re-addition can't accidentally
|
||||
// surface a Coach affordance from this card while the
|
||||
// operator has the flag off.
|
||||
coachEnabled && onAskCoach
|
||||
? (prefill: string) => onAskCoach(prefill)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { stripChartTokens } from "@/lib/insights/chart-tokens";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -40,13 +39,30 @@ export function InsightStatusCard({
|
||||
if (!flags.insightStatus) return null;
|
||||
|
||||
if (loading) {
|
||||
// v1.4.37 — structured skeleton over the centred spinner. When the
|
||||
// per-metric status route had to fall back to the 20 s provider
|
||||
// race the user used to stare at a single centred spinner with
|
||||
// "Lade…" copy, which gave no sense of progress and pinned the
|
||||
// card to a flat dot. The skeleton paints the actual rendered
|
||||
// geometry (icon dot, title bar, three text lines, footer) so the
|
||||
// loading state previews where the assessment will land. Heights
|
||||
// mirror `<CardTitle>` (`text-base` → 1 rem) and the prose
|
||||
// (`text-sm` → 0.875 rem) so the post-load swap reflows by less
|
||||
// than a row.
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-center py-8">
|
||||
<Loader2 className="text-dracula-purple h-5 w-5 animate-spin motion-reduce:animate-none" />
|
||||
<span className="text-muted-foreground ml-2 text-sm">
|
||||
{t("common.loading")}
|
||||
</span>
|
||||
<Card aria-busy="true" aria-live="polite" data-testid="insight-status-card-loading">
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-muted h-5 w-5 animate-pulse rounded motion-reduce:animate-none" />
|
||||
<div className="bg-muted h-4 w-32 animate-pulse rounded motion-reduce:animate-none" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<div className="bg-muted h-3.5 w-full animate-pulse rounded motion-reduce:animate-none" />
|
||||
<div className="bg-muted h-3.5 w-11/12 animate-pulse rounded motion-reduce:animate-none" />
|
||||
<div className="bg-muted h-3.5 w-9/12 animate-pulse rounded motion-reduce:animate-none" />
|
||||
<div className="bg-muted/70 h-3 w-1/3 animate-pulse rounded motion-reduce:animate-none" />
|
||||
<span className="sr-only">{t("common.loading")}</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { Quote } from "lucide-react";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
@@ -47,6 +48,15 @@ export function SuggestedPrompts({
|
||||
className,
|
||||
}: SuggestedPromptsProps) {
|
||||
const { t } = useTranslations();
|
||||
// v1.4.37 W5 — every chip is a Coach affordance: clicking one seeds
|
||||
// the Coach drawer's composer and opens it. When the operator turns
|
||||
// the global Coach flag off the strip must vanish along with the
|
||||
// hero action button and the drawer mount. The HeroStrip caller
|
||||
// already guards on `flags.coach`; the in-component gate is
|
||||
// defence-in-depth so a future caller that mounts <SuggestedPrompts>
|
||||
// outside the hero band can never leak a Coach surface.
|
||||
const flags = useFeatureFlags();
|
||||
if (!flags.coach) return null;
|
||||
const items =
|
||||
prompts ??
|
||||
DEFAULT_PROMPT_KEYS.map((key) => t(`insights.suggestedPrompts.${key}`));
|
||||
|
||||
@@ -117,7 +117,7 @@ function SidebarUserSection({ collapsed }: { collapsed: boolean }) {
|
||||
<DropdownMenuContent
|
||||
side="right"
|
||||
align="end"
|
||||
className="w-56"
|
||||
className="w-60"
|
||||
sideOffset={8}
|
||||
>
|
||||
<div className="flex items-center gap-3 px-2 py-2">
|
||||
|
||||
@@ -81,7 +81,7 @@ export function TopBar() {
|
||||
<span className="hidden sm:inline">{user.username}</span>
|
||||
<ChevronDown className="h-3 w-3 opacity-60" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuContent align="end" className="w-60">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/settings/account" className="cursor-pointer">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
/**
|
||||
* v1.4.37 W7c — when the list filter is a cumulative HK type, the
|
||||
* list view renders one row per user-TZ day with the day's total and
|
||||
* a chevron that drills back into the per-sample chunks via a
|
||||
* separate query. This test mocks both queries (the parent + the
|
||||
* drill-down) and asserts the rendered surface paints the collapsed
|
||||
* shape without leaking per-sample rows by default.
|
||||
*/
|
||||
|
||||
const collapsed = [
|
||||
{
|
||||
id: "day:ACTIVITY_STEPS:2026-05-15",
|
||||
type: "ACTIVITY_STEPS",
|
||||
value: 12000,
|
||||
unit: "steps",
|
||||
source: "APPLE_HEALTH",
|
||||
measuredAt: "2026-05-15T10:00:00.000Z",
|
||||
notes: null,
|
||||
dayKey: "2026-05-15",
|
||||
sampleCount: 42,
|
||||
},
|
||||
];
|
||||
|
||||
// Per-mock TanStack Query stub: when the queryKey starts with
|
||||
// "measurement-drilldown" we serve nothing (drill-down should not
|
||||
// fire until the chevron is clicked, which static render never
|
||||
// triggers).
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
|
||||
if (
|
||||
Array.isArray(queryKey) &&
|
||||
queryKey[0] === "measurement-drilldown"
|
||||
) {
|
||||
return { data: undefined, isLoading: false };
|
||||
}
|
||||
return {
|
||||
data: { measurements: collapsed, meta: { total: 1 } },
|
||||
isLoading: false,
|
||||
};
|
||||
},
|
||||
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
|
||||
useMutation: () => ({
|
||||
mutate: vi.fn(),
|
||||
mutateAsync: vi.fn(),
|
||||
isPending: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => "/measurements",
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-auth", () => ({
|
||||
useAuth: () => ({
|
||||
user: { id: "u1", username: "marc", role: "USER" },
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { MeasurementList } from "../measurement-list";
|
||||
|
||||
function render(locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<MeasurementList />
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("MeasurementList — cumulative-type collapsed view (W7c)", () => {
|
||||
it("renders the daily-total caption with the sample count", () => {
|
||||
const html = render("en");
|
||||
// The daily-total caption ("(42 samples)") sits next to the
|
||||
// day's total ("12000 steps") on the collapsed row.
|
||||
expect(html).toContain("12,000 steps");
|
||||
expect(html).toMatch(/\(42 samples\)/);
|
||||
});
|
||||
|
||||
it("renders a chevron-expand button on the collapsed row", () => {
|
||||
const html = render("en");
|
||||
expect(html).toContain('data-testid="measurement-day-expand"');
|
||||
// The chevron exposes its expanded state via aria-expanded so
|
||||
// assistive tech announces the toggle correctly.
|
||||
expect(html).toMatch(/aria-expanded="false"/);
|
||||
});
|
||||
|
||||
it("does not paint edit/delete affordances on the synthesised daily row", () => {
|
||||
const html = render("en");
|
||||
// The edit + delete actions are hidden because the synthetic
|
||||
// `day:…` id has no real Measurement row backing it. The chevron
|
||||
// is the only action.
|
||||
expect(html).not.toMatch(/aria-label="Edit"/);
|
||||
expect(html).not.toMatch(/aria-label="Delete"/);
|
||||
});
|
||||
|
||||
it("localises the daily-total caption in German", () => {
|
||||
const html = render("de");
|
||||
expect(html).toMatch(/\(42 Einzelwerte\)/);
|
||||
});
|
||||
});
|
||||
@@ -48,15 +48,17 @@ import {
|
||||
Trash2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronDown,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
ArrowUpDown,
|
||||
MoreHorizontal,
|
||||
} from "lucide-react";
|
||||
import { useId, useState } from "react";
|
||||
import { Fragment, useId, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { CUMULATIVE_DAY_SUM_TYPES } from "@/lib/measurements/cumulative-day-sum";
|
||||
import { invalidateKeys, measurementDependentKeys } from "@/lib/query-keys";
|
||||
import { DateTimeInput } from "@/components/ui/date-input";
|
||||
import {
|
||||
@@ -65,6 +67,15 @@ import {
|
||||
MEASUREMENT_TYPE_COLORS as TYPE_COLORS,
|
||||
} from "./measurement-list-meta";
|
||||
|
||||
/**
|
||||
* v1.4.37 W7c — cumulative HK types whose list view collapses to one
|
||||
* row per user-TZ day with an expand-chevron drill-down to the
|
||||
* per-sample chunks. Mirrors the server-side
|
||||
* `CUMULATIVE_DAY_SUM_TYPES` so the route's `groupBy=day` branch and
|
||||
* the client's filter-detection agree on the same five identifiers.
|
||||
*/
|
||||
const CUMULATIVE_TYPES = new Set<string>(CUMULATIVE_DAY_SUM_TYPES);
|
||||
|
||||
interface Measurement {
|
||||
id: string;
|
||||
type: string;
|
||||
@@ -73,6 +84,13 @@ interface Measurement {
|
||||
source: string;
|
||||
measuredAt: string;
|
||||
notes: string | null;
|
||||
/**
|
||||
* v1.4.37 W7c — present only on collapsed daily rows returned by
|
||||
* `?type=…&groupBy=day`. Drives the expand chevron + the drill-down
|
||||
* fetch keyed by the user's calendar day.
|
||||
*/
|
||||
dayKey?: string;
|
||||
sampleCount?: number;
|
||||
}
|
||||
|
||||
interface MeasurementListProps {
|
||||
@@ -140,6 +158,21 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
const [sortBy, setSortBy] = useState<string>("measuredAt");
|
||||
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
|
||||
|
||||
// v1.4.37 W7c — set of dayKeys whose drill-down is currently
|
||||
// expanded. Each key maps to a one-shot query that lazy-fetches
|
||||
// the per-sample rows for that calendar day on first open.
|
||||
const [expandedDayKeys, setExpandedDayKeys] = useState<Set<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
function toggleExpand(dayKey: string) {
|
||||
setExpandedDayKeys((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(dayKey)) next.delete(dayKey);
|
||||
else next.add(dayKey);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
const [editing, setEditing] = useState<Measurement | null>(null);
|
||||
const [editValue, setEditValue] = useState("");
|
||||
const [editMeasuredAt, setEditMeasuredAt] = useState("");
|
||||
@@ -172,6 +205,16 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
// v1.4.37 W7c — when the type filter is a cumulative HK type
|
||||
// (steps, active energy, distance, flights, daylight) the list
|
||||
// collapses to one row per user-TZ day via the route's
|
||||
// `groupBy=day` mode. The chevron in the row drills back into the
|
||||
// per-sample chunks via a separate `dayKey=…` query. Matches the
|
||||
// Apple Health.app / Garmin / Withings pattern documented in
|
||||
// `.planning/research/v1437-step-aggregation.md` §"How the leaders
|
||||
// do it" — never list per-sample chunks as the default view.
|
||||
const isCumulativeFilter = CUMULATIVE_TYPES.has(typeFilter);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
"measurements",
|
||||
@@ -179,6 +222,7 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
page,
|
||||
sortBy,
|
||||
sortDir,
|
||||
isCumulativeFilter ? "groupBy=day" : "raw",
|
||||
],
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams();
|
||||
@@ -187,6 +231,22 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
params.set("offset", String((page - 1) * PAGE_SIZE));
|
||||
params.set("sortBy", sortBy);
|
||||
params.set("sortDir", sortDir);
|
||||
if (isCumulativeFilter) {
|
||||
params.set("groupBy", "day");
|
||||
// The collapsed mode synthesises one row per day from the
|
||||
// window of raw samples. Use the server-side ceiling (5000)
|
||||
// so a chatty pre-drain Apple-Watch account (≈200 per-sample
|
||||
// chunks/day on the busiest days) still fills several screens
|
||||
// of daily rows before the nightly drain reduces each day to
|
||||
// a single `stats:` row. Post-drain the scan is trivially
|
||||
// short — every day reduces to 1 row.
|
||||
params.set("limit", "5000");
|
||||
// The synthesised rows live entirely in the collapse branch
|
||||
// — pagination/offset don't apply on the server side. Reset
|
||||
// the offset so a sort-direction flip doesn't paginate into
|
||||
// an empty slice.
|
||||
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();
|
||||
@@ -269,7 +329,16 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
},
|
||||
});
|
||||
|
||||
const totalPages = data ? Math.ceil(data.meta.total / PAGE_SIZE) : 0;
|
||||
// v1.4.37 W7c — the collapsed daily view paints up to 5000
|
||||
// synthesised rows in one shot (one row per day for the
|
||||
// configured window). Pagination would force a second server
|
||||
// round-trip that re-fires the same scan, so the day-grouped
|
||||
// path collapses to a single page. Per-sample lists continue to
|
||||
// paginate at PAGE_SIZE = 25.
|
||||
const totalPages =
|
||||
data && !isCumulativeFilter
|
||||
? Math.ceil(data.meta.total / PAGE_SIZE)
|
||||
: 0;
|
||||
|
||||
function startEdit(measurement: Measurement) {
|
||||
if (onEdit) {
|
||||
@@ -450,62 +519,118 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.measurements.map((m) => (
|
||||
<TableRow key={m.id}>
|
||||
<TableCell className="pl-4">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={TYPE_COLORS[m.type] ?? ""}
|
||||
>
|
||||
{TYPE_LABEL_KEYS[m.type]
|
||||
? t(TYPE_LABEL_KEYS[m.type])
|
||||
: m.type}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-semibold tabular-nums">
|
||||
{m.value} {m.unit}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground text-sm">
|
||||
{formatDateTime(m.measuredAt)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{m.notes ? (
|
||||
<span title={m.notes}>
|
||||
{truncateComment(m.notes)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
{data.measurements.map((m) => {
|
||||
const isGrouped =
|
||||
m.dayKey !== undefined && m.sampleCount !== undefined;
|
||||
const isExpanded = isGrouped
|
||||
? expandedDayKeys.has(m.dayKey as string)
|
||||
: false;
|
||||
return (
|
||||
<Fragment key={m.id}>
|
||||
<TableRow>
|
||||
<TableCell className="pl-4">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={TYPE_COLORS[m.type] ?? ""}
|
||||
>
|
||||
{TYPE_LABEL_KEYS[m.type]
|
||||
? t(TYPE_LABEL_KEYS[m.type])
|
||||
: m.type}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-semibold tabular-nums">
|
||||
{fmt.integer(m.value)} {m.unit}
|
||||
{isGrouped && (
|
||||
<span className="text-muted-foreground ml-2 text-xs font-normal">
|
||||
{t("measurements.dailyTotalCaption", {
|
||||
count: fmt.integer(
|
||||
m.sampleCount as number,
|
||||
),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground text-sm">
|
||||
{formatDateTime(m.measuredAt)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{m.notes ? (
|
||||
<span title={m.notes}>
|
||||
{truncateComment(m.notes)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{m.source !== "MANUAL" && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
data-testid="measurement-source-badge"
|
||||
className={`text-xs ${sourceBadgeClass(m.source)}`.trim()}
|
||||
>
|
||||
{formatMeasurementSource(m.source, t)}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="pr-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{isGrouped ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
data-testid="measurement-day-expand"
|
||||
onClick={() =>
|
||||
toggleExpand(m.dayKey as string)
|
||||
}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={
|
||||
isExpanded
|
||||
? t("measurements.collapseDay")
|
||||
: t("measurements.expandDay")
|
||||
}
|
||||
>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => startEdit(m)}
|
||||
aria-label={t("common.edit")}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<DeleteButton
|
||||
onConfirm={() =>
|
||||
deleteMutation.mutate(m.id)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{isGrouped && isExpanded && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="p-0">
|
||||
<DayDrillDown
|
||||
type={m.type}
|
||||
dayKey={m.dayKey as string}
|
||||
unit={m.unit}
|
||||
layout="desktop"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{m.source !== "MANUAL" && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
data-testid="measurement-source-badge"
|
||||
className={`text-xs ${sourceBadgeClass(m.source)}`.trim()}
|
||||
>
|
||||
{formatMeasurementSource(m.source, t)}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="pr-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => startEdit(m)}
|
||||
aria-label={t("common.edit")}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<DeleteButton
|
||||
onConfirm={() => deleteMutation.mutate(m.id)}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
@@ -514,75 +639,116 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
<div className="space-y-2 md:hidden">
|
||||
{data.measurements.map((m) => {
|
||||
const Icon = TYPE_ICONS[m.type];
|
||||
const isGrouped =
|
||||
m.dayKey !== undefined && m.sampleCount !== undefined;
|
||||
const isExpanded = isGrouped
|
||||
? expandedDayKeys.has(m.dayKey as string)
|
||||
: false;
|
||||
return (
|
||||
<div
|
||||
key={m.id}
|
||||
className="bg-card border-border flex items-center justify-between rounded-lg border p-3"
|
||||
className="bg-card border-border rounded-lg border p-3"
|
||||
>
|
||||
<div className="flex items-center gap-2.5 overflow-hidden">
|
||||
{Icon && (
|
||||
<div
|
||||
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${TYPE_COLORS[m.type] ?? ""}`}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
{/* v1.4.27 MB7 / CF-76 — bump the metadata
|
||||
badges from `text-[10px]` to `text-[11px]`
|
||||
so the legibility floor (12 px is the
|
||||
mobile baseline; 11 px is the lowest
|
||||
tolerated value for non-primary chrome)
|
||||
holds across the row. The badge heights
|
||||
stay at `h-5` / `h-4` since the type-
|
||||
preface badge owns vertical real estate
|
||||
inside the headline line. */}
|
||||
{(m.type === "BLOOD_PRESSURE_SYS" ||
|
||||
m.type === "BLOOD_PRESSURE_DIA") && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="mr-1.5 h-5 px-1 text-[11px]"
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2.5 overflow-hidden">
|
||||
{Icon && (
|
||||
<div
|
||||
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${TYPE_COLORS[m.type] ?? ""}`}
|
||||
>
|
||||
{t(TYPE_LABEL_KEYS[m.type])}
|
||||
</Badge>
|
||||
<Icon className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<span className="font-semibold tabular-nums">
|
||||
{m.value} {m.unit}
|
||||
</span>
|
||||
<p className="text-muted-foreground truncate text-xs">
|
||||
<span>{formatDateTime(m.measuredAt)}</span>
|
||||
{m.source !== "MANUAL" && (
|
||||
<div className="min-w-0">
|
||||
{/* v1.4.27 MB7 / CF-76 — bump the metadata
|
||||
badges from `text-[10px]` to `text-[11px]`
|
||||
so the legibility floor (12 px is the
|
||||
mobile baseline; 11 px is the lowest
|
||||
tolerated value for non-primary chrome)
|
||||
holds across the row. */}
|
||||
{(m.type === "BLOOD_PRESSURE_SYS" ||
|
||||
m.type === "BLOOD_PRESSURE_DIA") && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
data-testid="measurement-source-badge"
|
||||
className={`ml-1.5 h-4 px-1 text-[11px] ${sourceBadgeClass(m.source)}`.trim()}
|
||||
className="mr-1.5 h-5 px-1 text-[11px]"
|
||||
>
|
||||
{formatMeasurementSource(m.source, t)}
|
||||
{t(TYPE_LABEL_KEYS[m.type])}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
{m.notes && (
|
||||
<span className="font-semibold tabular-nums">
|
||||
{fmt.integer(m.value)} {m.unit}
|
||||
</span>
|
||||
{isGrouped && (
|
||||
<span className="text-muted-foreground ml-1.5 text-[11px]">
|
||||
{t("measurements.dailyTotalCaption", {
|
||||
count: fmt.integer(m.sampleCount as number),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
<p className="text-muted-foreground truncate text-xs">
|
||||
{truncateComment(m.notes)}
|
||||
<span>{formatDateTime(m.measuredAt)}</span>
|
||||
{m.source !== "MANUAL" && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
data-testid="measurement-source-badge"
|
||||
className={`ml-1.5 h-4 px-1 text-[11px] ${sourceBadgeClass(m.source)}`.trim()}
|
||||
>
|
||||
{formatMeasurementSource(m.source, t)}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
{m.notes && (
|
||||
<p className="text-muted-foreground truncate text-xs">
|
||||
{truncateComment(m.notes)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{isGrouped ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-11"
|
||||
data-testid="measurement-day-expand"
|
||||
onClick={() => toggleExpand(m.dayKey as string)}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={
|
||||
isExpanded
|
||||
? t("measurements.collapseDay")
|
||||
: t("measurements.expandDay")
|
||||
}
|
||||
>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-11"
|
||||
onClick={() => startEdit(m)}
|
||||
aria-label={t("common.edit")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<DeleteButton
|
||||
className="size-11"
|
||||
onConfirm={() => deleteMutation.mutate(m.id)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-11"
|
||||
onClick={() => startEdit(m)}
|
||||
aria-label={t("common.edit")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<DeleteButton
|
||||
className="size-11"
|
||||
onConfirm={() => deleteMutation.mutate(m.id)}
|
||||
{isGrouped && isExpanded && (
|
||||
<DayDrillDown
|
||||
type={m.type}
|
||||
dayKey={m.dayKey as string}
|
||||
unit={m.unit}
|
||||
layout="mobile"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -807,6 +973,106 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.37 W7c — lazy drill-down for a collapsed cumulative-type day.
|
||||
* Fires a separate `GET /api/measurements?type=…&dayKey=…` only when
|
||||
* the row is expanded; the result is rendered as a nested list of the
|
||||
* per-sample chunks that summed into the parent row's daily total.
|
||||
*/
|
||||
function DayDrillDown({
|
||||
type,
|
||||
dayKey,
|
||||
unit,
|
||||
layout,
|
||||
}: {
|
||||
type: string;
|
||||
dayKey: string;
|
||||
unit: string;
|
||||
layout: "desktop" | "mobile";
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["measurement-drilldown", type, dayKey],
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams();
|
||||
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[] };
|
||||
},
|
||||
enabled: isAuthenticated,
|
||||
// The drill-down is per-day — once fetched it rarely needs to
|
||||
// re-fetch (the underlying day has already stabilised for
|
||||
// anything older than the drain's 36 h cutoff). Keep it cached
|
||||
// for the session.
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="text-muted-foreground flex items-center gap-2 py-2 text-xs">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-destructive py-2 text-xs">
|
||||
{t("measurements.saveError")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const rows = data?.measurements ?? [];
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
<div className="text-muted-foreground py-2 text-xs">
|
||||
{t("measurements.emptyDescription")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (layout === "desktop") {
|
||||
return (
|
||||
<div className="bg-muted/40 space-y-1 p-2">
|
||||
{rows.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className="flex items-center justify-between gap-3 px-2 py-1 text-xs"
|
||||
>
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
{formatDateTime(s.measuredAt)}
|
||||
</span>
|
||||
<span className="font-medium tabular-nums">
|
||||
{s.value} {unit}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="bg-muted/40 mt-2 space-y-1 rounded-md p-2">
|
||||
{rows.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className="flex items-center justify-between gap-2 px-1 py-1 text-xs"
|
||||
>
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
{formatDateTime(s.measuredAt)}
|
||||
</span>
|
||||
<span className="font-medium tabular-nums">
|
||||
{s.value} {unit}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SortableHead({
|
||||
column,
|
||||
label,
|
||||
|
||||
@@ -61,13 +61,16 @@ function seedIntake(
|
||||
const sortDir = opts.sortDir ?? "desc";
|
||||
const limit = opts.limit ?? 25;
|
||||
const offset = opts.offset ?? 0;
|
||||
// v1.4.37 W3 — the component pins `status:"completed"` on the
|
||||
// server-side query and threads it through the cache key, so the
|
||||
// seed mirrors that shape verbatim.
|
||||
client.setQueryData(
|
||||
[
|
||||
"medications",
|
||||
medId,
|
||||
"intake",
|
||||
"list",
|
||||
{ sortBy, sortDir, limit, offset },
|
||||
{ sortBy, sortDir, limit, offset, status: "completed" },
|
||||
],
|
||||
{ events: rows, meta: { total, limit, offset } },
|
||||
);
|
||||
@@ -93,10 +96,7 @@ describe("<IntakeHistoryListV2> — empty state", () => {
|
||||
it("renders the empty-state title and CTA in English", () => {
|
||||
const client = makeClient();
|
||||
seedIntake(client, "med-1", []);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-1" />,
|
||||
client,
|
||||
);
|
||||
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
|
||||
expect(html).toContain("No intakes recorded yet");
|
||||
expect(html).toContain("Open daily intake");
|
||||
expect(html).toContain('href="/medications"');
|
||||
@@ -138,23 +138,101 @@ describe("<IntakeHistoryListV2> — populated rows", () => {
|
||||
createdAt: "2026-05-14T20:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-1" />,
|
||||
client,
|
||||
);
|
||||
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
|
||||
expect(html).toContain("Taken");
|
||||
expect(html).toContain("Skipped");
|
||||
expect(html).toContain("Website");
|
||||
expect(html).toContain("Telegram / Reminder");
|
||||
});
|
||||
|
||||
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:
|
||||
// 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
|
||||
// skipped row "Eingenommen".
|
||||
const client = makeClient();
|
||||
seedIntake(client, "med-status", [
|
||||
{
|
||||
id: "evt-taken",
|
||||
medicationId: "med-status",
|
||||
scheduledFor: "2026-05-15T08:00:00.000Z",
|
||||
takenAt: "2026-05-15T08:02:00.000Z",
|
||||
skipped: false,
|
||||
source: "WEB",
|
||||
createdAt: "2026-05-15T08:02:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "evt-skipped",
|
||||
medicationId: "med-status",
|
||||
scheduledFor: "2026-05-14T08:00:00.000Z",
|
||||
takenAt: null,
|
||||
skipped: true,
|
||||
source: "REMINDER",
|
||||
createdAt: "2026-05-14T20:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-status" />,
|
||||
client,
|
||||
);
|
||||
|
||||
// Distinct lucide icons per branch — proves the row matched the
|
||||
// correct status arm and isn't just printing a label.
|
||||
expect(html).toContain("lucide-check");
|
||||
expect(html).toContain("lucide-skip-forward");
|
||||
|
||||
// The green styling pins the taken branch visually so a future
|
||||
// refactor cannot silently collapse the two chips back into one
|
||||
// neutral badge.
|
||||
expect(html).toMatch(/bg-green-500\/20[^"]*text-green-400/);
|
||||
|
||||
// Skipped rows render as a muted outline chip — never as the
|
||||
// secondary "Eingenommen" badge.
|
||||
expect(html).toMatch(/text-muted-foreground[^"]*gap-1[^"]*text-xs/);
|
||||
|
||||
expect(html).toContain("Taken");
|
||||
expect(html).toContain("Skipped");
|
||||
});
|
||||
|
||||
it("renders the skipped chip in German without leaking the Eingenommen label", () => {
|
||||
// v1.4.37 W3 — UAT echo. Marc reported a German row labelled
|
||||
// both "übersprungen" and "eingenommen". The fix means a
|
||||
// skipped-only fixture renders "Übersprungen" exactly once and
|
||||
// "Eingenommen" zero times.
|
||||
const client = makeClient();
|
||||
seedIntake(client, "med-skipped", [
|
||||
{
|
||||
id: "evt-skipped",
|
||||
medicationId: "med-skipped",
|
||||
scheduledFor: "2026-04-29T05:00:00.000Z",
|
||||
takenAt: null,
|
||||
skipped: true,
|
||||
source: "REMINDER",
|
||||
createdAt: "2026-04-29T05:01:00.000Z",
|
||||
},
|
||||
]);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-skipped" />,
|
||||
client,
|
||||
"de",
|
||||
);
|
||||
|
||||
// Locate the table-body slice so we only count chip labels, not
|
||||
// the column headers (which also say "Eingenommen" for the
|
||||
// takenAt column header).
|
||||
const tbodyMatch = html.match(/<tbody[\s\S]*?<\/tbody>/);
|
||||
expect(tbodyMatch).not.toBeNull();
|
||||
const body = tbodyMatch?.[0] ?? "";
|
||||
|
||||
expect(body).toContain("Übersprungen");
|
||||
expect(body).not.toContain("Eingenommen");
|
||||
});
|
||||
|
||||
it("renders the section title across both locales", () => {
|
||||
const client = makeClient();
|
||||
seedIntake(client, "med-1", []);
|
||||
const enHtml = render(
|
||||
<IntakeHistoryListV2 medicationId="med-1" />,
|
||||
client,
|
||||
);
|
||||
const enHtml = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
|
||||
expect(enHtml).toContain("Intake history");
|
||||
|
||||
const deClient = makeClient();
|
||||
@@ -182,10 +260,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
|
||||
createdAt: "2026-05-15T08:02:00.000Z",
|
||||
},
|
||||
]);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-1" />,
|
||||
client,
|
||||
);
|
||||
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
|
||||
// Default sort = takenAt desc, so the "taken" header carries the
|
||||
// arrow-down icon and the "scheduled" header carries the neutral
|
||||
// dual-arrow icon.
|
||||
@@ -235,10 +310,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
|
||||
],
|
||||
50,
|
||||
);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-2" />,
|
||||
client,
|
||||
);
|
||||
const html = render(<IntakeHistoryListV2 medicationId="med-2" />, client);
|
||||
expect(html).toContain("Previous");
|
||||
expect(html).toContain("Next");
|
||||
// a11y: pagination buttons clear the 44 px mobile touch floor and
|
||||
@@ -265,10 +337,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
|
||||
],
|
||||
1,
|
||||
);
|
||||
const html = render(
|
||||
<IntakeHistoryListV2 medicationId="med-3" />,
|
||||
client,
|
||||
);
|
||||
const html = render(<IntakeHistoryListV2 medicationId="med-3" />, client);
|
||||
expect(html).not.toContain(">Previous<");
|
||||
expect(html).not.toContain(">Next<");
|
||||
});
|
||||
|
||||
@@ -164,10 +164,13 @@ beforeEach(() => {
|
||||
|
||||
describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
it("renders the GLP-1 variant when treatmentClass === 'GLP1' is active", () => {
|
||||
// Headline differentiator: the GLP-1 card stamps the
|
||||
// `medications.treatmentClassGlp1` badge ("GLP-1 injection")
|
||||
// which the generic card never renders. Presence of the badge is
|
||||
// the contract pin for "GLP-1 variant is showing".
|
||||
// v1.4.37 W4b — the category-label slot now mirrors the generic
|
||||
// card (real `medication.category` lookup) so Ramipril and
|
||||
// Mounjaro share the same row shape. The variant differentiator
|
||||
// moved into the GLP-1-specific rows below the header (last/next
|
||||
// injection, rotation hint). We verify the GLP-1 card no longer
|
||||
// hard-codes the treatment-class label into the category slot,
|
||||
// and that the actual category lookup wins.
|
||||
const client = makeClient();
|
||||
seedCompliance(client, med7p5.id);
|
||||
seedGlp1Details(client, med7p5.id, {});
|
||||
@@ -177,7 +180,9 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
client,
|
||||
);
|
||||
|
||||
expect(html).toContain("GLP-1 injection");
|
||||
// Category is OTHER → "Other" badge wins.
|
||||
expect(html).toContain("Other");
|
||||
expect(html).not.toContain("GLP-1 injection");
|
||||
// v1.4.28 FB-G1 — the Syringe glyph + middle-dot separator on the
|
||||
// list row are gone. The list row reads as the canonical two-line
|
||||
// shape: `{name} {dose}` on line 1, class label on line 2.
|
||||
@@ -357,13 +362,15 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
expect(html).not.toContain("Low stock");
|
||||
});
|
||||
|
||||
it("side-effect quick-log button hands off the medication object", () => {
|
||||
// SSR can't fire DOM clicks, so we smoke-check the contract:
|
||||
// - the button renders when onLogSideEffect is supplied
|
||||
// - invoking the handler synchronously delivers the GLP-1
|
||||
// medication object the parent will then prefill MoodEntry with
|
||||
// (the parent's MoodEntry mutation reads med.name to build the
|
||||
// pre-tagged side-effect entry).
|
||||
it("side-effect quick-log moves into the header actions overflow", () => {
|
||||
// v1.4.37 W4b — the side-effect quick-log no longer sits in the
|
||||
// primary actions row (which used to read as a three-button row
|
||||
// and broke symmetry with the generic Ramipril card). It now
|
||||
// lives behind a kebab overflow in the header `actions` slot.
|
||||
// SSR doesn't open Radix Portal content, so we assert the trigger
|
||||
// surfaces with the localised `common.moreOptions` aria-label and
|
||||
// smoke-check that invoking the handler delivers the GLP-1
|
||||
// medication object the parent prefills MoodEntry with.
|
||||
const client = makeClient();
|
||||
seedCompliance(client, med7p5.id);
|
||||
seedGlp1Details(client, med7p5.id, {});
|
||||
@@ -378,21 +385,27 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
client,
|
||||
);
|
||||
|
||||
// Button renders with the localised label.
|
||||
expect(html).toContain("Log side effect");
|
||||
// Kebab trigger renders with the localised aria-label.
|
||||
expect(html).toContain('aria-label="More options"');
|
||||
// The side-effect button must no longer ride alongside
|
||||
// Eingenommen / Übersprungen in the primary actions row.
|
||||
expect(html).not.toMatch(
|
||||
/class="[^"]*flex[^"]*gap-2[^"]*"[^>]*>[\s\S]*?Log side effect/,
|
||||
);
|
||||
|
||||
// Invoke the supplied handler the way the button's onClick would —
|
||||
// pins the prefill payload contract for MoodEntry.
|
||||
// Invoke the supplied handler the way the menu item's onClick
|
||||
// would — pins the prefill payload contract for MoodEntry.
|
||||
handler(med7p5);
|
||||
expect(handler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: "Mounjaro", treatmentClass: "GLP1" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the side-effect button when onLogSideEffect is not supplied", () => {
|
||||
// Back-compat: the button is opt-in via the prop. Pages that
|
||||
// haven't wired the MoodEntry hand-off yet should still render
|
||||
// the card without a dead button.
|
||||
it("omits the overflow kebab when onLogSideEffect is not supplied", () => {
|
||||
// Back-compat: the overflow is opt-in via the prop. Pages that
|
||||
// haven't wired the MoodEntry hand-off yet render Mounjaro with
|
||||
// exactly the same header-actions shape as Ramipril (history +
|
||||
// edit, no kebab) so the medications list stays symmetric.
|
||||
const client = makeClient();
|
||||
seedCompliance(client, med7p5.id);
|
||||
seedGlp1Details(client, med7p5.id, {});
|
||||
@@ -402,7 +415,7 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
client,
|
||||
);
|
||||
|
||||
expect(html).not.toContain("Log side effect");
|
||||
expect(html).not.toContain('aria-label="More options"');
|
||||
});
|
||||
|
||||
it("AI-disabled state: no Coach hand-off button is rendered today", () => {
|
||||
@@ -446,8 +459,11 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
expect(html).toContain("opacity-60");
|
||||
expect(html).toContain("Paused since");
|
||||
// Primary actions ("Taken" / "Skipped") are suppressed for
|
||||
// inactive medications.
|
||||
expect(html).not.toContain("Log side effect");
|
||||
// inactive medications. The header-actions overflow trigger is
|
||||
// unconditionally absent when `onLogSideEffect` is not supplied
|
||||
// (this test fixture doesn't wire it), so Mounjaro and Ramipril
|
||||
// headers stay shape-equivalent in the paused state.
|
||||
expect(html).not.toContain('aria-label="More options"');
|
||||
});
|
||||
|
||||
it("renders German copy under the 'de' locale", () => {
|
||||
@@ -468,7 +484,12 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
|
||||
"de",
|
||||
);
|
||||
|
||||
expect(html).toContain("GLP-1-Injektion");
|
||||
// v1.4.37 W4b — the German category badge now comes from the
|
||||
// shared category-label lookup (Sonstiges for OTHER) instead of
|
||||
// the hard-coded "GLP-1-Injektion" label, so the GLP-1 card stays
|
||||
// visually symmetric with the generic card on the medications list.
|
||||
expect(html).toContain("Sonstiges");
|
||||
expect(html).not.toContain("GLP-1-Injektion");
|
||||
expect(html).toContain("Letzter Termin:");
|
||||
expect(html).toContain("Bauch, unten links");
|
||||
// v1.4.28 retired the "Dosis-Historie" disclosure on the GLP-1 card.
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { MedicationCard } from "@/components/medications/medication-card";
|
||||
import {
|
||||
Glp1MedicationCard,
|
||||
type Glp1Medication,
|
||||
} from "@/components/medications/glp1-medication-card";
|
||||
|
||||
/**
|
||||
* v1.4.37 W4b — symmetry contract between the generic medication card
|
||||
* (Ramipril/non-GLP-1) and the GLP-1 variant (Mounjaro). Marc reported
|
||||
* during the v1.4.37 UX audit that the two cards "felt different"
|
||||
* even though both should read as the same row shape. These tests pin
|
||||
* the load-bearing structural seams so a future refactor can't quietly
|
||||
* regress the parity.
|
||||
*
|
||||
* What we assert:
|
||||
* 1. Header `actions` cluster — both cards always render `History`
|
||||
* and `Pencil` icon buttons. The Mounjaro card optionally renders
|
||||
* an additional kebab when `onLogSideEffect` is wired; absent the
|
||||
* prop the headers are byte-shape equivalent.
|
||||
* 2. Category-label badge — both cards consult the same
|
||||
* `getMedicationCategoryLabel` lookup. No card hard-codes the
|
||||
* `medications.treatmentClassGlp1` string into the slot.
|
||||
* 3. Take-now status pill — when the current time is inside a
|
||||
* configured schedule window and `lastTakenAt` is null/older, both
|
||||
* cards render the `medications.takeNow` localised text.
|
||||
* 4. Primary actions row — exactly two buttons (Eingenommen /
|
||||
* Übersprungen). The side-effect quick-log lives in the header
|
||||
* overflow when wired, not in this row.
|
||||
* 5. Purple dose accent — both cards render
|
||||
* `font-medium text-purple-400` on the upcoming schedule dose.
|
||||
*/
|
||||
|
||||
function makeClient(): QueryClient {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: 0, staleTime: Infinity },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function render(
|
||||
node: React.ReactNode,
|
||||
client: QueryClient,
|
||||
locale: "en" | "de" = "en",
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>
|
||||
<QueryClientProvider client={client}>{node}</QueryClientProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function seedCompliance(client: QueryClient, medId: string) {
|
||||
client.setQueryData(["medications", medId, "compliance"], {
|
||||
compliance7: { rate: 90, streak: 0, totalExpected: 7, taken: 6 },
|
||||
compliance30: { rate: 88 },
|
||||
});
|
||||
}
|
||||
|
||||
function seedGlp1Details(client: QueryClient, medId: string) {
|
||||
client.setQueryData(["medications", medId, "glp1-details"], {
|
||||
doseChanges: [],
|
||||
recentIntakes: [],
|
||||
inventory: null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule that fires every day of the week from 00:00 to 23:59 so
|
||||
* the SSR snapshot always lands inside the current window regardless
|
||||
* of the host clock — pinning the "take now" pill assertion.
|
||||
*/
|
||||
const allDayWindow = {
|
||||
windowStart: "00:00",
|
||||
windowEnd: "23:59",
|
||||
label: null,
|
||||
daysOfWeek: null,
|
||||
};
|
||||
|
||||
const ramipril = {
|
||||
id: "med-ramipril-1",
|
||||
name: "Ramipril",
|
||||
dose: "5 mg",
|
||||
category: "BLOOD_PRESSURE",
|
||||
treatmentClass: undefined as string | undefined,
|
||||
active: true,
|
||||
notificationsEnabled: true,
|
||||
pausedAt: null,
|
||||
lastTakenAt: null,
|
||||
todayEventCount: 0,
|
||||
schedules: [
|
||||
{
|
||||
id: "s-ramipril-1",
|
||||
...allDayWindow,
|
||||
dose: "5 mg",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mounjaro: Glp1Medication = {
|
||||
id: "med-mounjaro-1",
|
||||
name: "Mounjaro",
|
||||
dose: "7.5 mg",
|
||||
category: "HORMONE",
|
||||
treatmentClass: "GLP1",
|
||||
dosesPerUnit: 4,
|
||||
active: true,
|
||||
notificationsEnabled: true,
|
||||
pausedAt: null,
|
||||
lastTakenAt: null,
|
||||
todayEventCount: 0,
|
||||
schedules: [
|
||||
{
|
||||
id: "s-mounjaro-1",
|
||||
...allDayWindow,
|
||||
dose: "7.5 mg",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("medication card symmetry — Ramipril vs Mounjaro", () => {
|
||||
it("both cards render History + Pencil header buttons", () => {
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramipril.id);
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramipril} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
|
||||
for (const html of [ramiprilHtml, mounjaroHtml]) {
|
||||
expect(html).toContain("lucide-history");
|
||||
expect(html).toContain("lucide-pencil");
|
||||
}
|
||||
});
|
||||
|
||||
it("neither card paints a kebab when no overflow prop is wired", () => {
|
||||
// Symmetry default: without onLogSideEffect, the Mounjaro header
|
||||
// shape matches the Ramipril header exactly (history + edit only).
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramipril.id);
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramipril} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
|
||||
for (const html of [ramiprilHtml, mounjaroHtml]) {
|
||||
expect(html).not.toContain('aria-label="More options"');
|
||||
}
|
||||
});
|
||||
|
||||
it("Mounjaro gains a kebab when onLogSideEffect is supplied (GLP-1-only)", () => {
|
||||
const client = makeClient();
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const html = render(
|
||||
<Glp1MedicationCard
|
||||
medication={mounjaro}
|
||||
onEdit={() => {}}
|
||||
onLogSideEffect={() => {}}
|
||||
/>,
|
||||
client,
|
||||
);
|
||||
|
||||
expect(html).toContain('aria-label="More options"');
|
||||
});
|
||||
|
||||
it("category label uses the shared category-map lookup on both cards", () => {
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramipril.id);
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramipril} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
|
||||
// Ramipril → BLOOD_PRESSURE → "Blood Pressure".
|
||||
expect(ramiprilHtml).toContain("Blood Pressure");
|
||||
// Mounjaro → HORMONE → "Hormones". The card must NOT hard-code
|
||||
// the treatment-class label into the slot any more.
|
||||
expect(mounjaroHtml).toContain("Hormones");
|
||||
expect(mounjaroHtml).not.toContain("GLP-1 injection");
|
||||
});
|
||||
|
||||
it("both cards render the take-now pill when inside the current schedule window", () => {
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramipril.id);
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramipril} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
|
||||
for (const html of [ramiprilHtml, mounjaroHtml]) {
|
||||
expect(html).toContain("Take now");
|
||||
// Coloured-pill contract — the in_window pill class carries
|
||||
// the success token, not the warning token.
|
||||
expect(html).toContain("text-success");
|
||||
}
|
||||
});
|
||||
|
||||
it("primary actions row carries exactly two buttons on both cards", () => {
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramipril.id);
|
||||
seedCompliance(client, mounjaro.id);
|
||||
seedGlp1Details(client, mounjaro.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramipril} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard
|
||||
medication={mounjaro}
|
||||
onEdit={() => {}}
|
||||
onLogSideEffect={() => {}}
|
||||
/>,
|
||||
client,
|
||||
);
|
||||
|
||||
for (const html of [ramiprilHtml, mounjaroHtml]) {
|
||||
// Taken / Skipped — and no third in-row button. We assert the
|
||||
// primary-actions buttons via icon class names since those
|
||||
// surface on both cards.
|
||||
expect(html).toContain("lucide-check");
|
||||
expect(html).toContain("lucide-skip-forward");
|
||||
}
|
||||
// The Stethoscope glyph is GLP-1-only; SSR doesn't open the
|
||||
// Radix Portal so even when wired the menu item is hidden from
|
||||
// the initial markup. The primary row must NOT carry it.
|
||||
expect(mounjaroHtml).not.toMatch(
|
||||
/class="[^"]*flex[^"]*gap-2[^"]*"[^>]*>[\s\S]*?lucide-stethoscope/,
|
||||
);
|
||||
});
|
||||
|
||||
it("purple dose accent surfaces on the upcoming schedule dose on both cards", () => {
|
||||
// Pin the asymmetry from the v1.4.37 UX audit (item 11): the
|
||||
// GLP-1 card historically lacked the purple accent. Both cards
|
||||
// must now stamp the same `text-purple-400` token on the
|
||||
// schedule dose. We render at a window that's NOT currently
|
||||
// active so the "next intake" line (which carries the accent)
|
||||
// surfaces instead of the take-now pill.
|
||||
const futureWindow = {
|
||||
windowStart: "01:00",
|
||||
windowEnd: "02:00",
|
||||
label: null,
|
||||
daysOfWeek: null,
|
||||
};
|
||||
const ramiprilFuture = {
|
||||
...ramipril,
|
||||
schedules: [
|
||||
{
|
||||
id: "s-ramipril-future",
|
||||
...futureWindow,
|
||||
dose: "5 mg",
|
||||
},
|
||||
],
|
||||
};
|
||||
const mounjaroFuture: Glp1Medication = {
|
||||
...mounjaro,
|
||||
schedules: [
|
||||
{
|
||||
id: "s-mounjaro-future",
|
||||
...futureWindow,
|
||||
dose: "7.5 mg",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const client = makeClient();
|
||||
seedCompliance(client, ramiprilFuture.id);
|
||||
seedCompliance(client, mounjaroFuture.id);
|
||||
seedGlp1Details(client, mounjaroFuture.id);
|
||||
|
||||
const ramiprilHtml = render(
|
||||
<MedicationCard medication={ramiprilFuture} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const mounjaroHtml = render(
|
||||
<Glp1MedicationCard medication={mounjaroFuture} onEdit={() => {}} />,
|
||||
client,
|
||||
);
|
||||
|
||||
// Both surfaces carry the purple token on the upcoming dose.
|
||||
expect(ramiprilHtml).toContain("text-purple-400");
|
||||
expect(mounjaroHtml).toContain("text-purple-400");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEffect, useReducer, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Flame,
|
||||
History,
|
||||
Loader2,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
SkipForward,
|
||||
Stethoscope,
|
||||
@@ -16,16 +17,29 @@ import {
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
|
||||
import { formatDateTime, formatTime } from "@/lib/format";
|
||||
import { formatTimeWindowRange } from "@/lib/time-window-format";
|
||||
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
|
||||
import {
|
||||
describeInjectionSite,
|
||||
nextInjectionSite,
|
||||
type InjectionSiteKey,
|
||||
} from "@/lib/medications/injection-sites";
|
||||
import {
|
||||
reduceCurrentWindowStatus,
|
||||
toBerlinDate,
|
||||
} from "@/lib/medications/window-status";
|
||||
|
||||
/**
|
||||
* v1.4.25 W4d — GLP-1 medication card variant.
|
||||
*
|
||||
@@ -77,6 +91,7 @@ export interface Glp1Medication {
|
||||
notificationsEnabled: boolean;
|
||||
pausedAt: string | null;
|
||||
lastTakenAt: string | null;
|
||||
todayEventCount?: number;
|
||||
schedules: ScheduleLite[];
|
||||
}
|
||||
|
||||
@@ -155,9 +170,10 @@ export function Glp1MedicationCard({
|
||||
onLogSideEffect,
|
||||
}: Glp1MedicationCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
const { t, locale } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const [intakeLoading, setIntakeLoading] = useState<string | null>(null);
|
||||
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
|
||||
|
||||
const { data: compliance } = useQuery({
|
||||
queryKey: ["medications", medication.id, "compliance"],
|
||||
@@ -171,6 +187,20 @@ export function Glp1MedicationCard({
|
||||
enabled: medication.active,
|
||||
});
|
||||
|
||||
// v1.4.37 W4b — same reminder-thresholds source as the generic
|
||||
// medication card so the take-now / overdue / very-overdue pill
|
||||
// tiers identically on both surfaces.
|
||||
const { data: thresholds } = useQuery({
|
||||
queryKey: ["settings", "reminder-thresholds"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/reminder-thresholds");
|
||||
if (!res.ok) return null;
|
||||
const json = await res.json();
|
||||
return json.data as { lateMinutes: number; missedMinutes: number };
|
||||
},
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
// Pull GLP-1-specific extras (dose history + recent injection sites +
|
||||
// pen inventory). Lives behind a dedicated endpoint so the standard
|
||||
// medications grid loads in parallel without paying for it.
|
||||
@@ -185,6 +215,14 @@ export function Glp1MedicationCard({
|
||||
staleTime: 60 * 1000,
|
||||
});
|
||||
|
||||
// Re-render once a minute so the in-window / overdue pill tracks
|
||||
// wall-clock progress without a route reload — mirrors the generic
|
||||
// medication card's tick cadence.
|
||||
useEffect(() => {
|
||||
const interval = setInterval(forceUpdate, 60_000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
async function recordIntake(skipped: boolean) {
|
||||
const key = skipped ? "skip" : "take";
|
||||
setIntakeLoading(key);
|
||||
@@ -209,6 +247,28 @@ export function Glp1MedicationCard({
|
||||
const rate30 = compliance?.compliance30?.rate ?? 0;
|
||||
const streak = compliance?.compliance7?.streak ?? 0;
|
||||
|
||||
// v1.4.37 W4b — symmetric take-now / overdue pill with the generic
|
||||
// card. Sort schedules by `windowStart` so the most-actionable
|
||||
// earliest window wins when multiple GLP-1 windows overlap (rare
|
||||
// today; the parity is what matters).
|
||||
const sortedSchedules = [...medication.schedules].sort(
|
||||
(a, b) =>
|
||||
a.windowStart.localeCompare(b.windowStart) ||
|
||||
a.windowEnd.localeCompare(b.windowEnd),
|
||||
);
|
||||
const nowBerlin = toBerlinDate(now);
|
||||
const lateMinutes = thresholds?.lateMinutes ?? 120;
|
||||
const missedMinutes = thresholds?.missedMinutes ?? 240;
|
||||
const currentWindowStatus = reduceCurrentWindowStatus({
|
||||
schedules: sortedSchedules,
|
||||
nowBerlin,
|
||||
lateMinutes,
|
||||
missedMinutes,
|
||||
active: medication.active,
|
||||
lastTakenAt: medication.lastTakenAt,
|
||||
todayEventCount: medication.todayEventCount ?? 0,
|
||||
});
|
||||
|
||||
const recentInjections = details?.recentIntakes ?? [];
|
||||
const lastSite =
|
||||
recentInjections.find((i) => i.injectionSite)?.injectionSite ?? null;
|
||||
@@ -280,20 +340,86 @@ export function Glp1MedicationCard({
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
{/* v1.4.37 W4b — GLP-1 specifics (side-effect quick-log etc.)
|
||||
live in the header actions overflow so the primary action
|
||||
row stays the canonical two-button shape (Eingenommen /
|
||||
Übersprungen) shared with the generic medication card. The
|
||||
kebab only renders when at least one overflow item is wired
|
||||
for this medication kind. */}
|
||||
{onLogSideEffect && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="min-h-11 min-w-11"
|
||||
aria-label={t("common.moreOptions")}
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuItem
|
||||
onClick={() => onLogSideEffect(medication)}
|
||||
className="whitespace-nowrap"
|
||||
>
|
||||
<Stethoscope className="mr-2 h-4 w-4" />
|
||||
{t("medications.glp1LogSideEffect")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const categoryLabel = getMedicationCategoryLabel(medication.category, t);
|
||||
|
||||
return (
|
||||
<Card className={medication.active ? "" : "opacity-60"}>
|
||||
<MedicationCardHeader
|
||||
name={medication.name}
|
||||
dose={medication.dose}
|
||||
categoryLabel={t("medications.treatmentClassGlp1")}
|
||||
categoryLabel={categoryLabel}
|
||||
stateBadges={stateBadges}
|
||||
actions={headerActions}
|
||||
/>
|
||||
|
||||
<CardContent className="space-y-3.5">
|
||||
{/* v1.4.37 W4b — take-now / overdue / very-overdue pill,
|
||||
byte-equivalent with the generic medication card. The
|
||||
GLP-1 card historically omitted this row, which made
|
||||
Mounjaro feel different from Ramipril on the medications
|
||||
grid even though the underlying schedule contract is
|
||||
the same shape. */}
|
||||
{currentWindowStatus.status && (
|
||||
<p className="text-sm">
|
||||
<span
|
||||
className={
|
||||
currentWindowStatus.status === "in_window"
|
||||
? "text-success font-medium"
|
||||
: currentWindowStatus.status === "late"
|
||||
? "text-dracula-yellow font-medium"
|
||||
: "text-warning font-medium"
|
||||
}
|
||||
>
|
||||
{currentWindowStatus.status === "in_window"
|
||||
? t("medications.takeNow")
|
||||
: currentWindowStatus.status === "late"
|
||||
? t("medications.overdue")
|
||||
: t("medications.veryOverdue")}
|
||||
</span>
|
||||
<span className="text-muted-foreground hidden sm:inline">
|
||||
{" "}
|
||||
—{" "}
|
||||
{formatTimeWindowRange(
|
||||
currentWindowStatus.schedule!.windowStart,
|
||||
currentWindowStatus.schedule!.windowEnd,
|
||||
locale,
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Injection state — last + next */}
|
||||
<div className="space-y-1 text-sm">
|
||||
{medication.lastTakenAt && (
|
||||
@@ -308,7 +434,21 @@ export function Glp1MedicationCard({
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-foreground/85">{nextInjectionLabel()}</p>
|
||||
<p className="text-foreground/85">
|
||||
{nextInjectionLabel()}
|
||||
{/* v1.4.37 W4b — purple dose accent on the upcoming
|
||||
schedule dose, byte-equivalent with the generic
|
||||
medication card. Schedule.dose can override the
|
||||
medication-level dose during titration, so we surface
|
||||
it here when set. Hidden below sm: to keep the narrow
|
||||
viewport row tight, matching the generic card. */}
|
||||
{schedule?.dose && (
|
||||
<span className="hidden font-medium text-purple-400 sm:inline">
|
||||
{" "}
|
||||
— {schedule.dose}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Rotation hint — only when we have a last + recommended site
|
||||
@@ -379,18 +519,20 @@ export function Glp1MedicationCard({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Primary actions row — matches the generic card's
|
||||
min-h-11 tap-target rule. The third button opens the
|
||||
side-effect log pre-tagged with the GLP-1 drug name. */}
|
||||
{/* Primary actions row — byte-equivalent with the generic
|
||||
medication card. v1.4.37 W4b moved the GLP-1-specific
|
||||
side-effect quick-log out of this row and into the
|
||||
header-actions overflow (kebab) so Mounjaro and Ramipril
|
||||
share the canonical two-button primary row. */}
|
||||
{medication.active && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
className="min-h-11 flex-1"
|
||||
onClick={() => recordIntake(false)}
|
||||
disabled={!!intakeLoading}
|
||||
>
|
||||
{intakeLoading === "take" ? (
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : (
|
||||
<Check className="mr-1 h-4 w-4" />
|
||||
)}
|
||||
@@ -403,22 +545,12 @@ export function Glp1MedicationCard({
|
||||
disabled={!!intakeLoading}
|
||||
>
|
||||
{intakeLoading === "skip" ? (
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : (
|
||||
<SkipForward className="mr-1 h-4 w-4" />
|
||||
)}
|
||||
{t("medications.skipped")}
|
||||
</Button>
|
||||
{onLogSideEffect && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="min-h-11"
|
||||
onClick={() => onLogSideEffect(medication)}
|
||||
>
|
||||
<Stethoscope className="mr-1 h-4 w-4" />
|
||||
{t("medications.glp1LogSideEffect")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@@ -3,18 +3,21 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, ArrowUp, ArrowDown, ArrowUpDown, History } from "lucide-react";
|
||||
import {
|
||||
Loader2,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
ArrowUpDown,
|
||||
History,
|
||||
Check,
|
||||
SkipForward,
|
||||
} from "lucide-react";
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { EmptyState } from "@/components/ui/empty-state";
|
||||
import {
|
||||
Table,
|
||||
@@ -40,8 +43,19 @@ import {
|
||||
* - Paginated 25/page via the existing `?limit=&offset=` query on
|
||||
* `GET /api/medications/[id]/intake`. The route already supports
|
||||
* `sortBy=takenAt|scheduledFor|createdAt|source` + `sortDir=asc|desc`.
|
||||
* - v1.4.37 W3: filters server-side with `?status=completed` so the
|
||||
* detail-page list shows only rows the user actually actioned
|
||||
* (taken OR skipped). The ambiguous "missed / never confirmed"
|
||||
* rows (`takenAt IS NULL AND skipped = false`) stay hidden here
|
||||
* and remain visible on the calendar / today surfaces. This
|
||||
* restores the v1 component's effective behaviour and fixes the
|
||||
* bug where such rows rendered as "Eingenommen" with an empty
|
||||
* leading column.
|
||||
* - Sortable by `takenAt` (default) and `scheduledFor`. Click the
|
||||
* header to toggle the direction; switching column resets to desc.
|
||||
* - Status chip: green Check + "Eingenommen" for taken rows,
|
||||
* outline SkipForward + "Übersprungen" for skipped rows. The
|
||||
* component never labels a row both at once.
|
||||
* - Source badge surfaces WEB / API / REMINDER / IMPORT using the
|
||||
* existing `medications.source*` keys.
|
||||
* - Empty state copy + CTA back to the daily intake page.
|
||||
@@ -74,6 +88,13 @@ interface IntakeHistoryListV2Props {
|
||||
type SortKey = "takenAt" | "scheduledFor";
|
||||
|
||||
const DEFAULT_PAGE_SIZE = 25;
|
||||
/**
|
||||
* v1.4.37 W3 — pinned to "completed" for the detail-page surface so
|
||||
* planned / missed rows never leak into the table. Lifted to a
|
||||
* module-level constant so the queryKey stays stable across renders
|
||||
* and `setQueryData` in tests can pre-seed the same shape.
|
||||
*/
|
||||
const STATUS_FILTER = "completed";
|
||||
|
||||
export function IntakeHistoryListV2({
|
||||
medicationId,
|
||||
@@ -95,7 +116,7 @@ export function IntakeHistoryListV2({
|
||||
medicationId,
|
||||
"intake",
|
||||
"list",
|
||||
{ sortBy, sortDir, limit: pageSize, offset },
|
||||
{ sortBy, sortDir, limit: pageSize, offset, status: STATUS_FILTER },
|
||||
],
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams({
|
||||
@@ -103,6 +124,7 @@ export function IntakeHistoryListV2({
|
||||
sortDir,
|
||||
limit: String(pageSize),
|
||||
offset: String(offset),
|
||||
status: STATUS_FILTER,
|
||||
});
|
||||
const res = await fetch(
|
||||
`/api/medications/${medicationId}/intake?${params.toString()}`,
|
||||
@@ -206,36 +228,65 @@ export function IntakeHistoryListV2({
|
||||
{sortIndicator("scheduledFor")}
|
||||
</button>
|
||||
</TableHead>
|
||||
<TableHead>{t("medications.intakeHistoryColStatus")}</TableHead>
|
||||
<TableHead>{t("medications.intakeHistoryColSource")}</TableHead>
|
||||
<TableHead>
|
||||
{t("medications.intakeHistoryColStatus")}
|
||||
</TableHead>
|
||||
<TableHead>
|
||||
{t("medications.intakeHistoryColSource")}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{events.map((event) => (
|
||||
<TableRow key={event.id}>
|
||||
<TableCell className="text-sm">
|
||||
{event.takenAt ? formatters.dateTime(event.takenAt) : "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{formatters.dateTime(event.scheduledFor)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={event.skipped ? "outline" : "secondary"}
|
||||
className="text-xs"
|
||||
>
|
||||
{event.skipped
|
||||
? t("medications.intakeHistoryStatusSkipped")
|
||||
: t("medications.intakeHistoryStatusTaken")}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{sourceLabels[event.source] ?? event.source}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{events.map((event) => {
|
||||
// v1.4.37 W3 — `status=completed` server filter
|
||||
// guarantees that every row is either a taken or a
|
||||
// skipped event. We derive the branch from the data
|
||||
// itself rather than trusting a single `skipped`
|
||||
// flag so a malformed row (e.g. `skipped:false` with
|
||||
// `takenAt:null`, the v1.4.36 regression) never
|
||||
// sneaks past as "Eingenommen".
|
||||
const isTaken = !event.skipped && !!event.takenAt;
|
||||
const isSkipped = event.skipped;
|
||||
return (
|
||||
<TableRow key={event.id}>
|
||||
<TableCell className="text-sm">
|
||||
{event.takenAt
|
||||
? formatters.dateTime(event.takenAt)
|
||||
: "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{formatters.dateTime(event.scheduledFor)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{isTaken ? (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="gap-1 bg-green-500/20 text-xs text-green-400"
|
||||
>
|
||||
<Check aria-hidden="true" className="h-3 w-3" />
|
||||
{t("medications.intakeHistoryStatusTaken")}
|
||||
</Badge>
|
||||
) : isSkipped ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-muted-foreground gap-1 text-xs"
|
||||
>
|
||||
<SkipForward
|
||||
aria-hidden="true"
|
||||
className="h-3 w-3"
|
||||
/>
|
||||
{t("medications.intakeHistoryStatusSkipped")}
|
||||
</Badge>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{sourceLabels[event.source] ?? event.source}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
|
||||
@@ -10,6 +10,12 @@ import { MedicationCardHeader } from "@/components/medications/MedicationCardHea
|
||||
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { formatTimeWindowRange } from "@/lib/time-window-format";
|
||||
import { formatDateTime, formatTime } from "@/lib/format";
|
||||
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
|
||||
import {
|
||||
parseTimeToMinutes,
|
||||
reduceCurrentWindowStatus,
|
||||
toBerlinDate,
|
||||
} from "@/lib/medications/window-status";
|
||||
import {
|
||||
Check,
|
||||
SkipForward,
|
||||
@@ -71,33 +77,6 @@ interface MedicationCardProps {
|
||||
onEdit: (med: Medication) => void;
|
||||
}
|
||||
|
||||
function parseTimeToMinutes(value: string): number {
|
||||
const [h, m] = value.split(":").map(Number);
|
||||
if (
|
||||
!Number.isFinite(h) ||
|
||||
!Number.isFinite(m) ||
|
||||
h < 0 ||
|
||||
h > 23 ||
|
||||
m < 0 ||
|
||||
m > 59
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
return h * 60 + m;
|
||||
}
|
||||
|
||||
function toBerlinDate(date: Date): Date {
|
||||
// Intentionally en-US: this is not user-facing display — it produces a
|
||||
// parseable string ("1/2/2026, 3:04:05 PM") that we feed back into Date
|
||||
// to shift the *value* from UTC to Berlin-local for arithmetic. Display
|
||||
// formatting goes through useFormatters() elsewhere.
|
||||
return new Date(
|
||||
date.toLocaleString("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function getNextOccurrenceTimestamp(
|
||||
schedule: Schedule,
|
||||
nowBerlin: Date,
|
||||
@@ -139,67 +118,6 @@ function getNextOccurrenceTimestamp(
|
||||
return null;
|
||||
}
|
||||
|
||||
type MedicationWindowStatus = "in_window" | "late" | "very_late" | null;
|
||||
|
||||
function getWindowStatus(
|
||||
schedule: Schedule,
|
||||
nowBerlin: Date,
|
||||
lateMinutes: number,
|
||||
missedMinutes: number,
|
||||
): MedicationWindowStatus {
|
||||
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
|
||||
const startMins = parseTimeToMinutes(schedule.windowStart);
|
||||
let endMins = parseTimeToMinutes(schedule.windowEnd);
|
||||
|
||||
// Handle overnight windows
|
||||
if (endMins <= startMins) endMins += 24 * 60;
|
||||
const adjustedNow =
|
||||
nowMins < startMins && endMins > 24 * 60 ? nowMins + 24 * 60 : nowMins;
|
||||
|
||||
// Currently in window
|
||||
if (adjustedNow >= startMins && adjustedNow <= endMins) return "in_window";
|
||||
|
||||
// Past window end: check late thresholds
|
||||
const minutesPastEnd = adjustedNow - endMins;
|
||||
if (minutesPastEnd > 0 && minutesPastEnd <= lateMinutes) return "late";
|
||||
if (minutesPastEnd > lateMinutes && minutesPastEnd <= missedMinutes)
|
||||
return "very_late";
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isLastIntakeInCurrentWindow(
|
||||
lastTakenAt: string | null,
|
||||
schedule: Schedule,
|
||||
nowBerlin: Date,
|
||||
): boolean {
|
||||
if (!lastTakenAt) return false;
|
||||
|
||||
const intake = toBerlinDate(new Date(lastTakenAt));
|
||||
|
||||
// Must be same calendar day
|
||||
if (
|
||||
intake.getFullYear() !== nowBerlin.getFullYear() ||
|
||||
intake.getMonth() !== nowBerlin.getMonth() ||
|
||||
intake.getDate() !== nowBerlin.getDate()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const intakeMins = intake.getHours() * 60 + intake.getMinutes();
|
||||
const startMins = parseTimeToMinutes(schedule.windowStart);
|
||||
let endMins = parseTimeToMinutes(schedule.windowEnd);
|
||||
|
||||
// Handle overnight windows
|
||||
if (endMins <= startMins) endMins += 24 * 60;
|
||||
const adjustedIntake =
|
||||
intakeMins < startMins && endMins > 24 * 60
|
||||
? intakeMins + 24 * 60
|
||||
: intakeMins;
|
||||
|
||||
return adjustedIntake >= startMins && adjustedIntake <= endMins;
|
||||
}
|
||||
|
||||
export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t, locale } = useTranslations();
|
||||
@@ -255,21 +173,7 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
|
||||
const rate7 = compliance?.compliance7?.rate ?? 0;
|
||||
const rate30 = compliance?.compliance30?.rate ?? 0;
|
||||
const streak = compliance?.compliance7?.streak ?? 0;
|
||||
const categoryLabels: Record<string, string> = {
|
||||
BLOOD_PRESSURE: t("medications.categoryBloodPressure"),
|
||||
VITAMIN: t("medications.categoryVitamin"),
|
||||
SUPPLEMENT: t("medications.categorySupplement"),
|
||||
PAIN_RELIEF: t("medications.categoryPainRelief"),
|
||||
ALLERGY: t("medications.categoryAllergy"),
|
||||
DIGESTIVE: t("medications.categoryDigestive"),
|
||||
THYROID: t("medications.categoryThyroid"),
|
||||
HORMONE: t("medications.categoryHormone"),
|
||||
SKIN: t("medications.categorySkin"),
|
||||
SLEEP_AID: t("medications.categorySleepAid"),
|
||||
OTHER: t("medications.categoryOther"),
|
||||
};
|
||||
const categoryLabel =
|
||||
categoryLabels[medication.category] ?? t("medications.categoryOther");
|
||||
const categoryLabel = getMedicationCategoryLabel(medication.category, t);
|
||||
const sortedSchedules = [...medication.schedules].sort(
|
||||
(a, b) =>
|
||||
a.windowStart.localeCompare(b.windowStart) ||
|
||||
@@ -293,55 +197,15 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
|
||||
const lateMinutes = thresholds?.lateMinutes ?? 120;
|
||||
const missedMinutes = thresholds?.missedMinutes ?? 240;
|
||||
|
||||
// Count schedules that are past their window (overdue today)
|
||||
const passedScheduleCount = medication.active
|
||||
? sortedSchedules.filter((s) => {
|
||||
const recurrence = parseScheduleRecurrence(s.daysOfWeek);
|
||||
if (
|
||||
recurrence.daysOfWeek.length > 0 &&
|
||||
!recurrence.daysOfWeek.includes(nowBerlin.getDay())
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const endMins = parseTimeToMinutes(s.windowEnd);
|
||||
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
|
||||
return nowMins > endMins;
|
||||
}).length
|
||||
: 0;
|
||||
|
||||
const todayEvents = medication.todayEventCount ?? 0;
|
||||
const hasUncoveredOverdue = todayEvents < passedScheduleCount;
|
||||
|
||||
const currentWindowStatus = medication.active
|
||||
? sortedSchedules.reduce<{
|
||||
status: MedicationWindowStatus;
|
||||
schedule: Schedule | null;
|
||||
}>(
|
||||
(best, s) => {
|
||||
const status = getWindowStatus(
|
||||
s,
|
||||
nowBerlin,
|
||||
lateMinutes,
|
||||
missedMinutes,
|
||||
);
|
||||
if (!status) return best;
|
||||
// Don't show late/very_late if all overdue schedules are covered by events
|
||||
if (status !== "in_window" && !hasUncoveredOverdue) return best;
|
||||
// Don't show in_window if last intake is already within this window today
|
||||
if (
|
||||
status === "in_window" &&
|
||||
isLastIntakeInCurrentWindow(medication.lastTakenAt, s, nowBerlin)
|
||||
)
|
||||
return best;
|
||||
const priority = { in_window: 3, late: 2, very_late: 1 };
|
||||
if (!best.status || priority[status] > priority[best.status]) {
|
||||
return { status, schedule: s };
|
||||
}
|
||||
return best;
|
||||
},
|
||||
{ status: null, schedule: null },
|
||||
)
|
||||
: { status: null, schedule: null };
|
||||
const currentWindowStatus = reduceCurrentWindowStatus({
|
||||
schedules: sortedSchedules,
|
||||
nowBerlin,
|
||||
lateMinutes,
|
||||
missedMinutes,
|
||||
active: medication.active,
|
||||
lastTakenAt: medication.lastTakenAt,
|
||||
todayEventCount: medication.todayEventCount ?? 0,
|
||||
});
|
||||
|
||||
function formatLastTakenAt(value: string): string {
|
||||
// Intentionally en-CA: gives YYYY-MM-DD which is locale-independent and
|
||||
|
||||
@@ -326,7 +326,12 @@ export function GettingStartedChecklist() {
|
||||
onClick={() => setExpanded((prev) => !prev)}
|
||||
aria-expanded={expanded}
|
||||
aria-controls="getting-started-body"
|
||||
className="hover:text-foreground -m-1 flex min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors"
|
||||
// v1.4.37 W-CI — lift the toggle to clear the WCAG 2.5.5 mobile
|
||||
// tap-target floor on Pixel-5 (Marc's iOS-textarea-zoom sweep
|
||||
// pinned the floor at 44 px; the previous `p-1` padding left
|
||||
// the toggle at 32 px). `sm:min-h-10` returns to the desktop
|
||||
// 40 px tier so the dashboard header rhythm is unchanged.
|
||||
className="hover:text-foreground -m-1 flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors sm:min-h-10"
|
||||
>
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
@@ -353,7 +358,14 @@ export function GettingStartedChecklist() {
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
// v1.4.37 W-CI — the shadcn `default` Button is `h-10` (40 px)
|
||||
// across breakpoints; lift to 44 px on mobile to clear the
|
||||
// WCAG 2.5.5 floor that the rest of the input primitives
|
||||
// follow via `h-11 sm:h-10`. The dismiss CTA is one of the
|
||||
// few primary buttons rendered above the fold on the
|
||||
// onboarded-user dashboard so the regression was visible to
|
||||
// the touch-target spec.
|
||||
className="text-muted-foreground hover:text-foreground min-h-11 sm:min-h-10"
|
||||
onClick={() => setDismissedAll(true)}
|
||||
>
|
||||
{t("gettingStarted.dismissAll")}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveInitialTimezone } from "../account-section";
|
||||
|
||||
/**
|
||||
* v1.4.37 — silent browser-timezone auto-seed for the account
|
||||
* profile picker.
|
||||
*
|
||||
* The retired "Browser-Zeitzone übernehmen" button used to ask the
|
||||
* user to opt in; v1.4.37 seeds the form for them on first mount
|
||||
* whenever the stored value is still the Europe/Berlin default and
|
||||
* the browser reports a different IANA zone. The helper that drives
|
||||
* that decision is pure so the contract can be pinned without
|
||||
* mounting the full AccountSection component tree (which depends on
|
||||
* react-query, useAuth, next/navigation, etc.).
|
||||
*/
|
||||
|
||||
describe("resolveInitialTimezone — v1.4.37 silent auto-seed", () => {
|
||||
it("pre-fills the browser zone when the stored value is the Berlin default and the browser is elsewhere", () => {
|
||||
expect(resolveInitialTimezone("Europe/Berlin", "America/New_York")).toBe(
|
||||
"America/New_York",
|
||||
);
|
||||
});
|
||||
|
||||
it("pre-fills the browser zone when the stored value is null and the browser is elsewhere", () => {
|
||||
expect(resolveInitialTimezone(null, "Asia/Tokyo")).toBe("Asia/Tokyo");
|
||||
});
|
||||
|
||||
it("pre-fills the browser zone when the stored value is an empty string and the browser is elsewhere", () => {
|
||||
expect(resolveInitialTimezone("", "Europe/London")).toBe("Europe/London");
|
||||
});
|
||||
|
||||
it("keeps Berlin when the browser is also Berlin (no seed needed)", () => {
|
||||
expect(resolveInitialTimezone("Europe/Berlin", "Europe/Berlin")).toBe(
|
||||
"Europe/Berlin",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps Berlin when the browser detection returned an empty string", () => {
|
||||
// detectBrowserTimezone falls back to Europe/Berlin on engines
|
||||
// without Intl.DateTimeFormat, but guard against future shapes
|
||||
// that hand back an empty string.
|
||||
expect(resolveInitialTimezone("Europe/Berlin", "")).toBe("Europe/Berlin");
|
||||
});
|
||||
|
||||
it("respects any non-Berlin stored value — explicit user choice wins over browser detection", () => {
|
||||
expect(
|
||||
resolveInitialTimezone("America/Los_Angeles", "Europe/Berlin"),
|
||||
).toBe("America/Los_Angeles");
|
||||
});
|
||||
|
||||
it("respects a non-Berlin stored value even when the browser reports a different non-Berlin zone", () => {
|
||||
// User stored Pacific, then opened the form from a hotel in
|
||||
// Tokyo. The stored value still wins; the user can change it
|
||||
// explicitly via the picker if they want.
|
||||
expect(resolveInitialTimezone("America/Los_Angeles", "Asia/Tokyo")).toBe(
|
||||
"America/Los_Angeles",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* v1.4.37 W7a — Arztbericht hero card contract.
|
||||
*
|
||||
* The flagship doctor-report PDF surface was promoted from one of five
|
||||
* grid cards into a hero card at the top of `/settings/export`. This
|
||||
* suite pins the SSR contract:
|
||||
*
|
||||
* 1. The hero renders with the expected `data-testid` slot.
|
||||
* 2. The value statement is present (Marc-Voice copy, no AI mention).
|
||||
* 3. The CTA button is present, clears the 44 px touch floor, and
|
||||
* carries an `aria-describedby` link to the value statement.
|
||||
* 4. The CTA is wired to a click handler (the prop `data-testid`
|
||||
* surface is the e2e contract).
|
||||
* 5. Both DE and EN locales resolve their copy without leaking the
|
||||
* raw i18n key.
|
||||
*
|
||||
* Project convention is SSR-only tests (no `@testing-library/react`).
|
||||
* The actual click-flow + PDF generation is exercised by the e2e
|
||||
* Playwright path and the dialog's own integration tests.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => "/settings/export",
|
||||
}));
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { ArztberichtHeroCard } from "../arztbericht-hero-card";
|
||||
|
||||
function renderSSR(node: React.ReactElement, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("<ArztberichtHeroCard> — SSR contract", () => {
|
||||
it("renders the hero slot with eyebrow + title", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report"');
|
||||
// Title falls back to the existing doctorReport.title key — keeps
|
||||
// a single source-of-truth for the brand name.
|
||||
expect(html).toContain("Doctor Report");
|
||||
// Eyebrow surfaces the use-case framing.
|
||||
expect(html).toContain("Doctor visit");
|
||||
});
|
||||
|
||||
it("renders the value statement as a Marc-Voice one-liner", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report-value"');
|
||||
expect(html).toContain("printable PDF report");
|
||||
// No AI/Coach name-drop in the user-facing artefact (Marc-Voice).
|
||||
expect(html.toLowerCase()).not.toContain("coach");
|
||||
expect(html.toLowerCase()).not.toContain(" ai ");
|
||||
});
|
||||
|
||||
it("renders the CTA with min-h-11 touch target + aria-describedby", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
|
||||
// 44 px touch floor (WCAG 2.5.5) — the hero CTA pins `h-11` on
|
||||
// mobile and falls back to the compact `sm:h-10` on pointer
|
||||
// devices.
|
||||
expect(html).toContain("h-11");
|
||||
// Aria-describedby links the CTA to the value statement so screen
|
||||
// readers announce the framing alongside the action label.
|
||||
expect(html).toMatch(/aria-describedby="[^"]+"/);
|
||||
});
|
||||
|
||||
it("does NOT leak raw i18n keys", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
expect(html).not.toContain("settings.sections.export.hero");
|
||||
expect(html).not.toContain("settings.sections.export.cards.doctorReport");
|
||||
});
|
||||
|
||||
it("renders German copy when the DE locale is active", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />, "de");
|
||||
expect(html).toContain("Arztbericht");
|
||||
expect(html).toContain("Arzttermin");
|
||||
// Umlauts encoded as their literal UTF-8 character (not their HTML
|
||||
// entity), matching the rest of the codebase.
|
||||
expect(html).toContain("druckbarer PDF-Bericht");
|
||||
expect(html).not.toContain("settings.sections.export.hero");
|
||||
});
|
||||
|
||||
it("uses the hero-gradient + glow-purple visual treatment", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
// Same surface utilities as the Insights hero strip — keeps the
|
||||
// app's hero language consistent.
|
||||
expect(html).toContain("hero-gradient");
|
||||
expect(html).toContain("glow-purple");
|
||||
});
|
||||
|
||||
it("does not paint dialog markup in the closed-state SSR pass", () => {
|
||||
// Radix Dialog renders its portal content lazily, so the closed
|
||||
// SSR pass never carries `role="dialog"`. The CTA testid IS
|
||||
// present so the e2e suite can drive the open from there. Pinning
|
||||
// this contract guards against an accidental `defaultOpen={true}`
|
||||
// regression that would briefly paint the dialog above the page on
|
||||
// every cold mount.
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
|
||||
expect(html).not.toContain('role="dialog"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("<ArztberichtHeroCard> — heading hierarchy", () => {
|
||||
it("uses an <h2> so it nests cleanly below the page-level <h1>", () => {
|
||||
const html = renderSSR(<ArztberichtHeroCard />);
|
||||
// Page-level h1 (settings-section-export-title) wraps the section;
|
||||
// hero owns the h2 slot. The export-section test pins the outer
|
||||
// h1; this assertion pins the hero's contribution.
|
||||
expect(html).toMatch(/<h2[^>]*id="export-hero-doctor-report-title"/);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,24 @@
|
||||
/**
|
||||
* v1.4.16 Phase B7 — Settings → Export section.
|
||||
*
|
||||
* The acceptance criterion for the consolidated Export menu is "five cards":
|
||||
* 1. Doctor Report (PDF)
|
||||
* The acceptance criterion for the consolidated Export menu was "five
|
||||
* cards":
|
||||
* 1. Doctor Report (PDF) — promoted to the hero in v1.4.37 W7a;
|
||||
* now lives at the top of the page, NOT in the grid
|
||||
* 2. Measurements CSV
|
||||
* 3. Medications CSV (with optional intake-history toggle)
|
||||
* 4. Mood CSV
|
||||
* 5. Full JSON Backup
|
||||
*
|
||||
* Each card must surface a title, a 1-line description, and a download/generate
|
||||
* button. SSR-only smoke test — interaction is exercised by the e2e suite.
|
||||
* Each card must surface a title, a 1-line description, and a
|
||||
* download/generate button. SSR-only smoke test — interaction is
|
||||
* exercised by the e2e suite.
|
||||
*
|
||||
* v1.4.37 W7a — the doctor-report card was extracted into
|
||||
* `<ArztberichtHeroCard>` and rendered above the grid. The remaining
|
||||
* four cards stay under a "Weitere Export-Optionen" / "Other export
|
||||
* options" sub-heading. The hero owns its own contract test; this
|
||||
* suite pins the page-level shape.
|
||||
*/
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
@@ -51,12 +60,27 @@ describe("<ExportSection> — SSR smoke", () => {
|
||||
expect(html).not.toContain("settings.sections.export.");
|
||||
});
|
||||
|
||||
it("renders exactly five export cards", () => {
|
||||
it("renders the Arztbericht hero card at the top of the page", () => {
|
||||
const html = render(<ExportSection />);
|
||||
// The hero owns its own contract suite; here we pin that the page
|
||||
// mounts it, and that the legacy in-grid doctor-report card is
|
||||
// gone (v1.4.37 W7a moved it into the hero).
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report"');
|
||||
expect(html).not.toContain('data-testid="export-card-doctor-report"');
|
||||
});
|
||||
|
||||
it("renders the 'Other export options' sub-heading above the grid", () => {
|
||||
const html = render(<ExportSection />);
|
||||
expect(html).toContain("Other export options");
|
||||
expect(html).toContain('id="settings-section-export-other-title"');
|
||||
});
|
||||
|
||||
it("renders exactly four secondary export cards in the grid", () => {
|
||||
const html = render(<ExportSection />);
|
||||
// Each card carries a stable data-testid so the e2e suite can target
|
||||
// them without relying on the localised label.
|
||||
// them without relying on the localised label. The doctor-report
|
||||
// card is no longer in this grid — it's the hero above.
|
||||
const ids = [
|
||||
"export-card-doctor-report",
|
||||
"export-card-measurements-csv",
|
||||
"export-card-medications-csv",
|
||||
"export-card-mood-csv",
|
||||
@@ -75,17 +99,20 @@ describe("<ExportSection> — SSR smoke", () => {
|
||||
expect(html).toContain('data-testid="export-medications-include-intake"');
|
||||
});
|
||||
|
||||
it("renders a download/generate button per card", () => {
|
||||
it("renders a download/generate button per secondary card + the hero CTA", () => {
|
||||
const html = render(<ExportSection />);
|
||||
// Buttons are typed `button` and decorated with a stable testid so a
|
||||
// single regex finds all five — the labels themselves are i18n'd.
|
||||
// Four secondary cards each carry an `export-action-*` testid; the
|
||||
// hero owns the `export-hero-doctor-report-action` slot.
|
||||
const buttonMatches = html.match(/data-testid="export-action-/g);
|
||||
expect(buttonMatches?.length ?? 0).toBe(5);
|
||||
expect(buttonMatches?.length ?? 0).toBe(4);
|
||||
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
|
||||
});
|
||||
|
||||
it("German locale renders the DE heading", () => {
|
||||
it("German locale renders the DE heading + hero copy", () => {
|
||||
const html = render(<ExportSection />, "de");
|
||||
expect(html).toContain("Export");
|
||||
expect(html).toContain("Arztbericht");
|
||||
expect(html).toContain("Weitere Export-Optionen");
|
||||
expect(html).not.toContain("settings.sections.export.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { TimezonePicker } from "../timezone-picker";
|
||||
|
||||
/**
|
||||
* v1.4.37 — the "Browser-Zeitzone übernehmen" / "Use browser timezone"
|
||||
* affordance retired. Auto-seeding now happens silently inside the
|
||||
* account-section bootstrap (`detectBrowserTimezone()` on first mount
|
||||
* when the stored value is still the Europe/Berlin default), so the
|
||||
* picker chrome is just `<Label>` + `<NativeSelect>` + the hint line.
|
||||
*
|
||||
* These SSR smoke tests pin that contract end-to-end so a regression
|
||||
* that re-adds either the button copy or the icon would fail the
|
||||
* suite before reaching production.
|
||||
*/
|
||||
|
||||
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("<TimezonePicker> v1.4.37 affordance removal", () => {
|
||||
it("renders the label, select, and hint without the legacy button (en)", () => {
|
||||
const html = render(
|
||||
<TimezonePicker value="Europe/Berlin" onChange={() => {}} />,
|
||||
);
|
||||
expect(html).toContain("Timezone");
|
||||
expect(html).toContain("Used for chart axis labels");
|
||||
expect(html).not.toContain("Use browser timezone");
|
||||
});
|
||||
|
||||
it("renders the label, select, and hint without the legacy button (de)", () => {
|
||||
const html = render(
|
||||
<TimezonePicker value="Europe/Berlin" onChange={() => {}} />,
|
||||
"de",
|
||||
);
|
||||
expect(html).toContain("Zeitzone");
|
||||
expect(html).not.toContain("Browser-Zeitzone übernehmen");
|
||||
});
|
||||
|
||||
it("keeps the stored value selectable even when not in the IANA list", () => {
|
||||
// A made-up zone simulates an engine where the runtime IANA list
|
||||
// has rolled but the user's stored value is still valid. The
|
||||
// picker keeps the value as an extra <option> so the form does
|
||||
// not silently fall back to the first list entry.
|
||||
const html = render(
|
||||
<TimezonePicker value="Antarctica/Casey" onChange={() => {}} />,
|
||||
);
|
||||
expect(html).toContain("Antarctica/Casey");
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,7 @@ 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";
|
||||
import { detectBrowserTimezone, DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
|
||||
interface PasskeyInfo {
|
||||
id: string;
|
||||
@@ -59,6 +60,46 @@ interface PasskeyInfo {
|
||||
// contract now. Existing `<select className={NATIVE_SELECT_CLASS}>`
|
||||
// call sites in this file swapped to `<NativeSelect>` below.
|
||||
|
||||
/**
|
||||
* v1.4.37 — silent browser-zone auto-seed for the timezone picker.
|
||||
*
|
||||
* Until v1.4.37 the picker carried a "Browser-Zeitzone übernehmen" /
|
||||
* "Use browser timezone" button so the user could overwrite the
|
||||
* Europe/Berlin seed with their detected zone on demand. The button
|
||||
* was visually noisy next to the picker on mobile and almost every
|
||||
* user wants the browser zone anyway, so the affordance retired and
|
||||
* the bootstrap effect seeds the form for them.
|
||||
*
|
||||
* Rules:
|
||||
*
|
||||
* - If the stored value is anything other than the Europe/Berlin
|
||||
* default, respect it. The user explicitly picked it.
|
||||
* - If the stored value is the Europe/Berlin default but the
|
||||
* browser actually IS in Berlin, leave it alone — the picker
|
||||
* stays on Berlin and the next save is a no-op.
|
||||
* - If the stored value is the default AND the browser reports a
|
||||
* non-Berlin zone, pre-fill the picker with the detected zone.
|
||||
* The form's existing submit handler persists the change on the
|
||||
* next save; no toast, no banner, no opt-in.
|
||||
*
|
||||
* The bootstrap deliberately runs inline during render (the strict
|
||||
* `react-hooks/set-state-in-effect` rule outlaws setState in an
|
||||
* effect for this hydration shape), so this helper has to stay
|
||||
* pure — no DOM access, no `useState`. The detected browser zone is
|
||||
* passed in by the caller via `detectBrowserTimezone()`.
|
||||
*/
|
||||
export function resolveInitialTimezone(
|
||||
storedTimezone: string | null | undefined,
|
||||
detectedBrowserTimezone: string,
|
||||
): string {
|
||||
const stored = storedTimezone || DEFAULT_TIMEZONE;
|
||||
const shouldAutoSeed =
|
||||
stored === DEFAULT_TIMEZONE &&
|
||||
detectedBrowserTimezone.length > 0 &&
|
||||
detectedBrowserTimezone !== DEFAULT_TIMEZONE;
|
||||
return shouldAutoSeed ? detectedBrowserTimezone : stored;
|
||||
}
|
||||
|
||||
export function AccountSection() {
|
||||
const { t, locale, setLocale } = useTranslations();
|
||||
const { user, isLoading, isAuthenticated, refetch } = useAuth();
|
||||
@@ -130,7 +171,7 @@ export function AccountSection() {
|
||||
: "",
|
||||
);
|
||||
setGender(user.gender ?? "");
|
||||
setTimezone(user.timezone || "Europe/Berlin");
|
||||
setTimezone(resolveInitialTimezone(user.timezone, detectBrowserTimezone()));
|
||||
}
|
||||
|
||||
async function handleSaveProfile(e: React.FormEvent) {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* v1.4.37 W7a — Settings → Export Arztbericht hero card.
|
||||
*
|
||||
* The doctor-report PDF is HealthLog's flagship export — the artefact a
|
||||
* user actually carries into a doctor's appointment. The v1.4.16 phase
|
||||
* B7 layout treated it as one of five equal cards in the grid, which
|
||||
* undersold the feature. Marc 2026-05-17:
|
||||
*
|
||||
* "Können wir unter Einstellungen > Export den Arztbericht als Hero
|
||||
* Card machen?"
|
||||
*
|
||||
* This component lifts the doctor-report card out of the grid and
|
||||
* paints it with the same `hero-gradient + glow-purple` visual treatment
|
||||
* as the Insights hero strip (`src/components/insights/hero-strip.tsx`),
|
||||
* so the surface feels consistent with the rest of the app. The CTA
|
||||
* routes through the existing `<DoctorReportDialog>` + `/api/doctor-
|
||||
* report` flow — only the framing changed.
|
||||
*
|
||||
* Layout:
|
||||
*
|
||||
* ┌─ hero ────────────────────────────────────────────┐
|
||||
* │ [icon] eyebrow │
|
||||
* │ H2 title (settings.sections.export.cards. │
|
||||
* │ doctorReport.title) │
|
||||
* │ one-line value statement │
|
||||
* │ ───── │
|
||||
* │ [Configure & generate] PDF · printable │
|
||||
* └───────────────────────────────────────────────────┘
|
||||
*
|
||||
* Mobile-first: at < sm the CTA stacks below the value statement (the
|
||||
* action row is `flex-wrap`), the hero pads down to `px-4 py-5`, and
|
||||
* the title clamps to a single line.
|
||||
*
|
||||
* a11y:
|
||||
* - The CTA button clears the 44 px touch floor (`min-h-11`).
|
||||
* - `focus-visible:ring` ships via the default `<Button>` variant.
|
||||
* - The CTA is `aria-describedby={valueStatementId}` so a screen
|
||||
* reader announces the value statement alongside the action.
|
||||
* - The hero's `<h2>` slots beneath the page-level `<h1>` so the
|
||||
* outline reads h1 (Export) → h2 (Arztbericht hero) → h2
|
||||
* (Weitere Export-Optionen) → h2 (each remaining card).
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { Loader2, Stethoscope } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DoctorReportDialog,
|
||||
type DoctorReportSubmitPayload,
|
||||
} from "@/components/doctor-report/doctor-report-dialog";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function ArztberichtHeroCard() {
|
||||
const { t, locale } = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [defaultPracticeName, setDefaultPracticeName] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const valueStatementId = useId();
|
||||
|
||||
// Pre-fill the practice name from the user profile so the dialog opens
|
||||
// ready-to-submit. Best-effort: if the request fails, the dialog still
|
||||
// works without a pre-fill — mirrors the legacy `<DoctorReportCard>`.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch("/api/auth/me", { credentials: "include" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (cancelled || !json) return;
|
||||
const name = json?.data?.lastReportPracticeName;
|
||||
if (typeof name === "string") setDefaultPracticeName(name);
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore — pre-fill is a UX nicety
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(payload: DoctorReportSubmitPayload) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/doctor-report", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
startDate: payload.startDate,
|
||||
endDate: payload.endDate,
|
||||
practiceName: payload.practiceName,
|
||||
sections: payload.sections,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setError(`${res.status}`);
|
||||
return;
|
||||
}
|
||||
const json = await res.json();
|
||||
const { generateDoctorReportPDF } =
|
||||
await import("@/lib/doctor-report-pdf");
|
||||
const doc = generateDoctorReportPDF(json.data, { t, locale });
|
||||
const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report";
|
||||
doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`);
|
||||
if (payload.practiceName) setDefaultPracticeName(payload.practiceName);
|
||||
setOpen(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
data-testid="export-hero-doctor-report"
|
||||
aria-labelledby="export-hero-doctor-report-title"
|
||||
className={cn(
|
||||
"hero-gradient glow-purple animate-insight-in",
|
||||
// `isolate` traps the purple glow inside the hero so the
|
||||
// shadow doesn't leak through the cards below — same trick
|
||||
// the Insights `<HeroStrip>` uses.
|
||||
"relative isolate overflow-hidden rounded-xl px-4 py-5 sm:px-6 sm:py-6",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Stethoscope
|
||||
className="text-dracula-purple h-5 w-5 shrink-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
|
||||
{t("settings.sections.export.hero.eyebrow")}
|
||||
</span>
|
||||
</div>
|
||||
<h2
|
||||
id="export-hero-doctor-report-title"
|
||||
className="text-2xl leading-tight font-semibold tracking-tight sm:text-[28px]"
|
||||
>
|
||||
{t("settings.sections.export.cards.doctorReport.title")}
|
||||
</h2>
|
||||
<p
|
||||
id={valueStatementId}
|
||||
data-testid="export-hero-doctor-report-value"
|
||||
className="text-muted-foreground max-w-2xl text-sm leading-relaxed"
|
||||
>
|
||||
{t("settings.sections.export.hero.valueStatement")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 border-t border-border/50 pt-4">
|
||||
<Button
|
||||
data-testid="export-hero-doctor-report-action"
|
||||
variant="default"
|
||||
// `min-h-11` (44 px) is the WCAG 2.5.5 touch-target floor;
|
||||
// we override the default `<Button>` height on mobile and
|
||||
// fall back to the compact `sm:h-10` on pointer devices.
|
||||
className="h-11 px-5 text-sm font-medium sm:h-10"
|
||||
onClick={() => setOpen(true)}
|
||||
disabled={busy}
|
||||
aria-describedby={valueStatementId}
|
||||
>
|
||||
{busy && (
|
||||
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
|
||||
)}
|
||||
{t("settings.sections.export.hero.cta")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{t("settings.sections.export.hero.formatHint")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="text-destructive text-xs">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DoctorReportDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
defaultPracticeName={defaultPracticeName}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -9,16 +9,23 @@
|
||||
* per export type, each with its own filter inputs and a clear
|
||||
* "Download" / "Generate" button.
|
||||
*
|
||||
* 1. Doctor Report (PDF) — date range + practice name dialog
|
||||
* 1. Doctor Report (PDF) — hero card at the top of the page
|
||||
* (v1.4.37 W7a, see
|
||||
* `<ArztberichtHeroCard>`)
|
||||
* 2. Measurements CSV — optional `since`/`until`
|
||||
* 3. Medications CSV — optional intake-history toggle
|
||||
* 4. Mood CSV — optional `since`/`until`
|
||||
* 5. Full JSON Backup — single-file user-scoped dump
|
||||
*
|
||||
* v1.4.37 W7a — the doctor-report card was promoted to the page hero so
|
||||
* the flagship "PDF for the doctor" flow no longer competes for visual
|
||||
* weight with the secondary CSV/JSON exports. The remaining four cards
|
||||
* live under a "Weitere Export-Optionen" sub-heading.
|
||||
*
|
||||
* Mobile-first: cards stack on `<md`, two-column grid on `>=md`.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Download,
|
||||
FileJson,
|
||||
@@ -26,7 +33,6 @@ import {
|
||||
FileText,
|
||||
Loader2,
|
||||
Pill,
|
||||
Stethoscope,
|
||||
Waves,
|
||||
} from "lucide-react";
|
||||
|
||||
@@ -34,13 +40,10 @@ import { Button } from "@/components/ui/button";
|
||||
import { DateInput } from "@/components/ui/date-input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
DoctorReportDialog,
|
||||
type DoctorReportSubmitPayload,
|
||||
} from "@/components/doctor-report/doctor-report-dialog";
|
||||
import { ArztberichtHeroCard } from "@/components/settings/arztbericht-hero-card";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
type ExportFormat = "PDF" | "CSV" | "JSON";
|
||||
type ExportFormat = "CSV" | "JSON";
|
||||
|
||||
/**
|
||||
* Trigger a browser download for a given URL by spinning up an anchor
|
||||
@@ -82,14 +85,33 @@ export function ExportSection() {
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{/* Mobile: single column. Desktop (md+): 2-column grid. */}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<DoctorReportCard />
|
||||
<MeasurementsCsvCard />
|
||||
<MedicationsCsvCard />
|
||||
<MoodCsvCard />
|
||||
<FullBackupCard />
|
||||
</div>
|
||||
{/* v1.4.37 W7a — Arztbericht hero. The doctor-report PDF is the
|
||||
flagship "data out" path; the previous grid layout buried it
|
||||
alongside the four CSV/JSON exports. The hero now sits at the
|
||||
top of the page; the same generation flow runs underneath. */}
|
||||
<ArztberichtHeroCard />
|
||||
|
||||
{/* v1.4.37 W7a — secondary export options. The doctor-report
|
||||
card moved into the hero above, so this group renders the
|
||||
four remaining destinations under a dedicated sub-heading.
|
||||
Mobile: single column. Desktop (md+): 2-column grid. */}
|
||||
<section
|
||||
aria-labelledby="settings-section-export-other-title"
|
||||
className="space-y-3"
|
||||
>
|
||||
<h2
|
||||
id="settings-section-export-other-title"
|
||||
className="text-base font-semibold tracking-tight"
|
||||
>
|
||||
{t("settings.sections.export.otherOptionsHeading")}
|
||||
</h2>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<MeasurementsCsvCard />
|
||||
<MedicationsCsvCard />
|
||||
<MoodCsvCard />
|
||||
<FullBackupCard />
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -140,110 +162,6 @@ function ExportCardShell({
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────────────────── Doctor Report ───────────────────────────
|
||||
|
||||
function DoctorReportCard() {
|
||||
const { t, locale } = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [defaultPracticeName, setDefaultPracticeName] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Pre-fill the practice name from the user profile so the dialog opens
|
||||
// ready-to-submit. Best-effort: if the request fails, the dialog still
|
||||
// works without a pre-fill.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch("/api/auth/me", { credentials: "include" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (cancelled || !json) return;
|
||||
const name = json?.data?.lastReportPracticeName;
|
||||
if (typeof name === "string") setDefaultPracticeName(name);
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore — pre-fill is a UX nicety
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(payload: DoctorReportSubmitPayload) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/doctor-report", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
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) {
|
||||
setError(`${res.status}`);
|
||||
return;
|
||||
}
|
||||
const json = await res.json();
|
||||
const { generateDoctorReportPDF } =
|
||||
await import("@/lib/doctor-report-pdf");
|
||||
const doc = generateDoctorReportPDF(json.data, { t, locale });
|
||||
const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report";
|
||||
doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`);
|
||||
if (payload.practiceName) setDefaultPracticeName(payload.practiceName);
|
||||
setOpen(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ExportCardShell
|
||||
testId="export-card-doctor-report"
|
||||
icon={Stethoscope}
|
||||
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"
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={() => setOpen(true)}
|
||||
disabled={busy}
|
||||
>
|
||||
{busy && <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />}
|
||||
{t("settings.sections.export.cards.doctorReport.action")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{error && (
|
||||
<p role="alert" className="text-destructive text-xs">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<DoctorReportDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
defaultPracticeName={defaultPracticeName}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
</ExportCardShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────────────────── CSV cards ───────────────────────────
|
||||
|
||||
interface DateRangeFieldsProps {
|
||||
|
||||
@@ -3,29 +3,30 @@
|
||||
/**
|
||||
* 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
|
||||
* Renders a native `<select>` over `Intl.supportedValuesOf('timeZone')`.
|
||||
* 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.
|
||||
*
|
||||
* v1.4.37 — the "Browser-Zeitzone übernehmen" button retired. The
|
||||
* account-section bootstrap effect now seeds the form silently with
|
||||
* `detectBrowserTimezone()` on first mount when the stored value is
|
||||
* still the Europe/Berlin default, so the affordance is no longer
|
||||
* needed and the picker reads cleaner alongside the surrounding form
|
||||
* rows.
|
||||
*
|
||||
* 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 { useMemo } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import {
|
||||
detectBrowserTimezone,
|
||||
listSupportedTimezones,
|
||||
} from "@/lib/tz/format";
|
||||
import { listSupportedTimezones } from "@/lib/tz/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
// v1.4.27 MB7 / CF-52 — the in-file `NATIVE_SELECT_CLASS` constant
|
||||
@@ -54,11 +55,6 @@ export function TimezonePicker({
|
||||
// `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");
|
||||
|
||||
@@ -75,20 +71,6 @@ export function TimezonePicker({
|
||||
autoComplete="off"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">{labelHint}</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleUseBrowserTz}
|
||||
aria-label={
|
||||
detected
|
||||
? t("settings.timezoneDetectAria", { tz: detected })
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Compass className="mr-2 h-4 w-4" />
|
||||
{t("settings.timezoneDetect")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -96,46 +78,23 @@ export function TimezonePicker({
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={id}>{t("settings.timezone")}</Label>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<NativeSelect
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="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>
|
||||
))}
|
||||
</NativeSelect>
|
||||
{/* v1.4.33 — visible label is "use browser zone"; the actual
|
||||
IANA zone is read out via aria-label so screen-reader users
|
||||
still hear which zone the click will apply. Previously the
|
||||
label inlined `(Europe/Berlin)`, which on a 393 CSS px
|
||||
viewport wrapped the button to two lines and broke height
|
||||
parity with the adjacent select. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleUseBrowserTz}
|
||||
className="sm:w-auto"
|
||||
aria-label={
|
||||
detected
|
||||
? t("settings.timezoneDetectAria", { tz: detected })
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Compass className="mr-2 h-4 w-4" />
|
||||
{t("settings.timezoneDetect")}
|
||||
</Button>
|
||||
</div>
|
||||
<NativeSelect
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="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>
|
||||
))}
|
||||
</NativeSelect>
|
||||
<p className="text-muted-foreground text-xs">{labelHint}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,24 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { TargetCard, type TargetCardData } from "../target-card";
|
||||
import { DEFAULT_ASSISTANT_FLAGS } from "@/hooks/use-feature-flags";
|
||||
|
||||
// v1.4.37 W4a item 9 — when the operator disables the Coach feature
|
||||
// flag globally, the per-card CTA must disappear. The hook reads from
|
||||
// QueryClientContext but falls back to the all-on default in SSR;
|
||||
// the flag-off path needs an explicit mock so the test can drive the
|
||||
// negative case without a QueryClientProvider.
|
||||
vi.mock("@/hooks/use-feature-flags", async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import("@/hooks/use-feature-flags")
|
||||
>("@/hooks/use-feature-flags");
|
||||
return {
|
||||
...actual,
|
||||
useFeatureFlags: vi.fn(() => actual.DEFAULT_ASSISTANT_FLAGS),
|
||||
};
|
||||
});
|
||||
|
||||
const { useFeatureFlags } = await import("@/hooks/use-feature-flags");
|
||||
|
||||
/**
|
||||
* v1.4.25 W3e — `<TargetCard>` composition. Three load-bearing cases:
|
||||
@@ -100,6 +118,35 @@ describe("<TargetCard>", () => {
|
||||
expect(html).not.toContain('data-slot="target-coach-cta"');
|
||||
});
|
||||
|
||||
// v1.4.37 W4a item 9 — operator-level feature flag.
|
||||
it("suppresses the Coach CTA when the global Coach flag is OFF", () => {
|
||||
// Swap the mock for this case only — flag-off should hide the
|
||||
// CTA regardless of the user-level aiEnabled state. Restore the
|
||||
// all-on default so the rest of the suite doesn't see a leaked
|
||||
// mock state.
|
||||
vi.mocked(useFeatureFlags).mockReturnValueOnce({
|
||||
...DEFAULT_ASSISTANT_FLAGS,
|
||||
coach: false,
|
||||
});
|
||||
const html = render({
|
||||
target: fullDataTarget,
|
||||
aiEnabled: true,
|
||||
onAskCoach: vi.fn(),
|
||||
});
|
||||
expect(html).not.toContain('data-slot="target-coach-cta"');
|
||||
});
|
||||
|
||||
it("renders the Coach CTA when both aiEnabled AND the global Coach flag are ON", () => {
|
||||
// Positive control: the default-mock returns the all-on flag set,
|
||||
// so the CTA should mount when aiEnabled is also true.
|
||||
const html = render({
|
||||
target: fullDataTarget,
|
||||
aiEnabled: true,
|
||||
onAskCoach: vi.fn(),
|
||||
});
|
||||
expect(html).toContain('data-slot="target-coach-cta"');
|
||||
});
|
||||
|
||||
it("renders MOOD_STABILITY headline as a verbal label, not the σ value", () => {
|
||||
const moodStability: TargetCardData = {
|
||||
...fullDataTarget,
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { moodStabilityLabel } from "@/lib/targets/mood-stability-label";
|
||||
import { ConsistencyStrip } from "./consistency-strip";
|
||||
import { RangeBar } from "./range-bar";
|
||||
@@ -343,6 +344,13 @@ export function TargetCard({
|
||||
sourceLink,
|
||||
}: TargetCardProps) {
|
||||
const { t, locale } = useTranslations();
|
||||
// v1.4.37 W4a item 9 — when the operator disables the Coach
|
||||
// feature flag globally, every per-card "Ask the coach" CTA must
|
||||
// disappear (not greyed-out, not a placeholder). The card's
|
||||
// existing `aiEnabled` gate guards on the user-level provider
|
||||
// chain; this flag guards on the operator-level feature switch.
|
||||
// Both must be ON for the CTA to mount.
|
||||
const flags = useFeatureFlags();
|
||||
|
||||
// v1.4.25 W3f — per-card edit affordance. Cog top-right of every
|
||||
// card opens the edit dialog; the dialog handles the read-only path
|
||||
@@ -413,9 +421,15 @@ export function TargetCard({
|
||||
data-slot="target-card"
|
||||
data-target-type={target.type}
|
||||
data-status={statusGroup}
|
||||
className="flex h-full flex-col"
|
||||
// v1.4.37 W4a item 3 — override the Card primitive's default
|
||||
// `gap-4 md:gap-6` to `gap-3 md:gap-4`. The default gap stacked
|
||||
// on top of the CardHeader's `pb-3` rendered a ~36 px dead
|
||||
// space between "Blutdruck optimal" and the headline number;
|
||||
// the tighter rhythm pulls the value back under the label so
|
||||
// the card reads as one unit instead of two separated blocks.
|
||||
className="flex h-full flex-col gap-3 md:gap-4"
|
||||
>
|
||||
<CardHeader className="gap-2 pb-3 sm:gap-3">
|
||||
<CardHeader className="gap-2 pb-0 sm:gap-3">
|
||||
{/* Row 1: icon + label (left) ⋯ status pill + edit-cog (right
|
||||
on sm+, stacked on mobile). Stacking on mobile keeps the
|
||||
headline number visible at sub-380px viewports where an
|
||||
@@ -662,7 +676,7 @@ export function TargetCard({
|
||||
source link right. `mt-auto` pins to card bottom so grid
|
||||
cells align. */}
|
||||
<div className="mt-auto flex flex-row items-center justify-between gap-3 pt-1">
|
||||
{aiEnabled && (
|
||||
{aiEnabled && flags.coach && (
|
||||
<TargetCoachButton
|
||||
prefill={coachPrefill}
|
||||
sources={coachSources}
|
||||
|
||||
@@ -74,7 +74,13 @@ function DropdownMenuItem({
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex min-h-11 cursor-default items-center gap-2 rounded-sm px-2 py-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
// v1.4.37 W4a item 2 — `whitespace-nowrap` keeps every
|
||||
// dropdown row on a single line (the sidebar 3-dot menu's
|
||||
// "Benachrichtigungs-Center" otherwise wrapped at the
|
||||
// hyphen on sub-pixel rounding inside the legacy w-56
|
||||
// container). Applies app-wide so the top-bar w-48 menus
|
||||
// get the same protection.
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex min-h-11 cursor-default items-center gap-2 rounded-sm px-2 py-2 text-sm whitespace-nowrap outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -41,7 +41,15 @@ function SelectTrigger({
|
||||
// clear WCAG 2.5.5 and shrinks to 40 px on sm+ to match the
|
||||
// desktop input rhythm. `size=sm` (filter chips) intentionally
|
||||
// keeps the 32 px footprint.
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-11 data-[size=default]:sm:h-10 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
// v1.4.37 W4a item 4 — split the trigger's horizontal padding
|
||||
// (`pl-3 pr-2.5`) and push the chevron icon 4 px further right
|
||||
// via `[&_svg:last-child]:mr-1` so the trailing glyph parks at
|
||||
// the same visual gutter as the browser-native date-input
|
||||
// calendar icon (~16-20 px on Chromium). The old uniform
|
||||
// `px-3` parked the chevron 12 px from the edge, which read
|
||||
// visibly tighter than the date-picker glyph when both
|
||||
// controls shared a form row.
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent pl-3 pr-2.5 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-11 data-[size=default]:sm:h-10 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:last-child]:mr-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
Reference in new issue
Block a user