mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-11 05:42:19 +00:00
fix(medications): every intake path converges on the slot, and caches cannot resurrect a pre-write body
The external ingest endpoint was the one intake writer that never attributed to the minted band: it stored a bare row beside the pending slot, so an early take through the API showed as the last intake while the slot kept demanding a dose, the ledger recorded an extra plus a miss, and the day tally counted both. It now resolves the band and converges onto the pending row like every other path, the Telegram confirm and skip buttons do the same preferring the reminder's own slot, and the nightly convergence pass heals the pairs this has already produced — one band match, one live anchor row, both days' rollups recomputed. The cache layer fences in-flight builders on invalidation so a read can neither join a pre-write build nor have a background refresh re-cache a pre-write body as fresh. Ad-hoc rows no longer resolve a different slot through the six-hour radius, a bounded early grace credits a take up to an hour before the window without crossing the previous band, day-scale cadences taken early downgrade the slot-day prompt instead of inviting a double dose, the overdue pill ignores the projector's pending mints, created intakes carry the same plausibility bounds as edits, slot moves keep the recorded injection site and dose, both affected days recompute on a moved toggle, deliberate slot-less skips converge instead of orphaning, the coach reads adherence from the ledger, the cards and quick-add run in the user's timezone with the served next-due as the gate, and schedule-revision, wipe and restore writes invalidate the caches they feed.
This commit is contained in:
1 parent
ea29e9cf1b
commit
aaecd141ee
53 files changed
+2550
-202
No files matched your search
@@ -116,6 +116,65 @@ describe("pickDefaultMedicationId — auto-select heuristic", () => {
|
||||
expect(result).toBe("b");
|
||||
});
|
||||
|
||||
it("does not pre-select a medication whose server next-due is in the future (v1.16.9)", () => {
|
||||
// The band alone reads "in window" at 10:00 Berlin, but the server
|
||||
// says the next unresolved dose is tomorrow (a rolling cadence whose
|
||||
// dose was taken) — the gate must keep the heuristic off it.
|
||||
const now = new Date("2026-05-12T08:00:00Z"); // 10:00 Berlin (UTC+2)
|
||||
const result = pickDefaultMedicationId(
|
||||
[
|
||||
makeMed("a", { name: "Aaa" }),
|
||||
makeMed("b", {
|
||||
name: "Bbb",
|
||||
nextDueAt: "2026-05-13T06:00:00.000Z", // tomorrow
|
||||
nextDueOverdue: false,
|
||||
schedules: [
|
||||
{
|
||||
id: "s1",
|
||||
windowStart: "08:00",
|
||||
windowEnd: "11:00",
|
||||
daysOfWeek: null,
|
||||
label: null,
|
||||
dose: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
now,
|
||||
);
|
||||
// Nothing genuinely due → alphabetical fallback ("Aaa").
|
||||
expect(result).toBe("a");
|
||||
});
|
||||
|
||||
it("does not pre-select a day-scale medication already taken early in its period (v1.16.9)", () => {
|
||||
// Weekly Tuesday med (2026-05-12 is a Tuesday), taken two days ago.
|
||||
const now = new Date("2026-05-12T08:00:00Z"); // 10:00 Berlin
|
||||
const result = pickDefaultMedicationId(
|
||||
[
|
||||
makeMed("a", { name: "Aaa" }),
|
||||
makeMed("b", {
|
||||
name: "Bbb",
|
||||
lastTakenAt: "2026-05-10T07:00:00.000Z", // Sunday — early take
|
||||
nextDueAt: "2026-05-12T07:00:00.000Z", // today's slot (unresolved)
|
||||
nextDueOverdue: true,
|
||||
schedules: [
|
||||
{
|
||||
id: "s1",
|
||||
windowStart: "09:00",
|
||||
windowEnd: "09:00",
|
||||
daysOfWeek: "2",
|
||||
timesOfDay: ["09:00"],
|
||||
label: null,
|
||||
dose: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
now,
|
||||
);
|
||||
expect(result).toBe("a");
|
||||
});
|
||||
|
||||
it("falls back to the alphabetical-first active medication when nothing is due", () => {
|
||||
// 03:00 Berlin time: no schedules overlap. The helper should
|
||||
// alphabetically sort and pick the leading id, "ramipril".
|
||||
|
||||
@@ -80,6 +80,15 @@ export interface MedicationOption {
|
||||
schedules: Schedule[];
|
||||
lastTakenAt: string | null;
|
||||
todayEventCount: number | null;
|
||||
/**
|
||||
* v1.16.9 — the server display-due verdict from `GET /api/medications`
|
||||
* (`nextDueAt` + `nextDueOverdue`). Threaded into the default pick so
|
||||
* the quick-add gates its "due now" heuristic exactly like the cards:
|
||||
* a rolling cadence whose next dose is days away must not pre-select.
|
||||
* Optional for older mocks; absent keeps the legacy band-only pick.
|
||||
*/
|
||||
nextDueAt?: string | null;
|
||||
nextDueOverdue?: boolean;
|
||||
}
|
||||
|
||||
interface MedicationIntakeQuickAddProps {
|
||||
@@ -127,6 +136,10 @@ export function pickDefaultMedicationId(
|
||||
|
||||
const nowBerlin = toBerlinDate(now);
|
||||
const due = actives.find((m) => {
|
||||
// v1.16.9 — the same server display-due gate the cards apply: a
|
||||
// future (non-overdue) next-due suppresses the overdue tiers and a
|
||||
// day-scale dose taken early in its period must not pre-select.
|
||||
const nextDueMs = m.nextDueAt ? new Date(m.nextDueAt).getTime() : NaN;
|
||||
const status = reduceCurrentWindowStatus({
|
||||
schedules: m.schedules,
|
||||
nowBerlin,
|
||||
@@ -135,8 +148,14 @@ export function pickDefaultMedicationId(
|
||||
active: true,
|
||||
lastTakenAt: m.lastTakenAt,
|
||||
todayEventCount: m.todayEventCount ?? 0,
|
||||
nextDue:
|
||||
m.nextDueAt === undefined
|
||||
? undefined
|
||||
: Number.isFinite(nextDueMs)
|
||||
? { at: new Date(nextDueMs), overdue: m.nextDueOverdue === true }
|
||||
: null,
|
||||
});
|
||||
return status.status !== null;
|
||||
return status.status !== null && !status.takenEarly;
|
||||
});
|
||||
if (due) return due.id;
|
||||
|
||||
|
||||
@@ -71,6 +71,8 @@ export interface MedicationCardBodyProps {
|
||||
status: Exclude<MedicationWindowStatus, null>;
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
/** v1.16.9 — day-scale early-take context (see the pill). */
|
||||
takenEarly?: boolean;
|
||||
} | null;
|
||||
|
||||
/**
|
||||
@@ -178,7 +180,17 @@ export function MedicationCardBody({
|
||||
overdue tier arrives with the compliance query, and a line
|
||||
popping in late used to shift every row below it (CLS). */}
|
||||
<div className="min-h-5">
|
||||
{overdueLabel ? (
|
||||
{windowStatus?.takenEarly ? (
|
||||
// v1.16.9 — taken-early context outranks the overdue line: a
|
||||
// day-scale dose already taken earlier in its period must never
|
||||
// escalate into a take prompt (double-dose risk).
|
||||
<MedicationStatusPill
|
||||
status={windowStatus.status}
|
||||
windowStart={windowStatus.windowStart}
|
||||
windowEnd={windowStatus.windowEnd}
|
||||
takenEarly
|
||||
/>
|
||||
) : overdueLabel ? (
|
||||
<p className="text-destructive flex items-center gap-1 text-sm font-medium">
|
||||
<AlertTriangle className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
{overdueLabel}
|
||||
|
||||
@@ -9,6 +9,14 @@ interface MedicationStatusPillProps {
|
||||
status: Exclude<MedicationWindowStatus, null>;
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
/**
|
||||
* v1.16.9 — day-scale early-take context. When true the dose was
|
||||
* already taken earlier in the cadence period (a weekly shot days
|
||||
* before its slot day), so the pill renders a calm "taken early" note
|
||||
* instead of the take-now / overdue prompt — prompting a full take on
|
||||
* the slot day would be a double-dose prompt.
|
||||
*/
|
||||
takenEarly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,9 +31,25 @@ export function MedicationStatusPill({
|
||||
status,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
takenEarly = false,
|
||||
}: MedicationStatusPillProps) {
|
||||
const { t, locale } = useTranslations();
|
||||
|
||||
if (takenEarly) {
|
||||
return (
|
||||
<p className="text-sm">
|
||||
<span className="text-muted-foreground inline-flex items-center gap-1 font-medium">
|
||||
<CircleCheck className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
{t("medications.takenEarly")}
|
||||
</span>
|
||||
<span className="text-muted-foreground hidden sm:inline">
|
||||
{" "}
|
||||
— {formatTimeWindowRange(windowStart, windowEnd, locale)}
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<p className="text-sm">
|
||||
<span
|
||||
|
||||
@@ -23,9 +23,10 @@ import { LogInjectionSiteDialog } from "@/components/medications/log-injection-s
|
||||
import { useGlobalExcludedInjectionSites } from "@/lib/medications/use-injection-site-prefs";
|
||||
import {
|
||||
reduceCurrentWindowStatus,
|
||||
toBerlinDate,
|
||||
toZonedDate,
|
||||
} from "@/lib/medications/window-status";
|
||||
import { resolveDisplayedSlotInstant } from "@/components/medications/card-parts/displayed-slot-instant";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useMedicationComplianceSummary } from "@/lib/queries/use-medication-compliance-summary";
|
||||
|
||||
/**
|
||||
@@ -166,6 +167,10 @@ export function Glp1MedicationCard({
|
||||
}: Glp1MedicationCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
// v1.16.9 — the card reasons in the PROFILE timezone; Berlin stays the
|
||||
// last-resort fallback for logged-out mounts and legacy fixtures.
|
||||
const { user } = useAuth();
|
||||
const userTz = user?.timezone || "Europe/Berlin";
|
||||
const fmt = useFormatters();
|
||||
const weekdayLabel = useWeekdayLabel();
|
||||
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
|
||||
@@ -288,7 +293,7 @@ export function Glp1MedicationCard({
|
||||
a.windowStart.localeCompare(b.windowStart) ||
|
||||
a.windowEnd.localeCompare(b.windowEnd),
|
||||
);
|
||||
const nowBerlin = toBerlinDate(now);
|
||||
const nowBerlin = toZonedDate(now, userTz);
|
||||
const lateMinutes = thresholds?.lateMinutes ?? 120;
|
||||
const missedMinutes = thresholds?.missedMinutes ?? 240;
|
||||
const currentWindowStatus = reduceCurrentWindowStatus({
|
||||
@@ -299,6 +304,7 @@ export function Glp1MedicationCard({
|
||||
active: medication.active,
|
||||
lastTakenAt: medication.lastTakenAt,
|
||||
todayEventCount: medication.todayEventCount ?? 0,
|
||||
tz: userTz,
|
||||
// v1.16.6 — gate the pill on the server display-due so a rolling
|
||||
// cadence whose next injection is days away can never paint an overdue
|
||||
// pill today. `undefined` (older payloads / fixtures) keeps legacy
|
||||
@@ -319,6 +325,7 @@ export function Glp1MedicationCard({
|
||||
currentWindowStatus,
|
||||
nextDueAt: medication.nextDueAt,
|
||||
now,
|
||||
timeZone: userTz,
|
||||
});
|
||||
|
||||
// v1.15.9 — the recent-injection list now feeds ONLY the post-dose
|
||||
@@ -439,6 +446,7 @@ export function Glp1MedicationCard({
|
||||
// legacy schedule window (which may be stale / degenerate).
|
||||
windowStart: currentWindowStatus.window!.start,
|
||||
windowEnd: currentWindowStatus.window!.end,
|
||||
takenEarly: currentWindowStatus.takenEarly,
|
||||
}
|
||||
: null
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { formatDateTime, formatTime } from "@/lib/format";
|
||||
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
|
||||
import {
|
||||
reduceCurrentWindowStatus,
|
||||
toBerlinDate,
|
||||
toZonedDate,
|
||||
} from "@/lib/medications/window-status";
|
||||
import { resolveDisplayedSlotInstant } from "@/components/medications/card-parts/displayed-slot-instant";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
@@ -26,6 +26,7 @@ import { apiGet, apiPost } from "@/lib/api/api-fetch";
|
||||
import { useMedicationComplianceSummary } from "@/lib/queries/use-medication-compliance-summary";
|
||||
import { LogInjectionSiteDialog } from "@/components/medications/log-injection-site-dialog";
|
||||
import { useGlobalExcludedInjectionSites } from "@/lib/medications/use-injection-site-prefs";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import type { InjectionSiteKey } from "@/lib/medications/injection-sites";
|
||||
|
||||
interface Schedule {
|
||||
@@ -104,6 +105,11 @@ export function MedicationCard({
|
||||
}: MedicationCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t, locale } = useTranslations();
|
||||
// v1.16.9 — the card reasons in the PROFILE timezone (the snapshot the
|
||||
// session carries); Berlin stays the last-resort fallback so logged-out
|
||||
// mounts and legacy fixtures behave unchanged.
|
||||
const { user } = useAuth();
|
||||
const userTz = user?.timezone || "Europe/Berlin";
|
||||
const fmt = useFormatters();
|
||||
const weekdayLabel = useWeekdayLabel();
|
||||
// v1.8.5 — post-dose injection-site prompt state. Holds the intake
|
||||
@@ -199,7 +205,7 @@ export function MedicationCard({
|
||||
a.windowStart.localeCompare(b.windowStart) ||
|
||||
a.windowEnd.localeCompare(b.windowEnd),
|
||||
);
|
||||
const nowBerlin = toBerlinDate(new Date());
|
||||
const nowBerlin = toZonedDate(new Date(), userTz);
|
||||
// v1.8.4 — the next-due instant comes from the server (`nextDueAt`,
|
||||
// computed by the canonical recurrence engine anchored on the last
|
||||
// intake). The day label below derives from it; the window-range /
|
||||
@@ -224,6 +230,7 @@ export function MedicationCard({
|
||||
active: medication.active,
|
||||
lastTakenAt: medication.lastTakenAt,
|
||||
todayEventCount: medication.todayEventCount ?? 0,
|
||||
tz: userTz,
|
||||
// v1.16.6 — gate the pill on the server display-due so a rolling
|
||||
// cadence whose next dose is tomorrow can never paint an overdue pill
|
||||
// today. `undefined` (older payloads / fixtures) keeps legacy behaviour.
|
||||
@@ -244,6 +251,7 @@ export function MedicationCard({
|
||||
currentWindowStatus,
|
||||
nextDueAt: medication.nextDueAt,
|
||||
now: new Date(),
|
||||
timeZone: userTz,
|
||||
});
|
||||
|
||||
function formatLastTakenAt(value: string): string {
|
||||
@@ -251,7 +259,7 @@ export function MedicationCard({
|
||||
// string-comparable for the today / yesterday / older bucketing below.
|
||||
// The actual user-facing display goes through formatTime / formatDateTime.
|
||||
const dayFormatter = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Berlin",
|
||||
timeZone: userTz,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
@@ -314,7 +322,7 @@ export function MedicationCard({
|
||||
// Format day label relative to today
|
||||
let dayLabel = "";
|
||||
if (nextAt) {
|
||||
const nextDate = toBerlinDate(new Date(nextAt));
|
||||
const nextDate = toZonedDate(new Date(nextAt), userTz);
|
||||
const todayStr = `${nowBerlin.getFullYear()}-${nowBerlin.getMonth()}-${nowBerlin.getDate()}`;
|
||||
const nextStr = `${nextDate.getFullYear()}-${nextDate.getMonth()}-${nextDate.getDate()}`;
|
||||
const tomorrow = new Date(nowBerlin);
|
||||
@@ -381,6 +389,7 @@ export function MedicationCard({
|
||||
// legacy schedule window (which may be stale / degenerate).
|
||||
windowStart: currentWindowStatus.window!.start,
|
||||
windowEnd: currentWindowStatus.window!.end,
|
||||
takenEarly: currentWindowStatus.takenEarly,
|
||||
}
|
||||
: null
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user