mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
Serve the device's day strain on the strain page when no proxy exists
The recovery page charts the band's own DAY_STRAIN while the strain score page read only the computed proxy, so one account showed weeks of strain on one page and 'not enough data' on the other. Without a proxy row in the window the derived strain read now falls back to DAY_STRAIN: the score is the reading as a share of the device scale, an additive 'device' block carries the native value, and the course below the card charts that same series.
This commit is contained in:
1 parent
605d9b1fb4
commit
ac482c508d
13 files changed
+241
-13
No files matched your search
@@ -3,6 +3,7 @@
|
||||
import { Sparkles } from "lucide-react";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { resolveIntlLocale } from "@/lib/format-locale";
|
||||
import { useDerivedMetric } from "./use-derived-metric";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { QueryErrorRow } from "@/components/ui/query-error-row";
|
||||
@@ -109,7 +110,7 @@ export function CompositeScoreAnatomy({
|
||||
metric,
|
||||
className,
|
||||
}: CompositeScoreAnatomyProps) {
|
||||
const { t } = useTranslations();
|
||||
const { t, locale } = useTranslations();
|
||||
|
||||
const query = useDerivedMetric<
|
||||
SleepScoreValue | ReadinessValue | WellnessScoreValue
|
||||
@@ -135,7 +136,15 @@ export function CompositeScoreAnatomy({
|
||||
// the displayed framing honest per-score. `null` (RECOVERY / STRESS, or no
|
||||
// cache row yet) renders nothing.
|
||||
let anchorLine: string | null = null;
|
||||
if (metric === "STRAIN_SCORE" && data?.status === "ok" && data.value) {
|
||||
// Strain served from the device's own day strain (no computed proxy in the
|
||||
// window): the card says so, and the course below charts that same series.
|
||||
const deviceStrain =
|
||||
metric === "STRAIN_SCORE" && data?.status === "ok" && data.value
|
||||
? ((data.value as WellnessScoreValue).device ?? null)
|
||||
: null;
|
||||
if (deviceStrain) {
|
||||
anchorLine = t("insights.derived.composite.STRAIN_SCORE.deviceSource");
|
||||
} else if (metric === "STRAIN_SCORE" && data?.status === "ok" && data.value) {
|
||||
const anchor = (data.value as WellnessScoreValue).anchor;
|
||||
if (anchor === "personal") {
|
||||
anchorLine = t("insights.derived.composite.STRAIN_SCORE.anchorPersonal");
|
||||
@@ -238,7 +247,15 @@ export function CompositeScoreAnatomy({
|
||||
// READINESS component keys verbatim. STRESS / STRAIN stay row-less.
|
||||
const v = data.value as WellnessScoreValue;
|
||||
score = v.score;
|
||||
caption = t(`insights.derived.scoreRing.band.${v.band}`);
|
||||
caption = v.device
|
||||
? t("insights.derived.composite.STRAIN_SCORE.deviceCaption", {
|
||||
value: v.device.value.toLocaleString(resolveIntlLocale(locale), {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
}),
|
||||
max: v.device.scaleMax,
|
||||
})
|
||||
: t(`insights.derived.scoreRing.band.${v.band}`);
|
||||
if (metric === "RECOVERY_SCORE" && v.components) {
|
||||
contributors = v.components
|
||||
.map((c) => ({
|
||||
@@ -275,7 +292,10 @@ export function CompositeScoreAnatomy({
|
||||
data.status !== "ok" ? null : metric === "RECOVERY_SCORE" ||
|
||||
metric === "STRESS_SCORE" ||
|
||||
metric === "STRAIN_SCORE" ? (
|
||||
<ScoreHistoryChart type={metric} hue={METRIC_HUE[metric]} />
|
||||
<ScoreHistoryChart
|
||||
type={deviceStrain ? "DAY_STRAIN" : metric}
|
||||
hue={METRIC_HUE[metric]}
|
||||
/>
|
||||
) : series && series.length >= 2 ? (
|
||||
<ScoreHistoryCard
|
||||
series={series}
|
||||
|
||||
@@ -33,8 +33,9 @@ export function ScoreHistoryChart({
|
||||
type,
|
||||
hue,
|
||||
}: {
|
||||
/** The stored measurement type the score is written as. */
|
||||
type: "RECOVERY_SCORE" | "STRESS_SCORE" | "STRAIN_SCORE";
|
||||
/** The stored measurement type the score is written as — or, for a strain
|
||||
* score served from the device, the device's own `DAY_STRAIN`. */
|
||||
type: "RECOVERY_SCORE" | "STRESS_SCORE" | "STRAIN_SCORE" | "DAY_STRAIN";
|
||||
hue: RingHue;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
@@ -313,3 +313,76 @@ describe("computeWellnessScore", () => {
|
||||
expect(where.source).toBe("COMPUTED");
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeWellnessScore — strain reads the device's day strain", () => {
|
||||
// `/insights/recovery` charts the band's own DAY_STRAIN. The strain page
|
||||
// must not call the same account "not enough data": with no computed proxy
|
||||
// in the window it serves the device's day strain, on the device's scale.
|
||||
function byType(rows: Record<string, unknown[]>) {
|
||||
findMany.mockImplementation(
|
||||
async (args: { where: { type: string } }) => rows[args.where.type] ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
it("falls back to DAY_STRAIN when no computed strain score exists", async () => {
|
||||
byType({
|
||||
STRAIN_SCORE: [],
|
||||
DAY_STRAIN: [
|
||||
{
|
||||
value: 10.5,
|
||||
measuredAt: new Date("2026-06-02T04:00:00Z"),
|
||||
source: "WHOOP",
|
||||
},
|
||||
{
|
||||
value: 14.7,
|
||||
measuredAt: new Date("2026-06-01T04:00:00Z"),
|
||||
source: "WHOOP",
|
||||
},
|
||||
],
|
||||
});
|
||||
const r = await computeWellnessScore("STRAIN_SCORE", "u1", PROFILE, {
|
||||
now: NOW,
|
||||
});
|
||||
expect(r.status).toBe("ok");
|
||||
if (r.status !== "ok") return;
|
||||
const v = r.value as WellnessScoreValue;
|
||||
expect(v.device).toEqual({ value: 10.5, scaleMax: 21 });
|
||||
expect(v.score).toBe(50);
|
||||
expect(v.daysInWindow).toBe(2);
|
||||
expect(r.provenance.inputs).toEqual(["DAY_STRAIN"]);
|
||||
});
|
||||
|
||||
it("keeps the computed proxy when one exists", async () => {
|
||||
byType({
|
||||
STRAIN_SCORE: [
|
||||
{
|
||||
value: 64,
|
||||
measuredAt: new Date("2026-06-01T12:00:00Z"),
|
||||
source: "COMPUTED",
|
||||
},
|
||||
],
|
||||
DAY_STRAIN: [
|
||||
{
|
||||
value: 10.5,
|
||||
measuredAt: new Date("2026-06-02T04:00:00Z"),
|
||||
source: "WHOOP",
|
||||
},
|
||||
],
|
||||
});
|
||||
const r = await computeWellnessScore("STRAIN_SCORE", "u1", PROFILE, {
|
||||
now: NOW,
|
||||
});
|
||||
expect(r.status).toBe("ok");
|
||||
if (r.status !== "ok") return;
|
||||
expect(r.value.score).toBe(64);
|
||||
expect(r.value.device ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it("stays insufficient with neither", async () => {
|
||||
byType({});
|
||||
const r = await computeWellnessScore("STRAIN_SCORE", "u1", PROFILE, {
|
||||
now: NOW,
|
||||
});
|
||||
expect(r.status).toBe("insufficient");
|
||||
});
|
||||
});
|
||||
@@ -68,8 +68,24 @@ export interface WellnessScoreValue {
|
||||
* non-breaking).
|
||||
*/
|
||||
components?: ReadinessComponent[] | null;
|
||||
/**
|
||||
* STRAIN only — set when the score is the device's own day strain rather
|
||||
* than the server's computed proxy: no proxy row exists in the window, but
|
||||
* the band delivered `DAY_STRAIN` (WHOOP's 0–21 scale). `value` is the
|
||||
* device's latest reading on its own scale; `score` is that reading as a
|
||||
* share of `scaleMax`, so the ring and the band keep their 0–100 contract.
|
||||
* Absent whenever the computed proxy is the source.
|
||||
*/
|
||||
device?: { value: number; scaleMax: number } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The device-native day-strain scale. WHOOP reports cycle strain on 0–21;
|
||||
* the ingest validation (`DAY_STRAIN: { min: 0, max: 21 }`) pins the same
|
||||
* bound, so a stored reading can never exceed it.
|
||||
*/
|
||||
export const DEVICE_STRAIN_SCALE_MAX = 21;
|
||||
|
||||
/** The three persisted score types this engine serves. */
|
||||
export const WELLNESS_SCORE_TYPES = {
|
||||
RECOVERY_SCORE: "RECOVERY_SCORE",
|
||||
@@ -176,6 +192,26 @@ export async function computeWellnessScore(
|
||||
)
|
||||
: rawRows;
|
||||
|
||||
// STRAIN has a second, device-native source: the band's own DAY_STRAIN,
|
||||
// which `/insights/recovery` charts. Without a computed proxy in the window
|
||||
// the strain page reads that same series instead of reporting "not enough
|
||||
// data" for an account the recovery page shows weeks of strain for.
|
||||
if (rows.length === 0 && type === "STRAIN_SCORE") {
|
||||
const deviceRows = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: "DAY_STRAIN",
|
||||
deletedAt: null,
|
||||
measuredAt: { gte: cutoff, lte: now },
|
||||
},
|
||||
select: { value: true, measuredAt: true, source: true },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
});
|
||||
if (deviceRows.length > 0) {
|
||||
return buildDeviceStrain(deviceRows, windowDays, computedAt);
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return buildInsufficient<WellnessScoreValue>({
|
||||
coverage: {
|
||||
@@ -270,3 +306,55 @@ export async function computeWellnessScore(
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** A device day-strain reading as a 0–100 share of the device scale. */
|
||||
function deviceStrainShare(value: number): number {
|
||||
const clamped = Math.min(Math.max(value, 0), DEVICE_STRAIN_SCALE_MAX);
|
||||
return Math.round((clamped / DEVICE_STRAIN_SCALE_MAX) * 100);
|
||||
}
|
||||
|
||||
function buildDeviceStrain(
|
||||
rows: { value: number; measuredAt: Date }[],
|
||||
windowDays: number,
|
||||
computedAt: string,
|
||||
): Derived<WellnessScoreValue> {
|
||||
const latest = rows[0];
|
||||
const score = deviceStrainShare(latest.value);
|
||||
const prior = rows.slice(1).map((r) => deviceStrainShare(r.value));
|
||||
const trendDelta =
|
||||
prior.length > 0
|
||||
? Math.round(score - prior.reduce((s, v) => s + v, 0) / prior.length)
|
||||
: null;
|
||||
return buildOk<WellnessScoreValue>({
|
||||
value: {
|
||||
score,
|
||||
band: bandWellnessScore("STRAIN_SCORE", score),
|
||||
trendDelta,
|
||||
daysInWindow: rows.length,
|
||||
asOf: latest.measuredAt.toISOString(),
|
||||
series: rows
|
||||
.slice(0, SPARKLINE_MAX_POINTS)
|
||||
.map((r) => deviceStrainShare(r.value))
|
||||
.reverse(),
|
||||
anchor: null,
|
||||
components: null,
|
||||
device: {
|
||||
value: Math.round(latest.value * 10) / 10,
|
||||
scaleMax: DEVICE_STRAIN_SCALE_MAX,
|
||||
},
|
||||
},
|
||||
coverage: {
|
||||
requiredInputs: 1,
|
||||
presentInputs: 1,
|
||||
historyDays: rows.length,
|
||||
missing: [],
|
||||
},
|
||||
confidence: { score: 90, band: "high" },
|
||||
provenance: {
|
||||
inputs: ["DAY_STRAIN"],
|
||||
source: "DAY",
|
||||
windowDays,
|
||||
computedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -254,6 +254,20 @@ export const wellnessScoreValue = z
|
||||
.describe(
|
||||
"RECOVERY only, and only when the canonical value is the server's computed proxy — a device-native recovery percentage is not our blend and carries no decomposition.",
|
||||
),
|
||||
device: z
|
||||
.object({
|
||||
value: z
|
||||
.number()
|
||||
.describe("The device's latest day strain on its own scale."),
|
||||
scaleMax: z
|
||||
.number()
|
||||
.describe("Top of the device scale (21 for WHOOP day strain)."),
|
||||
})
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"STRAIN only — present when no computed strain score exists in the window and the score is served from the device's own DAY_STRAIN instead. `score` is then `value` as a 0–100 share of `scaleMax`. Absent when the computed proxy is the source.",
|
||||
),
|
||||
})
|
||||
.meta({ id: "WellnessScoreValue" });
|
||||
|
||||
|
||||
Reference in new issue
Block a user