mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
chore(release): v1.4.40 — comprehensive Critical+High architecture closure plus iOS PB30 enablement
Eleven touch-disjoint waves landed on develop plus a six-axis QA reconcile round before tagging. See CHANGELOG.md for the user-facing prose; this commit message documents the wave + report inventory for release-management traceability. Waves shipped (each with a phase report under .planning/): - phase-W-POOL-v1440-report.md — p-limit(4) wrapper around the analytics 15-way fan-out + pg.Pool max raised 10 -> 20. Closes the v1.4.39 empirical-trace finding #1 (Prisma pool starvation). - phase-W-DELETED-v1440-report.md — 11 reader-tier helpers + 3 integration contracts close audit Critical Finding #3 (soft-delete invisibility) across dashboard, analytics, summaries, rollup tiers, and the Coach snapshot path. - phase-W-INSIGHTS-v1440-report.md — mood-rollup swap on the three /api/insights/{features,targets,cards} routes plus the compliance-rollup hook gap closure for bulk-projection mints; the post-QA reconcile patch closes the six remaining measurement.findMany sites in the cluster that still leaked tombstoned rows. - phase-W-INFRA-v1440-report.md — rollup helper umbrella consolidation under src/lib/rollups/* with zero orphan re-exports; lint, typecheck, knip, and 93/93 rollup tests green post-restructure. - phase-W-RSC-v1440-report.md — per-tile Suspense boundaries plus the queryKey factory-bypass walker test (extended to comparison/ in the reconcile pass). - phase-W-PRIVACY-v1440-report.md — bilingual /privacy page with 17 paired-section tests pinning the 9 SB-3 disclosure requirements. - phase-W-AASA-v1440-report.md — /.well-known/apple-app-site-association endpoint pinned to S8WDX4W5KX.dev.healthlog.app with app-ID parity assertions guarding against split rotation. - phase-W-APNS-NOTIFY-v1440-report.md — MEDICATION_REMINDER time-sensitive APNs payload (priority 10 + interruption-level) scoped via a parameterised test that pins all 6 other event-types do not bypass Focus. AP-2 .p8 install gates real delivery. - phase-W-CONSENT-v1440-report.md — AI consent receipts CRUD with append-only invariant pinned in test; revoke-then-regrant leaves both rows; idempotent DELETE returns 200 + receipt: null. - phase-W-WMY-WIRE-v1440-report.md — three previously-dead WMY readers (week/month/year) wired through summaries-slice and health-score-fast-path with a linear-composability parity test pinning the cross-consumer routing contract. - phase-W-GHOSTS-v1440-report.md — ~1 177 lines of dead code removed across 9 atomic commits; startOfUtcDay + wallClockInTz consolidation eliminates a sibling-drift risk; knip whitelist trimmed to three files pending follow-up. QA reconcile patches applied per the v1.4.40 QA round (six reports under .planning/round-v1440-QA-*-findings.md): - senior C1 — dashboard-suspense-boundaries regex aligned with the post-W-INFRA Thread 2 userTimezone-local lift. - senior H1 — soft-delete filter added to the six remaining insights measurement.findMany sites. - specialist H1 — Promise.allSettled around bulk-projection compliance recompute on both /api/medications/intake and /api/dashboard/summary. - ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets factory; walker test extended to src/components/comparison/. - security M1 — consent artefact 64 KB cap enforced via Buffer.byteLength (UTF-8 bytes, not UTF-16 code units). Quality gates green at tag: pnpm typecheck, pnpm lint, pnpm knip --include files,dependencies,binaries,unlisted, pnpm test --run (4726 passing / 1 skipped). Tests 4525 -> 4726 unit + 1 skipped over the v1.4.39 -> v1.4.40 span. User-facing prose: see CHANGELOG.md.
This commit is contained in:
1 parent
f9996552ed
commit
1114cf7e63
146 files changed
+8207
-2279
No files matched your search
@@ -1,31 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { berlinDayKey } from "../berlin-day";
|
||||
|
||||
/**
|
||||
* v1.4.22 W5 reconcile (Code-MED-3) — pin that the helper buckets a
|
||||
* 23:30-Berlin reading on Tuesday into the Tuesday key, regardless of
|
||||
* UTC offset (CET / CEST, DST).
|
||||
*/
|
||||
describe("berlinDayKey", () => {
|
||||
it("buckets a 23:30-Berlin reading on Tuesday into Tuesday's key (CEST)", () => {
|
||||
// 2025-10-25T21:30:00Z = 2025-10-25T23:30 CEST (Saturday before DST end)
|
||||
expect(berlinDayKey(new Date("2025-10-25T21:30:00Z"))).toBe("2025-10-25");
|
||||
});
|
||||
|
||||
it("buckets a 23:30-Berlin reading after DST end into the right Berlin day", () => {
|
||||
// 2025-10-26 is the DST end day in Europe/Berlin (CET takes over).
|
||||
// 2025-10-26T22:30:00Z = 2025-10-26T23:30 CET — still Sunday in Berlin.
|
||||
expect(berlinDayKey(new Date("2025-10-26T22:30:00Z"))).toBe("2025-10-26");
|
||||
});
|
||||
|
||||
it("crosses the UTC-midnight boundary in Berlin's favour", () => {
|
||||
// 2026-05-09T22:30:00Z falls on 2026-05-10T00:30 CEST — Berlin says
|
||||
// Sunday, UTC says Saturday. The helper must follow Berlin.
|
||||
expect(berlinDayKey(new Date("2026-05-09T22:30:00Z"))).toBe("2026-05-10");
|
||||
});
|
||||
|
||||
it("returns YYYY-MM-DD format (sortable, padded)", () => {
|
||||
expect(berlinDayKey(new Date("2026-01-09T12:00:00Z"))).toBe("2026-01-09");
|
||||
expect(berlinDayKey(new Date("2026-12-09T12:00:00Z"))).toBe("2026-12-09");
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,7 @@ vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/measurements/rollup-coverage", () => ({
|
||||
vi.mock("@/lib/rollups/measurement-coverage", () => ({
|
||||
isFullyCovered: vi.fn(),
|
||||
probeRollupCoverage: vi.fn(),
|
||||
}));
|
||||
@@ -29,7 +29,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
isFullyCovered,
|
||||
probeRollupCoverage,
|
||||
} from "@/lib/measurements/rollup-coverage";
|
||||
} from "@/lib/rollups/measurement-coverage";
|
||||
import { computeBpInTargetFastPath } from "../bp-in-target-fast-path";
|
||||
|
||||
const MEASUREMENT_FIND_MANY = prisma.measurement.findMany as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
@@ -22,7 +22,7 @@ vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/measurements/rollup-coverage", () => ({
|
||||
vi.mock("@/lib/rollups/measurement-coverage", () => ({
|
||||
isFullyCovered: vi.fn(),
|
||||
probeRollupCoverage: vi.fn(),
|
||||
}));
|
||||
@@ -32,7 +32,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
isFullyCovered,
|
||||
probeRollupCoverage,
|
||||
} from "@/lib/measurements/rollup-coverage";
|
||||
} from "@/lib/rollups/measurement-coverage";
|
||||
import {
|
||||
CORRELATION_WINDOW_DAYS,
|
||||
computeCorrelationHypothesesFastPath,
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { DataPoint } from "../trends";
|
||||
import {
|
||||
pairByTimestamp,
|
||||
pearsonCorrelation,
|
||||
weeklyAverages,
|
||||
} from "../correlations";
|
||||
import { pairByTimestamp, pearsonCorrelation } from "../correlations";
|
||||
|
||||
function makePoints(values: number[], startDaysAgo = 30): DataPoint[] {
|
||||
const now = Date.now();
|
||||
@@ -107,57 +103,3 @@ describe("pearsonCorrelation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("weeklyAverages", () => {
|
||||
it("returns empty for empty input", () => {
|
||||
expect(weeklyAverages([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("groups data points by ISO week", () => {
|
||||
const data = makePoints(
|
||||
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83],
|
||||
14,
|
||||
);
|
||||
const result = weeklyAverages(data);
|
||||
// 14 days = 2-3 weeks
|
||||
expect(result.length).toBeGreaterThanOrEqual(2);
|
||||
expect(result.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("averages values within same week", () => {
|
||||
const now = new Date();
|
||||
// Find the Monday of current week
|
||||
const day = now.getDay();
|
||||
const monday = new Date(now);
|
||||
monday.setDate(now.getDate() - day + (day === 0 ? -6 : 1));
|
||||
monday.setHours(12, 0, 0, 0);
|
||||
|
||||
const tuesday = new Date(monday);
|
||||
tuesday.setDate(monday.getDate() + 1);
|
||||
|
||||
const data: DataPoint[] = [
|
||||
{ date: monday, value: 70 },
|
||||
{ date: tuesday, value: 80 },
|
||||
];
|
||||
const result = weeklyAverages(data);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].value).toBe(75);
|
||||
});
|
||||
|
||||
// v3 audit caught a TZ bug: a Sunday-evening Berlin reading (e.g. 22:00
|
||||
// local = 21:00 UTC in summer / 21:00 UTC in winter via DST) bucketed
|
||||
// into next week on UTC servers because `Date.getDay()` was system-local.
|
||||
// The Berlin-TZ-aware implementation puts the same point into THIS week.
|
||||
it("buckets Sunday-evening Berlin into the same ISO week as the preceding Monday", () => {
|
||||
// 2024-08-04 is a Sunday; 22:00 Berlin = 20:00 UTC (CEST). The Monday
|
||||
// of the same Berlin week is 2024-07-29.
|
||||
const sundayEveningBerlin = new Date("2024-08-04T20:00:00.000Z");
|
||||
const mondayMidday = new Date("2024-07-29T11:00:00.000Z");
|
||||
const result = weeklyAverages([
|
||||
{ date: mondayMidday, value: 70 },
|
||||
{ date: sundayEveningBerlin, value: 90 },
|
||||
]);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].value).toBe(80); // (70 + 90) / 2
|
||||
expect(result[0].date.toISOString()).toBe("2024-07-29T00:00:00.000Z");
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,7 @@ vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/measurements/rollup-coverage", () => ({
|
||||
vi.mock("@/lib/rollups/measurement-coverage", () => ({
|
||||
isFullyCovered: vi.fn(),
|
||||
probeRollupCoverage: vi.fn(),
|
||||
}));
|
||||
@@ -32,7 +32,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
isFullyCovered,
|
||||
probeRollupCoverage,
|
||||
} from "@/lib/measurements/rollup-coverage";
|
||||
} from "@/lib/rollups/measurement-coverage";
|
||||
import { computeUserHealthScoreFastPath } from "../health-score-fast-path";
|
||||
|
||||
const MEASUREMENT_FIND_MANY = prisma.measurement.findMany as unknown as ReturnType<typeof vi.fn>;
|
||||
@@ -102,6 +102,11 @@ describe("computeUserHealthScoreFastPath", () => {
|
||||
computedAt: now,
|
||||
},
|
||||
]);
|
||||
// v1.4.40 W-WMY-WIRE — the parallel long-window read fires
|
||||
// alongside the DAY-bucket read; mock its `findMany` to return
|
||||
// a coverage miss so the annotate carries `weightLongWindow:
|
||||
// null` and the score shape is unchanged.
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([]);
|
||||
// Weight source-attribution read (narrow 2-column).
|
||||
MEASUREMENT_FIND_MANY
|
||||
.mockResolvedValueOnce([
|
||||
@@ -147,6 +152,170 @@ describe("computeUserHealthScoreFastPath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.4.40 W-WMY-WIRE — pin the long-window weight wiring through
|
||||
* `readBestGranularityRollups`. The score shape is unchanged; the
|
||||
* weightLongWindow annotate makes the rollup-tier consumption
|
||||
* verifiable in production wide-events.
|
||||
*/
|
||||
describe("long-window weight wiring (W-WMY-WIRE)", () => {
|
||||
it("surfaces a MONTH-granularity weightLongWindow mean on the rollup branch", async () => {
|
||||
const coverage = new Map<string, boolean>([["WEIGHT", true]]);
|
||||
FULLY_COVERED.mockReturnValue(true);
|
||||
PROBE.mockResolvedValue(coverage);
|
||||
|
||||
const now = new Date("2026-05-17T12:00:00.000Z");
|
||||
// DAY-bucket read (trailing 37 days) — single bucket, irrelevant
|
||||
// for the long-window assertion.
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 82.5,
|
||||
minValue: 82.5,
|
||||
maxValue: 82.5,
|
||||
sd: null,
|
||||
slope: null,
|
||||
r2: null,
|
||||
computedAt: now,
|
||||
},
|
||||
]);
|
||||
// readBestGranularityRollups(WEIGHT, 365) — first call is the
|
||||
// MONTH probe (floor 181 d). Two MONTH buckets, count-weighted
|
||||
// mean = (12*82 + 18*80) / 30 = 80.8.
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
bucketStart: new Date("2025-08-01T00:00:00.000Z"),
|
||||
count: 12,
|
||||
mean: 82,
|
||||
minValue: 80,
|
||||
maxValue: 84,
|
||||
sd: 1,
|
||||
slope: 0,
|
||||
r2: 0,
|
||||
sumValue: null,
|
||||
},
|
||||
{
|
||||
bucketStart: new Date("2025-09-01T00:00:00.000Z"),
|
||||
count: 18,
|
||||
mean: 80,
|
||||
minValue: 78,
|
||||
maxValue: 83,
|
||||
sd: 1,
|
||||
slope: 0,
|
||||
r2: 0,
|
||||
sumValue: null,
|
||||
},
|
||||
]);
|
||||
// Source attribution + BP-SYS attribution reads.
|
||||
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
measuredAt: new Date("2026-05-10T08:00:00.000Z"),
|
||||
source: "WITHINGS",
|
||||
},
|
||||
]).mockResolvedValueOnce([]);
|
||||
|
||||
await computeUserHealthScoreFastPath({
|
||||
userId: "user-longwindow",
|
||||
bpInTargetPct: 85,
|
||||
heightCm: 178,
|
||||
now,
|
||||
coverage,
|
||||
});
|
||||
|
||||
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
|
||||
const pathCall = calls.find(
|
||||
(c) => c?.meta?.healthScore?.path === "rollup",
|
||||
);
|
||||
expect(pathCall).toBeDefined();
|
||||
const longWindow = pathCall?.meta?.healthScore?.weightLongWindow;
|
||||
expect(longWindow).not.toBeNull();
|
||||
expect(longWindow?.granularity).toBe("MONTH");
|
||||
expect(longWindow?.buckets).toBe(2);
|
||||
// Σ(count*mean) / Σcount = (12*82 + 18*80) / 30 = 80.8 → rounded.
|
||||
expect(longWindow?.mean).toBeCloseTo(80.8, 5);
|
||||
});
|
||||
|
||||
it("emits weightLongWindow:null when the WMY tier carries no buckets", async () => {
|
||||
const coverage = new Map<string, boolean>([["WEIGHT", true]]);
|
||||
FULLY_COVERED.mockReturnValue(true);
|
||||
PROBE.mockResolvedValue(coverage);
|
||||
|
||||
const now = new Date("2026-05-17T12:00:00.000Z");
|
||||
// DAY-bucket read.
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
|
||||
count: 1,
|
||||
mean: 82.5,
|
||||
minValue: 82.5,
|
||||
maxValue: 82.5,
|
||||
sd: null,
|
||||
slope: null,
|
||||
r2: null,
|
||||
computedAt: now,
|
||||
},
|
||||
]);
|
||||
// Long-window read — every granularity returns empty (router
|
||||
// walks MONTH → WEEK → DAY; 365 d skips YEAR floor).
|
||||
ROLLUP_FIND_MANY.mockResolvedValue([]);
|
||||
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
measuredAt: new Date("2026-05-10T08:00:00.000Z"),
|
||||
source: "WITHINGS",
|
||||
},
|
||||
]).mockResolvedValueOnce([]);
|
||||
|
||||
await computeUserHealthScoreFastPath({
|
||||
userId: "user-no-longwindow",
|
||||
bpInTargetPct: 85,
|
||||
heightCm: 178,
|
||||
now,
|
||||
coverage,
|
||||
});
|
||||
|
||||
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
|
||||
const pathCall = calls.find(
|
||||
(c) => c?.meta?.healthScore?.path === "rollup",
|
||||
);
|
||||
expect(pathCall?.meta?.healthScore?.weightLongWindow).toBeNull();
|
||||
});
|
||||
|
||||
it("omits the long-window read on the live fallback branch", async () => {
|
||||
const coverage = new Map<string, boolean>([["WEIGHT", false]]);
|
||||
FULLY_COVERED.mockReturnValue(false);
|
||||
PROBE.mockResolvedValue(coverage);
|
||||
|
||||
const now = new Date("2026-05-17T12:00:00.000Z");
|
||||
// Weight live read + BP source attribution.
|
||||
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
measuredAt: new Date("2026-05-10T08:00:00.000Z"),
|
||||
value: 82.5,
|
||||
source: "MANUAL",
|
||||
},
|
||||
]).mockResolvedValueOnce([]);
|
||||
|
||||
await computeUserHealthScoreFastPath({
|
||||
userId: "user-live-nowmy",
|
||||
bpInTargetPct: 80,
|
||||
heightCm: 178,
|
||||
now,
|
||||
coverage,
|
||||
});
|
||||
|
||||
// The live branch never issues the long-window probe — guards
|
||||
// against accidentally double-reading on cold mounts where the
|
||||
// raw weight findMany is already doing the work.
|
||||
expect(ROLLUP_FIND_MANY).not.toHaveBeenCalled();
|
||||
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
|
||||
const pathCall = calls.find(
|
||||
(c) => c?.meta?.healthScore?.path === "live",
|
||||
);
|
||||
expect(pathCall?.meta?.healthScore?.weightLongWindow).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("live fallback — WEIGHT not covered", () => {
|
||||
it("reads raw weight rows and pins path:live", async () => {
|
||||
const coverage = new Map<string, boolean>([
|
||||
|
||||
@@ -291,7 +291,164 @@ describe("computeSummariesSlice", () => {
|
||||
// probe + narrow aggregate + latests + rollup GROUP BY
|
||||
// (v1.4.37.2 — the prior `findMany` is gone). No heavy aggregate.
|
||||
expect(RAW).toHaveBeenCalledTimes(4);
|
||||
expect(ROLLUP_FIND_MANY).toHaveBeenCalledTimes(0);
|
||||
// v1.4.40 W-WMY-WIRE — the year-ago baseline probe runs
|
||||
// `readBestGranularityRollups(userId, type, 395)` per
|
||||
// type-with-data via `prisma.measurementRollup.findMany`. The
|
||||
// 395-day window skips the YEAR floor (731 d) and walks MONTH
|
||||
// → WEEK → DAY on full coverage miss; the default mock returns
|
||||
// `[]` so all three reachable tiers probe.
|
||||
expect(ROLLUP_FIND_MANY).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.4.40 W-WMY-WIRE — pin the wiring of the WMY readers into the
|
||||
* slim slice. The pre-v1.4.40 shape hardcoded `avg30LastYear` to
|
||||
* `null`; we now populate it from `readBestGranularityRollups` when
|
||||
* the YEAR / MONTH / WEEK / DAY tier carries buckets that overlap
|
||||
* the `[now-395d, now-365d)` slice.
|
||||
*/
|
||||
describe("year-over-year wiring (avg30LastYear)", () => {
|
||||
it("populates avg30LastYear from MONTH buckets that overlap the year-ago slice", async () => {
|
||||
// Coverage probe shows WEIGHT covered → rollup happy path.
|
||||
RAW.mockResolvedValueOnce([{ type: "WEIGHT", has_buckets: true }])
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "WEIGHT",
|
||||
avg7: 82,
|
||||
avg30: 82.5,
|
||||
slope7: 0,
|
||||
r2_7: 0,
|
||||
slope30: 0,
|
||||
r2_30: 0,
|
||||
slope90: 0,
|
||||
r2_90: 0,
|
||||
},
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", value: 82.7, measured_at: new Date() },
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", count: 5, min: 82, max: 84, mean: 83 },
|
||||
]);
|
||||
|
||||
// Year-ago slice MONTH bucket — `bucketStart` placed 380 days
|
||||
// ago so it falls inside `[now-395d, now-365d)`. Single bucket
|
||||
// (count=10, mean=85) → weighted mean = 85.
|
||||
const yearAgoBucketStart = new Date(
|
||||
Date.now() - 380 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
bucketStart: yearAgoBucketStart,
|
||||
count: 10,
|
||||
mean: 85,
|
||||
sd: 1,
|
||||
slope: 0,
|
||||
r2: 0,
|
||||
sumValue: null,
|
||||
minValue: 83,
|
||||
maxValue: 87,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await computeSummariesSlice("user-yoy");
|
||||
|
||||
expect(result.summaries.WEIGHT.avg30LastYear).toBe(85);
|
||||
// Router asked MONTH first (395 > 181, 395 < 731 → skip YEAR).
|
||||
expect(ROLLUP_FIND_MANY.mock.calls[0][0].where.granularity).toBe("MONTH");
|
||||
});
|
||||
|
||||
it("leaves avg30LastYear null when no bucket overlaps the year-ago slice", async () => {
|
||||
RAW.mockResolvedValueOnce([{ type: "WEIGHT", has_buckets: true }])
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "WEIGHT",
|
||||
avg7: 82,
|
||||
avg30: 82.5,
|
||||
slope7: 0,
|
||||
r2_7: 0,
|
||||
slope30: 0,
|
||||
r2_30: 0,
|
||||
slope90: 0,
|
||||
r2_90: 0,
|
||||
},
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", value: 82.7, measured_at: new Date() },
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", count: 5, min: 82, max: 84, mean: 83 },
|
||||
]);
|
||||
|
||||
// MONTH bucket placed 30 days ago — inside the YEAR / MONTH /
|
||||
// WEEK 395-day window the router asks for, but outside the
|
||||
// `[now-395d, now-365d)` slice. The helper returns null.
|
||||
const recentBucket = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
ROLLUP_FIND_MANY.mockResolvedValueOnce([
|
||||
{
|
||||
bucketStart: recentBucket,
|
||||
count: 10,
|
||||
mean: 82,
|
||||
sd: 1,
|
||||
slope: 0,
|
||||
r2: 0,
|
||||
sumValue: null,
|
||||
minValue: 80,
|
||||
maxValue: 84,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await computeSummariesSlice("user-recent");
|
||||
|
||||
expect(result.summaries.WEIGHT.avg30LastYear).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves avg30LastYear null when every granularity misses (no coverage)", async () => {
|
||||
RAW.mockResolvedValueOnce([{ type: "WEIGHT", has_buckets: true }])
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
type: "WEIGHT",
|
||||
avg7: 82,
|
||||
avg30: 82.5,
|
||||
slope7: 0,
|
||||
r2_7: 0,
|
||||
slope30: 0,
|
||||
r2_30: 0,
|
||||
slope90: 0,
|
||||
r2_90: 0,
|
||||
},
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", value: 82.7, measured_at: new Date() },
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ type: "WEIGHT", count: 5, min: 82, max: 84, mean: 83 },
|
||||
]);
|
||||
|
||||
// Default mock returns `[]` for every findMany call → router
|
||||
// walks YEAR → MONTH → WEEK → DAY and gives up.
|
||||
ROLLUP_FIND_MANY.mockResolvedValue([]);
|
||||
|
||||
const result = await computeSummariesSlice("user-empty-yoy");
|
||||
|
||||
expect(result.summaries.WEIGHT.avg30LastYear).toBeNull();
|
||||
// 395d window skips YEAR (floor 731 d) → MONTH → WEEK → DAY,
|
||||
// three reachable tiers all probed on full coverage miss.
|
||||
expect(ROLLUP_FIND_MANY).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("only probes types that actually have data in the current window", async () => {
|
||||
// Coverage probe + rollup GROUP BY both report zero rows → no
|
||||
// types-with-data, so the year-ago probe must NOT fan out.
|
||||
RAW.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([]);
|
||||
|
||||
await computeSummariesSlice("user-no-data");
|
||||
|
||||
expect(ROLLUP_FIND_MANY).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
movingAverage,
|
||||
trendSlope,
|
||||
detectAnomalies,
|
||||
summarize,
|
||||
@@ -15,27 +14,6 @@ function makePoints(values: number[], startDaysAgo = 30): DataPoint[] {
|
||||
}));
|
||||
}
|
||||
|
||||
describe("movingAverage", () => {
|
||||
it("returns empty for empty input", () => {
|
||||
expect(movingAverage([], 7)).toEqual([]);
|
||||
});
|
||||
|
||||
it("calculates moving average over window", () => {
|
||||
const data = makePoints([70, 71, 72, 73, 74, 75, 76], 7);
|
||||
const result = movingAverage(data, 3);
|
||||
expect(result).toHaveLength(7);
|
||||
// Last point should be avg of last 3 days
|
||||
expect(result[result.length - 1].value).toBeCloseTo(75, 0);
|
||||
});
|
||||
|
||||
it("handles single data point", () => {
|
||||
const data = makePoints([100], 1);
|
||||
const result = movingAverage(data, 7);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].value).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("trendSlope", () => {
|
||||
it("returns null for insufficient data", () => {
|
||||
expect(trendSlope([], 7)).toBeNull();
|
||||
|
||||
Reference in new issue
Block a user