mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Let a checkup be skipped or pushed back, and remember every outcome
Refs #223. A due Vorsorge item could only be done, deleted or ignored; Telegram's postpone moved the date with no trace. Both decisions are first-class now, and both are honest: - POST /{id}/skip (no body): the interval restarts from the skip instant through the recurrence engine, lastSkippedAt is stamped, skipCount increments, any snooze clears. lastSatisfiedAt is NEVER touched — done and skipped stay distinguishable forever, enforced in the primitive and pinned by tests. - POST /{id}/snooze ({until: YYYY-MM-DD}): the server resolves the day to the notifyHour in the profile timezone and moves snoozedUntil and nextDueAt to the same instant, so every due-state consumer follows without knowing snooze exists. At least tomorrow, at most five years. - GET /{id}/history: the new append-only completion ledger (MeasurementReminderEvent), one row per satisfy from every engine path and per skip, onTime derived at write time against the due instant that was current when the event landed. Two anchor fixes close the backdated-event gaps: the auto-resolve floor is now the later of last satisfy and last skip (an old reading synced late no longer resolves the cycle the user just skipped), and a backdated real result re-anchors the next due at the later of its own instant and the skip decision. Screenings stay skippable and snoozable — the satisfy-side 409 guards claimed fulfilment; a skip claims the opposite. Appointment reminders 404 on all three routes, in the lookup, like every by-id sibling. /checkups gains the postpone sheet (quick chips, date field, the skip zone with its own confirm) in both view branches, with muted meta lines and no card colour change. The MCP preventive-care tool carries the resolved fields; the OpenAPI contract publishes all three paths and the widened DTO.
This commit is contained in:
1 parent
cd12b3886e
commit
5619783648
35 files changed
+3715
-115
No files matched your search
@@ -341,7 +341,9 @@ export async function resolveClosableReminder(
|
||||
rrule: true,
|
||||
anchorDate: true,
|
||||
notifyHour: true,
|
||||
nextDueAt: true,
|
||||
lastSatisfiedAt: true,
|
||||
lastSkippedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
@@ -349,11 +351,14 @@ export async function resolveClosableReminder(
|
||||
if (row.origin === "ENCOUNTER") return undefined;
|
||||
return {
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
intervalDays: row.intervalDays,
|
||||
rrule: row.rrule,
|
||||
anchorDate: row.anchorDate,
|
||||
notifyHour: row.notifyHour,
|
||||
nextDueAt: row.nextDueAt,
|
||||
lastSatisfiedAt: row.lastSatisfiedAt,
|
||||
lastSkippedAt: row.lastSkippedAt,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -399,6 +404,7 @@ export async function closeCheckupForVisit(
|
||||
reminder,
|
||||
timezone,
|
||||
satisfiedAt,
|
||||
"encounter",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -271,6 +271,9 @@ export async function runMeasurementReminderTick(
|
||||
reminder,
|
||||
timezone,
|
||||
satisfiedAt,
|
||||
// Which arm of `findSatisfyingEvent` matched: a typed reminder
|
||||
// resolves from a Measurement, a free-text one from a LabResult.
|
||||
reminder.measurementType !== null ? "auto_measurement" : "auto_lab",
|
||||
);
|
||||
if (result.satisfied) {
|
||||
summary.autoResolved += 1;
|
||||
@@ -491,6 +494,7 @@ export async function runReminderSatisfyForUser(
|
||||
reminder,
|
||||
timezone,
|
||||
satisfiedAt,
|
||||
reminder.measurementType !== null ? "auto_measurement" : "auto_lab",
|
||||
);
|
||||
if (result.satisfied) {
|
||||
summary.satisfied += 1;
|
||||
|
||||
@@ -684,6 +684,9 @@ describe("get_preventive_care", () => {
|
||||
location: null,
|
||||
nextDueAt: "2000-01-01T00:00:00.000Z",
|
||||
lastSatisfiedAt: null,
|
||||
snoozedUntil: null,
|
||||
lastSkippedAt: null,
|
||||
skipCount: 0,
|
||||
enabled: true,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -735,6 +738,9 @@ describe("get_preventive_care", () => {
|
||||
location: "Praxis <<<USER_TEXT_START>>>Dr. Example",
|
||||
nextDueAt: null,
|
||||
lastSatisfiedAt: null,
|
||||
snoozedUntil: null,
|
||||
lastSkippedAt: null,
|
||||
skipCount: 0,
|
||||
enabled: true,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -796,6 +802,9 @@ describe("get_preventive_care", () => {
|
||||
location: null,
|
||||
nextDueAt,
|
||||
lastSatisfiedAt: null,
|
||||
snoozedUntil: null,
|
||||
lastSkippedAt: null,
|
||||
skipCount: 0,
|
||||
enabled: true,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
|
||||
@@ -895,6 +895,13 @@ const getPreventiveCareOutput: z.ZodRawShape = {
|
||||
overdue: z.boolean(),
|
||||
location: z.string().nullable(),
|
||||
lastSatisfiedAt: z.string().nullable(),
|
||||
// v1.37.20 (#223) — resolved skip/snooze state. Without these the
|
||||
// model sees a due date jump with no cause and invents one.
|
||||
// `lastSatisfiedAt` stays the ONLY completed signal: a skip is
|
||||
// recorded as a skip, never as done.
|
||||
snoozedUntil: z.string().nullable(),
|
||||
lastSkippedAt: z.string().nullable(),
|
||||
skipCount: z.number(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
@@ -1714,6 +1721,10 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
: false,
|
||||
location: dto.location !== null ? fenceUserText(dto.location) : null,
|
||||
lastSatisfiedAt: dto.lastSatisfiedAt,
|
||||
// Timestamps + a counter, no free text — nothing to fence here.
|
||||
snoozedUntil: dto.snoozedUntil,
|
||||
lastSkippedAt: dto.lastSkippedAt,
|
||||
skipCount: dto.skipCount,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ const base = {
|
||||
measurementType: null,
|
||||
anchorDate: null,
|
||||
lastSatisfiedAt: null,
|
||||
lastSkippedAt: null,
|
||||
createdAt: new Date("2026-06-01T00:00:00Z"),
|
||||
} as const;
|
||||
|
||||
@@ -46,6 +47,63 @@ describe("satisfactionFloor", () => {
|
||||
expect(satisfactionFloor({ ...base, anchorDate: anchor })).toEqual(anchor);
|
||||
expect(satisfactionFloor(base)).toEqual(base.createdAt);
|
||||
});
|
||||
|
||||
// v1.37.20 (#223) — the skip arm of the floor. Watched red: with the old
|
||||
// `lastSatisfiedAt ?? anchorDate ?? createdAt` floor both assertions below
|
||||
// failed (the fresh skip was invisible and a backdated reading resolved
|
||||
// the cycle the user had just skipped).
|
||||
it("takes the LATER of lastSatisfiedAt and lastSkippedAt", () => {
|
||||
const satisfied = new Date("2026-06-10T00:00:00Z");
|
||||
const skipped = new Date("2026-06-20T00:00:00Z");
|
||||
expect(
|
||||
satisfactionFloor({
|
||||
...base,
|
||||
lastSatisfiedAt: satisfied,
|
||||
lastSkippedAt: skipped,
|
||||
}),
|
||||
).toEqual(skipped);
|
||||
// And symmetric — a satisfy after the skip wins again.
|
||||
expect(
|
||||
satisfactionFloor({
|
||||
...base,
|
||||
lastSatisfiedAt: skipped,
|
||||
lastSkippedAt: satisfied,
|
||||
}),
|
||||
).toEqual(skipped);
|
||||
});
|
||||
|
||||
it("uses a lone lastSkippedAt as the floor before anchor/created fall backs", () => {
|
||||
const skipped = new Date("2026-06-20T00:00:00Z");
|
||||
const anchor = new Date("2026-06-05T00:00:00Z");
|
||||
expect(
|
||||
satisfactionFloor({
|
||||
...base,
|
||||
lastSkippedAt: skipped,
|
||||
anchorDate: anchor,
|
||||
}),
|
||||
).toEqual(skipped);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findSatisfyingEvent after a skip", () => {
|
||||
it("does not resolve the fresh skip cycle from a reading older than the skip", async () => {
|
||||
// A backdated sync (an old reading arriving late) predates the skip the
|
||||
// user just made. The floor must sit AT the skip, so the query asks for
|
||||
// events strictly after it — the stale reading cannot match.
|
||||
const skipped = new Date("2026-06-20T00:00:00Z");
|
||||
const prisma = makePrisma({ measurement: null });
|
||||
|
||||
await findSatisfyingEvent(prisma as never, "u1", {
|
||||
...base,
|
||||
measurementType: "WEIGHT",
|
||||
lastSkippedAt: skipped,
|
||||
});
|
||||
|
||||
const where = prisma.measurement.findFirst.mock.calls[0]![0].where as {
|
||||
measuredAt: { gt: Date };
|
||||
};
|
||||
expect(where.measuredAt.gt).toEqual(skipped);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findSatisfyingEvent", () => {
|
||||
|
||||
@@ -3,10 +3,17 @@
|
||||
* re-anchored reschedule. The cron, the manual satisfy route, and the
|
||||
* eventful worker all route through it, so these tests pin the invariants
|
||||
* every caller relies on.
|
||||
*
|
||||
* v1.37.20 (#223) — extended for the skip/snooze feature: the ledger append
|
||||
* (iOS #68), the skip-aware satisfy anchor, snooze clearing, and the
|
||||
* `skipReminder` primitive with its hard invariant (`lastSatisfiedAt` is
|
||||
* never touched by a skip). Watched red: the pre-#223 suite went red on the
|
||||
* widened `SatisfiableReminder` shape and the new `source` argument before
|
||||
* this file was updated — proof the type system walks every caller.
|
||||
*/
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { satisfyReminder } from "../satisfy";
|
||||
import { satisfyReminder, skipReminder } from "../satisfy";
|
||||
|
||||
const TZ = "Europe/Berlin";
|
||||
|
||||
@@ -15,12 +22,13 @@ function makePrisma(updateManyCount = 1) {
|
||||
where: Record<string, unknown>;
|
||||
data: Record<string, unknown>;
|
||||
}> = [];
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const prisma = {
|
||||
measurementReminder: {
|
||||
// v1.18.1 — `satisfyReminder` now writes via a conditional
|
||||
// `updateMany` so the forward-only guard re-asserts at the DB row
|
||||
// (close the cron-vs-worker TOCTOU). `updateManyCount` simulates a
|
||||
// racing writer having already advanced the row (count === 0).
|
||||
// v1.18.1 — `satisfyReminder` writes via a conditional `updateMany` so
|
||||
// the forward-only guard re-asserts at the DB row (close the
|
||||
// cron-vs-worker TOCTOU). `updateManyCount` simulates a racing writer
|
||||
// having already advanced the row (count === 0).
|
||||
updateMany: vi.fn(
|
||||
async ({
|
||||
where,
|
||||
@@ -34,8 +42,14 @@ function makePrisma(updateManyCount = 1) {
|
||||
},
|
||||
),
|
||||
},
|
||||
measurementReminderEvent: {
|
||||
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
|
||||
events.push(data);
|
||||
return { id: "evt", ...data };
|
||||
}),
|
||||
},
|
||||
};
|
||||
return { prisma, updates };
|
||||
return { prisma, updates, events };
|
||||
}
|
||||
|
||||
function reminder(
|
||||
@@ -43,11 +57,14 @@ function reminder(
|
||||
) {
|
||||
return {
|
||||
id: "r1",
|
||||
userId: "u1",
|
||||
intervalDays: 7,
|
||||
rrule: null,
|
||||
anchorDate: null,
|
||||
notifyHour: 9,
|
||||
nextDueAt: null,
|
||||
lastSatisfiedAt: null,
|
||||
lastSkippedAt: null,
|
||||
createdAt: new Date("2026-06-01T00:00:00Z"),
|
||||
...overrides,
|
||||
};
|
||||
@@ -58,7 +75,13 @@ describe("satisfyReminder", () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await satisfyReminder(prisma as never, reminder(), TZ, at);
|
||||
const result = await satisfyReminder(
|
||||
prisma as never,
|
||||
reminder(),
|
||||
TZ,
|
||||
at,
|
||||
"manual",
|
||||
);
|
||||
|
||||
expect(result.satisfied).toBe(true);
|
||||
expect(result.nextDueAt).toBeInstanceOf(Date);
|
||||
@@ -74,7 +97,7 @@ describe("satisfyReminder", () => {
|
||||
const { prisma } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
await satisfyReminder(prisma as never, reminder(), TZ, at);
|
||||
await satisfyReminder(prisma as never, reminder(), TZ, at, "manual");
|
||||
|
||||
const call = prisma.measurementReminder.updateMany.mock
|
||||
.calls[0][0] as unknown as {
|
||||
@@ -88,15 +111,23 @@ describe("satisfyReminder", () => {
|
||||
});
|
||||
|
||||
it("treats a racing-writer updateMany count of 0 as a forward-only no-op", async () => {
|
||||
const { prisma } = makePrisma(0);
|
||||
const { prisma, events } = makePrisma(0);
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await satisfyReminder(prisma as never, reminder(), TZ, at);
|
||||
const result = await satisfyReminder(
|
||||
prisma as never,
|
||||
reminder(),
|
||||
TZ,
|
||||
at,
|
||||
"manual",
|
||||
);
|
||||
|
||||
// The in-memory guard passed (lastSatisfiedAt null) but the DB write
|
||||
// matched no row — a concurrent satisfy already advanced it. No-op.
|
||||
// matched no row — a concurrent satisfy already advanced it. No-op, and
|
||||
// crucially NO ledger row: an unapplied satisfy must leave no history.
|
||||
expect(result.satisfied).toBe(false);
|
||||
expect(result.nextDueAt).toBeNull();
|
||||
expect(events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("advances when the event is strictly after the existing lastSatisfiedAt", async () => {
|
||||
@@ -109,6 +140,7 @@ describe("satisfyReminder", () => {
|
||||
reminder({ lastSatisfiedAt: prev }),
|
||||
TZ,
|
||||
at,
|
||||
"manual",
|
||||
);
|
||||
|
||||
expect(result.satisfied).toBe(true);
|
||||
@@ -125,6 +157,7 @@ describe("satisfyReminder", () => {
|
||||
reminder({ lastSatisfiedAt: prev }),
|
||||
TZ,
|
||||
stale,
|
||||
"manual",
|
||||
);
|
||||
|
||||
expect(result.satisfied).toBe(false);
|
||||
@@ -142,9 +175,198 @@ describe("satisfyReminder", () => {
|
||||
reminder({ lastSatisfiedAt: same }),
|
||||
TZ,
|
||||
same,
|
||||
"manual",
|
||||
);
|
||||
|
||||
expect(result.satisfied).toBe(false);
|
||||
expect(prisma.measurementReminder.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the snooze cursor on satisfy", async () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
await satisfyReminder(prisma as never, reminder(), TZ, at, "manual");
|
||||
|
||||
expect(updates[0].data.snoozedUntil).toBeNull();
|
||||
});
|
||||
|
||||
it("appends a SATISFIED ledger row with write-time onTime (on time)", async () => {
|
||||
const { prisma, events } = makePrisma();
|
||||
const due = new Date("2026-06-15T07:00:00Z");
|
||||
const at = new Date("2026-06-14T18:00:00Z"); // before due → on time
|
||||
|
||||
await satisfyReminder(
|
||||
prisma as never,
|
||||
reminder({ nextDueAt: due }),
|
||||
TZ,
|
||||
at,
|
||||
"auto_measurement",
|
||||
);
|
||||
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
userId: "u1",
|
||||
reminderId: "r1",
|
||||
kind: "SATISFIED",
|
||||
occurredAt: at,
|
||||
onTime: true,
|
||||
source: "auto_measurement",
|
||||
});
|
||||
});
|
||||
|
||||
it("derives onTime=false when the event lands after the pre-event due instant", async () => {
|
||||
const { prisma, events } = makePrisma();
|
||||
const due = new Date("2026-06-10T07:00:00Z");
|
||||
const late = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
await satisfyReminder(
|
||||
prisma as never,
|
||||
reminder({ nextDueAt: due }),
|
||||
TZ,
|
||||
late,
|
||||
"manual",
|
||||
);
|
||||
|
||||
expect(events[0].onTime).toBe(false);
|
||||
});
|
||||
|
||||
it("never lets a backdated satisfy re-anchor behind a fresh skip (max anchor)", async () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const skippedAt = new Date("2026-06-20T10:00:00Z");
|
||||
const backdated = new Date("2026-06-14T18:00:00Z"); // real event, older sync
|
||||
|
||||
const result = await satisfyReminder(
|
||||
prisma as never,
|
||||
reminder({ lastSkippedAt: skippedAt }),
|
||||
TZ,
|
||||
backdated,
|
||||
"auto_measurement",
|
||||
);
|
||||
|
||||
// The event is honestly recorded as lastSatisfiedAt …
|
||||
expect(result.satisfied).toBe(true);
|
||||
expect(updates[0].data.lastSatisfiedAt).toEqual(backdated);
|
||||
// … but the reschedule anchors on the LATER skip: next due lands a full
|
||||
// interval after the skip decision, never behind it.
|
||||
expect((updates[0].data.nextDueAt as Date).getTime()).toBeGreaterThan(
|
||||
skippedAt.getTime(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("skipReminder", () => {
|
||||
it("stamps lastSkippedAt, increments skipCount, clears snooze — and never touches lastSatisfiedAt", async () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await skipReminder(prisma as never, reminder(), TZ, at);
|
||||
|
||||
expect(result.skipped).toBe(true);
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(updates[0].data.lastSkippedAt).toEqual(at);
|
||||
expect(updates[0].data.skipCount).toEqual({ increment: 1 });
|
||||
expect(updates[0].data.snoozedUntil).toBeNull();
|
||||
// THE hard invariant of the whole feature: a skip is not a completion.
|
||||
expect("lastSatisfiedAt" in updates[0].data).toBe(false);
|
||||
});
|
||||
|
||||
it("restarts a rolling interval from the skip instant", async () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await skipReminder(prisma as never, reminder(), TZ, at);
|
||||
|
||||
// +7d at the 09:00 notify hour, strictly after the skip.
|
||||
expect(result.nextDueAt).toBeInstanceOf(Date);
|
||||
expect((updates[0].data.nextDueAt as Date).getTime()).toBeGreaterThan(
|
||||
at.getTime() + 6 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
});
|
||||
|
||||
it("walks an rrule cadence to the next occurrence strictly after the skip", async () => {
|
||||
const { prisma, updates } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await skipReminder(
|
||||
prisma as never,
|
||||
reminder({ intervalDays: null, rrule: "FREQ=YEARLY" }),
|
||||
TZ,
|
||||
at,
|
||||
);
|
||||
|
||||
expect(result.skipped).toBe(true);
|
||||
expect((updates[0].data.nextDueAt as Date).getTime()).toBeGreaterThan(
|
||||
at.getTime(),
|
||||
);
|
||||
});
|
||||
|
||||
it("is a forward-only no-op at or behind the last satisfy OR the last skip", async () => {
|
||||
const { prisma, events } = makePrisma();
|
||||
const cursor = new Date("2026-06-17T08:00:00Z");
|
||||
const stale = new Date("2026-06-10T08:00:00Z");
|
||||
|
||||
const bySatisfy = await skipReminder(
|
||||
prisma as never,
|
||||
reminder({ lastSatisfiedAt: cursor }),
|
||||
TZ,
|
||||
stale,
|
||||
);
|
||||
const bySkip = await skipReminder(
|
||||
prisma as never,
|
||||
reminder({ lastSkippedAt: cursor }),
|
||||
TZ,
|
||||
stale,
|
||||
);
|
||||
|
||||
expect(bySatisfy.skipped).toBe(false);
|
||||
expect(bySkip.skipped).toBe(false);
|
||||
expect(prisma.measurementReminder.updateMany).not.toHaveBeenCalled();
|
||||
expect(events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("re-asserts forward-only against BOTH cursors in the conditional updateMany", async () => {
|
||||
const { prisma } = makePrisma();
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
await skipReminder(prisma as never, reminder(), TZ, at);
|
||||
|
||||
const call = prisma.measurementReminder.updateMany.mock
|
||||
.calls[0][0] as unknown as {
|
||||
where: { id: string; AND: unknown[] };
|
||||
};
|
||||
expect(call.where.id).toBe("r1");
|
||||
expect(call.where.AND).toEqual([
|
||||
{ OR: [{ lastSatisfiedAt: null }, { lastSatisfiedAt: { lt: at } }] },
|
||||
{ OR: [{ lastSkippedAt: null }, { lastSkippedAt: { lt: at } }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats a racing-writer updateMany count of 0 as a no-op with no ledger row", async () => {
|
||||
const { prisma, events } = makePrisma(0);
|
||||
const at = new Date("2026-06-14T18:00:00Z");
|
||||
|
||||
const result = await skipReminder(prisma as never, reminder(), TZ, at);
|
||||
|
||||
expect(result.skipped).toBe(false);
|
||||
expect(events).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("appends a SKIPPED ledger row with source 'skip' and write-time onTime", async () => {
|
||||
const { prisma, events } = makePrisma();
|
||||
const due = new Date("2026-06-10T07:00:00Z");
|
||||
const at = new Date("2026-06-14T18:00:00Z"); // skipping while overdue
|
||||
|
||||
await skipReminder(prisma as never, reminder({ nextDueAt: due }), TZ, at);
|
||||
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
userId: "u1",
|
||||
reminderId: "r1",
|
||||
kind: "SKIPPED",
|
||||
occurredAt: at,
|
||||
onTime: false,
|
||||
source: "skip",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,16 @@ export interface MeasurementReminderDtoShape {
|
||||
location: string | null;
|
||||
nextDueAt: string | null;
|
||||
lastSatisfiedAt: string | null;
|
||||
/**
|
||||
* v1.37.20 (#223) — the three skip/snooze fields are resolved timestamps
|
||||
* plus a counter; clients only ever compare against the clock (snoozed =
|
||||
* `snoozedUntil > now`; skipped cycle = `lastSkippedAt > lastSatisfiedAt`)
|
||||
* and never recompute cadence. `lastSatisfiedAt` stays the ONLY completed
|
||||
* signal — skip and snooze never move it.
|
||||
*/
|
||||
snoozedUntil: string | null;
|
||||
lastSkippedAt: string | null;
|
||||
skipCount: number;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -85,6 +95,9 @@ export function toMeasurementReminderDto(
|
||||
lastSatisfiedAt: row.lastSatisfiedAt
|
||||
? row.lastSatisfiedAt.toISOString()
|
||||
: null,
|
||||
snoozedUntil: row.snoozedUntil ? row.snoozedUntil.toISOString() : null,
|
||||
lastSkippedAt: row.lastSkippedAt ? row.lastSkippedAt.toISOString() : null,
|
||||
skipCount: row.skipCount,
|
||||
enabled: row.enabled,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
|
||||
@@ -26,6 +26,13 @@ export interface ResolvableReminder {
|
||||
measurementType: import("@/generated/prisma/client").MeasurementType | null;
|
||||
anchorDate: Date | null;
|
||||
lastSatisfiedAt: Date | null;
|
||||
/**
|
||||
* v1.37.20 (#223) — the last honest skip. Part of the floor: a reading
|
||||
* OLDER than a fresh skip must not auto-resolve the cycle the user just
|
||||
* skipped. Required (not optional) so no call site can silently feed a
|
||||
* pre-skip shape and reopen the gap.
|
||||
*/
|
||||
lastSkippedAt: Date | null;
|
||||
createdAt: Date;
|
||||
/**
|
||||
* Optional so the many callers that construct this shape by hand keep
|
||||
@@ -36,12 +43,26 @@ export interface ResolvableReminder {
|
||||
}
|
||||
|
||||
/**
|
||||
* The floor a satisfying event must land strictly after: the last satisfy,
|
||||
* else the anchor, else the create instant. A reading inside the current
|
||||
* due cycle means the user already measured.
|
||||
* The floor a satisfying event must land strictly after: the later of the
|
||||
* last satisfy and the last skip, else the anchor, else the create instant.
|
||||
* A reading inside the current due cycle means the user already measured.
|
||||
*
|
||||
* v1.37.20 (#223) — the skip arm: skipping restarts the cycle at the skip
|
||||
* instant, so a reading that predates the skip belongs to the cycle the
|
||||
* user deliberately let go and must not resolve the fresh one. Without it
|
||||
* a backdated sync would silently undo the skip decision.
|
||||
*/
|
||||
export function satisfactionFloor(reminder: ResolvableReminder): Date {
|
||||
return reminder.lastSatisfiedAt ?? reminder.anchorDate ?? reminder.createdAt;
|
||||
const cursor =
|
||||
reminder.lastSatisfiedAt !== null || reminder.lastSkippedAt !== null
|
||||
? new Date(
|
||||
Math.max(
|
||||
reminder.lastSatisfiedAt?.getTime() ?? 0,
|
||||
reminder.lastSkippedAt?.getTime() ?? 0,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
return cursor ?? reminder.anchorDate ?? reminder.createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,21 +8,30 @@
|
||||
* reschedule logic — one place stamps `lastSatisfiedAt` and recomputes the
|
||||
* server-authoritative `nextDueAt`.
|
||||
*
|
||||
* Two invariants the primitive owns:
|
||||
* Invariants the primitive owns:
|
||||
*
|
||||
* 1. **Forward-only.** `lastSatisfiedAt` only ever moves forward. A
|
||||
* cron poll and an ingest enqueue can both fire for the same reading;
|
||||
* the second is a no-op (returns `false`) rather than re-stamping an
|
||||
* older instant. This is what makes the cron a safe idempotent
|
||||
* safety-net behind the eventful hook.
|
||||
* 2. **Re-anchored reschedule.** `nextDueAt` is recomputed from the
|
||||
* satisfy instant via the canonical recurrence engine
|
||||
* (`computeReminderNextDueAt`), so a freshly-satisfied reminder rolls
|
||||
* strictly past the current due cycle and the self-tracker never gets
|
||||
* nagged.
|
||||
* 2. **Re-anchored reschedule.** `nextDueAt` is recomputed via the
|
||||
* canonical recurrence engine (`computeReminderNextDueAt`) from
|
||||
* `max(satisfiedAt, lastSkippedAt)` — the satisfy instant, unless the
|
||||
* user has since skipped, in which case a BACKDATED real result is
|
||||
* recorded as `lastSatisfiedAt` but never drags the due date back
|
||||
* behind the skip decision (v1.37.20, #223).
|
||||
* 3. **Ledger append.** A successful satisfy appends one
|
||||
* `MeasurementReminderEvent` row (iOS #68) with `onTime` derived at
|
||||
* write time against the pre-event `nextDueAt` — the only moment that
|
||||
* value still exists.
|
||||
* 4. **Snooze clearing.** A satisfy recomputes `nextDueAt`, so it nulls
|
||||
* `snoozedUntil` — the snooze cursor never outlives the cycle it
|
||||
* pushed back.
|
||||
*
|
||||
* Pure-ish: it reads the row fields it is handed and issues one Prisma
|
||||
* update. The caller supplies the reminder row + the user's timezone.
|
||||
* Pure-ish: it reads the row fields it is handed and issues one conditional
|
||||
* update plus one ledger insert. The caller supplies the reminder row, the
|
||||
* user's timezone, and which engine path it is (`source`).
|
||||
*/
|
||||
import type { PrismaClient } from "@/generated/prisma/client";
|
||||
import {
|
||||
@@ -30,17 +39,43 @@ import {
|
||||
type ReminderScheduleInput,
|
||||
} from "@/lib/measurement-reminders/scheduling";
|
||||
|
||||
/**
|
||||
* Which engine path produced a ledger event. Closed set — the ledger's
|
||||
* `source` column is asserted here, not free text.
|
||||
*
|
||||
* Declared as a runtime tuple as well as a type (v1.37.20, #223 / iOS #68):
|
||||
* the backup payload schema validates the `source` a restore is handed
|
||||
* against this exact set, and a Zod enum needs the values at runtime. One
|
||||
* declaration, so the validator cannot drift from the engine.
|
||||
*/
|
||||
export const REMINDER_EVENT_SOURCES = [
|
||||
"manual",
|
||||
"auto_measurement",
|
||||
"auto_lab",
|
||||
"telegram",
|
||||
"vaccination",
|
||||
"encounter",
|
||||
"skip",
|
||||
] as const;
|
||||
|
||||
export type ReminderEventSource = (typeof REMINDER_EVENT_SOURCES)[number];
|
||||
|
||||
/**
|
||||
* The reminder fields `satisfyReminder` needs. A subset of the Prisma row
|
||||
* so callers (and tests) can construct it without the full model.
|
||||
* `userId` and the pre-event `nextDueAt` feed the ledger append;
|
||||
* `lastSkippedAt` feeds the skip-aware re-anchor.
|
||||
*/
|
||||
export interface SatisfiableReminder {
|
||||
id: string;
|
||||
userId: string;
|
||||
intervalDays: number | null;
|
||||
rrule: string | null;
|
||||
anchorDate: Date | null;
|
||||
notifyHour: number;
|
||||
nextDueAt: Date | null;
|
||||
lastSatisfiedAt: Date | null;
|
||||
lastSkippedAt: Date | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
@@ -53,20 +88,40 @@ export interface SatisfyResult {
|
||||
nextDueAt: Date | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `onTime` is derived at write time, against the reminder's `nextDueAt` as
|
||||
* it stood BEFORE this event re-anchored it: the event landed at or before
|
||||
* the due instant, or the cadence had no computable due (a one-shot whose
|
||||
* slot already fired counts as late only while a due instant exists to be
|
||||
* late against). After the write the pre-event value is gone, which is why
|
||||
* clients consume this resolved boolean and never re-derive it.
|
||||
*/
|
||||
function deriveOnTime(preEventNextDueAt: Date | null, occurredAt: Date) {
|
||||
return (
|
||||
preEventNextDueAt === null ||
|
||||
occurredAt.getTime() <= preEventNextDueAt.getTime()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a reminder's cadence satisfied at `satisfiedAt` and reschedule.
|
||||
*
|
||||
* Forward-only: if `satisfiedAt` is not strictly after the existing
|
||||
* `lastSatisfiedAt`, nothing is written and `{ satisfied: false }` is
|
||||
* returned. Otherwise stamps `lastSatisfiedAt = satisfiedAt`, recomputes
|
||||
* `nextDueAt` from the satisfy instant, persists both, and returns
|
||||
* `nextDueAt` anchored at `max(satisfiedAt, lastSkippedAt)`, clears any
|
||||
* snooze, appends the SATISFIED ledger row, and returns
|
||||
* `{ satisfied: true, nextDueAt }`.
|
||||
*
|
||||
* HARD INVARIANT (the mirror of the skip primitive's): only a satisfy ever
|
||||
* writes `lastSatisfiedAt`. Skip and snooze never touch it.
|
||||
*/
|
||||
export async function satisfyReminder(
|
||||
prisma: PrismaClient,
|
||||
reminder: SatisfiableReminder,
|
||||
timezone: string,
|
||||
satisfiedAt: Date,
|
||||
source: Exclude<ReminderEventSource, "skip">,
|
||||
): Promise<SatisfyResult> {
|
||||
// Forward-only guard. A null `lastSatisfiedAt` always advances. Equal
|
||||
// instants are a no-op so a cron poll behind an already-applied ingest
|
||||
@@ -78,19 +133,26 @@ export async function satisfyReminder(
|
||||
return { satisfied: false, nextDueAt: null };
|
||||
}
|
||||
|
||||
// v1.37.20 (#223) — skip-aware anchor: a backdated real result (an old
|
||||
// reading synced late, a corrected visit date) is honestly recorded as
|
||||
// `lastSatisfiedAt`, but the NEXT due date never lands behind a skip the
|
||||
// user made after that event. Without the max() a fresh skip's re-anchor
|
||||
// would be silently undone by any older reading arriving afterwards.
|
||||
const anchorAt =
|
||||
reminder.lastSkippedAt !== null &&
|
||||
reminder.lastSkippedAt.getTime() > satisfiedAt.getTime()
|
||||
? reminder.lastSkippedAt
|
||||
: satisfiedAt;
|
||||
|
||||
const scheduleInput: ReminderScheduleInput = {
|
||||
intervalDays: reminder.intervalDays,
|
||||
rrule: reminder.rrule,
|
||||
anchorDate: reminder.anchorDate,
|
||||
notifyHour: reminder.notifyHour,
|
||||
lastSatisfiedAt: satisfiedAt,
|
||||
lastSatisfiedAt: anchorAt,
|
||||
createdAt: reminder.createdAt,
|
||||
};
|
||||
const nextDueAt = computeReminderNextDueAt(
|
||||
scheduleInput,
|
||||
timezone,
|
||||
satisfiedAt,
|
||||
);
|
||||
const nextDueAt = computeReminderNextDueAt(scheduleInput, timezone, anchorAt);
|
||||
|
||||
// v1.18.1 — close the forward-only TOCTOU: the in-memory guard above can
|
||||
// pass concurrently in the cron poll AND the eventful worker for the same
|
||||
@@ -104,11 +166,123 @@ export async function satisfyReminder(
|
||||
id: reminder.id,
|
||||
OR: [{ lastSatisfiedAt: null }, { lastSatisfiedAt: { lt: satisfiedAt } }],
|
||||
},
|
||||
data: { lastSatisfiedAt: satisfiedAt, nextDueAt },
|
||||
// A recompute of `nextDueAt` clears the snooze cursor — the real event
|
||||
// ended the cycle the snooze was pushing back.
|
||||
data: { lastSatisfiedAt: satisfiedAt, nextDueAt, snoozedUntil: null },
|
||||
});
|
||||
if (result.count === 0) {
|
||||
return { satisfied: false, nextDueAt: null };
|
||||
}
|
||||
|
||||
// Ledger append (iOS #68): exactly one row per applied satisfy, from
|
||||
// every path, because every path is this primitive. Written after the
|
||||
// conditional update so a forward-only no-op leaves no row.
|
||||
await prisma.measurementReminderEvent.create({
|
||||
data: {
|
||||
userId: reminder.userId,
|
||||
reminderId: reminder.id,
|
||||
kind: "SATISFIED",
|
||||
occurredAt: satisfiedAt,
|
||||
onTime: deriveOnTime(reminder.nextDueAt, satisfiedAt),
|
||||
source,
|
||||
},
|
||||
});
|
||||
|
||||
return { satisfied: true, nextDueAt };
|
||||
}
|
||||
|
||||
export interface SkipResult {
|
||||
/** True when the skip applied; false when it was a forward-only no-op
|
||||
* (the row already advanced past the skip instant). */
|
||||
skipped: boolean;
|
||||
/** The recomputed next-due instant when skipped, else `null`. */
|
||||
nextDueAt: Date | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.37.20 (#223) — honestly skip the current due cycle at `skippedAt`
|
||||
* (always the server clock; the route takes no body).
|
||||
*
|
||||
* The interval restarts from the skip instant: `nextDueAt` is recomputed
|
||||
* with the skip standing in as the rolling anchor (an rrule cadence walks
|
||||
* to its next occurrence strictly after the skip). `lastSkippedAt` is
|
||||
* stamped, `skipCount` incremented, any snooze cleared.
|
||||
*
|
||||
* HARD INVARIANT: `lastSatisfiedAt` is NEVER touched here. A skip is not a
|
||||
* completion — the ledger records it as `SKIPPED` and every surface that
|
||||
* shows "last done" keeps showing the last real result.
|
||||
*
|
||||
* Forward-only against BOTH cursors: a skip at/behind the last satisfy or
|
||||
* the last skip is a no-op, enforced in the conditional `updateMany` (the
|
||||
* same TOCTOU pattern `satisfyReminder` uses).
|
||||
*/
|
||||
export async function skipReminder(
|
||||
prisma: PrismaClient,
|
||||
reminder: SatisfiableReminder,
|
||||
timezone: string,
|
||||
skippedAt: Date,
|
||||
): Promise<SkipResult> {
|
||||
const floor = Math.max(
|
||||
reminder.lastSatisfiedAt?.getTime() ?? 0,
|
||||
reminder.lastSkippedAt?.getTime() ?? 0,
|
||||
);
|
||||
if (floor > 0 && skippedAt.getTime() <= floor) {
|
||||
return { skipped: false, nextDueAt: null };
|
||||
}
|
||||
|
||||
// The skip stands in as the rolling anchor: skip + interval at the notify
|
||||
// hour, or the next rrule occurrence strictly after the skip.
|
||||
const scheduleInput: ReminderScheduleInput = {
|
||||
intervalDays: reminder.intervalDays,
|
||||
rrule: reminder.rrule,
|
||||
anchorDate: reminder.anchorDate,
|
||||
notifyHour: reminder.notifyHour,
|
||||
lastSatisfiedAt: skippedAt,
|
||||
createdAt: reminder.createdAt,
|
||||
};
|
||||
const nextDueAt = computeReminderNextDueAt(
|
||||
scheduleInput,
|
||||
timezone,
|
||||
skippedAt,
|
||||
);
|
||||
|
||||
const result = await prisma.measurementReminder.updateMany({
|
||||
where: {
|
||||
id: reminder.id,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ lastSatisfiedAt: null },
|
||||
{ lastSatisfiedAt: { lt: skippedAt } },
|
||||
],
|
||||
},
|
||||
{
|
||||
OR: [{ lastSkippedAt: null }, { lastSkippedAt: { lt: skippedAt } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
// `lastSatisfiedAt` is conspicuously absent — see the invariant above.
|
||||
data: {
|
||||
lastSkippedAt: skippedAt,
|
||||
skipCount: { increment: 1 },
|
||||
snoozedUntil: null,
|
||||
nextDueAt,
|
||||
},
|
||||
});
|
||||
if (result.count === 0) {
|
||||
return { skipped: false, nextDueAt: null };
|
||||
}
|
||||
|
||||
await prisma.measurementReminderEvent.create({
|
||||
data: {
|
||||
userId: reminder.userId,
|
||||
reminderId: reminder.id,
|
||||
kind: "SKIPPED",
|
||||
occurredAt: skippedAt,
|
||||
onTime: deriveOnTime(reminder.nextDueAt, skippedAt),
|
||||
source: "skip",
|
||||
},
|
||||
});
|
||||
|
||||
return { skipped: true, nextDueAt };
|
||||
}
|
||||
@@ -13,6 +13,10 @@ import {
|
||||
updateMeasurementReminderSchema,
|
||||
measurementReminderDto,
|
||||
measurementReminderCompletionDto,
|
||||
measurementReminderSkipDto,
|
||||
measurementReminderHistoryDto,
|
||||
snoozeMeasurementReminderSchema,
|
||||
listReminderHistorySchema,
|
||||
} from "@/lib/validations/measurement-reminders";
|
||||
import {
|
||||
dataEnvelope,
|
||||
@@ -206,4 +210,89 @@ export const measurementReminderPaths: NonNullable<ZodOpenApiObject["paths"]> =
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/measurement-reminders/{id}/skip": {
|
||||
post: {
|
||||
tags: ["MeasurementReminders"],
|
||||
summary: "Skip the current due cycle (v1.37.20)",
|
||||
description:
|
||||
"Honestly skips the current due cycle — no body; the skip instant is the server clock. The interval restarts from the skip (rolling: skip + N days at the notify hour; rrule: next occurrence strictly after the skip), lastSkippedAt is stamped, skipCount incremented, any snooze cleared, and a SKIPPED row lands in the completion ledger. lastSatisfiedAt is never touched: a skip is not a completion. Screening reminders are skippable (the satisfy-side 409 guards claimed fulfilment; a skip claims the opposite). Owner-scoped; an appointment (encounter) reminder 404s.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description:
|
||||
"Skip applied (skipped=true) or forward-only no-op (skipped=false); reminder carries the canonical post-skip DTO.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
measurementReminderSkipDto,
|
||||
"MeasurementReminderSkipEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...reminderNotFound,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/measurement-reminders/{id}/snooze": {
|
||||
post: {
|
||||
tags: ["MeasurementReminders"],
|
||||
summary: "Snooze to a calendar day (v1.37.20)",
|
||||
description:
|
||||
"Pushes the current due date back to a named calendar day (YYYY-MM-DD), resolved server-side to the reminder's notifyHour in the profile timezone. snoozedUntil and nextDueAt are set to the same instant, so every due-state consumer moves together and the cursor self-expires. The regular cadence is untouched — lastSatisfiedAt, lastSkippedAt and the anchor stay put. Must be at least tomorrow and at most five years out (422 otherwise). Repeated snoozes: last one wins. Owner-scoped; an appointment reminder 404s.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
"application/json": { schema: snoozeMeasurementReminderSchema },
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "Snooze applied; reminder carries the resolved DTO.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.object({ reminder: measurementReminderDto }),
|
||||
"MeasurementReminderSnoozeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...reminderNotFound,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/measurement-reminders/{id}/history": {
|
||||
get: {
|
||||
tags: ["MeasurementReminders"],
|
||||
summary: "Completion ledger, newest first (v1.37.20)",
|
||||
description:
|
||||
"Paginated completion ledger for one reminder (iOS #68): one row per satisfy (from any path) and per skip, newest first. onTime is derived server-side at write time against the due instant that was current when the event landed. History begins at the release that introduced the ledger — the single-cursor engine holds nothing to backfill from. Owner-scoped; an appointment reminder 404s.",
|
||||
requestParams: {
|
||||
path: z.object({ id: z.string() }),
|
||||
query: listReminderHistorySchema,
|
||||
},
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The reminder's completion ledger page.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
measurementReminderHistoryDto,
|
||||
"MeasurementReminderHistoryEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...reminderNotFound,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -15,4 +15,7 @@ export const measurementReminderKeys = {
|
||||
measurementReminderDelete: () => ["measurement-reminders", "delete"] as const,
|
||||
measurementReminderSatisfy: () =>
|
||||
["measurement-reminders", "satisfy"] as const,
|
||||
/** v1.37.20 (#223) — honest skip + snooze mutations. */
|
||||
measurementReminderSkip: () => ["measurement-reminders", "skip"] as const,
|
||||
measurementReminderSnooze: () => ["measurement-reminders", "snooze"] as const,
|
||||
};
|
||||
@@ -151,6 +151,17 @@ export function recordActivityVerbLine(
|
||||
return t("recordSharing.activityVerb.measurementReminderSatisfy", {
|
||||
name,
|
||||
});
|
||||
// v1.37.20 (#223) — the honest skip and the snooze read differently in
|
||||
// the feed on purpose: one says a cycle was let go, the other that a due
|
||||
// date moved. Neither reads as "done".
|
||||
case "measurementReminder.skip":
|
||||
return t("recordSharing.activityVerb.measurementReminderSkip", {
|
||||
name,
|
||||
});
|
||||
case "measurementReminder.snooze":
|
||||
return t("recordSharing.activityVerb.measurementReminderSnooze", {
|
||||
name,
|
||||
});
|
||||
|
||||
case "labResult.update":
|
||||
return t("recordSharing.activityVerb.labResultUpdate", { name });
|
||||
|
||||
@@ -838,13 +838,16 @@ export async function handleCallback(update: TelegramUpdate) {
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
// v1.19.2 — the target metric; drives the optional numeric capture.
|
||||
measurementType: true,
|
||||
intervalDays: true,
|
||||
rrule: true,
|
||||
anchorDate: true,
|
||||
notifyHour: true,
|
||||
nextDueAt: true,
|
||||
lastSatisfiedAt: true,
|
||||
lastSkippedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
@@ -857,7 +860,7 @@ export async function handleCallback(update: TelegramUpdate) {
|
||||
return;
|
||||
}
|
||||
const tz = user.timezone || DEFAULT_TIMEZONE;
|
||||
await satisfyReminder(prisma, reminder, tz, new Date());
|
||||
await satisfyReminder(prisma, reminder, tz, new Date(), "telegram");
|
||||
await answerTelegramCallbackQuery(
|
||||
botToken,
|
||||
callback.id,
|
||||
|
||||
@@ -100,12 +100,15 @@ export async function satisfyBoostersForDose(
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
vaccinationAntigen: true,
|
||||
intervalDays: true,
|
||||
rrule: true,
|
||||
anchorDate: true,
|
||||
notifyHour: true,
|
||||
nextDueAt: true,
|
||||
lastSatisfiedAt: true,
|
||||
lastSkippedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
@@ -125,11 +128,14 @@ export async function satisfyBoostersForDose(
|
||||
for (const reminder of ordered) {
|
||||
const row: SatisfiableReminder = {
|
||||
id: reminder.id,
|
||||
userId: reminder.userId,
|
||||
intervalDays: reminder.intervalDays,
|
||||
rrule: reminder.rrule,
|
||||
anchorDate: reminder.anchorDate,
|
||||
notifyHour: reminder.notifyHour,
|
||||
nextDueAt: reminder.nextDueAt,
|
||||
lastSatisfiedAt: reminder.lastSatisfiedAt,
|
||||
lastSkippedAt: reminder.lastSkippedAt,
|
||||
createdAt: reminder.createdAt,
|
||||
};
|
||||
// `satisfyReminder` types its client as the full `PrismaClient` because
|
||||
@@ -142,6 +148,7 @@ export async function satisfyBoostersForDose(
|
||||
row,
|
||||
timezone,
|
||||
occurredAt,
|
||||
"vaccination",
|
||||
);
|
||||
if (result.satisfied) satisfiedReminderIds.push(reminder.id);
|
||||
}
|
||||
|
||||
@@ -210,6 +210,9 @@ export const measurementReminderDto = z
|
||||
location: z.string().nullable(),
|
||||
nextDueAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
lastSatisfiedAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
snoozedUntil: z.iso.datetime({ offset: true }).nullable(),
|
||||
lastSkippedAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
skipCount: z.number().int(),
|
||||
enabled: z.boolean(),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
updatedAt: z.iso.datetime({ offset: true }),
|
||||
@@ -217,7 +220,7 @@ export const measurementReminderDto = z
|
||||
.meta({
|
||||
id: "MeasurementReminderDTO",
|
||||
description:
|
||||
"A Vorsorge reminder. nextDueAt is server-computed (server-authoritative). A free-text reminder carries measurementType=null and resolves only on a manual satisfy. origin distinguishes a user-created (VORSORGE) reminder from one minted by a Coach cadence suggestion (COACH); endsOn bounds a finite course window (null = open-ended).",
|
||||
"A Vorsorge reminder. nextDueAt is server-computed (server-authoritative). A free-text reminder carries measurementType=null and resolves only on a manual satisfy. origin distinguishes a user-created (VORSORGE) reminder from one minted by a Coach cadence suggestion (COACH); endsOn bounds a finite course window (null = open-ended). snoozedUntil/lastSkippedAt/skipCount are resolved values: snoozed means snoozedUntil > now, a skipped cycle means lastSkippedAt > lastSatisfiedAt; clients compare against the clock and never recompute cadence. lastSatisfiedAt stays the only completed signal — skip and snooze never move it.",
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -240,5 +243,93 @@ export const measurementReminderCompletionDto = z
|
||||
.meta({
|
||||
id: "MeasurementReminderCompletion",
|
||||
description:
|
||||
"Result of an explicit reminder completion. completed=true when this call advanced lastSatisfiedAt; completed=false when an earlier satisfy or a matching reading had already fulfilled the current cycle (idempotent no-op). reminder is the canonical post-completion DTO.",
|
||||
"Result of an explicit reminder completion. completed=true when this call advanced lastSatisfiedAt; completed=false when an earlier satisfy or a matching reading already fulfilled the current cycle (idempotent no-op). reminder is the canonical post-completion DTO.",
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.37.20 (#223) — snooze body. Day precision on purpose: the client names
|
||||
* a local calendar day, the server resolves it to that day's notifyHour in
|
||||
* the profile timezone. No client-supplied instant ever anchors the cadence.
|
||||
* The range gate (tomorrow .. +5 years) lives in the route, where the
|
||||
* profile timezone is known.
|
||||
*/
|
||||
export const snoozeMeasurementReminderSchema = z
|
||||
.object({
|
||||
until: z.iso.date(),
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementReminderSnooze",
|
||||
description:
|
||||
"Push a reminder's current due date back to a calendar day (YYYY-MM-DD). The server resolves the day to the reminder's notifyHour in the profile timezone. Must be at least tomorrow and at most five years out. The regular cadence is untouched: lastSatisfiedAt and the anchor stay where they are, and the reminder resumes its normal interval after the snoozed cycle.",
|
||||
});
|
||||
|
||||
export type SnoozeMeasurementReminderInput = z.infer<
|
||||
typeof snoozeMeasurementReminderSchema
|
||||
>;
|
||||
|
||||
/**
|
||||
* v1.37.20 (#223) — skip result. `skipped=false` is the forward-only no-op
|
||||
* (a concurrent skip or satisfy already advanced the row).
|
||||
*/
|
||||
export const measurementReminderSkipDto = z
|
||||
.object({
|
||||
skipped: z.boolean(),
|
||||
reminder: measurementReminderDto,
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementReminderSkip",
|
||||
description:
|
||||
"Result of skipping the current due cycle. skipped=true when this call recorded the skip and restarted the interval from the skip instant; skipped=false when a concurrent skip or satisfy already advanced the row (idempotent no-op). A skip never touches lastSatisfiedAt — it is recorded honestly as a skip, not a completion.",
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.37.20 (iOS #68) — completion-ledger query + row. History starts with
|
||||
* the release that ships the ledger; the single-cursor engine holds nothing
|
||||
* to backfill from.
|
||||
*/
|
||||
export const listReminderHistorySchema = z
|
||||
.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementReminderHistoryQuery",
|
||||
description: "Pagination for the reminder completion ledger.",
|
||||
});
|
||||
|
||||
export const measurementReminderEventDto = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
kind: z.enum(["SATISFIED", "SKIPPED"]),
|
||||
occurredAt: z.iso.datetime({ offset: true }),
|
||||
onTime: z.boolean(),
|
||||
source: z.enum([
|
||||
"manual",
|
||||
"auto_measurement",
|
||||
"auto_lab",
|
||||
"telegram",
|
||||
"vaccination",
|
||||
"encounter",
|
||||
"skip",
|
||||
]),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementReminderEvent",
|
||||
description:
|
||||
"One completion-ledger row: an honest fulfilment (SATISFIED) or an honest skip (SKIPPED). onTime is derived server-side at write time against the due instant that was current when the event landed — clients never re-derive it. History begins at the release that introduced the ledger.",
|
||||
});
|
||||
|
||||
export const measurementReminderHistoryDto = z
|
||||
.object({
|
||||
events: z.array(measurementReminderEventDto),
|
||||
meta: z.object({
|
||||
total: z.number().int(),
|
||||
limit: z.number().int(),
|
||||
offset: z.number().int(),
|
||||
}),
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementReminderHistory",
|
||||
description: "Paginated completion ledger for one reminder, newest first.",
|
||||
});
|
||||
Reference in new issue
Block a user