mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(insights): add tag-by-metric crosstab and deprecate the moodLog webhook
Extend the mood-relations surface from mood to a health metric. For each structured mood tag present on enough days, compare a metric's value on tag-present vs tag-absent days: active energy on workout days (same day), sleep length on nights tagged sleep (same day), and next-day recovery after a tag like alcohol or food (D to D+1 lag). The comparison reuses the existing statistics engine wholesale — the Welch two-sample t-test, the per-group day floors, the confidence band, and the Benjamini-Hochberg FDR control already used by the influence and discovery boards — so no new statistics code lands. Only pairs that clear p < 0.05 and the FDR control surface, ranked by adjusted q then absolute delta and capped at eight rows. The result rides on GET /api/mood/insights as a new additive `tagMetricCrosstab` field and renders as a confidence-gated, observational card on the mood insights page, framed as an association in your own data rather than a cause. The endpoint is server-rendered and not in the OpenAPI contract, so no contract change is required. Deprecate the standalone moodLog integration. Mood is now tracked fully inside HealthLog through entries, structured tags, and rated factors, so the external webhook and reverse-sync bridge no longer add anything. The webhook route, the push and pull helpers, and the validation schemas carry an @deprecated note pointing at the native path; the surface stays functional this release and is slated for removal in a future major. The settings card shows a deprecation hint, localised across all six locales.
This commit is contained in:
1 parent
65b00e3a73
commit
cfb97593a3
19 files changed
+971
-1
No files matched your search
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* v1.12.0 — tag × health-metric crosstab over the real DB read path.
|
||||
*
|
||||
* Seeds a user with structured-tagged mood entries and ACTIVE_ENERGY_BURNED
|
||||
* measurements, then asserts `fetchMoodAggregates` (the production read +
|
||||
* orchestration used by `GET /api/mood/insights`) returns a populated
|
||||
* `tagMetricCrosstab` row with the expected delta + display unit + lag mode.
|
||||
* Exercises the widened measurement `type: { in: [...] }` filter and the
|
||||
* structured-tag join end-to-end against Postgres.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
import { fetchMoodAggregates } from "@/lib/insights/mood-aggregates";
|
||||
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const TEST_USER_ID = "user-crosstab";
|
||||
const dayMs = 24 * 60 * 60 * 1000;
|
||||
const NOW = new Date("2026-06-01T12:00:00.000Z");
|
||||
|
||||
function dayKey(offset: number): string {
|
||||
return new Date(NOW.getTime() - offset * dayMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncateAllTables(getPrismaClient());
|
||||
const prisma = getPrismaClient();
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: TEST_USER_ID,
|
||||
username: "crosstab",
|
||||
email: "crosstab@example.test",
|
||||
timezone: "Europe/Berlin",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("mood-insights tag × metric crosstab (DB read path)", () => {
|
||||
it("surfaces a structured tag × ACTIVE_ENERGY_BURNED same-day association", async () => {
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
// The structured-tag catalog is seeded by migrations (0118/0119) and is
|
||||
// NOT truncated between tests — use an existing catalog tag rather than
|
||||
// minting one (its `key` is globally unique).
|
||||
const tag = await prisma.moodTag.findFirst({
|
||||
include: { category: true },
|
||||
orderBy: { key: "asc" },
|
||||
});
|
||||
expect(tag).toBeTruthy();
|
||||
|
||||
// 12 tag-present days with high active energy, 12 tag-absent with low.
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const present = i < 12;
|
||||
const ts = new Date(NOW.getTime() - i * dayMs);
|
||||
const moodEntry = await prisma.moodEntry.create({
|
||||
data: {
|
||||
userId: TEST_USER_ID,
|
||||
date: dayKey(i),
|
||||
mood: "GUT",
|
||||
score: present ? 4 : 3,
|
||||
source: "WEB",
|
||||
moodLoggedAt: ts,
|
||||
...(present
|
||||
? { tagLinks: { create: [{ moodTagId: tag!.id }] } }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
expect(moodEntry.id).toBeTruthy();
|
||||
await prisma.measurement.create({
|
||||
data: {
|
||||
userId: TEST_USER_ID,
|
||||
type: "ACTIVE_ENERGY_BURNED",
|
||||
value: present ? 600 + (i % 2 === 0 ? 20 : -20) : 350 + (i % 2 === 0 ? 20 : -20),
|
||||
unit: "kcal",
|
||||
source: "APPLE_HEALTH",
|
||||
measuredAt: ts,
|
||||
externalId: `stats:HKQuantityTypeIdentifierActiveEnergyBurned:${dayKey(i)}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const aggregates = await fetchMoodAggregates(TEST_USER_ID, NOW);
|
||||
const row = aggregates.tagMetricCrosstab.find(
|
||||
(r) => r.tag === tag!.key && r.metricKey === "activeEnergy",
|
||||
);
|
||||
|
||||
expect(row).toBeDefined();
|
||||
expect(row!.display).toBe("kcal");
|
||||
expect(row!.mode).toBe("sameDay");
|
||||
expect(row!.labelKey).toBe(tag!.labelKey);
|
||||
expect(row!.categoryKey).toBe(tag!.category.key);
|
||||
expect(row!.withDays).toBe(12);
|
||||
expect(row!.withoutDays).toBe(12);
|
||||
expect(row!.withAvg).toBeCloseTo(600, 0);
|
||||
expect(row!.withoutAvg).toBeCloseTo(350, 0);
|
||||
expect(row!.delta).toBeGreaterThan(0);
|
||||
expect(row!.confidence).toBe("high");
|
||||
expect(row!.qValue).toBeLessThanOrEqual(0.1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user