mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
Merge branch 'fix/v1437-reads' into release/v1.43.7
This commit is contained in:
commit
f6e0d72193
74 files changed
+1783
-2804
No files matched your search
@@ -6,7 +6,7 @@ import { analyticsQuerySchema } from "@/lib/validations/analytics";
|
||||
import { NO_STORE_BUT_BFCACHE } from "@/lib/http/cache-headers";
|
||||
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { summarize, type DataPoint } from "@/lib/analytics/trends";
|
||||
import { computeSummariesSlice } from "@/lib/analytics/summaries-slice";
|
||||
import { readSummariesSlice } from "@/lib/analytics/summaries-slice";
|
||||
import { resolveEffectiveBpTargets } from "@/lib/analytics/effective-range";
|
||||
import { bpTargetsEqual, getBpTargets } from "@/lib/analytics/bp-targets";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
@@ -103,14 +103,7 @@ export const GET = apiHandler(async (request?: Request) => {
|
||||
// tile strip's next mount should repaint from the prior summaries
|
||||
// instantly while one background recompute refreshes them, instead
|
||||
// of paying the 2-SQL-pass rebuild inline.
|
||||
const slim = await cachedSwr(
|
||||
caches.analytics as ServerCache<
|
||||
Awaited<ReturnType<typeof computeSummariesSlice>>
|
||||
>,
|
||||
`${user.id}|summaries`,
|
||||
() => computeSummariesSlice(user.id),
|
||||
annotate,
|
||||
);
|
||||
const slim = await readSummariesSlice(user.id, { serveStale: true });
|
||||
// Drop the types whose module the user turned off, from the SAME map
|
||||
// the snapshot builder gates on (`SUMMARY_TYPE_MODULE`, via
|
||||
// `gateSummariesByModules`). With `NEXT_PUBLIC_DASHBOARD_SNAPSHOT=false`
|
||||
@@ -282,7 +275,7 @@ async function buildAnalyticsResponse(user: AuthedUser, locale: Locale) {
|
||||
// release; previously only the live walk produced it)
|
||||
// - `avg30LastYear` populated for any type whose WMY tier carries
|
||||
// the year-ago window
|
||||
// - `lastSeenByType` from the `DISTINCT ON (type)` latest read
|
||||
// - `lastSeenByType` from the per-type latest read
|
||||
//
|
||||
// `anomalyCount` and `slope90` left this wire in v1.37.19: the slim
|
||||
// path could never compute the former (it always reported 0) and no
|
||||
@@ -292,7 +285,7 @@ async function buildAnalyticsResponse(user: AuthedUser, locale: Locale) {
|
||||
// `avg30LastYear` on types with no WMY coverage, which matches the
|
||||
// pre-fix behaviour for tenants whose year-ago window happened to
|
||||
// fall outside the 425-day floor.
|
||||
const slim = await computeSummariesSlice(user.id);
|
||||
const slim = await readSummariesSlice(user.id);
|
||||
// Same module gate as the slim slice and the snapshot builder — the
|
||||
// default slice feeds the dashboard too (it is the thick half of the
|
||||
// legacy two-cell path), so it cannot be the one feed that leaks a
|
||||
|
||||
@@ -78,6 +78,7 @@ import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { buildMedsTodayBlock } from "@/lib/dashboard/meds-today";
|
||||
import { computeStreak } from "@/lib/dashboard/streak";
|
||||
import {
|
||||
readActivityDayKeys,
|
||||
readLatestEver,
|
||||
readSparkBuckets,
|
||||
} from "@/lib/dashboard/summary-reads";
|
||||
@@ -329,15 +330,6 @@ function trendOf(values: number[]): MetricCard["trend"] {
|
||||
return delta > 0 ? "up" : "down";
|
||||
}
|
||||
|
||||
/** v1.4.38 W-F — distinct activity day-keys from the streak window.
|
||||
* The route only needs YYYY-MM-DD strings, so the aggregate runs
|
||||
* `date_trunc('day', m.measured_at AT TIME ZONE $userTz)` and returns
|
||||
* the day-keys directly. At most 365 rows; vs. the legacy `findMany`
|
||||
* which could return tens of thousands. */
|
||||
interface ActivityDayRow {
|
||||
day_key: string;
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
|
||||
// provider anywhere on the path.
|
||||
@@ -532,27 +524,8 @@ async function buildDashboardSummary(
|
||||
select: { takenAt: true, scheduledFor: true },
|
||||
}),
|
||||
),
|
||||
// v1.4.38 W-F — replaces the legacy 365-day `measurement.findMany`
|
||||
// that pulled every raw row in the window only to collapse them to
|
||||
// day-keys in JS. The SQL `date_trunc` returns at most 365 rows
|
||||
// even on accounts with millions of step samples. The `userTz`
|
||||
// conversion is folded server-side so the day boundary matches
|
||||
// `userDayKey`'s output (it formats the timestamp in the user's
|
||||
// tz before slicing YYYY-MM-DD).
|
||||
time(
|
||||
"streakDays",
|
||||
() =>
|
||||
prisma.$queryRaw<ActivityDayRow[]>`
|
||||
SELECT DISTINCT
|
||||
to_char(
|
||||
(m."measured_at" AT TIME ZONE ${userTz}),
|
||||
'YYYY-MM-DD'
|
||||
) AS day_key
|
||||
FROM measurements m
|
||||
WHERE m."user_id" = ${userId}
|
||||
AND m."measured_at" >= ${streakWindowStart}
|
||||
AND m."deleted_at" IS NULL
|
||||
`,
|
||||
time("streakDays", () =>
|
||||
readActivityDayKeys(prisma, userId, userTz, streakWindowStart, now),
|
||||
),
|
||||
// v1.11.4 — raw per-stage SLEEP_DURATION rows for the night-total
|
||||
// tile. `SLEEP_DURATION` is stored one row per STAGE per night
|
||||
@@ -635,13 +608,9 @@ async function buildDashboardSummary(
|
||||
}
|
||||
|
||||
// v1.4.38 W-F — activity-day set assembled from the bounded streak
|
||||
// queries. The measurement side already arrives as YYYY-MM-DD keys
|
||||
// from the SQL `date_trunc + AT TIME ZONE` aggregate, byte-identical
|
||||
// to what `userDayKey(measuredAt, userTz)` would produce in JS.
|
||||
const activityDays = new Set<string>();
|
||||
for (const row of measurementStreakDays) {
|
||||
if (row.day_key) activityDays.add(row.day_key);
|
||||
}
|
||||
// queries. The measurement side arrives as local YYYY-MM-DD keys, the
|
||||
// same keys `userDayKey(measuredAt, userTz)` produces for the intakes.
|
||||
const activityDays = new Set<string>(measurementStreakDays);
|
||||
for (const e of streakActivity) {
|
||||
activityDays.add(userDayKey(e.takenAt ?? e.scheduledFor, userTz));
|
||||
}
|
||||
|
||||
@@ -569,16 +569,10 @@ describe("GET /api/insights/comprehensive — envelope shape", () => {
|
||||
expect(body.data.moodSummary?.count).toBe(2);
|
||||
});
|
||||
|
||||
it("derives weight × BP scatter from daily-bucketed series", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
// Five day-aligned pairs (n >= 5 unlocks pearsonCorrelation).
|
||||
const days = [
|
||||
"2026-05-01",
|
||||
"2026-05-02",
|
||||
"2026-05-03",
|
||||
"2026-05-04",
|
||||
"2026-05-05",
|
||||
];
|
||||
function mockWeightBpDays(count: number) {
|
||||
const days = Array.from({ length: count }, (_, i) =>
|
||||
new Date(Date.UTC(2026, 4, 1 + i)).toISOString().slice(0, 10),
|
||||
);
|
||||
(buildComprehensiveAggregate as ReturnType<typeof vi.fn>).mockResolvedValue(
|
||||
{
|
||||
summaries: {},
|
||||
@@ -592,22 +586,41 @@ describe("GET /api/insights/comprehensive — envelope shape", () => {
|
||||
})),
|
||||
},
|
||||
firstMeasurementAt: new Date(),
|
||||
totalMeasurements: 10,
|
||||
totalMeasurements: count * 2,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
type WeightBpBody = {
|
||||
data: {
|
||||
scatterData: Array<{ weight: number; sysBP: number }>;
|
||||
weightBpCorrelation: { r: number; n: number } | null;
|
||||
};
|
||||
};
|
||||
|
||||
it("derives weight × BP scatter from daily-bucketed series", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
mockWeightBpDays(25);
|
||||
|
||||
const res = await callGet(makeReq());
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
scatterData: Array<{ weight: number; sysBP: number }>;
|
||||
weightBpCorrelation: { r: number; n: number } | null;
|
||||
};
|
||||
};
|
||||
expect(body.data.scatterData).toHaveLength(5);
|
||||
const body = (await res.json()) as WeightBpBody;
|
||||
expect(body.data.scatterData).toHaveLength(25);
|
||||
expect(body.data.scatterData[0]).toEqual({ weight: 80, sysBP: 120 });
|
||||
// Perfect linear relationship → r === 1.
|
||||
// Perfect linear relationship over 25 days → r === 1.
|
||||
expect(body.data.weightBpCorrelation?.r).toBe(1);
|
||||
expect(body.data.weightBpCorrelation?.n).toBe(5);
|
||||
expect(body.data.weightBpCorrelation?.n).toBe(25);
|
||||
});
|
||||
|
||||
it("reports no correlation below the significance bar every surface uses", async () => {
|
||||
// Five perfectly aligned days: the scatter shows them, but five points
|
||||
// cannot carry a correlation (n >= 20 and p < 0.05).
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
mockWeightBpDays(5);
|
||||
|
||||
const res = await callGet(makeReq());
|
||||
const body = (await res.json()) as WeightBpBody;
|
||||
expect(body.data.scatterData).toHaveLength(5);
|
||||
expect(body.data.weightBpCorrelation).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -849,13 +862,10 @@ describe("GET /api/insights/comprehensive — mood × metric local-day pairing (
|
||||
// tier in R12. Both read the UTC `dailyByType` / UTC `scheduledFor`
|
||||
// slice, so their output must be invariant to the caller's timezone.
|
||||
// Run the SAME fixture under UTC then America/New_York and deep-equal.
|
||||
const days = [
|
||||
"2026-05-01",
|
||||
"2026-05-02",
|
||||
"2026-05-03",
|
||||
"2026-05-04",
|
||||
"2026-05-05",
|
||||
];
|
||||
// 25 days: a correlation has to clear n >= 20 and p < 0.05 to exist.
|
||||
const days = Array.from({ length: 25 }, (_, i) =>
|
||||
new Date(Date.UTC(2026, 4, 1 + i)).toISOString().slice(0, 10),
|
||||
);
|
||||
const aggregate = {
|
||||
summaries: {},
|
||||
bpRawRows: { sys: [], dia: [] },
|
||||
@@ -896,20 +906,20 @@ describe("GET /api/insights/comprehensive — mood × metric local-day pairing (
|
||||
scheduleRevisions: [],
|
||||
pauseEras: [],
|
||||
};
|
||||
// Intake taken on the first three days, logged as skipped on the last
|
||||
// two → a non-degenerate continuity series. The skips used to be absent
|
||||
// Intake taken on the first fifteen days, logged as skipped on the
|
||||
// last ten → a non-degenerate continuity series. The skips used to be absent
|
||||
// rows: a day with no record read as a measured 0 % continuity, which is
|
||||
// the fabrication the route no longer makes, and a fixture that relies on
|
||||
// it would be pinning the defect rather than the timezone question this
|
||||
// test asks. Recording the two days as skips keeps five paired days AND
|
||||
// test asks. Recording the days as skips keeps every day paired AND
|
||||
// keeps every one of them a thing the person actually logged.
|
||||
const intakeEvents = days.map((d, i) => ({
|
||||
medicationId: "med-bp",
|
||||
userId: "user-comp-1",
|
||||
deletedAt: null,
|
||||
scheduledFor: new Date(`${d}T07:00:00Z`),
|
||||
takenAt: i < 3 ? new Date(`${d}T07:05:00Z`) : null,
|
||||
skipped: i >= 3,
|
||||
takenAt: i < 15 ? new Date(`${d}T07:05:00Z`) : null,
|
||||
skipped: i >= 15,
|
||||
}));
|
||||
|
||||
function primeMocks() {
|
||||
@@ -948,7 +958,8 @@ describe("GET /api/insights/comprehensive — mood × metric local-day pairing (
|
||||
);
|
||||
// And the guard is meaningful only if these joins actually produced
|
||||
// output to compare.
|
||||
expect(utcBody.data.scatterData).toHaveLength(5);
|
||||
expect(utcBody.data.scatterData).toHaveLength(25);
|
||||
expect(utcBody.data.weightBpCorrelation).not.toBeNull();
|
||||
expect(utcBody.data.bpMedicationCorrelation).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
generateAlerts,
|
||||
} from "@/lib/analytics/classifications";
|
||||
import {
|
||||
pearsonCorrelation,
|
||||
significantPearsonCorrelation,
|
||||
type PairedPoint,
|
||||
} from "@/lib/analytics/correlations";
|
||||
import {
|
||||
@@ -285,7 +285,7 @@ export async function buildComprehensiveResponse(user: AuthedUser) {
|
||||
const weightDaily = aggregate.dailyByType.WEIGHT ?? [];
|
||||
const sysDaily = aggregate.dailyByType.BLOOD_PRESSURE_SYS ?? [];
|
||||
const weightBpPairs: PairedPoint[] = joinDailyByDay(weightDaily, sysDaily);
|
||||
const weightBpCorrelation = pearsonCorrelation(weightBpPairs);
|
||||
const weightBpCorrelation = significantPearsonCorrelation(weightBpPairs);
|
||||
const scatterData = weightBpPairs.map((p) => ({
|
||||
weight: p.a,
|
||||
sysBP: p.b,
|
||||
@@ -308,11 +308,11 @@ export async function buildComprehensiveResponse(user: AuthedUser) {
|
||||
);
|
||||
|
||||
const moodBpPairs = pairMoodWithDaily(dailyMoodEntries, sysDailyLocal);
|
||||
const moodBpCorrelation = pearsonCorrelation(moodBpPairs);
|
||||
const moodBpCorrelation = significantPearsonCorrelation(moodBpPairs);
|
||||
const moodBpScatterData = moodBpPairs.map((p) => ({ mood: p.a, sysBP: p.b }));
|
||||
|
||||
const moodWeightPairs = pairMoodWithDaily(dailyMoodEntries, weightDailyLocal);
|
||||
const moodWeightCorrelation = pearsonCorrelation(moodWeightPairs);
|
||||
const moodWeightCorrelation = significantPearsonCorrelation(moodWeightPairs);
|
||||
const moodWeightScatterData = moodWeightPairs.map((p) => ({
|
||||
mood: p.a,
|
||||
weight: p.b,
|
||||
@@ -374,7 +374,7 @@ export async function buildComprehensiveResponse(user: AuthedUser) {
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([day, stats]) => ({ day, value: stats.sum / stats.count }));
|
||||
const moodPulsePairs = pairMoodWithDaily(dailyMoodEntries, restingPulseDaily);
|
||||
const moodPulseCorrelation = pearsonCorrelation(moodPulsePairs);
|
||||
const moodPulseCorrelation = significantPearsonCorrelation(moodPulsePairs);
|
||||
const moodPulseScatterData = moodPulsePairs.map((p) => ({
|
||||
mood: p.a,
|
||||
pulse: p.b,
|
||||
@@ -558,7 +558,7 @@ export async function buildComprehensiveResponse(user: AuthedUser) {
|
||||
});
|
||||
}
|
||||
|
||||
const corr = pearsonCorrelation(pairs);
|
||||
const corr = significantPearsonCorrelation(pairs);
|
||||
if (corr) {
|
||||
bpMedicationCorrelation = {
|
||||
...corr,
|
||||
@@ -667,7 +667,7 @@ function deriveDailyLocalMeans(
|
||||
|
||||
/**
|
||||
* Daily-key inner join between two daily-aggregated series. Returns
|
||||
* `PairedPoint` shapes compatible with `pearsonCorrelation`.
|
||||
* `PairedPoint` shapes compatible with `significantPearsonCorrelation`.
|
||||
*
|
||||
* Inputs are sorted ASC by `day` (the aggregator's ORDER BY
|
||||
* guarantees that). The walk is O(n + m) merge-join style instead of
|
||||
|
||||
@@ -170,9 +170,9 @@ beforeEach(() => {
|
||||
(
|
||||
prisma.moodEntryRollup.findMany as ReturnType<typeof vi.fn>
|
||||
).mockResolvedValue([]);
|
||||
// v1.28.25 — the latest-ever-per-type read is a raw `DISTINCT ON`
|
||||
// (Prisma's `distinct` dedups client-side after pulling every row).
|
||||
(prisma.$queryRawUnsafe as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||
// The latest-ever-per-type read (`readLatestEver`).
|
||||
(prisma.$queryRaw as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||
vi.mocked(readGlucoseTargetSummaries).mockResolvedValue([]);
|
||||
vi.mocked(readRestingPulseProxy).mockResolvedValue([]);
|
||||
});
|
||||
@@ -321,35 +321,30 @@ describe("GET /api/insights/targets — mood-rollup tier swap", () => {
|
||||
expect(moodTarget).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reads latest-ever-per-type via raw DISTINCT ON with the one-year floor", async () => {
|
||||
// Audit High finding 3 established the 365-day floor; v1.28.25 moves
|
||||
// the read onto a real Postgres `DISTINCT ON` (Prisma's `distinct`
|
||||
// dedups in the driver AFTER pulling every row in the window, which
|
||||
// on a dense-type tenant shipped a year of raw rows to Node just to
|
||||
// keep seven). Pin the raw query: DISTINCT ON, per-type descending
|
||||
// walk, user id + floored date as bound parameters.
|
||||
it("reads latest-ever-per-type one index probe per type, floored at one year", async () => {
|
||||
// Audit High finding 3 established the 365-day floor. The read is the
|
||||
// shared `readLatestEver`: driven from the type list, one LIMIT 1 probe
|
||||
// per type, so a dense type never sorts a year of raw rows to keep one.
|
||||
await callGet(makeReq());
|
||||
|
||||
const rawCalls = (prisma.$queryRawUnsafe as ReturnType<typeof vi.fn>).mock
|
||||
.calls;
|
||||
const distinctCall = rawCalls.find(
|
||||
(c) => typeof c[0] === "string" && c[0].includes("DISTINCT ON"),
|
||||
const rawCalls = (prisma.$queryRaw as ReturnType<typeof vi.fn>).mock.calls;
|
||||
const latestCall = rawCalls.find(
|
||||
(c) =>
|
||||
Array.isArray(c[0]) &&
|
||||
(c[0] as string[]).join("?").includes("CROSS JOIN LATERAL"),
|
||||
);
|
||||
expect(distinctCall).toBeDefined();
|
||||
const [sql, boundUserId, flooredAt] = distinctCall as [
|
||||
string,
|
||||
string,
|
||||
Date,
|
||||
];
|
||||
expect(sql).toContain(`DISTINCT ON (m."type")`);
|
||||
expect(sql).toContain(`ORDER BY m."type" ASC, m."measured_at" DESC`);
|
||||
// Parameter-bound, never spliced: user id + date ride $1/$2.
|
||||
expect(sql).toContain("$1");
|
||||
expect(sql).toContain("$2");
|
||||
expect(boundUserId).toBe("user-targets-1");
|
||||
expect(latestCall).toBeDefined();
|
||||
const [strings, ...values] = latestCall as [string[], ...unknown[]];
|
||||
expect(strings.join("?")).not.toContain("DISTINCT ON");
|
||||
expect(values).toContain("user-targets-1");
|
||||
const floor = values.find(
|
||||
(v): v is { values: unknown[] } =>
|
||||
typeof v === "object" && v !== null && !Array.isArray(v),
|
||||
);
|
||||
const flooredAt = floor?.values[0];
|
||||
expect(flooredAt).toBeInstanceOf(Date);
|
||||
const oneYearMs = 365 * 24 * 60 * 60 * 1000;
|
||||
const ageMs = Date.now() - flooredAt.getTime();
|
||||
const ageMs = Date.now() - (flooredAt as Date).getTime();
|
||||
// Floor is somewhere around one year ago — give a ±1-hour window
|
||||
// for clock drift between the route's `Date.now()` and the test
|
||||
// assertion.
|
||||
@@ -454,7 +449,7 @@ describe("GET /api/insights/targets — mood-rollup tier swap", () => {
|
||||
timeZone,
|
||||
),
|
||||
);
|
||||
(prisma.$queryRawUnsafe as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
(prisma.$queryRaw as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
{ type: "WEIGHT", value: 70 },
|
||||
{ type: "BLOOD_PRESSURE_SYS", value: 125 },
|
||||
{ type: "BLOOD_PRESSURE_DIA", value: 75 },
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
import { resolveSeriesReferenceLines } from "@/lib/measurements/series-reference-lines";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { resolveJobLocale } from "@/lib/i18n/job-locale";
|
||||
import { READING_SPREAD, standardDeviation } from "@/lib/stats/spread";
|
||||
|
||||
/**
|
||||
* v1.11.4 — sleep is read row-per-stage (not from the day rollup), so its
|
||||
@@ -209,10 +210,8 @@ interface SeriesPoint {
|
||||
|
||||
function stdDev(values: number[]): number {
|
||||
if (values.length < 2) return 0;
|
||||
const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
|
||||
const variance =
|
||||
values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length;
|
||||
return Math.round(Math.sqrt(variance) * 100) / 100;
|
||||
const sd = standardDeviation(values, READING_SPREAD) ?? 0;
|
||||
return Math.round(sd * 100) / 100;
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
@@ -24,10 +24,12 @@ import { apiError, apiSuccess, returnAllZodIssues } from "@/lib/api-response";
|
||||
import {
|
||||
buildCadenceTimeline,
|
||||
computeNextDose,
|
||||
type CadenceEngineContext,
|
||||
} from "@/lib/medications/scheduling/cadence";
|
||||
import { complianceChips } from "@/lib/medications/scheduling/compliance";
|
||||
import {
|
||||
buildComplianceMedicationContext,
|
||||
COMPLIANCE_LEDGER_WINDOW_DAYS,
|
||||
COURSES_COMPLIANCE_SELECT,
|
||||
lastNonSkippedTakenAt,
|
||||
SCHEDULE_COMPLIANCE_SELECT,
|
||||
} from "@/lib/analytics/compliance";
|
||||
@@ -58,6 +60,11 @@ export const GET = apiHandler(
|
||||
schedules: { select: SCHEDULE_COMPLIANCE_SELECT },
|
||||
// v1.16.3 — archived schedule eras for era-aware chips/tallies.
|
||||
scheduleRevisions: { orderBy: { validFrom: "asc" } },
|
||||
// The pause eras and courses, so the chips tally the ledger the
|
||||
// detail page's rate reads: a paused day or a gap between two
|
||||
// courses expects nothing.
|
||||
pauseEras: { select: { pausedAt: true, resumedAt: true } },
|
||||
courses: COURSES_COMPLIANCE_SELECT,
|
||||
},
|
||||
});
|
||||
if (!med) {
|
||||
@@ -75,11 +82,13 @@ export const GET = apiHandler(
|
||||
const windowDays = parsed.data.days ?? 30;
|
||||
const asOf = new Date();
|
||||
|
||||
// Pull intake events covering the window + a small buffer so a dose
|
||||
// logged at the edge can still pair with its slot.
|
||||
const bufferMs = 24 * 60 * 60 * 1000;
|
||||
// The events the compliance ledger reads (its full trailing year plus a
|
||||
// day): the chips tally the same rows as the detail page, and a rolling
|
||||
// cadence re-anchors on the latest intake even when it predates the
|
||||
// chart's window.
|
||||
const from = new Date(
|
||||
asOf.getTime() - windowDays * 24 * 60 * 60 * 1000 - bufferMs,
|
||||
asOf.getTime() -
|
||||
(COMPLIANCE_LEDGER_WINDOW_DAYS + 1) * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
@@ -93,6 +102,8 @@ export const GET = apiHandler(
|
||||
scheduledFor: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
// A dose the auto-miss job closed counts as missed, as in the rate.
|
||||
autoMissed: true,
|
||||
// v1.15.20 — pinned takes bind by anchor in the chip tally so the
|
||||
// chips agree with the % + the history on a "zugeordnet" dose.
|
||||
attributionSource: true,
|
||||
@@ -121,16 +132,11 @@ export const GET = apiHandler(
|
||||
// legacy weekday walker (e.g. `FREQ=WEEKLY;BYDAY=MO` expands daily,
|
||||
// PRN counts as a real cadence) and disagrees with the dashboard.
|
||||
// Mirrors `analytics/compliance.ts`'s context construction.
|
||||
const lastIntakeAt = lastNonSkippedTakenAt(events);
|
||||
const engineCtx: CadenceEngineContext = {
|
||||
startsOn: med.startsOn,
|
||||
endsOn: med.endsOn,
|
||||
oneShot: med.oneShot,
|
||||
createdAt: med.createdAt,
|
||||
lastIntakeAt,
|
||||
timeZone: userTz,
|
||||
scheduleRevisions: med.scheduleRevisions,
|
||||
};
|
||||
const engineCtx = buildComplianceMedicationContext(
|
||||
med,
|
||||
lastNonSkippedTakenAt(events),
|
||||
userTz,
|
||||
);
|
||||
|
||||
// v1.39.1 (#1033) — intake tracking off: no chip, no next dose.
|
||||
const liveSchedules = dueSchedules(med);
|
||||
@@ -146,11 +152,10 @@ export const GET = apiHandler(
|
||||
const chips = complianceChips(
|
||||
liveSchedules,
|
||||
events,
|
||||
engineCtx,
|
||||
asOf,
|
||||
windowDays,
|
||||
anchor,
|
||||
userTz,
|
||||
engineCtx,
|
||||
);
|
||||
const next = computeNextDose(
|
||||
liveSchedules,
|
||||
|
||||
@@ -91,7 +91,7 @@ import {
|
||||
UNSTABLE_EXTERNAL_ID_REASON,
|
||||
type UnstableExternalIdShape,
|
||||
} from "@/lib/validations/external-id";
|
||||
import { dedupeWorkoutBatch } from "@/lib/workouts/canonical-rows";
|
||||
import { pickCanonicalWorkoutRows } from "@/lib/measurements/pick-canonical-workout-rows";
|
||||
import { WORKOUTS_WRITE_SCOPE } from "@/lib/workouts/scopes";
|
||||
import { EXTERNAL_SOURCE } from "@/lib/measurements/external-source";
|
||||
import { encryptRouteGeometry } from "@/lib/workouts/route-geometry-cipher";
|
||||
@@ -494,41 +494,29 @@ async function postBatch(request: NextRequest): Promise<Response> {
|
||||
});
|
||||
}
|
||||
|
||||
// v1.4.42 W5 — write-time cross-source dedup. The v1.5 iOS app
|
||||
// drains a HealthKit observer queue that frequently carries the
|
||||
// SAME logical workout from two paired sensors (Apple Watch +
|
||||
// Withings ScanWatch). Without this pass, both rows persist (their
|
||||
// `externalId`s differ → the `(userId, source, externalId)` unique
|
||||
// index never fires) and the read-time canonical-picker has to
|
||||
// carry the duplicate forward on every dashboard render.
|
||||
//
|
||||
// The helper is pure (no Prisma, no user lookups). It groups by
|
||||
// `(userId, activityType, startedAt ± 90 s)`, prefers the canonical
|
||||
// source ladder (APPLE_HEALTH > WITHINGS > MANUAL > IMPORT), and
|
||||
// breaks ties on calories > earliest createdAt > input order. Rows
|
||||
// dropped here surface to the iOS client as `duplicate` so the
|
||||
// sync cursor advances past them identically to the externalId
|
||||
// case below.
|
||||
const canonicalPrepared = dedupeWorkoutBatch(
|
||||
// Write-time cross-source dedup through the one workout picker the reads
|
||||
// use, with the same source ladder: one logical workout from two sources
|
||||
// in one batch (or one HealthKit session re-sent under a new id) lands
|
||||
// once. Rows the picker hides surface to the client as `duplicate`, so
|
||||
// the sync cursor advances past them like the externalId case below.
|
||||
const canonicalPrepared = pickCanonicalWorkoutRows(
|
||||
prepared.map((p) => ({
|
||||
index: p.index,
|
||||
userId: p.row.userId,
|
||||
activityType: p.row.sportType,
|
||||
sportType: p.row.sportType,
|
||||
startedAt: p.row.startedAt as Date,
|
||||
durationSec: p.row.durationSec,
|
||||
// Zod's `measurementSourceEnum.optional().default("MANUAL")`
|
||||
// guarantees `source` is set post-parse, but Prisma's
|
||||
// `WorkoutCreateManyInput` types it optional. Default through
|
||||
// the same fallback the validator uses so the picker's source
|
||||
// ladder still resolves on the rare row where TypeScript
|
||||
// can't prove the union.
|
||||
// `WorkoutCreateManyInput` types it optional.
|
||||
source: (p.row.source ?? "MANUAL") as MeasurementSource,
|
||||
caloriesKcal: p.row.totalEnergyKcal ?? null,
|
||||
// No createdAt yet — the row is pre-insert; the tie-breaker
|
||||
// falls through to input order via the `index` field below.
|
||||
index: p.index,
|
||||
avgHeartRate: p.row.avgHeartRate ?? null,
|
||||
maxHeartRate: p.row.maxHeartRate ?? null,
|
||||
metadata: p.row.metadata ?? null,
|
||||
})),
|
||||
userPriority?.sourcePriorityJson ?? null,
|
||||
);
|
||||
const survivingIndices = new Set(canonicalPrepared.map((r) => r.index ?? -1));
|
||||
const survivingIndices = new Set(canonicalPrepared.map((r) => r.index));
|
||||
const droppedByWriteDedup: number[] = [];
|
||||
for (const p of prepared) {
|
||||
if (!survivingIndices.has(p.index)) {
|
||||
|
||||
Reference in new issue
Block a user