mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
feat(measurements): add custom metrics (define, log, chart)
Add a user-defined custom-metric store alongside the built-in measurements on the Measurements surface. A user defines an arbitrary metric (name, unit, optional target window, decimals, description), logs values, and charts them. The store is a separate generic catalog + values pair, isolated from the closed measurement-type system: not synced, not in FHIR, not in insights — log and chart only. Names and units are plaintext, mirroring the biomarker catalog. The inline list lives beneath the measurement list (no new nav entry); tapping a metric opens a detail page with the trend chart, target band, stat strip, and an editable value history. Migration 0224 adds custom_metrics and custom_metric_entries.
This commit is contained in:
1 parent
150b827d01
commit
b3e6ba03d7
35 files changed
+4956
No files matched your search
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type {
|
||||
CustomMetricDto,
|
||||
CustomMetricEntryDto,
|
||||
CustomMetricEntryListResponse,
|
||||
} from "../types";
|
||||
|
||||
/**
|
||||
* The custom-metric detail page mirrors the labs biomarker detail: a
|
||||
* numbers-first stat strip over the values, the (lazy) chart, and the value
|
||||
* controls. This test seeds the metric + value queries and asserts the heading,
|
||||
* the stat strip, the chart placeholder, and the controls all paint.
|
||||
*/
|
||||
|
||||
vi.mock("@/lib/api/api-fetch", () => ({
|
||||
apiGet: () => new Promise(() => {}),
|
||||
apiDelete: vi.fn(),
|
||||
apiPost: vi.fn(),
|
||||
apiPatch: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-auth", () => ({
|
||||
useAuth: () => ({ isAuthenticated: true, user: { id: "u1" } }),
|
||||
}));
|
||||
|
||||
import { CustomMetricDetail } from "../custom-metric-detail";
|
||||
|
||||
const METRIC_ID = "cm-1";
|
||||
|
||||
const METRIC: CustomMetricDto = {
|
||||
id: METRIC_ID,
|
||||
name: "Morning grip strength",
|
||||
unit: "kg",
|
||||
targetLow: 20,
|
||||
targetHigh: 60,
|
||||
decimals: 1,
|
||||
description: "Right-hand grip measured first thing.",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function entry(
|
||||
id: string,
|
||||
value: number,
|
||||
measuredAt: string,
|
||||
): CustomMetricEntryDto {
|
||||
return {
|
||||
id,
|
||||
customMetricId: METRIC_ID,
|
||||
value,
|
||||
unit: "kg",
|
||||
measuredAt,
|
||||
note: null,
|
||||
createdAt: measuredAt,
|
||||
};
|
||||
}
|
||||
|
||||
const LIST: CustomMetricEntryListResponse = {
|
||||
entries: [
|
||||
entry("e3", 45, "2026-06-20T08:00:00.000Z"),
|
||||
entry("e2", 43, "2026-05-20T08:00:00.000Z"),
|
||||
entry("e1", 41, "2026-04-20T08:00:00.000Z"),
|
||||
],
|
||||
meta: { total: 3, limit: 200, offset: 0 },
|
||||
};
|
||||
|
||||
function renderWithCache() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
queryClient.setQueryData(queryKeys.customMetricDetail(METRIC_ID), METRIC);
|
||||
queryClient.setQueryData(
|
||||
queryKeys.customMetricEntries({
|
||||
customMetricId: METRIC_ID,
|
||||
sortDir: "desc",
|
||||
}),
|
||||
{ pages: [LIST], pageParams: [0] },
|
||||
);
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nProvider initialLocale="en">
|
||||
<CustomMetricDetail customMetricId={METRIC_ID} />
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("<CustomMetricDetail>", () => {
|
||||
const html = renderWithCache();
|
||||
|
||||
it("paints the metric heading", () => {
|
||||
expect(html).toContain("Morning grip strength");
|
||||
});
|
||||
|
||||
it("paints the user description", () => {
|
||||
expect(html).toContain("Right-hand grip measured first thing.");
|
||||
});
|
||||
|
||||
it("paints the numbers-first stat strip", () => {
|
||||
expect(html).toContain('data-slot="metric-stat-strip"');
|
||||
});
|
||||
|
||||
it("paints the chart placeholder (lazy chart shell)", () => {
|
||||
expect(html).toContain('data-slot="skeleton"');
|
||||
});
|
||||
|
||||
it("offers the edit + delete controls with hover tooltips", () => {
|
||||
expect(html).toContain('title="Edit"');
|
||||
expect(html).toContain('title="Delete"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
CartesianGrid,
|
||||
ComposedChart,
|
||||
Line,
|
||||
ReferenceArea,
|
||||
ReferenceLine,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
|
||||
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
|
||||
import { formatDateShort } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import { RichChartTooltip, type RichTooltipRow } from "../charts/chart-tooltip";
|
||||
import { formatMetricValue } from "./format-value";
|
||||
import type { CustomMetricEntryDto } from "./types";
|
||||
|
||||
/**
|
||||
* v1.25.5 — per-custom-metric trend chart, in the dashboard's visual language.
|
||||
*
|
||||
* A single line over time, the optional target window painted as a shaded
|
||||
* `ReferenceArea` band with dashed bound lines, range tabs (30 / 90 / 365 /
|
||||
* all), and the shared rich tooltip. The band uses a MUTED primary fill — never
|
||||
* a danger colour. Mirrors `lab-biomarker-chart`. Reads entries LIVE (no
|
||||
* rollup tier).
|
||||
*/
|
||||
|
||||
const RANGE_DAYS = [
|
||||
{ key: "30", days: 30 },
|
||||
{ key: "90", days: 90 },
|
||||
{ key: "365", days: 365 },
|
||||
{ key: "all", days: 0 },
|
||||
] as const;
|
||||
|
||||
type RangeKey = (typeof RANGE_DAYS)[number]["key"];
|
||||
|
||||
interface ChartPoint {
|
||||
timestamp: number;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export function CustomMetricChart({
|
||||
entries,
|
||||
unit,
|
||||
targetLow,
|
||||
targetHigh,
|
||||
decimals,
|
||||
}: {
|
||||
/** Entries for this metric, any order (sorted internally). */
|
||||
entries: CustomMetricEntryDto[];
|
||||
unit: string;
|
||||
targetLow: number | null;
|
||||
targetHigh: number | null;
|
||||
decimals: number | null;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const [range, setRange] = useState<RangeKey>("365");
|
||||
const [nowMs] = useState(() => Date.now());
|
||||
|
||||
const points = useMemo<ChartPoint[]>(() => {
|
||||
const sorted = [...entries].sort(
|
||||
(a, b) =>
|
||||
new Date(a.measuredAt).getTime() - new Date(b.measuredAt).getTime(),
|
||||
);
|
||||
const days = RANGE_DAYS.find((r) => r.key === range)?.days ?? 0;
|
||||
const filtered =
|
||||
days > 0
|
||||
? sorted.filter((r) => {
|
||||
const ageMs = nowMs - new Date(r.measuredAt).getTime();
|
||||
return ageMs <= days * 24 * 60 * 60 * 1000;
|
||||
})
|
||||
: sorted;
|
||||
return filtered.map((r) => ({
|
||||
timestamp: new Date(r.measuredAt).getTime(),
|
||||
value: r.value,
|
||||
}));
|
||||
}, [entries, range, nowMs]);
|
||||
|
||||
const yDomain = useMemo<[number, number]>(() => {
|
||||
const candidates = points.map((p) => p.value);
|
||||
if (targetLow != null) candidates.push(targetLow);
|
||||
if (targetHigh != null) candidates.push(targetHigh);
|
||||
if (candidates.length === 0) return [0, 1];
|
||||
const min = Math.min(...candidates);
|
||||
const max = Math.max(...candidates);
|
||||
const pad = (max - min || Math.abs(max) || 1) * 0.1;
|
||||
return [min - pad, max + pad];
|
||||
}, [points, targetLow, targetHigh]);
|
||||
|
||||
const animate = !prefersReducedMotion();
|
||||
const primary = "var(--primary)";
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-end gap-1">
|
||||
{RANGE_DAYS.map((r) => (
|
||||
<Button
|
||||
key={r.key}
|
||||
size="sm"
|
||||
variant={range === r.key ? "secondary" : "ghost"}
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => setRange(r.key)}
|
||||
>
|
||||
{t(`customMetrics.chart.range.${r.key}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{points.length === 0 ? (
|
||||
<p className="text-muted-foreground py-10 text-center text-sm">
|
||||
{t("customMetrics.chart.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<div>
|
||||
<ResponsiveContainer width="100%" height={CHART_HEIGHT_PX}>
|
||||
<ComposedChart
|
||||
data={points}
|
||||
margin={{ top: 8, right: 12, bottom: 4, left: 0 }}
|
||||
>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
vertical={false}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="timestamp"
|
||||
type="number"
|
||||
scale="time"
|
||||
domain={["dataMin", "dataMax"]}
|
||||
tickFormatter={(ts: number) => formatDateShort(new Date(ts))}
|
||||
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
|
||||
stroke="var(--border)"
|
||||
minTickGap={32}
|
||||
/>
|
||||
<YAxis
|
||||
domain={yDomain}
|
||||
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
|
||||
stroke="var(--border)"
|
||||
width={44}
|
||||
tickFormatter={(v: number) => formatMetricValue(v, decimals)}
|
||||
/>
|
||||
{targetLow != null && targetHigh != null ? (
|
||||
<ReferenceArea
|
||||
y1={targetLow}
|
||||
y2={targetHigh}
|
||||
fill={primary}
|
||||
fillOpacity={0.1}
|
||||
stroke="none"
|
||||
/>
|
||||
) : null}
|
||||
{targetLow != null ? (
|
||||
<ReferenceLine
|
||||
y={targetLow}
|
||||
stroke={primary}
|
||||
strokeOpacity={0.4}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
) : null}
|
||||
{targetHigh != null ? (
|
||||
<ReferenceLine
|
||||
y={targetHigh}
|
||||
stroke={primary}
|
||||
strokeOpacity={0.4}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
) : null}
|
||||
<Tooltip
|
||||
content={(props) => {
|
||||
const active = props.active ?? false;
|
||||
const payload = props.payload as
|
||||
ReadonlyArray<{ payload?: ChartPoint }> | undefined;
|
||||
const point = payload?.[0]?.payload;
|
||||
if (!active || !point) {
|
||||
return <RichChartTooltip active={false} rows={[]} />;
|
||||
}
|
||||
const rows: RichTooltipRow[] = [
|
||||
{
|
||||
name: t("customMetrics.chart.valueLabel"),
|
||||
value: `${formatMetricValue(point.value, decimals)} ${unit}`,
|
||||
color: primary,
|
||||
},
|
||||
];
|
||||
return (
|
||||
<RichChartTooltip
|
||||
active
|
||||
label={formatDateShort(new Date(point.timestamp))}
|
||||
rows={rows}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke={primary}
|
||||
strokeWidth={2}
|
||||
dot={{ r: 3, fill: primary }}
|
||||
activeDot={{ r: 5 }}
|
||||
isAnimationActive={animate}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { Gauge, ListOrdered, Pencil, Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { DeleteButton } from "@/components/data-list";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { EmptyState } from "@/components/ui/empty-state";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { MetricStatStrip } from "@/components/insights/metric-stat-strip";
|
||||
import { apiDelete, apiGet } from "@/lib/api/api-fetch";
|
||||
import { summarize, type DataSummary } from "@/lib/analytics/trends";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import type { ComponentProps } from "react";
|
||||
import { ChartErrorBoundary } from "@/components/charts/chart-error-state";
|
||||
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
|
||||
import { importWithRetry } from "@/lib/retry-import";
|
||||
|
||||
import { CustomMetricEntryForm } from "./custom-metric-entry-form";
|
||||
import { CustomMetricForm } from "./custom-metric-form";
|
||||
import type {
|
||||
CustomMetricDto,
|
||||
CustomMetricEntryDto,
|
||||
CustomMetricEntryListResponse,
|
||||
} from "./types";
|
||||
|
||||
// Defer the recharts chart through `next/dynamic` (ssr:false) so recharts is
|
||||
// off the detail page's first-load JS; the skeleton shell holds the layout.
|
||||
const CustomMetricChartLazy = dynamic(
|
||||
() =>
|
||||
importWithRetry(() => import("./custom-metric-chart")).then((mod) => ({
|
||||
default: mod.CustomMetricChart,
|
||||
})),
|
||||
{ ssr: false, loading: () => <ChartSkeleton /> },
|
||||
);
|
||||
function CustomMetricChart(
|
||||
props: ComponentProps<typeof CustomMetricChartLazy>,
|
||||
) {
|
||||
return (
|
||||
<ChartErrorBoundary>
|
||||
<CustomMetricChartLazy {...props} />
|
||||
</ChartErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
const ENTRIES_PAGE_SIZE = 200;
|
||||
|
||||
/**
|
||||
* v1.25.5 — per-custom-metric detail: heading + unit + static description,
|
||||
* numbers-first stat strip, the LIVE trend chart with the target band, and the
|
||||
* "show all values" sub-page link. Controls, left → right: Delete · Edit · Show
|
||||
* all values · Add value. Numeric-only. Mirrors the labs biomarker detail.
|
||||
*/
|
||||
export function CustomMetricDetail({
|
||||
customMetricId,
|
||||
}: {
|
||||
customMetricId: string;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [addFooterEl, setAddFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editFooterEl, setEditFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
|
||||
const {
|
||||
data: metric,
|
||||
isError: metricError,
|
||||
refetch: refetchMetric,
|
||||
} = useQuery({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
queryFn: () =>
|
||||
apiGet<CustomMetricDto>(`/api/custom-metrics/${customMetricId}`),
|
||||
});
|
||||
|
||||
const {
|
||||
data: list,
|
||||
isLoading,
|
||||
isError: listError,
|
||||
refetch: refetchList,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: queryKeys.customMetricEntries({
|
||||
customMetricId,
|
||||
sortDir: "desc",
|
||||
}),
|
||||
initialPageParam: 0,
|
||||
queryFn: ({ pageParam }) =>
|
||||
apiGet<CustomMetricEntryListResponse>(
|
||||
`/api/custom-metrics/${encodeURIComponent(
|
||||
customMetricId,
|
||||
)}/entries?limit=${ENTRIES_PAGE_SIZE}&offset=${pageParam}&sortDir=desc`,
|
||||
),
|
||||
getNextPageParam: (lastPage) => {
|
||||
const next = lastPage.meta.offset + lastPage.meta.limit;
|
||||
return next < lastPage.meta.total ? next : undefined;
|
||||
},
|
||||
});
|
||||
|
||||
const entries: CustomMetricEntryDto[] = useMemo(
|
||||
() => list?.pages.flatMap((p) => p.entries) ?? [],
|
||||
[list],
|
||||
);
|
||||
|
||||
const summary = useMemo<DataSummary | null>(
|
||||
() =>
|
||||
entries.length > 0
|
||||
? summarize(
|
||||
entries.map((r) => ({
|
||||
date: new Date(r.measuredAt),
|
||||
value: r.value,
|
||||
})),
|
||||
)
|
||||
: null,
|
||||
[entries],
|
||||
);
|
||||
|
||||
function afterAdd() {
|
||||
setAddOpen(false);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.customMetricEntries({
|
||||
customMetricId,
|
||||
sortDir: "desc",
|
||||
}),
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
});
|
||||
}
|
||||
|
||||
function afterEditMetric() {
|
||||
setEditOpen(false);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.customMetrics() });
|
||||
}
|
||||
|
||||
const deleteMetric = useMutation({
|
||||
mutationFn: () => apiDelete(`/api/custom-metrics/${customMetricId}`),
|
||||
onSuccess: () => {
|
||||
toast.success(t("customMetrics.deletedToast"));
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.customMetrics() });
|
||||
router.push("/measurements");
|
||||
},
|
||||
onError: () => toast.error(t("customMetrics.deleteError")),
|
||||
});
|
||||
|
||||
const description = metric?.description?.trim()
|
||||
? metric.description.trim()
|
||||
: t("customMetrics.detail.genericDescription");
|
||||
|
||||
if (metricError || listError) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header className="space-y-1.5">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{metric?.name ?? t("customMetrics.detail.title")}
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
{description}
|
||||
</p>
|
||||
</header>
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center gap-3 py-8 text-center">
|
||||
<p className="text-destructive text-sm">
|
||||
{t("customMetrics.loadError")}
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (metricError) void refetchMetric();
|
||||
if (listError) void refetchList();
|
||||
}}
|
||||
>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{metric?.name ?? <Skeleton className="h-7 w-32" />}
|
||||
</h1>
|
||||
{metric?.unit ? (
|
||||
<p className="text-muted-foreground text-xs sm:text-sm">
|
||||
{metric.unit}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{/* Controls, left → right: Delete · Edit · Show-all-values · Add. */}
|
||||
<DeleteButton
|
||||
onConfirm={() => deleteMetric.mutate()}
|
||||
title={t("customMetrics.deleteConfirmTitle")}
|
||||
description={t("customMetrics.deleteConfirmDescription")}
|
||||
confirmLabel={t("customMetrics.delete")}
|
||||
triggerTitle={t("customMetrics.delete")}
|
||||
className="min-h-11 min-w-11 sm:min-h-9 sm:min-w-9"
|
||||
iconClassName="h-4 w-4"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="min-h-11 min-w-11 sm:min-h-9 sm:min-w-9"
|
||||
onClick={() => setEditOpen(true)}
|
||||
disabled={!metric}
|
||||
aria-label={t("customMetrics.edit")}
|
||||
title={t("customMetrics.edit")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
{entries.length > 0 ? (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-slot="custom-metric-show-all-values"
|
||||
className="min-h-11 min-w-11 sm:min-h-9 sm:min-w-9"
|
||||
>
|
||||
<Link
|
||||
href={`/custom-metrics/${customMetricId}/values`}
|
||||
aria-label={t("customMetrics.showAllValues")}
|
||||
title={t("customMetrics.showAllValues")}
|
||||
>
|
||||
<ListOrdered className="h-4 w-4" aria-hidden="true" />
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
onClick={() => setAddOpen(true)}
|
||||
className="min-h-11 min-w-11 shrink-0 sm:min-h-9 sm:min-w-0"
|
||||
aria-label={t("customMetrics.addValue")}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">
|
||||
{t("customMetrics.addValue")}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
{description}
|
||||
</p>
|
||||
|
||||
{isLoading ? (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Skeleton className="h-60 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : entries.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<EmptyState
|
||||
icon={<Gauge className="size-6" />}
|
||||
title={t("customMetrics.detail.emptyTitle")}
|
||||
description={t("customMetrics.detail.emptyDescription")}
|
||||
action={
|
||||
<Button onClick={() => setAddOpen(true)}>
|
||||
{t("customMetrics.addValue")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<>
|
||||
<MetricStatStrip
|
||||
summary={summary}
|
||||
unit={metric?.unit ?? ""}
|
||||
seriesLabel={metric?.name}
|
||||
icon={Gauge}
|
||||
/>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<CustomMetricChart
|
||||
entries={entries}
|
||||
unit={metric?.unit ?? ""}
|
||||
targetLow={metric?.targetLow ?? null}
|
||||
targetHigh={metric?.targetHigh ?? null}
|
||||
decimals={metric?.decimals ?? null}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ResponsiveSheet
|
||||
open={addOpen}
|
||||
onOpenChange={setAddOpen}
|
||||
title={t("customMetrics.addValue")}
|
||||
description={t("customMetrics.entry.addDescription")}
|
||||
footer={
|
||||
<div ref={setAddFooterEl} className="flex w-full justify-end gap-2" />
|
||||
}
|
||||
>
|
||||
{metric ? (
|
||||
<CustomMetricEntryForm
|
||||
customMetricId={customMetricId}
|
||||
unit={metric.unit}
|
||||
footerSlot={addFooterEl}
|
||||
onSuccess={afterAdd}
|
||||
onCancel={() => setAddOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</ResponsiveSheet>
|
||||
|
||||
<ResponsiveSheet
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
title={t("customMetrics.editTitle")}
|
||||
description={t("customMetrics.defineDescription")}
|
||||
footer={
|
||||
<div
|
||||
ref={setEditFooterEl}
|
||||
className="flex w-full justify-end gap-2"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{metric ? (
|
||||
<CustomMetricForm
|
||||
existing={metric}
|
||||
footerSlot={editFooterEl}
|
||||
onSuccess={afterEditMetric}
|
||||
onCancel={() => setEditOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</ResponsiveSheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DateTimeField } from "@/components/ui/date-time-field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { ApiError, apiPost } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import type { CustomMetricEntryDto } from "./types";
|
||||
|
||||
const NOTE_MAX_LENGTH = 2000;
|
||||
|
||||
function parseDecimal(raw: string): number | null {
|
||||
const trimmed = raw.trim().replace(",", ".");
|
||||
if (trimmed === "") return null;
|
||||
const n = Number(trimmed);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** Local datetime string (`YYYY-MM-DDTHH:mm`) for "now", for the field default. */
|
||||
function nowLocal(): string {
|
||||
const d = new Date();
|
||||
const offset = d.getTimezoneOffset();
|
||||
return new Date(d.getTime() - offset * 60 * 1000).toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
interface CustomMetricEntryFormProps {
|
||||
customMetricId: string;
|
||||
unit: string;
|
||||
onSuccess?: () => void;
|
||||
onCancel?: () => void;
|
||||
footerSlot?: HTMLElement | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.25.5 — log a value against a custom metric. Numeric value + timestamp +
|
||||
* optional note. The server snapshots the metric's unit onto the entry.
|
||||
*/
|
||||
export function CustomMetricEntryForm({
|
||||
customMetricId,
|
||||
unit,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
footerSlot,
|
||||
}: CustomMetricEntryFormProps) {
|
||||
const { t } = useTranslations();
|
||||
const formId = useId();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [value, setValue] = useState("");
|
||||
const [measuredAt, setMeasuredAt] = useState(() => nowLocal());
|
||||
const [note, setNote] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
const numeric = parseDecimal(value);
|
||||
if (numeric === null) {
|
||||
setError(t("customMetrics.entry.valueError"));
|
||||
return;
|
||||
}
|
||||
const measuredDate = new Date(measuredAt);
|
||||
if (Number.isNaN(measuredDate.getTime())) {
|
||||
setError(t("customMetrics.entry.timestampError"));
|
||||
return;
|
||||
}
|
||||
|
||||
const body = {
|
||||
value: numeric,
|
||||
measuredAt: measuredDate.toISOString(),
|
||||
...(note.trim() ? { note: note.trim() } : {}),
|
||||
};
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await apiPost<CustomMetricEntryDto>(
|
||||
`/api/custom-metrics/${customMetricId}/entries`,
|
||||
body,
|
||||
);
|
||||
toast.success(t("customMetrics.entry.savedToast"));
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.customMetrics() });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["custom-metric-entries", customMetricId],
|
||||
});
|
||||
onSuccess?.();
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: t("customMetrics.entry.saveError");
|
||||
setError(message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const footerNode = (
|
||||
<>
|
||||
{onCancel ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onCancel}
|
||||
disabled={submitting}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="submit" form={formId} disabled={submitting}>
|
||||
{submitting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : null}
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<form id={formId} onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-value">
|
||||
{t("customMetrics.entry.value")}
|
||||
{unit ? ` (${unit})` : ""}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-value"
|
||||
inputMode="decimal"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-measuredAt">
|
||||
{t("customMetrics.entry.measuredAt")}
|
||||
</Label>
|
||||
<DateTimeField
|
||||
id="custom-metric-measuredAt"
|
||||
value={measuredAt}
|
||||
onChange={setMeasuredAt}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-note">
|
||||
{t("customMetrics.entry.note")}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="custom-metric-note"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
maxLength={NOTE_MAX_LENGTH}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-destructive text-sm" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{footerSlot ? (
|
||||
createPortal(footerNode, footerSlot)
|
||||
) : (
|
||||
<div className="flex justify-end gap-2">{footerNode}</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { ApiError, apiPatch, apiPost } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import type { CustomMetricDto } from "./types";
|
||||
|
||||
const DESCRIPTION_MAX_LENGTH = 2000;
|
||||
|
||||
/** Parse a free-text decimal that may use a comma separator. */
|
||||
function parseDecimal(raw: string): number | null {
|
||||
const trimmed = raw.trim().replace(",", ".");
|
||||
if (trimmed === "") return null;
|
||||
const n = Number(trimmed);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** Parse a free-text non-negative integer (display decimals). */
|
||||
function parseInteger(raw: string): number | null {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === "") return null;
|
||||
const n = Number(trimmed);
|
||||
return Number.isInteger(n) && n >= 0 ? n : null;
|
||||
}
|
||||
|
||||
interface CustomMetricFormProps {
|
||||
/** When set the form edits this metric; otherwise it defines a new one. */
|
||||
existing?: CustomMetricDto;
|
||||
onSuccess?: (saved: CustomMetricDto) => void;
|
||||
onCancel?: () => void;
|
||||
/**
|
||||
* When mounted inside a `<ResponsiveSheet>` the caller passes the sheet's
|
||||
* footer slot element here; the Cancel / Save row portals into it so the
|
||||
* bottom-sheet branch can sticky-pin it.
|
||||
*/
|
||||
footerSlot?: HTMLElement | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.25.5 — define or edit a custom metric.
|
||||
*
|
||||
* A metric is the feature's reusable definition: free-text name + unit, an
|
||||
* optional target window (set ONCE), optional display decimals, and an optional
|
||||
* description. Mirrors the biomarker form; numeric-only, no qualitative path.
|
||||
*/
|
||||
export function CustomMetricForm({
|
||||
existing,
|
||||
onSuccess,
|
||||
onCancel,
|
||||
footerSlot,
|
||||
}: CustomMetricFormProps) {
|
||||
const { t } = useTranslations();
|
||||
const formId = useId();
|
||||
|
||||
const [name, setName] = useState(existing?.name ?? "");
|
||||
const [unit, setUnit] = useState(existing?.unit ?? "");
|
||||
const [low, setLow] = useState(
|
||||
existing?.targetLow != null ? String(existing.targetLow) : "",
|
||||
);
|
||||
const [high, setHigh] = useState(
|
||||
existing?.targetHigh != null ? String(existing.targetHigh) : "",
|
||||
);
|
||||
const [decimals, setDecimals] = useState(
|
||||
existing?.decimals != null ? String(existing.decimals) : "",
|
||||
);
|
||||
const [description, setDescription] = useState(existing?.description ?? "");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!name.trim() || !unit.trim()) {
|
||||
setError(t("customMetrics.form.requiredError"));
|
||||
return;
|
||||
}
|
||||
|
||||
const lowVal = parseDecimal(low);
|
||||
const highVal = parseDecimal(high);
|
||||
if (lowVal !== null && highVal !== null && lowVal > highVal) {
|
||||
setError(t("customMetrics.form.rangeOrderError"));
|
||||
return;
|
||||
}
|
||||
const decimalsVal = parseInteger(decimals);
|
||||
|
||||
const body = {
|
||||
name: name.trim(),
|
||||
unit: unit.trim(),
|
||||
...(lowVal !== null ? { targetLow: lowVal } : {}),
|
||||
...(highVal !== null ? { targetHigh: highVal } : {}),
|
||||
...(decimalsVal !== null ? { decimals: decimalsVal } : {}),
|
||||
...(description.trim() ? { description: description.trim() } : {}),
|
||||
};
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const saved = existing
|
||||
? await apiPatch<CustomMetricDto>(
|
||||
`/api/custom-metrics/${existing.id}`,
|
||||
body,
|
||||
)
|
||||
: await apiPost<CustomMetricDto>("/api/custom-metrics", body);
|
||||
toast.success(
|
||||
existing
|
||||
? t("customMetrics.form.updatedToast")
|
||||
: t("customMetrics.form.savedToast"),
|
||||
);
|
||||
onSuccess?.(saved);
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: t("customMetrics.form.saveError");
|
||||
setError(message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const footerNode = (
|
||||
<>
|
||||
{onCancel ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onCancel}
|
||||
disabled={submitting}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="submit" form={formId} disabled={submitting}>
|
||||
{submitting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : null}
|
||||
{t("customMetrics.form.save")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<form id={formId} onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<Label htmlFor="custom-metric-name">
|
||||
{t("customMetrics.form.name")}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t("customMetrics.form.namePlaceholder")}
|
||||
maxLength={120}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-unit">
|
||||
{t("customMetrics.form.unit")}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-unit"
|
||||
value={unit}
|
||||
onChange={(e) => setUnit(e.target.value)}
|
||||
placeholder={t("customMetrics.form.unitPlaceholder")}
|
||||
maxLength={40}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-decimals">
|
||||
{t("customMetrics.form.decimals")}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-decimals"
|
||||
inputMode="numeric"
|
||||
value={decimals}
|
||||
onChange={(e) => setDecimals(e.target.value)}
|
||||
placeholder={t("customMetrics.form.decimalsPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-low">
|
||||
{t("customMetrics.form.targetLow")}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-low"
|
||||
inputMode="decimal"
|
||||
value={low}
|
||||
onChange={(e) => setLow(e.target.value)}
|
||||
placeholder={t("customMetrics.form.targetLowPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-high">
|
||||
{t("customMetrics.form.targetHigh")}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-high"
|
||||
inputMode="decimal"
|
||||
value={high}
|
||||
onChange={(e) => setHigh(e.target.value)}
|
||||
placeholder={t("customMetrics.form.targetHighPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<Label htmlFor="custom-metric-description">
|
||||
{t("customMetrics.form.description")}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="custom-metric-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder={t("customMetrics.form.descriptionPlaceholder")}
|
||||
maxLength={DESCRIPTION_MAX_LENGTH}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("customMetrics.form.targetHint")}
|
||||
</p>
|
||||
|
||||
{error ? (
|
||||
<p className="text-destructive text-sm" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{footerSlot ? (
|
||||
createPortal(footerNode, footerSlot)
|
||||
) : (
|
||||
<div className="flex justify-end gap-2">{footerNode}</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2, Pencil } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { DeleteButton, SortableHead } from "@/components/data-list";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DateTimeField } from "@/components/ui/date-time-field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTableSort } from "@/hooks/use-table-sort";
|
||||
import { ApiError, apiDelete, apiPatch } from "@/lib/api/api-fetch";
|
||||
import { formatDateShort } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import { formatMetricValue } from "./format-value";
|
||||
import type { CustomMetricEntryDto } from "./types";
|
||||
|
||||
const NOTE_MAX_LENGTH = 2000;
|
||||
|
||||
const DESC_COLUMNS = new Set(["measuredAt"]);
|
||||
|
||||
function toDateTimeLocal(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
const offset = d.getTimezoneOffset();
|
||||
return new Date(d.getTime() - offset * 60 * 1000).toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
function parseDecimal(raw: string): number | null {
|
||||
const trimmed = raw.trim().replace(",", ".");
|
||||
if (trimmed === "") return null;
|
||||
const n = Number(trimmed);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.25.5 — reverse-chronological value history for one custom metric, with
|
||||
* full edit + delete. An edit overwrites in place; delete hard-deletes (the
|
||||
* value store has no soft-delete tier).
|
||||
*/
|
||||
export function CustomMetricHistoryList({
|
||||
customMetricId,
|
||||
entries,
|
||||
unit,
|
||||
decimals,
|
||||
}: {
|
||||
customMetricId: string;
|
||||
entries: CustomMetricEntryDto[];
|
||||
unit: string;
|
||||
decimals: number | null;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { sortBy, sortDir, toggleSort } = useTableSort({
|
||||
defaultColumn: "measuredAt",
|
||||
defaultDir: "desc",
|
||||
descColumns: DESC_COLUMNS,
|
||||
});
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editValue, setEditValue] = useState("");
|
||||
const [editMeasuredAt, setEditMeasuredAt] = useState("");
|
||||
const [editNote, setEditNote] = useState("");
|
||||
const [editError, setEditError] = useState<string | null>(null);
|
||||
|
||||
function invalidate() {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.customMetrics() });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["custom-metric-entries", customMetricId],
|
||||
});
|
||||
}
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) =>
|
||||
apiDelete(`/api/custom-metrics/${customMetricId}/entries/${id}`),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success(t("customMetrics.entry.deletedToast"));
|
||||
},
|
||||
onError: () => toast.error(t("customMetrics.entry.deleteError")),
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (body: {
|
||||
id: string;
|
||||
value: number;
|
||||
measuredAt: string;
|
||||
note: string | null;
|
||||
}) =>
|
||||
apiPatch<CustomMetricEntryDto>(
|
||||
`/api/custom-metrics/${customMetricId}/entries/${body.id}`,
|
||||
{
|
||||
value: body.value,
|
||||
measuredAt: body.measuredAt,
|
||||
note: body.note,
|
||||
},
|
||||
),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
toast.success(t("customMetrics.entry.editedToast"));
|
||||
closeEdit();
|
||||
},
|
||||
onError: (err) => {
|
||||
setEditError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: t("customMetrics.entry.editError"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
function openEdit(entry: CustomMetricEntryDto) {
|
||||
setEditingId(entry.id);
|
||||
setEditValue(String(entry.value));
|
||||
setEditMeasuredAt(toDateTimeLocal(entry.measuredAt));
|
||||
setEditNote(entry.note ?? "");
|
||||
setEditError(null);
|
||||
}
|
||||
|
||||
function closeEdit() {
|
||||
if (updateMutation.isPending) return;
|
||||
setEditingId(null);
|
||||
setEditError(null);
|
||||
}
|
||||
|
||||
function submitEdit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!editingId) return;
|
||||
const numeric = parseDecimal(editValue);
|
||||
if (numeric === null) {
|
||||
setEditError(t("customMetrics.entry.valueError"));
|
||||
return;
|
||||
}
|
||||
const measuredDate = new Date(editMeasuredAt);
|
||||
if (Number.isNaN(measuredDate.getTime())) {
|
||||
setEditError(t("customMetrics.entry.timestampError"));
|
||||
return;
|
||||
}
|
||||
updateMutation.mutate({
|
||||
id: editingId,
|
||||
value: numeric,
|
||||
measuredAt: measuredDate.toISOString(),
|
||||
note: editNote.trim() ? editNote.trim() : null,
|
||||
});
|
||||
}
|
||||
|
||||
const ordered = useMemo(() => {
|
||||
const dir = sortDir === "asc" ? 1 : -1;
|
||||
return [...entries].sort((a, b) => {
|
||||
let cmp = 0;
|
||||
switch (sortBy) {
|
||||
case "value":
|
||||
cmp = a.value - b.value;
|
||||
break;
|
||||
case "note":
|
||||
cmp = Number(Boolean(a.note)) - Number(Boolean(b.note));
|
||||
break;
|
||||
case "measuredAt":
|
||||
default:
|
||||
cmp =
|
||||
new Date(a.measuredAt).getTime() - new Date(b.measuredAt).getTime();
|
||||
break;
|
||||
}
|
||||
if (cmp === 0) {
|
||||
cmp =
|
||||
new Date(a.measuredAt).getTime() - new Date(b.measuredAt).getTime();
|
||||
}
|
||||
return cmp * dir;
|
||||
});
|
||||
}, [entries, sortBy, sortDir]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<SortableHead
|
||||
column="value"
|
||||
label={t("customMetrics.entry.value")}
|
||||
currentSort={sortBy}
|
||||
currentDir={sortDir}
|
||||
onSort={toggleSort}
|
||||
/>
|
||||
<SortableHead
|
||||
column="measuredAt"
|
||||
label={t("customMetrics.entry.measuredAt")}
|
||||
currentSort={sortBy}
|
||||
currentDir={sortDir}
|
||||
onSort={toggleSort}
|
||||
/>
|
||||
<SortableHead
|
||||
column="note"
|
||||
label={t("customMetrics.entry.note")}
|
||||
currentSort={sortBy}
|
||||
currentDir={sortDir}
|
||||
onSort={toggleSort}
|
||||
/>
|
||||
<TableHead className="w-20 pr-4 text-right">
|
||||
<span className="sr-only">{t("customMetrics.entry.edit")}</span>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{ordered.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell className="font-semibold tabular-nums">
|
||||
{formatMetricValue(r.value, decimals)}
|
||||
{unit ? ` ${unit}` : ""}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground text-sm whitespace-nowrap">
|
||||
{formatDateShort(r.measuredAt, true)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground max-w-[12rem] truncate text-sm">
|
||||
{r.note ?? ""}
|
||||
</TableCell>
|
||||
<TableCell className="pr-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-11 sm:size-9"
|
||||
onClick={() => openEdit(r)}
|
||||
aria-label={t("customMetrics.entry.edit")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<DeleteButton
|
||||
onConfirm={() => deleteMutation.mutate(r.id)}
|
||||
title={t("customMetrics.entry.deleteConfirmTitle")}
|
||||
description={t(
|
||||
"customMetrics.entry.deleteConfirmDescription",
|
||||
)}
|
||||
confirmLabel={t("customMetrics.entry.delete")}
|
||||
className="size-11 sm:size-9"
|
||||
iconClassName="h-4 w-4"
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<ResponsiveSheet
|
||||
open={editingId !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) closeEdit();
|
||||
}}
|
||||
title={t("customMetrics.entry.editTitle")}
|
||||
description={t("customMetrics.entry.editDescription")}
|
||||
>
|
||||
<form onSubmit={submitEdit} className="space-y-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-edit-value">
|
||||
{t("customMetrics.entry.value")}
|
||||
{unit ? ` (${unit})` : ""}
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-metric-edit-value"
|
||||
inputMode="decimal"
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-edit-measuredAt">
|
||||
{t("customMetrics.entry.measuredAt")}
|
||||
</Label>
|
||||
<DateTimeField
|
||||
id="custom-metric-edit-measuredAt"
|
||||
value={editMeasuredAt}
|
||||
onChange={setEditMeasuredAt}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="custom-metric-edit-note">
|
||||
{t("customMetrics.entry.note")}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="custom-metric-edit-note"
|
||||
value={editNote}
|
||||
onChange={(e) => setEditNote(e.target.value)}
|
||||
maxLength={NOTE_MAX_LENGTH}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
{editError ? (
|
||||
<p className="text-destructive text-sm" role="alert">
|
||||
{editError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={closeEdit}
|
||||
disabled={updateMutation.isPending}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||||
) : null}
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</ResponsiveSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronRight, Gauge, Plus } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import { CustomMetricForm } from "./custom-metric-form";
|
||||
import { formatMetricValue } from "./format-value";
|
||||
import type { CustomMetricDto, CustomMetricListResponse } from "./types";
|
||||
|
||||
/**
|
||||
* v1.25.5 — inline list of the user's custom metrics, mounted ON the
|
||||
* Measurements surface beneath the built-in measurement list (NOT a separate
|
||||
* module or nav entry). Each row shows the latest logged value and links to the
|
||||
* metric's detail + chart page; an "+ add custom metric" affordance opens the
|
||||
* define-metric sheet.
|
||||
*/
|
||||
export function CustomMetricList() {
|
||||
const { t } = useTranslations();
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [addFooterEl, setAddFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: queryKeys.customMetrics(),
|
||||
queryFn: () => apiGet<CustomMetricListResponse>("/api/custom-metrics"),
|
||||
});
|
||||
|
||||
const metrics: CustomMetricDto[] = data?.customMetrics ?? [];
|
||||
|
||||
function afterAdd(saved: CustomMetricDto) {
|
||||
setAddOpen(false);
|
||||
// Land the user on the new metric's detail page so the next step (logging
|
||||
// a value) is one tap away.
|
||||
if (typeof window !== "undefined") {
|
||||
window.location.assign(`/custom-metrics/${saved.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-3" data-slot="custom-metric-list">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-lg font-semibold tracking-tight">
|
||||
{t("customMetrics.sectionTitle")}
|
||||
</h2>
|
||||
<p className="text-muted-foreground truncate text-xs sm:text-sm">
|
||||
{t("customMetrics.sectionSubtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="min-h-11 shrink-0 sm:min-h-9"
|
||||
onClick={() => setAddOpen(true)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">{t("customMetrics.add")}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<Card aria-hidden="true">
|
||||
<CardContent className="space-y-2 py-4">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
<Skeleton className="h-3 w-56" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : isError ? (
|
||||
<p role="alert" className="text-destructive py-4 text-center text-sm">
|
||||
{t("customMetrics.loadError")}
|
||||
</p>
|
||||
) : metrics.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center gap-3 py-6 text-center">
|
||||
<Gauge className="text-muted-foreground size-6" />
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("customMetrics.emptyDescription")}
|
||||
</p>
|
||||
<Button size="sm" onClick={() => setAddOpen(true)}>
|
||||
{t("customMetrics.add")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="divide-border divide-y p-0">
|
||||
{metrics.map((metric) => (
|
||||
<Link
|
||||
key={metric.id}
|
||||
href={`/custom-metrics/${metric.id}`}
|
||||
className="hover:bg-muted/40 flex items-center justify-between gap-3 px-4 py-2.5 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">
|
||||
{metric.name}
|
||||
</div>
|
||||
<div className="text-muted-foreground flex flex-wrap items-center gap-x-2 text-xs">
|
||||
{metric.latest ? (
|
||||
<>
|
||||
<span className="text-foreground font-semibold tabular-nums">
|
||||
{formatMetricValue(
|
||||
metric.latest.value,
|
||||
metric.decimals,
|
||||
)}
|
||||
{metric.unit ? ` ${metric.unit}` : ""}
|
||||
</span>
|
||||
<span>{formatDate(metric.latest.measuredAt)}</span>
|
||||
</>
|
||||
) : (
|
||||
<span>{t("customMetrics.noValuesYet")}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="text-muted-foreground h-4 w-4 shrink-0" />
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<ResponsiveSheet
|
||||
open={addOpen}
|
||||
onOpenChange={setAddOpen}
|
||||
title={t("customMetrics.defineTitle")}
|
||||
description={t("customMetrics.defineDescription")}
|
||||
footer={
|
||||
<div ref={setAddFooterEl} className="flex w-full justify-end gap-2" />
|
||||
}
|
||||
>
|
||||
<CustomMetricForm
|
||||
footerSlot={addFooterEl}
|
||||
onSuccess={afterAdd}
|
||||
onCancel={() => setAddOpen(false)}
|
||||
/>
|
||||
</ResponsiveSheet>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import { CustomMetricHistoryList } from "./custom-metric-history-list";
|
||||
import type {
|
||||
CustomMetricDto,
|
||||
CustomMetricEntryDto,
|
||||
CustomMetricEntryListResponse,
|
||||
} from "./types";
|
||||
|
||||
const ENTRIES_PAGE_SIZE = 200;
|
||||
|
||||
/**
|
||||
* v1.25.5 — the full value history for one custom metric, on its own
|
||||
* `/custom-metrics/[id]/values` route (mirroring the labs values sub-page).
|
||||
* Offset-paginated infinite query with "Load more".
|
||||
*/
|
||||
export function CustomMetricValuesList({
|
||||
customMetricId,
|
||||
}: {
|
||||
customMetricId: string;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
const { data: metric } = useQuery({
|
||||
queryKey: queryKeys.customMetricDetail(customMetricId),
|
||||
queryFn: () =>
|
||||
apiGet<CustomMetricDto>(`/api/custom-metrics/${customMetricId}`),
|
||||
});
|
||||
|
||||
const {
|
||||
data: list,
|
||||
isLoading,
|
||||
isError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: queryKeys.customMetricEntries({
|
||||
customMetricId,
|
||||
sortDir: "desc",
|
||||
}),
|
||||
initialPageParam: 0,
|
||||
queryFn: ({ pageParam }) =>
|
||||
apiGet<CustomMetricEntryListResponse>(
|
||||
`/api/custom-metrics/${encodeURIComponent(
|
||||
customMetricId,
|
||||
)}/entries?limit=${ENTRIES_PAGE_SIZE}&offset=${pageParam}&sortDir=desc`,
|
||||
),
|
||||
getNextPageParam: (lastPage) => {
|
||||
const next = lastPage.meta.offset + lastPage.meta.limit;
|
||||
return next < lastPage.meta.total ? next : undefined;
|
||||
},
|
||||
});
|
||||
|
||||
const entries: CustomMetricEntryDto[] = useMemo(
|
||||
() => list?.pages.flatMap((p) => p.entries) ?? [],
|
||||
[list],
|
||||
);
|
||||
const total = list?.pages[0]?.meta.total ?? 0;
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<p className="text-destructive py-8 text-center text-sm">
|
||||
{t("customMetrics.loadError")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <Skeleton className="h-60 w-full" />;
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<p className="text-muted-foreground py-8 text-center text-sm">
|
||||
{t("customMetrics.detail.emptyTitle")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{hasNextPage ? (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("customMetrics.showingLatestOf", {
|
||||
shown: entries.length,
|
||||
total,
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
<Card>
|
||||
<CardContent className="py-0">
|
||||
<CustomMetricHistoryList
|
||||
customMetricId={customMetricId}
|
||||
entries={entries}
|
||||
unit={metric?.unit ?? ""}
|
||||
decimals={metric?.decimals ?? null}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{hasNextPage ? (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
disabled={isFetchingNextPage}
|
||||
onClick={() => fetchNextPage()}
|
||||
>
|
||||
{isFetchingNextPage
|
||||
? t("common.loading")
|
||||
: t("customMetrics.loadMore")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* v1.25.5 — format a custom-metric value for display.
|
||||
*
|
||||
* When the metric defines a fixed number of decimals, honour it; otherwise fall
|
||||
* back to a compact representation that trims trailing zeros (up to 3 places).
|
||||
*/
|
||||
export function formatMetricValue(
|
||||
value: number,
|
||||
decimals: number | null | undefined,
|
||||
): string {
|
||||
if (!Number.isFinite(value)) return "—";
|
||||
if (decimals != null) {
|
||||
return value.toFixed(decimals);
|
||||
}
|
||||
// Compact default: round to at most 3 places and drop trailing zeros.
|
||||
return String(Math.round(value * 1000) / 1000);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/** The latest logged value carried on a custom-metric list row. */
|
||||
export interface CustomMetricLatest {
|
||||
value: number;
|
||||
unit: string;
|
||||
measuredAt: string;
|
||||
}
|
||||
|
||||
/** A user-defined custom metric as the API serialises it. */
|
||||
export interface CustomMetricDto {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: string;
|
||||
targetLow: number | null;
|
||||
targetHigh: number | null;
|
||||
decimals: number | null;
|
||||
description: string | null;
|
||||
/** Present on the list + create reads; absent on the bare detail read. */
|
||||
latest?: CustomMetricLatest | null;
|
||||
entryCount?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CustomMetricListResponse {
|
||||
customMetrics: CustomMetricDto[];
|
||||
}
|
||||
|
||||
/** A single logged custom-metric value as the API serialises it. */
|
||||
export interface CustomMetricEntryDto {
|
||||
id: string;
|
||||
customMetricId: string;
|
||||
value: number;
|
||||
unit: string;
|
||||
measuredAt: string;
|
||||
note: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CustomMetricEntryListResponse {
|
||||
entries: CustomMetricEntryDto[];
|
||||
meta: { total: number; limit: number; offset: number };
|
||||
}
|
||||
Reference in new issue
Block a user