mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
chore(release): v1.28.23 — sleep disagreement on the dashboard; Apple Health medication groundwork
The sleep source-discrepancy annotation now reaches the surfaces: SleepNight carries the MAIN session's annotation (naps never cross-compare), the analytics slim slice / dashboard snapshot / iOS summary thread it additively, and the dashboard sleep tile renders the shared discreet marker (extracted from the sleep panel — one implementation, two surfaces). Served totals unchanged, pinned by tests. Apple Health medications groundwork (server side of the medication-import request): IntakeSource gains APPLE_HEALTH; medications accept an external mirror identity (source-exclusive by policy) and dose imports carry the HK dose-event UUID — both idempotent per stable key, with the concurrent-create race resolved to the winner. Migration 0239, additive only. Entries without the new fields behave byte-identically. Hardening: doctor-report aggregation + PDF charts compute ranges with loops instead of spread calls — a report over a sample-dense year cannot overflow the call stack (the class fixed for the Google Health full sync).
This commit is contained in:
1 parent
755da41019
commit
c400e2aa88
29 files changed
+1585
-276
No files matched your search
@@ -1188,3 +1188,67 @@ describe("source discrepancy annotation", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("night-level source discrepancy (dashboard path)", () => {
|
||||
// Same fixture as the session-level suite: granular Apple (455 asleep)
|
||||
// next to a bare Withings aggregate claiming 615 for the same overnight
|
||||
// session.
|
||||
const discrepantOvernight: SleepStageRow[] = [
|
||||
srcRow("2026-06-04T00:30:00.000Z", "CORE", 300, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T03:00:00.000Z", "DEEP", 90, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T05:00:00.000Z", "REM", 65, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T05:30:00.000Z", "ASLEEP", 615, "WITHINGS"),
|
||||
];
|
||||
|
||||
it("carries the main session's annotation on the night without changing the served total", () => {
|
||||
const nights = reconstructSleepNights(discrepantOvernight, "UTC");
|
||||
expect(nights).toHaveLength(1);
|
||||
// The served total stays the winning writer's number — the annotation
|
||||
// observes, the writer collapse decides.
|
||||
expect(nights[0].asleepMinutes).toBe(455);
|
||||
expect(nights[0].sourceDiscrepancy).toEqual({
|
||||
deltaMinutes: 160,
|
||||
sources: [
|
||||
{ source: "WITHINGS", deviceType: null, asleepMinutes: 615 },
|
||||
{ source: "APPLE_HEALTH", deviceType: null, asleepMinutes: 455 },
|
||||
],
|
||||
});
|
||||
// The dashboard reads the night through `summarizeSleepNights`.
|
||||
const { latestNight } = summarizeSleepNights(discrepantOvernight, "UTC");
|
||||
expect(latestNight?.asleepMinutes).toBe(455);
|
||||
expect(latestNight?.sourceDiscrepancy).toEqual(nights[0].sourceDiscrepancy);
|
||||
});
|
||||
|
||||
it("ignores a nap-only disagreement — sessions never cross-compare", () => {
|
||||
// Clean single-writer overnight (455 asleep), then a same-wake-day nap
|
||||
// (> 3 h gap) where two writers clearly disagree (120 vs 200 → delta 80
|
||||
// > 45 min and > 20 % of 200). The nap's session-level annotation must
|
||||
// NOT leak onto the night: the night's marker reflects the MAIN
|
||||
// (overnight) session only.
|
||||
const rows: SleepStageRow[] = [
|
||||
srcRow("2026-06-04T00:30:00.000Z", "CORE", 300, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T03:00:00.000Z", "DEEP", 90, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T05:00:00.000Z", "REM", 65, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T15:00:00.000Z", "CORE", 120, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T15:00:00.000Z", "ASLEEP", 200, "WITHINGS"),
|
||||
];
|
||||
// Sanity: the nap session itself IS flagged at session level.
|
||||
const sessions = reconstructSleepSessions(rows, "UTC");
|
||||
expect(sessions).toHaveLength(2);
|
||||
expect(sessions[1].sourceDiscrepancy).not.toBeNull();
|
||||
|
||||
const { latestNight } = summarizeSleepNights(rows, "UTC");
|
||||
expect(latestNight?.night).toBe("2026-06-04");
|
||||
// Overnight (455) outweighs the nap (120) → main session is clean.
|
||||
expect(latestNight?.sourceDiscrepancy).toBeNull();
|
||||
});
|
||||
|
||||
it("stays null for a single-writer night", () => {
|
||||
const rows: SleepStageRow[] = [
|
||||
srcRow("2026-06-04T00:30:00.000Z", "CORE", 300, "APPLE_HEALTH"),
|
||||
srcRow("2026-06-04T03:00:00.000Z", "DEEP", 90, "APPLE_HEALTH"),
|
||||
];
|
||||
const { latestNight } = summarizeSleepNights(rows, "UTC");
|
||||
expect(latestNight?.sourceDiscrepancy).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,7 @@
|
||||
* have caught the empty-object short-circuit bug.
|
||||
*/
|
||||
import type { DataSummary } from "@/lib/analytics/trends";
|
||||
import type { SleepSourceDiscrepancy } from "@/lib/analytics/sleep-night";
|
||||
|
||||
export interface AnalyticsSlimLike {
|
||||
summaries?: Record<string, DataSummary> | null;
|
||||
@@ -37,6 +38,12 @@ export interface AnalyticsSlimLike {
|
||||
string,
|
||||
{ lastSeenAt: string; daysAgo: number } | null
|
||||
> | null;
|
||||
/**
|
||||
* v1.28.x — latest-night source-discrepancy annotation, carried by
|
||||
* both slices (the slim post-pass computes it; the thick body passes
|
||||
* it through). Additive and null-safe.
|
||||
*/
|
||||
sleepSourceDiscrepancy?: SleepSourceDiscrepancy | null;
|
||||
}
|
||||
|
||||
export interface AnalyticsThickLike extends AnalyticsSlimLike {
|
||||
@@ -64,6 +71,7 @@ export interface MergedDashboardAnalytics {
|
||||
bpInTargetCount90: number | null;
|
||||
bpInTargetSpanDays90: number | null;
|
||||
glucoseByContext: Record<string, unknown> | undefined;
|
||||
sleepSourceDiscrepancy: SleepSourceDiscrepancy | null;
|
||||
}
|
||||
|
||||
function hasContent(
|
||||
@@ -117,5 +125,13 @@ export function mergeSlimAndThickAnalytics(
|
||||
bpInTargetCount90: thick?.bpInTargetCount90 ?? null,
|
||||
bpInTargetSpanDays90: thick?.bpInTargetSpanDays90 ?? null,
|
||||
glucoseByContext: thick?.glucoseByContext ?? undefined,
|
||||
// Rides the same discriminator as `summaries`: whichever slice
|
||||
// supplied the summaries also supplies the sleep annotation, so the
|
||||
// marker can never point at a night the rendered headline doesn't
|
||||
// show. `?? null` tolerates older cached payloads without the field.
|
||||
sleepSourceDiscrepancy:
|
||||
(slimSummariesHaveContent
|
||||
? slim!.sleepSourceDiscrepancy
|
||||
: thick?.sleepSourceDiscrepancy) ?? null,
|
||||
};
|
||||
}
|
||||
@@ -276,6 +276,17 @@ export interface SleepNight {
|
||||
awakeMinutes: number | null;
|
||||
/** Per-stage minutes for the night (only stages the winning writer reported). */
|
||||
stages: Partial<Record<SleepStage, number>>;
|
||||
/**
|
||||
* Non-null when two writer buckets reported clearly different asleep
|
||||
* totals for the night's MAIN session — the same-wake-day session with
|
||||
* the most asleep minutes, normally the overnight block (see
|
||||
* `sessionSourceDiscrepancy`). Sessions never cross-compare: a nap's
|
||||
* writers are not measured against the overnight's. Observational only —
|
||||
* the served `asleepMinutes` stays the winning writer's total; the
|
||||
* annotation lets the UI mark the number with a discreet
|
||||
* "sources disagree" hint.
|
||||
*/
|
||||
sourceDiscrepancy: SleepSourceDiscrepancy | null;
|
||||
}
|
||||
|
||||
/** Sentinel for rows that carry no source — collapses to one bucket. */
|
||||
@@ -604,6 +615,15 @@ export function reconstructSleepNights(
|
||||
// edits.
|
||||
let latest = nightSessions[0].pool[0].measuredAt;
|
||||
const stages: Partial<Record<SleepStage, number>> = {};
|
||||
// MAIN session of the night = most asleep minutes (same per-session
|
||||
// asleep total the headline sums; tie → later wake instant, matching
|
||||
// `pickMainNightAndNaps`). Its FULL raw row set (every writer,
|
||||
// pre-collapse) feeds the night's source-discrepancy annotation —
|
||||
// per session, so a nap's writers never cross-compare against the
|
||||
// overnight block's.
|
||||
let mainSessionRows: SleepStageRow[] | null = null;
|
||||
let mainSessionAsleep = 0;
|
||||
let mainSessionEnd = Number.NEGATIVE_INFINITY;
|
||||
for (const { pool: sessionRows, all } of nightSessions) {
|
||||
// In-bed: union envelope across ALL writers in the session (sessions
|
||||
// are > 3 h apart, so per-session envelopes never overlap and summing
|
||||
@@ -620,10 +640,14 @@ export function reconstructSleepNights(
|
||||
const sawGranular = sawGranularStage(sessionRows);
|
||||
// Asleep total: sum per session so a granular overnight + a bare-only
|
||||
// nap both contribute (the merged-night nap under-count fix).
|
||||
asleep += asleepMinutesOf(sessionRows);
|
||||
const sessionAsleep = asleepMinutesOf(sessionRows);
|
||||
asleep += sessionAsleep;
|
||||
let sessionEnd = Number.NEGATIVE_INFINITY;
|
||||
for (const r of sessionRows) {
|
||||
const minutes = Number.isFinite(r.value) ? r.value : 0;
|
||||
if (r.measuredAt.getTime() > latest.getTime()) latest = r.measuredAt;
|
||||
if (r.measuredAt.getTime() > sessionEnd)
|
||||
sessionEnd = r.measuredAt.getTime();
|
||||
const stage = r.sleepStage;
|
||||
// Drop the redundant bare ASLEEP aggregate (and stage-less rows) from
|
||||
// the per-stage breakdown when this session has the granular partition,
|
||||
@@ -637,6 +661,15 @@ export function reconstructSleepNights(
|
||||
sawAwake = true;
|
||||
}
|
||||
}
|
||||
if (
|
||||
sessionAsleep > 0 &&
|
||||
(sessionAsleep > mainSessionAsleep ||
|
||||
(sessionAsleep === mainSessionAsleep && sessionEnd > mainSessionEnd))
|
||||
) {
|
||||
mainSessionAsleep = sessionAsleep;
|
||||
mainSessionEnd = sessionEnd;
|
||||
mainSessionRows = all;
|
||||
}
|
||||
}
|
||||
nights.push({
|
||||
night,
|
||||
@@ -645,6 +678,9 @@ export function reconstructSleepNights(
|
||||
inBedMinutes: sawInBed ? inBed : null,
|
||||
awakeMinutes: sawAwake ? awake : null,
|
||||
stages,
|
||||
sourceDiscrepancy: mainSessionRows
|
||||
? sessionSourceDiscrepancy(mainSessionRows)
|
||||
: null,
|
||||
});
|
||||
}
|
||||
return nights.sort((a, b) => (a.night < b.night ? -1 : 1));
|
||||
|
||||
@@ -82,6 +82,7 @@ import {
|
||||
import { readBestGranularityRollups } from "@/lib/rollups/measurement-read-wmy";
|
||||
import {
|
||||
summarizeSleepNights,
|
||||
type SleepSourceDiscrepancy,
|
||||
type SleepStageRow,
|
||||
} from "@/lib/analytics/sleep-night";
|
||||
import { resolveUserTimezone } from "@/lib/tz/resolver";
|
||||
@@ -247,6 +248,17 @@ export interface SummariesSlice {
|
||||
string,
|
||||
{ lastSeenAt: string; daysAgo: number } | null
|
||||
>;
|
||||
/**
|
||||
* v1.28.x — source-discrepancy annotation for the LATEST night's main
|
||||
* session (see `SleepNight.sourceDiscrepancy`): non-null when two writer
|
||||
* buckets reported clearly different asleep totals for the night behind
|
||||
* `summaries.SLEEP_DURATION.latest`. Observational only — the served
|
||||
* summary stays the winning writer's totals; the dashboard sleep tile
|
||||
* marks the number with a discreet "sources disagree" hint. Minutes are
|
||||
* whole (rounded), matching the `/api/sleep/night` serialisation.
|
||||
* Additive on the wire; every consumer must tolerate `null`.
|
||||
*/
|
||||
sleepSourceDiscrepancy: SleepSourceDiscrepancy | null;
|
||||
}
|
||||
|
||||
export async function computeSummariesSlice(
|
||||
@@ -362,12 +374,25 @@ async function withSleepNightTotals(
|
||||
resolveUserTimezone(userId),
|
||||
loadUserSourcePriority(userId),
|
||||
]);
|
||||
const { summary } = summarizeSleepNights(rows, tz, priorityJson);
|
||||
const { summary, latestNight } = summarizeSleepNights(rows, tz, priorityJson);
|
||||
// Preserve the slope tuples the night summary doesn't compute (the
|
||||
// dashboard tile reads slope30); recompute them off the night series is
|
||||
// out of scope here — the per-night `summarize()` already fills slope7 /
|
||||
// slope30 / slope90 from the night DataPoints, so use them directly.
|
||||
slice.summaries.SLEEP_DURATION = summary;
|
||||
// Additive, observational: the latest night's main session saw two
|
||||
// writer buckets with clearly different asleep totals. Round to whole
|
||||
// minutes, matching the `/api/sleep/night` serialisation.
|
||||
slice.sleepSourceDiscrepancy = latestNight?.sourceDiscrepancy
|
||||
? {
|
||||
deltaMinutes: Math.round(latestNight.sourceDiscrepancy.deltaMinutes),
|
||||
sources: latestNight.sourceDiscrepancy.sources.map((b) => ({
|
||||
source: b.source,
|
||||
deviceType: b.deviceType,
|
||||
asleepMinutes: Math.round(b.asleepMinutes),
|
||||
})),
|
||||
}
|
||||
: null;
|
||||
return slice;
|
||||
}
|
||||
|
||||
@@ -693,7 +718,7 @@ async function computeFromRollups(userId: string): Promise<SummariesSlice> {
|
||||
},
|
||||
});
|
||||
|
||||
return { summaries, bmi: null, lastSeenByType };
|
||||
return { summaries, bmi: null, lastSeenByType, sleepSourceDiscrepancy: null };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -938,7 +963,7 @@ async function computeFromLiveAggregate(
|
||||
},
|
||||
});
|
||||
|
||||
return { summaries, bmi: null, lastSeenByType };
|
||||
return { summaries, bmi: null, lastSeenByType, sleepSourceDiscrepancy: null };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
*/
|
||||
import type { PrismaClient, MeasurementType } from "@/generated/prisma/client";
|
||||
import { computeSummariesSlice } from "@/lib/analytics/summaries-slice";
|
||||
import type { SleepSourceDiscrepancy } from "@/lib/analytics/sleep-night";
|
||||
import { getUnitForType } from "@/lib/validations/measurement";
|
||||
import {
|
||||
summarize,
|
||||
@@ -384,6 +385,13 @@ export interface DashboardSnapshot {
|
||||
summary: DataSummary | null;
|
||||
entries: DashboardSnapshotMoodEntry[];
|
||||
};
|
||||
/**
|
||||
* v1.28.x — source-discrepancy annotation for the latest night behind
|
||||
* `summaries.SLEEP_DURATION.latest` (see `SummariesSlice`). Null when
|
||||
* the writers agree or the sleep module is off. Optional on the type
|
||||
* (additive contract) so older cached snapshots / fixtures stay valid.
|
||||
*/
|
||||
sleepSourceDiscrepancy?: SleepSourceDiscrepancy | null;
|
||||
};
|
||||
/** Thick phase — null on a rollup-coverage miss. */
|
||||
extras: DashboardSnapshotExtras | null;
|
||||
@@ -1233,6 +1241,10 @@ export async function buildDashboardSnapshot(
|
||||
summary: mood.entries.length > 0 ? mood.summary : null,
|
||||
entries: mood.entries,
|
||||
},
|
||||
// v1.28.x — gated like the SLEEP_DURATION summary itself: a
|
||||
// disabled sleep module carries no sleep annotation either.
|
||||
sleepSourceDiscrepancy:
|
||||
modules.sleep === false ? null : slimRaw.sleepSourceDiscrepancy,
|
||||
},
|
||||
extras: extrasResult?.extras ?? null,
|
||||
medsToday,
|
||||
|
||||
@@ -442,7 +442,9 @@ export function collapseMeasurementsToCanonical<T extends CanonicalCollapseRow>(
|
||||
? null
|
||||
: metricKeyForType(type as MeasurementType);
|
||||
if (!metricKey) {
|
||||
out.push(...rows);
|
||||
// Loop, not `push(...rows)` — a sample-dense type's window rows run to
|
||||
// six figures and a spread call overflows the stack (v1.28.22 class).
|
||||
for (const r of rows) out.push(r);
|
||||
continue;
|
||||
}
|
||||
const { canonicalRows } = pickCanonicalSourceRows(
|
||||
@@ -457,11 +459,28 @@ export function collapseMeasurementsToCanonical<T extends CanonicalCollapseRow>(
|
||||
// `pickCanonicalSourceRows` returns the spread copies; re-key back to the
|
||||
// original rows by reference identity is unnecessary because the spread
|
||||
// preserves every field the caller reads (value / measuredAt / type).
|
||||
out.push(...(canonicalRows as unknown as T[]));
|
||||
for (const r of canonicalRows as unknown as T[]) out.push(r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loop-based min/max over a value array. NEVER `Math.min(...values)` here: the
|
||||
* report window's per-type rows are raw measurements, and a sample-dense type
|
||||
* (per-sample heart rate, CGM glucose) runs to six figures over a year — a
|
||||
* spread call overflows the stack exactly on the heaviest accounts (the same
|
||||
* failure class as the Google Health fullSync tracker, fixed v1.28.22).
|
||||
*/
|
||||
function minMaxOf(values: readonly number[]): { min: number; max: number } {
|
||||
let min = Number.POSITIVE_INFINITY;
|
||||
let max = Number.NEGATIVE_INFINITY;
|
||||
for (const v of values) {
|
||||
if (v < min) min = v;
|
||||
if (v > max) max = v;
|
||||
}
|
||||
return { min, max };
|
||||
}
|
||||
|
||||
/**
|
||||
* Summarise RECOVERY_SCORE over the window from the CANONICAL row per day:
|
||||
* a WHOOP-native row wins over the COMPUTED proxy for the same day, so the
|
||||
@@ -491,8 +510,8 @@ export function summariseCanonicalRecovery(
|
||||
type: "RECOVERY_SCORE",
|
||||
latest: Math.round(latestRow.value),
|
||||
avg: Math.round(values.reduce((a, b) => a + b, 0) / values.length),
|
||||
min: Math.round(Math.min(...values)),
|
||||
max: Math.round(Math.max(...values)),
|
||||
min: Math.round(minMaxOf(values).min),
|
||||
max: Math.round(minMaxOf(values).max),
|
||||
count: values.length,
|
||||
latestAt: latestRow.measuredAt.toISOString(),
|
||||
};
|
||||
@@ -1025,8 +1044,7 @@ export async function collectDoctorReportData(
|
||||
const values = entries.map((e) => e.value);
|
||||
stats[type] = {
|
||||
avg: values.reduce((a, b) => a + b, 0) / values.length,
|
||||
min: Math.min(...values),
|
||||
max: Math.max(...values),
|
||||
...minMaxOf(values),
|
||||
count: values.length,
|
||||
latest: values[values.length - 1],
|
||||
};
|
||||
@@ -1164,8 +1182,8 @@ export async function collectDoctorReportData(
|
||||
moodScores.length > 0
|
||||
? {
|
||||
avg: moodScores.reduce((a, b) => a + b, 0) / moodScores.length,
|
||||
min: Math.min(...moodScores),
|
||||
max: Math.max(...moodScores),
|
||||
min: minMaxOf(moodScores).min,
|
||||
max: minMaxOf(moodScores).max,
|
||||
count: moodScores.length,
|
||||
distribution: {
|
||||
1: moodScores.filter((s) => s === 1).length,
|
||||
@@ -1207,8 +1225,7 @@ export async function collectDoctorReportData(
|
||||
const values = rows.map((r) => r.value);
|
||||
glucoseStats[ctx] = {
|
||||
avg: values.reduce((a, b) => a + b, 0) / values.length,
|
||||
min: Math.min(...values),
|
||||
max: Math.max(...values),
|
||||
...minMaxOf(values),
|
||||
count: values.length,
|
||||
latest: values[values.length - 1],
|
||||
};
|
||||
|
||||
@@ -401,9 +401,14 @@ function drawSparkline(
|
||||
doc.setTextColor(30, 30, 30);
|
||||
doc.text(label, x, y + labelHeight - 1.5);
|
||||
|
||||
const values = points.map((p) => p.value);
|
||||
const min = Math.min(...values);
|
||||
const max = Math.max(...values);
|
||||
// Loop, not `Math.min(...values)` — chart points can be sample-grain on
|
||||
// dense accounts and a spread call overflows the stack (v1.28.22 class).
|
||||
let min = Number.POSITIVE_INFINITY;
|
||||
let max = Number.NEGATIVE_INFINITY;
|
||||
for (const p of points) {
|
||||
if (p.value < min) min = p.value;
|
||||
if (p.value > max) max = p.value;
|
||||
}
|
||||
const range = max - min || 1;
|
||||
|
||||
const chartTop = y + labelHeight;
|
||||
|
||||
@@ -57,9 +57,10 @@ export interface ApplyCanonicalSlotWriteInput {
|
||||
* Source to stamp on a freshly-created slot row. `REMINDER` is the
|
||||
* Telegram-webhook path — its take / skip confirmations converge onto
|
||||
* the worker-minted pending row like every other write, and a fresh
|
||||
* create keeps the historical reminder provenance.
|
||||
* create keeps the historical reminder provenance. `APPLE_HEALTH`
|
||||
* (v1.28) is the bulk route's HealthKit dose-event import.
|
||||
*/
|
||||
createSource: "WEB" | "API" | "REMINDER";
|
||||
createSource: "WEB" | "API" | "REMINDER" | "APPLE_HEALTH";
|
||||
/**
|
||||
* v1.8.5 — resolved + server-validated injection site to persist on a
|
||||
* taken write. `null` = no site (the column stays / is set NULL). Only
|
||||
@@ -84,6 +85,16 @@ export interface ApplyCanonicalSlotWriteInput {
|
||||
* a recorded dose away.
|
||||
*/
|
||||
doseTaken?: string | null;
|
||||
/**
|
||||
* v1.28 — external dose-event identifier (HealthKit
|
||||
* `HKMedicationDoseEvent` UUID) to persist on the row. `null` / omitted
|
||||
* = no external id (the column stays untouched on an update, NULL on a
|
||||
* create). Like `injectionSite` / `doseTaken`, a write that carries no
|
||||
* id never clears a previously-recorded one. The bulk route dedups the
|
||||
* batch against the live `(userId, externalId)` unique before the
|
||||
* upsert, so a carried id is trusted fresh here.
|
||||
*/
|
||||
externalId?: string | null;
|
||||
}
|
||||
|
||||
export interface ApplyCanonicalSlotWriteResult {
|
||||
@@ -228,6 +239,7 @@ export async function applyCanonicalSlotWrite(
|
||||
injectionSite = null,
|
||||
attributionSource,
|
||||
doseTaken = null,
|
||||
externalId = null,
|
||||
} = input;
|
||||
|
||||
const rows = await findSlotRows(client, userId, medicationId, canonicalSlot);
|
||||
@@ -260,6 +272,8 @@ export async function applyCanonicalSlotWrite(
|
||||
...(attributionSource !== undefined && { attributionSource }),
|
||||
// v1.16.4 — dose override only when the write carries one.
|
||||
...(doseTaken !== null && { doseTaken }),
|
||||
// v1.28 — external dose-event id only when the write carries one.
|
||||
...(externalId !== null && { externalId }),
|
||||
},
|
||||
select: SLOT_ROW_SELECT,
|
||||
})) as SlotIntakeRow;
|
||||
@@ -307,6 +321,7 @@ async function applyToExisting(
|
||||
injectionSite = null,
|
||||
attributionSource,
|
||||
doseTaken = null,
|
||||
externalId = null,
|
||||
} = input;
|
||||
|
||||
const existingActioned = existing.takenAt !== null || existing.skipped;
|
||||
@@ -357,6 +372,10 @@ async function applyToExisting(
|
||||
// v1.16.4 — dose override only when this write carries one; never
|
||||
// clear a previously-recorded override with a null re-post.
|
||||
...(doseTaken !== null && { doseTaken }),
|
||||
// v1.28 — external dose-event id only when this write carries one
|
||||
// (an Apple dose converging onto a pre-minted pending slot row);
|
||||
// never clears a previously-recorded id.
|
||||
...(externalId !== null && { externalId }),
|
||||
},
|
||||
select: SLOT_ROW_SELECT,
|
||||
})) as SlotIntakeRow;
|
||||
|
||||
@@ -850,6 +850,25 @@ export const dashboardSnapshotResponse = z
|
||||
}),
|
||||
),
|
||||
}),
|
||||
// v1.28.x — additive: source-discrepancy annotation for the latest
|
||||
// night behind `summaries.SLEEP_DURATION.latest`. Same shape as the
|
||||
// per-session `sourceDiscrepancy` on the sleep-night resource.
|
||||
sleepSourceDiscrepancy: z
|
||||
.object({
|
||||
deltaMinutes: z.number().int().nonnegative(),
|
||||
sources: z.array(
|
||||
z.object({
|
||||
source: z.string(),
|
||||
deviceType: z.string().nullable(),
|
||||
asleepMinutes: z.number().int().nonnegative(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"Non-null when two writer buckets reported clearly different asleep totals for the latest night's main session (> 45 min apart and > 20% of the larger total). Observational only — the served summary stays the winning writer's totals; clients may show a discreet 'sources disagree' hint next to the sleep tile's headline. Null when the writers agree or the sleep module is off; optional for older cached snapshots.",
|
||||
),
|
||||
}),
|
||||
extras: z
|
||||
.object({
|
||||
|
||||
@@ -162,6 +162,33 @@ export const createMedicationSchema = z
|
||||
atcCode: atcCodeField,
|
||||
/** v1.9.0 — optional RxNorm RxCUI (secondary, US). */
|
||||
rxNormCode: rxNormCodeField,
|
||||
/**
|
||||
* v1.28 — mirrored-medication provenance. Only APPLE_HEALTH is
|
||||
* accepted here (the iOS 26+ HealthKit Medications sync); the other
|
||||
* IntakeSource values stay server-owned. Both-or-neither with
|
||||
* `externalId` (refine below).
|
||||
*/
|
||||
externalSource: z
|
||||
.literal("APPLE_HEALTH")
|
||||
.optional()
|
||||
.describe(
|
||||
"Marks the medication as MIRRORED from an external medication list. Only `APPLE_HEALTH` (the iOS 26+ HealthKit Medications sync) is accepted. Must be supplied together with `externalId`. A mirrored medication is source-exclusive: dose events from that source attach only to it, and the app's own dose-logging UI stays off it.",
|
||||
),
|
||||
/**
|
||||
* v1.28 — the source's stable concept identifier (HealthKit
|
||||
* `medicationConceptIdentifier`). Re-posting the same
|
||||
* `(externalSource, externalId)` pair returns the existing
|
||||
* medication (200) instead of creating a duplicate.
|
||||
*/
|
||||
externalId: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.optional()
|
||||
.describe(
|
||||
"Stable external identifier of the mirrored medication (the HealthKit `medicationConceptIdentifier`, max 128 chars). Must be supplied together with `externalSource`. Idempotent: re-posting the same pair returns the existing medication with status 200 instead of minting a duplicate.",
|
||||
),
|
||||
...courseWindowFields,
|
||||
/**
|
||||
* v1.16.11 — optional at the type level so an `asNeeded: true`
|
||||
@@ -170,6 +197,15 @@ export const createMedicationSchema = z
|
||||
*/
|
||||
schedules: z.array(scheduleSchema).optional(),
|
||||
})
|
||||
.refine(
|
||||
// v1.28 — mirrored-medication provenance is a pair: a source without
|
||||
// its concept id (or vice versa) can neither dedup nor mirror.
|
||||
(b) => (b.externalSource === undefined) === (b.externalId === undefined),
|
||||
{
|
||||
message: "externalSource and externalId must be supplied together",
|
||||
path: ["externalId"],
|
||||
},
|
||||
)
|
||||
.refine((b) => b.oneShot !== true || !!b.startsOn, {
|
||||
message: "startsOn is required when oneShot is true",
|
||||
path: ["startsOn"],
|
||||
@@ -203,7 +239,7 @@ export const createMedicationSchema = z
|
||||
.meta({
|
||||
id: "CreateMedicationRequest",
|
||||
description:
|
||||
'Create-medication body. The route enforces the v1.5 cross-field invariants on top of the per-schedule `rrule_xor_rolling` Zod refine: a `oneShot:true` medication may carry at most one schedule and that schedule must not declare a recurrence; `endsOn` is normalised to equal `startsOn` for one-shot doses; a recurring schedule with no `rrule`, `rollingIntervalDays`, or legacy `daysOfWeek` defaults to `rrule = "FREQ=DAILY"`; and `timesOfDay` is dual-written from `windowStart` when the caller omits it. v1.16.11 — `asNeeded: true` creates a PRN medication with ZERO schedules (`schedules` must be absent or empty, 422 otherwise); a scheduled medication still requires at least one schedule entry.',
|
||||
'Create-medication body. The route enforces the v1.5 cross-field invariants on top of the per-schedule `rrule_xor_rolling` Zod refine: a `oneShot:true` medication may carry at most one schedule and that schedule must not declare a recurrence; `endsOn` is normalised to equal `startsOn` for one-shot doses; a recurring schedule with no `rrule`, `rollingIntervalDays`, or legacy `daysOfWeek` defaults to `rrule = "FREQ=DAILY"`; and `timesOfDay` is dual-written from `windowStart` when the caller omits it. v1.16.11 — `asNeeded: true` creates a PRN medication with ZERO schedules (`schedules` must be absent or empty, 422 otherwise); a scheduled medication still requires at least one schedule entry. v1.28 — `externalSource` + `externalId` (both-or-neither) mark the medication as mirrored from Apple Health; re-posting the same pair is idempotent and returns the existing medication with status 200.',
|
||||
});
|
||||
|
||||
export const updateMedicationSchema = z
|
||||
|
||||
Reference in new issue
Block a user