feat(insights): persist correlation patterns

This commit is contained in:
Marc-André Bombeck committed 2026-07-28 14:01:11 +02:00
1 parent 8ece6f39cc
commit 666a85d311
53 files changed
+2129 -55

No files matched your search

@@ -44,6 +44,7 @@ const METRIC: CustomMetricDto = {
targetHigh: 60,
decimals: 1,
description: "Right-hand grip measured first thing.",
correlationEnabled: false,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
};
@@ -8,6 +8,7 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ApiError, apiPatch, apiPost } from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
@@ -73,6 +74,9 @@ export function CustomMetricForm({
existing?.decimals != null ? String(existing.decimals) : "",
);
const [description, setDescription] = useState(existing?.description ?? "");
const [correlationEnabled, setCorrelationEnabled] = useState(
existing?.correlationEnabled ?? false,
);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -100,6 +104,7 @@ export function CustomMetricForm({
...(highVal !== null ? { targetHigh: highVal } : {}),
...(decimalsVal !== null ? { decimals: decimalsVal } : {}),
...(description.trim() ? { description: description.trim() } : {}),
correlationEnabled,
};
setSubmitting(true);
@@ -227,6 +232,21 @@ export function CustomMetricForm({
rows={2}
/>
</div>
<div className="flex items-start justify-between gap-4 sm:col-span-2">
<div className="space-y-1">
<Label htmlFor="custom-metric-correlation-enabled">
{t("customMetrics.form.correlationEnabled")}
</Label>
<p className="text-muted-foreground text-xs">
{t("customMetrics.form.correlationEnabledHint")}
</p>
</div>
<Switch
id="custom-metric-correlation-enabled"
checked={correlationEnabled}
onCheckedChange={setCorrelationEnabled}
/>
</div>
</div>
<p className="text-muted-foreground text-xs">
+1
View File
@@ -14,6 +14,7 @@ export interface CustomMetricDto {
targetHigh: number | null;
decimals: number | null;
description: string | null;
correlationEnabled: boolean;
/** Present on the list + create reads; absent on the bare detail read. */
latest?: CustomMetricLatest | null;
entryCount?: number;
+21 -1
View File
@@ -1,6 +1,7 @@
"use client";
import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import { Activity, Sparkles } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -14,6 +15,10 @@ import type { CorrelationResult } from "@/lib/insights/correlations";
import type { CoachScopeSource } from "@/lib/ai/coach/types";
import { CONFIDENCE_BADGE_CLASS } from "./confidence-badge";
import { AskCoachAction } from "./ask-coach-action";
import {
PatternDismissButton,
PatternDismissedNotice,
} from "./pattern-dismiss-action";
/**
* v1.4.20 phase B3 — single Correlation card.
@@ -95,6 +100,10 @@ const COACH_QUESTION_BY_KIND: Record<CorrelationResult["kind"], string> = {
export function CorrelationCard({ result }: CorrelationCardProps) {
const { t } = useTranslations();
const initialDismissed =
result.status === "ok" && result.dismissed === true && !!result.patternId;
const [dismissed, setDismissed] = useState(initialDismissed);
useEffect(() => setDismissed(initialDismissed), [initialDismissed]);
const title = t(TITLE_KEY[result.kind]);
const subtitle = t(SUBTITLE_KEY[result.kind]);
const coachSources = COACH_SOURCES_BY_KIND[result.kind];
@@ -140,7 +149,12 @@ export function CorrelationCard({ result }: CorrelationCardProps) {
</div>
</CardHeader>
<CardContent className="space-y-3">
{result.status === "ok" ? (
{dismissed && result.status === "ok" && result.patternId ? (
<PatternDismissedNotice
patternId={result.patternId}
onRestored={() => setDismissed(false)}
/>
) : result.status === "ok" ? (
<>
<ScatterCorrelationChart
data={result.points}
@@ -188,6 +202,12 @@ export function CorrelationCard({ result }: CorrelationCardProps) {
question={t(COACH_QUESTION_BY_KIND[result.kind])}
scope={coachScope}
/>
{result.patternId ? (
<PatternDismissButton
patternId={result.patternId}
onDismissed={() => setDismissed(true)}
/>
) : null}
</div>
</>
) : (
@@ -1,7 +1,12 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "@/lib/i18n/context";
import { MoodExplainerIcon } from "./mood-explainer-icon";
import {
PatternDismissButton,
PatternDismissedNotice,
} from "@/components/insights/pattern-dismiss-action";
/**
* v1.11.5 (F3) — FDR-controlled discovered mood relations.
@@ -33,6 +38,11 @@ export interface DiscoveredCorrelation {
qValue: number;
interpretation: string;
lagDays: number;
behaviourLabel?: string;
outcomeLabel?: string;
patternId?: string;
canonicalKey?: string;
dismissed?: boolean;
}
export interface CorrelationDiscoveryResponse {
@@ -80,6 +90,23 @@ export function MoodDiscoveredRelations({
pairsTested: number;
}) {
const { t } = useTranslations();
const [dismissedIds, setDismissedIds] = useState(
() =>
new Set(
pairs
.filter((pair) => pair.dismissed && pair.patternId)
.map((pair) => pair.patternId as string),
),
);
useEffect(() => {
setDismissedIds(
new Set(
pairs
.filter((pair) => pair.dismissed && pair.patternId)
.map((pair) => pair.patternId as string),
),
);
}, [pairs]);
if (pairs.length === 0) return null;
@@ -106,7 +133,28 @@ export function MoodDiscoveredRelations({
{pairs.map((pair) => {
const moodIsOutcome = pair.outcome === "MOOD";
const channelKey = moodIsOutcome ? pair.behaviour : pair.outcome;
const factorLabel = t(CHANNEL_LABEL_KEY[channelKey] ?? channelKey);
const dynamicLabel = moodIsOutcome
? pair.behaviourLabel
: pair.outcomeLabel;
const factorLabel =
dynamicLabel ?? t(CHANNEL_LABEL_KEY[channelKey] ?? channelKey);
if (pair.patternId && dismissedIds.has(pair.patternId)) {
return (
<li key={pair.canonicalKey ?? pair.patternId} className="py-2">
<PatternDismissedNotice
compact
patternId={pair.patternId}
onRestored={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.delete(pair.patternId as string);
return next;
})
}
/>
</li>
);
}
const up = pair.r >= 0;
const sentenceKey = moodIsOutcome
? up
@@ -139,6 +187,19 @@ export function MoodDiscoveredRelations({
})}
/>
</span>
{pair.patternId ? (
<PatternDismissButton
patternId={pair.patternId}
onDismissed={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.add(pair.patternId as string);
return next;
})
}
className="self-start"
/>
) : null}
</li>
);
})}
@@ -1,10 +1,15 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "@/lib/i18n/context";
import { useUnitDisplay } from "@/hooks/use-unit-display";
import { moodTagIcon } from "@/components/mood/mood-tag-icons";
import { cn } from "@/lib/utils";
import type { MoodInfluenceConfidence } from "./mood-tag-influence";
import {
PatternDismissButton,
PatternDismissedNotice,
} from "@/components/insights/pattern-dismiss-action";
/**
* v1.14.0 — RATED-factor × vital crosstab card.
@@ -42,6 +47,9 @@ export interface MoodFactorMetricCrosstabRow {
pValue: number;
qValue: number;
confidence: MoodInfluenceConfidence;
patternId?: string;
canonicalKey?: string;
dismissed?: boolean;
}
const METRIC_LABEL_KEY: Record<string, string> = {
@@ -87,6 +95,23 @@ export function MoodFactorMetricCrosstab({
}) {
const { t } = useTranslations();
const unitDisplay = useUnitDisplay();
const [dismissedIds, setDismissedIds] = useState(
() =>
new Set(
rows
.filter((row) => row.dismissed && row.patternId)
.map((row) => row.patternId as string),
),
);
useEffect(() => {
setDismissedIds(
new Set(
rows
.filter((row) => row.dismissed && row.patternId)
.map((row) => row.patternId as string),
),
);
}, [rows]);
if (rows.length === 0) return null;
return (
@@ -96,6 +121,23 @@ export function MoodFactorMetricCrosstab({
</p>
<ul className="divide-border divide-y">
{rows.map((row) => {
if (row.patternId && dismissedIds.has(row.patternId)) {
return (
<li key={row.canonicalKey ?? row.patternId} className="py-2">
<PatternDismissedNotice
compact
patternId={row.patternId}
onRestored={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.delete(row.patternId as string);
return next;
})
}
/>
</li>
);
}
const Icon = moodTagIcon(row.icon);
const factorLabel = t(row.labelKey);
const metricLabel = t(
@@ -155,6 +197,19 @@ export function MoodFactorMetricCrosstab({
>
{t(CONFIDENCE_KEY[row.confidence])}
</span>
{row.patternId ? (
<PatternDismissButton
patternId={row.patternId}
onDismissed={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.add(row.patternId as string);
return next;
})
}
className="shrink-0"
/>
) : null}
</div>
<p className="text-muted-foreground text-xs">
{t(
@@ -1,9 +1,14 @@
"use client";
import { useEffect, useState } from "react";
import { useTranslations } from "@/lib/i18n/context";
import { moodTagIcon } from "@/components/mood/mood-tag-icons";
import { cn } from "@/lib/utils";
import type { MoodInfluenceConfidence } from "./mood-tag-influence";
import {
PatternDismissButton,
PatternDismissedNotice,
} from "@/components/insights/pattern-dismiss-action";
/**
* v1.12.0 — tag × health-metric crosstab card.
@@ -49,6 +54,9 @@ export interface MoodTagMetricCrosstabRow {
pValue: number;
qValue: number;
confidence: MoodInfluenceConfidence;
patternId?: string;
canonicalKey?: string;
dismissed?: boolean;
}
const METRIC_LABEL_KEY: Record<string, string> = {
@@ -94,6 +102,23 @@ export function MoodTagMetricCrosstab({
rows: MoodTagMetricCrosstabRow[];
}) {
const { t } = useTranslations();
const [dismissedIds, setDismissedIds] = useState(
() =>
new Set(
rows
.filter((row) => row.dismissed && row.patternId)
.map((row) => row.patternId as string),
),
);
useEffect(() => {
setDismissedIds(
new Set(
rows
.filter((row) => row.dismissed && row.patternId)
.map((row) => row.patternId as string),
),
);
}, [rows]);
if (rows.length === 0) return null;
return (
@@ -103,6 +128,23 @@ export function MoodTagMetricCrosstab({
</p>
<ul className="divide-border divide-y">
{rows.map((row) => {
if (row.patternId && dismissedIds.has(row.patternId)) {
return (
<li key={row.canonicalKey ?? row.patternId} className="py-2">
<PatternDismissedNotice
compact
patternId={row.patternId}
onRestored={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.delete(row.patternId as string);
return next;
})
}
/>
</li>
);
}
const Icon = moodTagIcon(row.icon);
const tagLabel = row.label ?? t(row.labelKey);
const metricLabel = t(
@@ -147,6 +189,19 @@ export function MoodTagMetricCrosstab({
>
{t(CONFIDENCE_KEY[row.confidence])}
</span>
{row.patternId ? (
<PatternDismissButton
patternId={row.patternId}
onDismissed={() =>
setDismissedIds((current) => {
const next = new Set(current);
next.add(row.patternId as string);
return next;
})
}
className="shrink-0"
/>
) : null}
</div>
<p className="text-muted-foreground text-xs">
{t(
@@ -2,6 +2,7 @@
import { useQuery } from "@tanstack/react-query";
import { TrendingUp } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TileHeader } from "@/components/insights/tile-header";
@@ -55,13 +56,11 @@ export function MoodWhatStandsOut({
retry: false,
});
const moodPairs =
isLoading || isError || !data ? [] : moodPairsOf(data.discovered);
const moodPairs = !data ? [] : moodPairsOf(data.discovered);
const hasNarratives = narratives.length > 0;
const hasDiscovered = moodPairs.length > 0;
// Both halves empty → render nothing rather than an empty card.
if (!hasNarratives && !hasDiscovered) return null;
if (!hasNarratives && !isLoading && !isError && !data) return null;
return (
<Card data-slot="mood-what-stands-out">
@@ -73,6 +72,29 @@ export function MoodWhatStandsOut({
</CardHeader>
<CardContent className="space-y-4">
{hasNarratives && <MoodNarrativeFeed items={narratives} />}
{isLoading ? (
<Skeleton
data-slot="mood-discovery-loading"
className="h-16 w-full"
/>
) : null}
{isError ? (
<p
data-slot="mood-discovery-error"
role="alert"
className="text-destructive text-sm"
>
{t("insights.pattern.loadError")}
</p>
) : null}
{!isLoading && !isError && data && !hasDiscovered ? (
<p
data-slot="mood-discovery-empty"
className="text-muted-foreground text-sm"
>
{t("insights.pattern.empty")}
</p>
) : null}
{hasDiscovered && (
<MoodDiscoveredRelations
pairs={moodPairs}
@@ -0,0 +1,113 @@
"use client";
import { EyeOff, RotateCcw, X } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { apiPatch } from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
interface PatternDecisionResponse {
id: string;
dismissed: boolean;
}
export function PatternDismissButton({
patternId,
onDismissed,
className,
}: {
patternId: string;
onDismissed: () => void;
className?: string;
}) {
const { t } = useTranslations();
const [pending, setPending] = useState(false);
async function dismiss() {
setPending(true);
try {
await apiPatch<PatternDecisionResponse>(
`/api/insights/patterns/${patternId}`,
{ dismissed: true },
);
onDismissed();
} catch {
toast.error(t("insights.pattern.dismissError"));
} finally {
setPending(false);
}
}
return (
<Button
type="button"
variant="ghost"
size="sm"
disabled={pending}
onClick={dismiss}
className={cn("gap-1.5", className)}
aria-label={t("insights.pattern.dismiss")}
>
<X className="size-3.5" aria-hidden="true" />
{t("insights.pattern.dismiss")}
</Button>
);
}
export function PatternDismissedNotice({
patternId,
onRestored,
compact = false,
}: {
patternId: string;
onRestored: () => void;
compact?: boolean;
}) {
const { t } = useTranslations();
const [pending, setPending] = useState(false);
async function restore() {
setPending(true);
try {
await apiPatch<PatternDecisionResponse>(
`/api/insights/patterns/${patternId}`,
{ dismissed: false },
);
onRestored();
} catch {
toast.error(t("insights.pattern.restoreError"));
} finally {
setPending(false);
}
}
return (
<div
data-slot="pattern-dismissed"
role="status"
className={cn(
"text-muted-foreground flex items-center justify-between gap-3 text-sm",
!compact && "rounded-md border px-3 py-2",
)}
>
<span className="flex items-center gap-2">
<EyeOff className="size-4 shrink-0" aria-hidden="true" />
{t("insights.pattern.dismissed")}
</span>
<Button
type="button"
variant="ghost"
size="sm"
disabled={pending}
onClick={restore}
className="gap-1.5"
>
<RotateCcw className="size-3.5" aria-hidden="true" />
{t("insights.pattern.restore")}
</Button>
</div>
);
}