mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 06:52:04 +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
@@ -11,7 +11,11 @@
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { updateIntakeEventSchema } from "@/lib/validations/medication";
|
||||
import {
|
||||
externalIntakeSchema,
|
||||
intakeSchema,
|
||||
updateIntakeEventSchema,
|
||||
} from "@/lib/validations/medication";
|
||||
|
||||
const HOUR_MS = 60 * 60 * 1000;
|
||||
const YEAR_MS = 365 * 24 * HOUR_MS;
|
||||
@@ -74,3 +78,70 @@ describe("updateIntakeEventSchema — takenAt bounds (P0-4)", () => {
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.16.9 — the same bounds on every CREATE path. The retro-add dialog
|
||||
* posts through `intakeSchema`, the iOS sync through the bulk entry
|
||||
* shape, external integrations through `externalIntakeSchema`; none of
|
||||
* them may insert a row the edit path would refuse.
|
||||
*/
|
||||
describe("intakeSchema — takenAt bounds on create (v1.16.9)", () => {
|
||||
it("rejects a future takenAt beyond the skew allowance", () => {
|
||||
const result = intakeSchema.safeParse({
|
||||
medicationId: "med-1",
|
||||
takenAt: new Date(Date.now() + HOUR_MS).toISOString(),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toContain("future");
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a takenAt more than 5 years in the past", () => {
|
||||
const result = intakeSchema.safeParse({
|
||||
medicationId: "med-1",
|
||||
takenAt: new Date(Date.now() - 6 * YEAR_MS).toISOString(),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0]?.message).toContain("5 years");
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts a recent takenAt and a body that omits it", () => {
|
||||
expect(
|
||||
intakeSchema.safeParse({
|
||||
medicationId: "med-1",
|
||||
takenAt: new Date(Date.now() - 2 * HOUR_MS).toISOString(),
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(intakeSchema.safeParse({ medicationId: "med-1" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("externalIntakeSchema — takenAt bounds on ingest (v1.16.9)", () => {
|
||||
it("rejects future and implausibly-old instants, accepts recent ones", () => {
|
||||
const future = externalIntakeSchema.safeParse({
|
||||
medicationName: "Metformin",
|
||||
idempotencyKey: "k-1",
|
||||
takenAt: new Date(Date.now() + HOUR_MS).toISOString(),
|
||||
});
|
||||
expect(future.success).toBe(false);
|
||||
|
||||
const ancient = externalIntakeSchema.safeParse({
|
||||
medicationName: "Metformin",
|
||||
idempotencyKey: "k-2",
|
||||
takenAt: new Date(Date.now() - 6 * YEAR_MS).toISOString(),
|
||||
});
|
||||
expect(ancient.success).toBe(false);
|
||||
|
||||
const ok = externalIntakeSchema.safeParse({
|
||||
medicationName: "Metformin",
|
||||
idempotencyKey: "k-3",
|
||||
takenAt: new Date(Date.now() - HOUR_MS).toISOString(),
|
||||
});
|
||||
expect(ok.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -163,6 +163,30 @@ function hhmmToMinutes(hhmm: string): number {
|
||||
return Number(h) * 60 + Number(m);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.15.19 introduced `takenAt` plausibility bounds on the EDIT path
|
||||
* (audit P0-4); v1.16.9 lifts them onto every CREATE path too (the
|
||||
* per-medication intake POST, the bulk endpoint, the external ingest) so
|
||||
* the retro-add dialog and a hand-rolled API call can't insert a row a
|
||||
* decade in the past or hours in the future. Future allowance covers
|
||||
* client clock skew; the 5-year floor matches the GLP-1 dose-change
|
||||
* validator's window. Slot-distance / medication-start checks stay in
|
||||
* the routes — the schema cannot see the medication.
|
||||
*/
|
||||
export const TAKEN_AT_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
||||
export const TAKEN_AT_MAX_AGE_MS = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** ISO `takenAt` → `Date` with the shared plausibility bounds applied. */
|
||||
export const boundedTakenAtSchema = z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.refine((d) => d.getTime() <= Date.now() + TAKEN_AT_CLOCK_SKEW_MS, {
|
||||
message: "takenAt must not be in the future",
|
||||
})
|
||||
.refine((d) => d.getTime() >= Date.now() - TAKEN_AT_MAX_AGE_MS, {
|
||||
message: "takenAt must be within the last 5 years",
|
||||
});
|
||||
|
||||
export const scheduleSchema = z
|
||||
.object({
|
||||
windowStart: z
|
||||
@@ -598,12 +622,10 @@ export const intakeSchema = z
|
||||
.describe(
|
||||
"Slot the dose belongs to. Defaults to `takenAt` (or `now()` when both are absent) so the compliance pairing logic can pin the dose to a schedule slot.",
|
||||
),
|
||||
takenAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
takenAt: boundedTakenAtSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"When the dose was actually taken. NULL when `skipped` is true; defaults to `now()` for non-skipped intakes.",
|
||||
"When the dose was actually taken. NULL when `skipped` is true; defaults to `now()` for non-skipped intakes. Must not lie in the future (5-minute clock-skew allowance) nor more than 5 years in the past.",
|
||||
),
|
||||
skipped: z
|
||||
.boolean()
|
||||
@@ -673,10 +695,8 @@ export const intakeSchema = z
|
||||
|
||||
export const externalIntakeSchema = z.object({
|
||||
medicationName: z.string().min(1).max(200),
|
||||
takenAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.optional(),
|
||||
// v1.16.9 — same plausibility bounds as the interactive create paths.
|
||||
takenAt: boundedTakenAtSchema.optional(),
|
||||
idempotencyKey: z.string().max(128),
|
||||
});
|
||||
|
||||
@@ -718,22 +738,9 @@ export const listIntakeEventsSchema = z.object({
|
||||
* checks stay out of the schema — it cannot see the medication — and live
|
||||
* in the route (start-date guard) + the edit dialog (non-blocking hint).
|
||||
*/
|
||||
const TAKEN_AT_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
||||
const TAKEN_AT_MAX_AGE_MS = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export const updateIntakeEventSchema = z
|
||||
.object({
|
||||
takenAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.refine((d) => d.getTime() <= Date.now() + TAKEN_AT_CLOCK_SKEW_MS, {
|
||||
message: "takenAt must not be in the future",
|
||||
})
|
||||
.refine((d) => d.getTime() >= Date.now() - TAKEN_AT_MAX_AGE_MS, {
|
||||
message: "takenAt must be within the last 5 years",
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
takenAt: boundedTakenAtSchema.nullable().optional(),
|
||||
skipped: z.boolean().optional(),
|
||||
scheduledFor: z.iso
|
||||
.datetime({ offset: true })
|
||||
|
||||
Reference in new issue
Block a user