mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 04:50:59 +00:00
fix(insights,medications): reconcile review findings on the v1.14.0 surfaces
- Medication cycle status: re-hydrate `nextDueAt` (it arrives as an ISO string over the wire) before the Berlin day-bucketing, so "next dose in N days" no longer drifts by a day near midnight or off Berlin. Covered by a new string-input test. - Wellness rings: drive the conic sheen off a fixed white so it always lightens (a near-black light-mode foreground under overlay was darkening the tile into a grey band); give the ring a transform transition so it scales smoothly with the tile lift instead of snapping; cap the green-band glow at a few breaths instead of an infinite drop-shadow repaint; deepen the light-mode stress and recovery end-stops for non-text contrast; track the sm/md column count to the active-score count so two or four scores never leave an empty cell. - Mood factor crosstab: bound the snapshot's cross-metric read to the 365-day window and exclude soft-deleted rows, so the factor deltas the model cites match the visible board over the same canonical row set (no recency-biased truncation, no soft-delete skew); thread the user's source priority so the per-day canonical pick agrees with the screen; render the delta neutrally rather than green/red, since a higher vital is good for steps but bad for resting heart rate and the board is observational. - Log-intake: surface an error when a pinned slot can't resolve to an instant instead of silently logging the dose through the unscheduled path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
dfda2a1c7e
commit
189202f4c6
14 files changed
+110
-28
No files matched your search
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Als ausgelassen erfassen",
|
||||
"noMedications": "Lege zuerst ein Medikament an, dann kannst du Einnahmen dafür erfassen.",
|
||||
"cancel": "Abbrechen",
|
||||
"submit": "Einnahme erfassen"
|
||||
"submit": "Einnahme erfassen",
|
||||
"slotError": "Der gewählte Slot konnte keiner Uhrzeit zugeordnet werden. Bitte wähle einen anderen Slot oder „Kein bestimmter Slot“."
|
||||
},
|
||||
"emptyTitle": "Noch keine Medikamente",
|
||||
"emptyDescription": "Lege Medikamente, Dosierungen und Einnahmefenster an, um Compliance zu erfassen.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Geteilt aus HealthLog — einem selbst gehosteten Gesundheits-Tracker."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Logged as skipped",
|
||||
"noMedications": "Add a medication first, then you can log intakes against it.",
|
||||
"cancel": "Cancel",
|
||||
"submit": "Log intake"
|
||||
"submit": "Log intake",
|
||||
"slotError": "The selected slot couldn’t be matched to a time. Pick another slot or “No specific slot”."
|
||||
},
|
||||
"emptyTitle": "No medications yet",
|
||||
"emptyDescription": "Add medications, dosages, and reminder windows to track compliance.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Shared from HealthLog — a self-hosted personal health tracker."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Registrar como omitida",
|
||||
"noMedications": "Añade primero un medicamento y luego podrás registrar tomas para él.",
|
||||
"cancel": "Cancelar",
|
||||
"submit": "Registrar toma"
|
||||
"submit": "Registrar toma",
|
||||
"slotError": "No se pudo asignar una hora al intervalo seleccionado. Elige otro intervalo o «Sin intervalo específico»."
|
||||
},
|
||||
"emptyTitle": "Aún no hay medicamentos",
|
||||
"emptyDescription": "Crea medicamentos, dosis y franjas horarias para registrar el cumplimiento.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Compartido desde HealthLog — un registro de salud autoalojado."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Enregistrer comme ignorée",
|
||||
"noMedications": "Ajoutez d’abord un médicament, puis vous pourrez enregistrer des prises pour celui-ci.",
|
||||
"cancel": "Annuler",
|
||||
"submit": "Enregistrer la prise"
|
||||
"submit": "Enregistrer la prise",
|
||||
"slotError": "Le créneau sélectionné n’a pas pu être associé à une heure. Choisissez un autre créneau ou « Aucun créneau précis »."
|
||||
},
|
||||
"emptyTitle": "Aucun médicament pour l’instant",
|
||||
"emptyDescription": "Crée des médicaments, des doses et des fenêtres horaires pour suivre l’observance.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Partagé depuis HealthLog — un suivi de santé auto-hébergé."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Registra come saltata",
|
||||
"noMedications": "Aggiungi prima un farmaco, poi potrai registrarne le assunzioni.",
|
||||
"cancel": "Annulla",
|
||||
"submit": "Registra assunzione"
|
||||
"submit": "Registra assunzione",
|
||||
"slotError": "Non è stato possibile associare un orario alla fascia selezionata. Scegli un’altra fascia o «Nessuna fascia specifica»."
|
||||
},
|
||||
"emptyTitle": "Ancora nessun farmaco",
|
||||
"emptyDescription": "Crea farmaci, dosi e fasce orarie per registrare l’aderenza.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Condiviso da HealthLog — un tracker della salute self-hosted."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -605,7 +605,8 @@
|
||||
"skippedLabel": "Zarejestruj jako pominięte",
|
||||
"noMedications": "Najpierw dodaj lek, a potem będziesz mógł rejestrować jego przyjęcia.",
|
||||
"cancel": "Anuluj",
|
||||
"submit": "Zarejestruj przyjęcie"
|
||||
"submit": "Zarejestruj przyjęcie",
|
||||
"slotError": "Nie udało się przypisać godziny do wybranego slotu. Wybierz inny slot lub „Brak konkretnego slotu”."
|
||||
},
|
||||
"emptyTitle": "Brak leków",
|
||||
"emptyDescription": "Utwórz leki, dawki i okna czasowe, aby śledzić przestrzeganie.",
|
||||
@@ -4867,4 +4868,4 @@
|
||||
},
|
||||
"footer": "Udostępnione z HealthLog — samodzielnie hostowanego trackera zdrowia."
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-4
@@ -294,13 +294,13 @@
|
||||
--ring-readiness-to: #18a34e;
|
||||
--tile-readiness: #14720a;
|
||||
--ring-recovery-from: #07857c;
|
||||
--ring-recovery-to: #12b3a3;
|
||||
--ring-recovery-to: #0e9c8f;
|
||||
--tile-recovery: #0a8f86;
|
||||
--ring-sleep-from: #2d5fc4;
|
||||
--ring-sleep-to: #4f7ae0;
|
||||
--tile-sleep: #2d5fc4;
|
||||
--ring-stress-from: #b06a16;
|
||||
--ring-stress-to: #d68a2a;
|
||||
--ring-stress-to: #c47a1e;
|
||||
--tile-stress: #a34d14;
|
||||
--ring-strain-from: #6b4fd0;
|
||||
--ring-strain-to: #8a6ff0;
|
||||
@@ -503,6 +503,10 @@
|
||||
.wellness-tile:active {
|
||||
transform: translateY(0) scale(0.985);
|
||||
}
|
||||
/* So the ring scales smoothly with the tile lift instead of snapping. */
|
||||
.wellness-tile [data-slot="score-ring"] {
|
||||
transition: transform 200ms var(--ring-ease);
|
||||
}
|
||||
|
||||
/*
|
||||
* v1.14.0 — the wellness-strip "signature reveal" motion system.
|
||||
@@ -554,9 +558,12 @@
|
||||
inset: 6%;
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
/* A specular highlight must always LIGHTEN. Under mix-blend overlay a
|
||||
near-black light-mode `--card-foreground` would darken the tile into a
|
||||
grey band, so the sheen rides a fixed white in both themes. */
|
||||
background: radial-gradient(
|
||||
circle at 50% 50%,
|
||||
color-mix(in srgb, var(--card-foreground) 70%, transparent) 0%,
|
||||
rgba(255, 255, 255, 0.72) 0%,
|
||||
transparent 70%
|
||||
);
|
||||
mix-blend-mode: overlay;
|
||||
@@ -606,7 +613,10 @@
|
||||
filter: drop-shadow(0 0 3px color-mix(in srgb, var(--ring-glow) 45%, transparent));
|
||||
}
|
||||
.wellness-ring-arc--pulse {
|
||||
animation: ringGlow 3.4s ease-in-out 2s infinite;
|
||||
/* Breathe a few times to celebrate a strong score, then settle — an
|
||||
infinite loop would repaint the (non-compositable) drop-shadow filter
|
||||
forever. Motion happens, then the surface goes calm. */
|
||||
animation: ringGlow 3.4s ease-in-out 2s 3;
|
||||
}
|
||||
@keyframes ringGlow {
|
||||
0%,
|
||||
@@ -622,6 +632,7 @@
|
||||
.wellness-tile,
|
||||
.wellness-tile:hover,
|
||||
.wellness-tile:active,
|
||||
.wellness-tile [data-slot="score-ring"],
|
||||
.wellness-tile:hover [data-slot="score-ring"] {
|
||||
transform: none;
|
||||
transition: none;
|
||||
|
||||
@@ -326,6 +326,15 @@ export function WellnessScores({
|
||||
5: "lg:grid-cols-5",
|
||||
};
|
||||
const lgCols = LG_COLS[Math.min(tiles.length, 5)] ?? "lg:grid-cols-5";
|
||||
// The sm/md row caps at 3 columns; track the actual tile count there too so
|
||||
// two or four active scores don't leave an empty cell that reads as a
|
||||
// missing tile (the same fill rule the lg row already follows).
|
||||
const SM_COLS: Record<number, string> = {
|
||||
1: "sm:grid-cols-1",
|
||||
2: "sm:grid-cols-2",
|
||||
3: "sm:grid-cols-3",
|
||||
};
|
||||
const smCols = SM_COLS[Math.min(tiles.length, 3)] ?? "sm:grid-cols-3";
|
||||
|
||||
return (
|
||||
<section
|
||||
@@ -342,7 +351,7 @@ export function WellnessScores({
|
||||
// `data-revealed` triggers the CSS tile-rise + sheen keyframes on the
|
||||
// fresh-session reveal; absent on subsequent mounts (paint final).
|
||||
data-revealed={play ? "true" : undefined}
|
||||
className={cn("grid grid-cols-2 gap-3 sm:grid-cols-3", lgCols)}
|
||||
className={cn("grid grid-cols-2 gap-3", smCols, lgCols)}
|
||||
>
|
||||
{tiles}
|
||||
</div>
|
||||
|
||||
@@ -106,11 +106,14 @@ export function MoodFactorMetricCrosstab({
|
||||
METRIC_LABEL_KEY[row.metricKey] ?? row.metricKey,
|
||||
);
|
||||
const unit = t(UNIT_KEY[row.display]);
|
||||
// `delta` = lowAvg − highAvg: negative = vital runs lower on the
|
||||
// low-factor (worse) days. The read-out is colored by sign.
|
||||
// `delta` = lowAvg − highAvg: positive = the vital runs higher on the
|
||||
// low-factor (worse) days. The number stays NEUTRAL — a higher value
|
||||
// is good for steps but bad for resting HR, and this board is
|
||||
// observational ("associations, not causes"), so colouring it
|
||||
// green/red would imply a health verdict the data doesn't support.
|
||||
// The sign prefix + `data-direction` carry the direction.
|
||||
const up = row.delta >= 0;
|
||||
const deltaText = `${up ? "+" : ""}${fmt(row.delta, row.display)} ${unit}`;
|
||||
const deltaColor = up ? "var(--success)" : "var(--destructive)";
|
||||
return (
|
||||
<li
|
||||
key={`${row.metricKey}:${row.factor}`}
|
||||
@@ -136,10 +139,7 @@ export function MoodFactorMetricCrosstab({
|
||||
metric: metricLabel,
|
||||
})}
|
||||
</span>
|
||||
<span
|
||||
className="shrink-0 text-sm font-semibold tabular-nums"
|
||||
style={{ color: deltaColor }}
|
||||
>
|
||||
<span className="text-foreground shrink-0 text-sm font-semibold tabular-nums">
|
||||
{deltaText}
|
||||
</span>
|
||||
<span
|
||||
|
||||
@@ -213,6 +213,19 @@ describe("medication cycle status — open-cycle line", () => {
|
||||
expect(html).toContain("lucide-circle-check");
|
||||
});
|
||||
|
||||
it("on_track reads the same day count when nextDueAt arrives as an ISO string", () => {
|
||||
// Over the wire `nextDueAt` is JSON, so it reaches the card as a string
|
||||
// even though the type says `Date`. The component must re-hydrate it for
|
||||
// the Berlin day-bucketing — a raw string would silently drift the count.
|
||||
const iso = inDays(4).toISOString() as unknown as Date;
|
||||
const html = render(
|
||||
<MedicationCycleStatus
|
||||
cycle={{ ...baseCycle, state: "on_track", nextDueAt: iso }}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain("Next dose in 4 days");
|
||||
});
|
||||
|
||||
it("on_track one day out reads tomorrow", () => {
|
||||
const html = render(
|
||||
<MedicationCycleStatus
|
||||
|
||||
@@ -78,8 +78,12 @@ export function MedicationCycleStatus({ cycle }: MedicationCycleStatusProps) {
|
||||
tone = "text-success";
|
||||
icon = <CircleCheck className="size-3.5 shrink-0" aria-hidden="true" />;
|
||||
const now = new Date();
|
||||
// `nextDueAt` is typed `Date` but arrives as an ISO string over the wire;
|
||||
// re-hydrate it so the Berlin day-bucketing (toLocaleString with a
|
||||
// timeZone) actually applies — a raw string would silently skip it and
|
||||
// drift the count by a day near midnight / off Berlin.
|
||||
const days = cycle.nextDueAt
|
||||
? calendarDayDelta(cycle.nextDueAt, now)
|
||||
? calendarDayDelta(new Date(cycle.nextDueAt), now)
|
||||
: null;
|
||||
if (days === null || days <= 0) {
|
||||
// on_track with the slot today (now < dueAt but same calendar day).
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -144,10 +145,20 @@ export function LogIntakeDialog({
|
||||
if (!medicationId || busy) return;
|
||||
const med = medications.find((m) => m.id === medicationId);
|
||||
if (!med) return;
|
||||
// A pinned slot must resolve to a real instant; if it can't, surface an
|
||||
// error rather than silently logging the dose through the unscheduled path
|
||||
// (which would miss the canonical slot upsert and could duplicate the row).
|
||||
let scheduledFor: string | undefined;
|
||||
if (slot !== NO_SLOT) {
|
||||
const iso = slotInstantIso(takenAt, slot);
|
||||
if (!iso) {
|
||||
toast.error(t("medications.logIntake.slotError"));
|
||||
return;
|
||||
}
|
||||
scheduledFor = iso;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const scheduledFor =
|
||||
slot !== NO_SLOT ? (slotInstantIso(takenAt, slot) ?? undefined) : undefined;
|
||||
const ok = await runLogIntake({
|
||||
medication: { id: med.id, name: med.name },
|
||||
skipped,
|
||||
|
||||
@@ -5,6 +5,7 @@ vi.mock("@/lib/db", () => ({
|
||||
auditLog: { findFirst: vi.fn(), create: vi.fn() },
|
||||
moodEntry: { findMany: vi.fn() },
|
||||
measurement: { findMany: vi.fn() },
|
||||
user: { findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -43,6 +44,11 @@ function stubCompletion(
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// The snapshot threads the user's source priority into the factor crosstab;
|
||||
// default to "no custom priority" so every test resolves it without stubbing.
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
sourcePriorityJson: null,
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("generateMoodStatusForUser — graded payload", () => {
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
} from "@/lib/insights/status-cache";
|
||||
import { returnTimeoutFallback } from "@/lib/insights/timeout-fallback";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
/**
|
||||
@@ -271,10 +272,23 @@ export async function generateMoodStatusForUser(
|
||||
// has its measurements; cap lifted to 365 d × 8 channels. `source` /
|
||||
// `deviceType` ride along so the crosstab's per-day canonical-source pick
|
||||
// de-dups a cumulative metric reported by two sources on the same day.
|
||||
// The crosstab + correlations only pair against the ~365-day window, so
|
||||
// bound the read to that window: it lets Postgres use the (userId,
|
||||
// measuredAt) index, caps memory to rows that can actually pair, and stops a
|
||||
// data-rich Apple-Health account from spending the 50k cap on a recency-
|
||||
// biased all-recent slice. `deletedAt: null` keeps soft-deleted rows (common
|
||||
// on HRV/RHR/steps re-sync) out of the FDR-gated factor deltas the model
|
||||
// cites as fact — matching the visible `/api/mood/insights` board exactly.
|
||||
const crossMetricWindowStart = new Date(
|
||||
now.getTime() - 365 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
const CROSS_METRIC_ROW_CAP = 50_000;
|
||||
const measurements = await prisma.measurement
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
measuredAt: { gte: crossMetricWindowStart },
|
||||
type: {
|
||||
in: [
|
||||
"WEIGHT",
|
||||
@@ -288,7 +302,7 @@ export async function generateMoodStatusForUser(
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: 50_000,
|
||||
take: CROSS_METRIC_ROW_CAP,
|
||||
select: {
|
||||
type: true,
|
||||
value: true,
|
||||
@@ -298,6 +312,9 @@ export async function generateMoodStatusForUser(
|
||||
},
|
||||
})
|
||||
.then((rows) => rows.reverse());
|
||||
if (measurements.length >= CROSS_METRIC_ROW_CAP) {
|
||||
annotate({ meta: { cross_metric_truncated: true } });
|
||||
}
|
||||
|
||||
const weightSeries = applyPayloadBudget(
|
||||
measurements
|
||||
@@ -379,10 +396,15 @@ export async function generateMoodStatusForUser(
|
||||
// measurements the snapshot already holds so the model's prose matches the
|
||||
// visible factor board (shown == sent). FDR-controlled + min-N-gated inside
|
||||
// `computeFactorMetricCrosstab` — never fabricated on thin data.
|
||||
// Thread the user's real source priority so the snapshot's per-day canonical
|
||||
// pick matches the visible factor board (a user who prefers WHOOP over Apple
|
||||
// for sleep collapses a SUM channel to the same source on screen + in prose).
|
||||
const userPriorityJson = await loadUserSourcePriority(userId);
|
||||
const factorCrosstab = computeFactorMetricCrosstab({
|
||||
entries,
|
||||
measurements,
|
||||
now,
|
||||
userPriorityJson,
|
||||
});
|
||||
|
||||
// v1.8.6 — the same threshold-gated narrative feed the user sees on
|
||||
|
||||
Reference in new issue
Block a user