mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
fix(insights): route alert-card compliance through the cadence-aware engine + deep data cleanups
The insights alert cards computed medication compliance with the naive `schedules.length × days` denominator, so a fully-adherent weekly injectable read ~14% and fired a false low-compliance alert (and a paused medication mis-fired the same way). Route the alert path through the canonical `calculateCompliance` engine like every other compliance surface — pause eras, schedule revisions and dose windows honoured. Document confirm: committing a numeric observation against an existing biomarker silently replaced the stated unit with the catalog's, with no conversion — a stated "6.1 mmol/L" against a mg/dL marker committed "6.1 mg/dL". Reject on a unit mismatch (fail closed) so the user reconciles on the review screen, the same posture as the unit-required guard. Wire grip strength, waist (with waist-to-height) and pain into the briefing feature set and the grounding allow-set so the clinical-depth signals reach the daily narrative; the mental-health screeners stay excluded by construction. Biomarker detail: fall back to a generic description for catalog-less markers, and keep the heading + description with a retry on the error state. Collapse the medication External-API and Lifecycle groups by default. Re-enable the insights scroll-to-top regression and assert the shipped main-content reset. Align the EN haemoglobin/haematocrit display names to British spelling. Drop the redundant `(userId, deletedAt)` index on inbound documents — a strict prefix of the new three-column index. Trim the dead MedicalDisclaimer variants to the one live `dataPosture`. Move the crisis-resources card off the retired amber tint to a calm destructive-subtle border. Add a registry invariant asserting every biomarker signal key resolves to a real catalog slug.
This commit is contained in:
1 parent
4702546cdb
commit
2321ce29db
21 files changed
+509
-80
No files matched your search
@@ -164,4 +164,68 @@ describe("GET /api/insights/cards", () => {
|
||||
expect(body.data[0].provider).toBe("anthropic");
|
||||
expect(body.data.some((c) => c.severity === "alert")).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT flag a fully-adherent weekly injectable as low compliance (#214 regression)", async () => {
|
||||
// Pre-fix this path used a naive `schedules.length × 7` denominator, so a
|
||||
// weekly Monday injectable with its one dose taken computed ~14% and fired
|
||||
// a false "Low compliance" warning. The cadence-aware engine counts only
|
||||
// the Monday in the window → 100%, no alert.
|
||||
vi.useFakeTimers();
|
||||
// Pin NOW to a Wednesday so the trailing 7-day window holds exactly one
|
||||
// Monday (the prior 2025-01-13).
|
||||
vi.setSystemTime(new Date("2025-01-15T12:00:00Z"));
|
||||
try {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.medication.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "med-weekly",
|
||||
name: "Weekly injectable",
|
||||
dose: null,
|
||||
active: true,
|
||||
asNeeded: false,
|
||||
oneShot: false,
|
||||
startsOn: null,
|
||||
endsOn: null,
|
||||
createdAt: new Date("2024-06-01T00:00:00Z"),
|
||||
scheduleRevisions: [],
|
||||
pauseEras: [],
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-mon",
|
||||
windowStart: "08:00",
|
||||
windowEnd: "10:00",
|
||||
daysOfWeek: "1",
|
||||
timesOfDay: ["08:30"],
|
||||
reminderGraceMinutes: null,
|
||||
rrule: "FREQ=WEEKLY;BYDAY=MO",
|
||||
rollingIntervalDays: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
cyclicOnWeeks: null,
|
||||
cyclicOffWeeks: null,
|
||||
doseWindows: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
] as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue([
|
||||
{
|
||||
medicationId: "med-weekly",
|
||||
scheduledFor: new Date("2025-01-13T08:30:00Z"),
|
||||
takenAt: new Date("2025-01-13T08:35:00Z"),
|
||||
skipped: false,
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await callGet(makeReq());
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
data: Array<{ title: string }>;
|
||||
};
|
||||
expect(body.data.some((c) => c.title.startsWith("Low compliance"))).toBe(
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,12 @@ import {
|
||||
type HealthAlert,
|
||||
} from "@/lib/analytics/classifications";
|
||||
import { pairByTimestamp } from "@/lib/analytics/correlations";
|
||||
import {
|
||||
buildComplianceMedicationContext,
|
||||
calculateCompliance,
|
||||
lastNonSkippedTakenAt,
|
||||
SCHEDULE_COMPLIANCE_SELECT,
|
||||
} from "@/lib/analytics/compliance";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
type Severity = "alert" | "caution" | "info" | "good";
|
||||
@@ -86,11 +92,17 @@ export const GET = apiHandler(async () => {
|
||||
select: { type: true, value: true, measuredAt: true },
|
||||
}),
|
||||
prisma.medication.findMany({
|
||||
where: { userId: user.id, active: true },
|
||||
// v1.16.11 — as-needed (PRN) medications never surface a compliance
|
||||
// rate (no expected doses).
|
||||
where: { userId: user.id, active: true, asNeeded: false },
|
||||
include: {
|
||||
schedules: true,
|
||||
// Schedules through the shared compliance select so the configured
|
||||
// per-dose windows reach the engine like every other surface.
|
||||
schedules: { select: SCHEDULE_COMPLIANCE_SELECT },
|
||||
// v1.16.3 — archived schedule eras for era-aware expected counts.
|
||||
scheduleRevisions: { orderBy: { validFrom: "asc" } },
|
||||
// v1.25 H-MED1 — pause eras so paused days drop out of the denominator.
|
||||
pauseEras: { select: { pausedAt: true, resumedAt: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
@@ -135,7 +147,12 @@ export const GET = apiHandler(async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Lightweight medication compliance for alert input.
|
||||
// Medication compliance for alert input — routed through the canonical
|
||||
// cadence-aware engine (`calculateCompliance`), the same single source of
|
||||
// truth the comprehensive insights, dashboard pillar, Coach snapshot and
|
||||
// doctor report use. The naive `schedules.length × days` denominator was a
|
||||
// #214 regression that falsely flagged weekly injectables and paused meds
|
||||
// as low-adherence on this user-facing alert path.
|
||||
const medicationCompliance: Array<{
|
||||
name: string;
|
||||
compliance7: number;
|
||||
@@ -150,8 +167,11 @@ export const GET = apiHandler(async () => {
|
||||
// v1.7.0 sync — exclude tombstoned rows.
|
||||
deletedAt: null,
|
||||
medicationId: { in: activeMeds.map((m) => m.id) },
|
||||
scheduledFor: { gte: new Date(Date.now() - 30 * 86_400_000) },
|
||||
// 90-day window: the rolling-cadence gap-walk re-anchors on prior
|
||||
// intakes outside the 30-day rate window.
|
||||
scheduledFor: { gte: ninetyDaysAgo },
|
||||
},
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
select: {
|
||||
medicationId: true,
|
||||
takenAt: true,
|
||||
@@ -165,26 +185,36 @@ export const GET = apiHandler(async () => {
|
||||
arr.push(e);
|
||||
eventsByMed.set(e.medicationId, arr);
|
||||
}
|
||||
const cutoff7 = Date.now() - 7 * 86_400_000;
|
||||
const tz = user.timezone || "Europe/Berlin";
|
||||
for (const med of activeMeds) {
|
||||
const events = eventsByMed.get(med.id) ?? [];
|
||||
const takenLast7 = events.filter(
|
||||
(e) =>
|
||||
e.takenAt !== null &&
|
||||
!e.skipped &&
|
||||
e.scheduledFor.getTime() >= cutoff7,
|
||||
).length;
|
||||
const taken30 = events.filter(
|
||||
(e) => e.takenAt !== null && !e.skipped,
|
||||
).length;
|
||||
const expected7 = med.schedules.length * 7;
|
||||
const expected30 = med.schedules.length * 30;
|
||||
const mapped = events.map((e) => ({
|
||||
takenAt: e.takenAt,
|
||||
skipped: e.skipped,
|
||||
scheduledFor: e.scheduledFor,
|
||||
}));
|
||||
// v1.7.0 SB-SCHED-2 — engine-routed denominator.
|
||||
const medicationContext = buildComplianceMedicationContext(
|
||||
med,
|
||||
lastNonSkippedTakenAt(mapped),
|
||||
tz,
|
||||
);
|
||||
const c7 = calculateCompliance(mapped, med.schedules, 7, med.createdAt, {
|
||||
medicationContext,
|
||||
});
|
||||
const c30 = calculateCompliance(
|
||||
mapped,
|
||||
med.schedules,
|
||||
30,
|
||||
med.createdAt,
|
||||
{
|
||||
medicationContext,
|
||||
},
|
||||
);
|
||||
medicationCompliance.push({
|
||||
name: med.name,
|
||||
compliance7:
|
||||
expected7 > 0 ? Math.round((takenLast7 / expected7) * 100) : 0,
|
||||
compliance30:
|
||||
expected30 > 0 ? Math.round((taken30 / expected30) * 100) : 0,
|
||||
compliance7: c7.rate,
|
||||
compliance30: c30.rate,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user