mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
feat(medications): as-needed medications log without a schedule
A medication can declare itself as-needed: no schedules, never due, never reminded, excluded from every compliance rate — but intakes log ad-hoc, consume inventory exactly like scheduled doses, and the history stays. The wizard offers it as a cadence choice and round- trips it on edit; card, table and detail show a calm marker where the next dose normally sits, the take-all dialog never collects one, and the supply runway stays unknowable by construction. (#316)
This commit is contained in:
1 parent
550f314a54
commit
3943dcfb72
43 files changed
+1273
-70
No files matched your search
@@ -769,7 +769,9 @@ async function buildCoachSnapshotImpl(
|
||||
// can be reconstructed per medication.
|
||||
const complianceMedsPromise = wantsCompliance
|
||||
? prisma.medication.findMany({
|
||||
where: { userId },
|
||||
// v1.16.11 — as-needed (PRN) medications never reach the Coach
|
||||
// compliance context (no expected doses, no rate).
|
||||
where: { userId, asNeeded: false },
|
||||
select: {
|
||||
id: true,
|
||||
startsOn: true,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* v1.16.11 (#316) — as-needed (PRN) medications are excluded from every
|
||||
* surface that computes or displays a compliance rate. A PRN medication
|
||||
* has no expected doses, so it must contribute NEITHER 0% NOR 100% to
|
||||
* any rate, streak, or aggregate.
|
||||
*
|
||||
* Source pins: each call site that feeds the compliance engine fetches
|
||||
* its medications with an explicit `asNeeded: false` predicate. The pin
|
||||
* walks the medication-feeding `findMany` of every rate-surfacing call
|
||||
* site (the documented set: Coach prompt, BP-status gate, health-score
|
||||
* pillar, insight features / targets / comprehensive, the nightly
|
||||
* compliance status, the batched card-compliance payload) and asserts
|
||||
* the predicate is present — a refactor that drops it fails here before
|
||||
* a PRN medication can drag a user's rate to 0% (never-taken-on-no-
|
||||
* schedule) or pad it to 100% (vacuous denominator).
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const CALL_SITES: Array<{ file: string; surface: string }> = [
|
||||
{
|
||||
file: "src/lib/analytics/health-score-fast-path.ts",
|
||||
surface: "health-score compliance pillar (dashboard)",
|
||||
},
|
||||
{
|
||||
file: "src/lib/insights/blood-pressure-status.ts",
|
||||
surface: "BP-status compliance gate",
|
||||
},
|
||||
{
|
||||
file: "src/lib/insights/medication-compliance-status.ts",
|
||||
surface: "nightly medication-compliance status",
|
||||
},
|
||||
{
|
||||
file: "src/lib/insights/features.ts",
|
||||
surface: "insight feature extraction (c7/c30/c90)",
|
||||
},
|
||||
{
|
||||
file: "src/app/api/insights/targets/route.ts",
|
||||
surface: "insight targets",
|
||||
},
|
||||
{
|
||||
file: "src/app/api/insights/comprehensive/route.ts",
|
||||
surface: "comprehensive insight",
|
||||
},
|
||||
{
|
||||
file: "src/lib/ai/coach/snapshot.ts",
|
||||
surface: "Coach prompt compliance context",
|
||||
},
|
||||
{
|
||||
file: "src/app/api/medications/compliance/route.ts",
|
||||
surface: "batched card/table compliance payload",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* The medication-feeding read at each call site must carry the
|
||||
* exclusion inside its `where`: an `asNeeded: false` predicate within
|
||||
* the few lines following a `medication.findMany(` opener (comment
|
||||
* lines between them are fine).
|
||||
*/
|
||||
function hasExcludingFindMany(source: string): boolean {
|
||||
let from = 0;
|
||||
for (;;) {
|
||||
const at = source.indexOf("medication.findMany(", from);
|
||||
if (at < 0) return false;
|
||||
const window = source.slice(at, at + 600);
|
||||
// No dot in the pattern, so no dotall flag is needed — `[^}]` and
|
||||
// `\s` both span newlines.
|
||||
if (/where:\s*\{[^}]*\basNeeded:\s*false\b/.test(window)) return true;
|
||||
from = at + 1;
|
||||
}
|
||||
}
|
||||
|
||||
describe("as-needed compliance exclusion — source pins (v1.16.11, #316)", () => {
|
||||
for (const { file, surface } of CALL_SITES) {
|
||||
it(`${surface} excludes asNeeded medications (${file})`, () => {
|
||||
const source = readFileSync(resolve(process.cwd(), file), "utf8");
|
||||
expect(
|
||||
hasExcludingFindMany(source),
|
||||
`${file} must fetch medications with \`asNeeded: false\``,
|
||||
).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it("the reminder tick carries the same predicate", () => {
|
||||
const source = readFileSync(
|
||||
resolve(
|
||||
process.cwd(),
|
||||
"src/lib/jobs/reminder/medication-reminder-check.ts",
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
expect(hasExcludingFindMany(source)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -305,7 +305,10 @@ export async function computeUserHealthScoreFastPath(
|
||||
orderBy: { moodLoggedAt: "asc" },
|
||||
}),
|
||||
prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.16.11 — as-needed (PRN) medications carry no expected doses
|
||||
// and are excluded from every compliance rate: they must
|
||||
// contribute neither 0% nor 100% to the score pillar.
|
||||
where: { userId, active: true, asNeeded: false },
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
|
||||
@@ -264,7 +264,9 @@ export async function generateBloodPressureStatusForUser(
|
||||
const weightVsSystolicCorrelation = pearsonCorrelation(weightVsSystolicPairs);
|
||||
|
||||
const activeMedications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.16.11 — as-needed (PRN) medications never feed the BP-status
|
||||
// compliance gate (no expected doses, no rate).
|
||||
where: { userId, active: true, asNeeded: false },
|
||||
// v1.15.20 — schedules through the shared compliance select so the
|
||||
// configured per-dose windows reach this surface like every other.
|
||||
include: {
|
||||
|
||||
@@ -911,7 +911,9 @@ export async function extractFeatures(
|
||||
|
||||
// Medications
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.16.11 — as-needed (PRN) medications never surface a compliance
|
||||
// rate (no expected doses), so the insight features exclude them.
|
||||
where: { userId, active: true, asNeeded: false },
|
||||
// v1.15.20 — schedules through the shared compliance select so the
|
||||
// configured per-dose windows reach this surface like every other.
|
||||
include: {
|
||||
|
||||
@@ -154,7 +154,9 @@ export async function generateMedicationComplianceStatusForUser(
|
||||
}
|
||||
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.16.11 — as-needed (PRN) medications never surface a compliance
|
||||
// rate (no expected doses).
|
||||
where: { userId, active: true, asNeeded: false },
|
||||
// v1.15.20 — schedules through the shared compliance select so the
|
||||
// configured per-dose windows reach this surface like every other.
|
||||
include: {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* v1.16.11 (#316) — the medication-reminder tick skips as-needed (PRN)
|
||||
* medications at the QUERY level: the candidate read carries
|
||||
* `asNeeded: false`, so a PRN medication never reaches the per-schedule
|
||||
* loop, never mints a missed-dose row, and never dispatches a phase
|
||||
* notification. (Structurally a PRN medication also has zero schedules,
|
||||
* so the loop would be a no-op — the predicate keeps it out of the
|
||||
* tick's per-medication intake reads entirely.)
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
const prismaMock = {
|
||||
telegramScheduledDeletion: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
medication: {
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
medicationIntakeEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
},
|
||||
telegramReminderMessage: {
|
||||
findUnique: vi.fn().mockResolvedValue(null),
|
||||
},
|
||||
user: {
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("@/lib/jobs/reminder/shared", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("@/lib/jobs/reminder/shared")>();
|
||||
return {
|
||||
...actual,
|
||||
getWorkerPrisma: () => prismaMock,
|
||||
workerLog: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@/lib/jobs/worker-status", () => ({
|
||||
recordError: vi.fn(),
|
||||
recordReminderCheck: vi.fn(),
|
||||
markWorkerStarted: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/logging/background", () => ({
|
||||
withBackgroundEvent: vi.fn(
|
||||
async (
|
||||
_name: string,
|
||||
fn: (evt: {
|
||||
addMeta: (k: string, v: unknown) => void;
|
||||
addWarning: (m: string) => void;
|
||||
setError: (e: unknown) => void;
|
||||
}) => Promise<void>,
|
||||
) =>
|
||||
fn({ addMeta: vi.fn(), addWarning: vi.fn(), setError: vi.fn() }),
|
||||
),
|
||||
}));
|
||||
vi.mock("@/lib/notifications/dispatcher", () => ({
|
||||
dispatchNotification: vi.fn().mockResolvedValue({ dispatched: true }),
|
||||
}));
|
||||
vi.mock("@/lib/crypto", () => ({ decrypt: vi.fn(() => "token") }));
|
||||
vi.mock("@/lib/telegram", () => ({ deleteMessage: vi.fn() }));
|
||||
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
|
||||
recomputeMedicationComplianceForEvent: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { handleReminderCheck } from "@/lib/jobs/reminder/medication-reminder-check";
|
||||
import { dispatchNotification } from "@/lib/notifications/dispatcher";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
prismaMock.telegramScheduledDeletion.findMany.mockResolvedValue([]);
|
||||
prismaMock.medication.updateMany.mockResolvedValue({ count: 0 });
|
||||
prismaMock.medication.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("handleReminderCheck — as-needed skip (v1.16.11, #316)", () => {
|
||||
it("queries only active NON-as-needed medications", async () => {
|
||||
await handleReminderCheck([]);
|
||||
|
||||
expect(prismaMock.medication.findMany).toHaveBeenCalledTimes(1);
|
||||
const args = prismaMock.medication.findMany.mock.calls[0][0] as {
|
||||
where: Record<string, unknown>;
|
||||
};
|
||||
expect(args.where).toEqual({ active: true, asNeeded: false });
|
||||
});
|
||||
|
||||
it("dispatches nothing when the candidate set is empty", async () => {
|
||||
await handleReminderCheck([]);
|
||||
expect(dispatchNotification).not.toHaveBeenCalled();
|
||||
expect(prismaMock.medicationIntakeEvent.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -133,9 +133,13 @@ export async function handleReminderCheck(jobs: Job<ReminderCheckPayload>[]) {
|
||||
data: { snoozedUntil: null },
|
||||
});
|
||||
|
||||
// Get all active medications with schedules and phase config
|
||||
// Get all active medications with schedules and phase config.
|
||||
// v1.16.11 — as-needed (PRN) medications never remind: they carry
|
||||
// zero schedules anyway (the per-schedule loop below would be a
|
||||
// no-op), but the explicit predicate keeps them out of the tick's
|
||||
// per-medication intake reads entirely.
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: { active: true },
|
||||
where: { active: true, asNeeded: false },
|
||||
include: {
|
||||
schedules: true,
|
||||
phaseConfig: true,
|
||||
|
||||
@@ -444,6 +444,37 @@ describe("consumeForIntake", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("consumes for an as-needed (schedule-less) medication exactly like a scheduled one (v1.16.11 #316)", async () => {
|
||||
// The consumption seam is MEDICATION-level: its only inputs are the
|
||||
// event row, the medication's `unitsPerDose`, and the container
|
||||
// pool — no schedule is read anywhere on the path (the fake client
|
||||
// doesn't even model one). An ad-hoc PRN intake therefore decrements
|
||||
// stock byte-identically to a slot-attributed dose.
|
||||
const state: FakeState = {
|
||||
unitsPerDose: 2,
|
||||
events: [takenEvent()],
|
||||
items: [
|
||||
item({
|
||||
id: "open",
|
||||
state: "IN_USE",
|
||||
unitsRemaining: 6,
|
||||
firstUseAt: new Date(NOW.getTime() - 2 * MS_PER_DAY),
|
||||
expiresAt: new Date(NOW.getTime() + 28 * MS_PER_DAY),
|
||||
}),
|
||||
],
|
||||
};
|
||||
const client = makeClient(state);
|
||||
await consumeForIntake(consumeArgs(client));
|
||||
|
||||
expect(state.items[0].unitsRemaining).toBe(4);
|
||||
expect(state.events[0].inventoryConsumption).toEqual([
|
||||
{ itemId: "open", units: 2 },
|
||||
]);
|
||||
// The hook never asked for a schedule — the medication read covers
|
||||
// `unitsPerDose` only.
|
||||
expect(client.medication.findFirst).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stamps an empty consumption when no tracked stock exists (exactly-once gate)", async () => {
|
||||
const state: FakeState = {
|
||||
unitsPerDose: 1,
|
||||
|
||||
@@ -480,3 +480,37 @@ describe("resolved-slot marks — ad-hoc rows only match their own anchor", () =
|
||||
expect(due!.at.toISOString()).toBe("2026-06-10T08:00:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.16.11 (#316) — as-needed (PRN) medications persist ZERO schedule
|
||||
* rows, so every due surface (list cards, dashboard, reminder worker)
|
||||
* resolves null by construction. Pin both the forward next-due and the
|
||||
* display-due (open-overdue) paths on the empty schedule list, with a
|
||||
* recent intake present — a logged ad-hoc take must not conjure a due.
|
||||
*/
|
||||
describe("as-needed (zero schedules) — never due", () => {
|
||||
it("computeNextDueAt returns null even with a recent intake", () => {
|
||||
const now = new Date();
|
||||
const next = computeNextDueAt({
|
||||
medication: makeMedication({ createdAt: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000) }),
|
||||
schedules: [],
|
||||
now,
|
||||
userTz: BERLIN,
|
||||
lastIntakeAt: new Date(now.getTime() - 2 * 60 * 60 * 1000),
|
||||
});
|
||||
expect(next).toBeNull();
|
||||
});
|
||||
|
||||
it("computeDisplayDue returns null — no overdue escalation can ever mint", () => {
|
||||
const now = new Date();
|
||||
const display = computeDisplayDue({
|
||||
medication: makeMedication({ createdAt: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000) }),
|
||||
schedules: [],
|
||||
now,
|
||||
userTz: BERLIN,
|
||||
lastIntakeAt: new Date(now.getTime() - 2 * 60 * 60 * 1000),
|
||||
resolvedSlots: [],
|
||||
});
|
||||
expect(display).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -38,6 +38,20 @@
|
||||
* Pure functions, no DB access. Caller fetches `lastIntakeAt`
|
||||
* (latest `MedicationIntakeEvent.takenAt`) and threads it through
|
||||
* `RecurrenceContext`.
|
||||
*
|
||||
* **As-needed medications (v1.16.11, #316).** A medication with
|
||||
* `Medication.asNeeded = true` carries ZERO schedule rows (enforced at
|
||||
* the create/update routes), so this engine is never consulted for it:
|
||||
* `computeNextDueAt` / `computeDisplayDue` return null on an empty
|
||||
* schedule list by construction, the reminder worker iterates no
|
||||
* schedules, the projector mints no slots, and compliance expands no
|
||||
* expected doses. The MEDICATION_LOW_STOCK runway is likewise null (no
|
||||
* consuming schedule) — that is correct and intended: an as-needed
|
||||
* supply is not falling on a predictable cadence, so no runway-based
|
||||
* alert can be honest. Intakes for such medications are ad-hoc rows
|
||||
* (`scheduledFor = takenAt`, the documented standalone-insert
|
||||
* contract); the schedule-level `scheduleType = "PRN"` early-returns
|
||||
* below are the per-schedule prior art for the same semantics.
|
||||
*/
|
||||
|
||||
import { RRule } from "rrule";
|
||||
|
||||
@@ -207,6 +207,11 @@ export const medicationResource = z
|
||||
.describe(
|
||||
"v1.5 single-administration flag. When true the medication has at most one schedule (no `rrule` / `rollingIntervalDays`), and `active` auto-flips to false once the dose is logged.",
|
||||
),
|
||||
asNeeded: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"v1.16.11 as-needed (PRN) flag. When true the medication carries ZERO schedules (the write routes 422 on any schedule entry alongside the flag): it is never due (`nextDueAt` stays null), never reminded, and excluded from every compliance rate/streak — but intakes still log as ad-hoc rows, inventory still consumes per `unitsPerDose`, and the history renders. Stays active indefinitely. Mutually exclusive with `oneShot`.",
|
||||
),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
updatedAt: z.iso.datetime({ offset: true }),
|
||||
schedules: z.array(medicationScheduleResource),
|
||||
|
||||
@@ -447,8 +447,31 @@ const courseWindowFields = {
|
||||
.describe(
|
||||
"Single-administration medication (e.g. flu shot, post-op single dose). When true the medication has at most one schedule with no `rrule` / `rollingIntervalDays`, and `active` auto-flips to false once the dose is logged (non-skipped).",
|
||||
),
|
||||
/**
|
||||
* v1.16.11 (#316) — as-needed (PRN) medication. No fixed schedule:
|
||||
* never due, never reminded, excluded from compliance, active
|
||||
* indefinitely. Intakes log ad-hoc and consume inventory. Carries
|
||||
* ZERO schedules — a `schedules` array alongside `asNeeded: true` is
|
||||
* a 422. Mutually exclusive with `oneShot`.
|
||||
*/
|
||||
asNeeded: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"As-needed (PRN) medication (pain relief, rescue inhaler). When true the medication carries NO schedules (supplying any schedule entry is a 422): it is never due, never reminded, and excluded from compliance rates/streaks, but intakes still log (ad-hoc), inventory still consumes, and the history renders. Stays active indefinitely. Mutually exclusive with `oneShot`.",
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* v1.16.11 — shared as-needed cross-field refines for the create +
|
||||
* update bodies: `asNeeded` and `oneShot` are mutually exclusive, and
|
||||
* an as-needed medication cannot carry schedule entries.
|
||||
*/
|
||||
const AS_NEEDED_ONE_SHOT_MESSAGE =
|
||||
"asNeeded and oneShot are mutually exclusive";
|
||||
const AS_NEEDED_SCHEDULES_MESSAGE =
|
||||
"An as-needed medication cannot carry schedules";
|
||||
|
||||
export const createMedicationSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(100),
|
||||
@@ -517,7 +540,12 @@ export const createMedicationSchema = z
|
||||
/** v1.9.0 — optional RxNorm RxCUI (secondary, US). */
|
||||
rxNormCode: rxNormCodeField,
|
||||
...courseWindowFields,
|
||||
schedules: z.array(scheduleSchema).min(1, "Mindestens ein Zeitfenster"),
|
||||
/**
|
||||
* v1.16.11 — optional at the type level so an `asNeeded: true`
|
||||
* create can omit it; the refine below keeps the legacy
|
||||
* at-least-one-schedule contract for every scheduled medication.
|
||||
*/
|
||||
schedules: z.array(scheduleSchema).optional(),
|
||||
})
|
||||
.refine((b) => b.oneShot !== true || !!b.startsOn, {
|
||||
message: "startsOn is required when oneShot is true",
|
||||
@@ -531,10 +559,30 @@ export const createMedicationSchema = z
|
||||
path: ["endsOn"],
|
||||
},
|
||||
)
|
||||
.refine((b) => !(b.asNeeded === true && b.oneShot === true), {
|
||||
message: AS_NEEDED_ONE_SHOT_MESSAGE,
|
||||
path: ["asNeeded"],
|
||||
})
|
||||
.refine(
|
||||
(b) =>
|
||||
b.asNeeded === true || (!!b.schedules && b.schedules.length >= 1),
|
||||
{
|
||||
message: "Mindestens ein Zeitfenster",
|
||||
path: ["schedules"],
|
||||
},
|
||||
)
|
||||
.refine(
|
||||
(b) =>
|
||||
b.asNeeded !== true || !b.schedules || b.schedules.length === 0,
|
||||
{
|
||||
message: AS_NEEDED_SCHEDULES_MESSAGE,
|
||||
path: ["schedules"],
|
||||
},
|
||||
)
|
||||
.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.",
|
||||
"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.",
|
||||
});
|
||||
|
||||
export const updateMedicationSchema = z
|
||||
@@ -626,10 +674,32 @@ export const updateMedicationSchema = z
|
||||
path: ["endsOn"],
|
||||
},
|
||||
)
|
||||
.refine((b) => !(b.asNeeded === true && b.oneShot === true), {
|
||||
message: AS_NEEDED_ONE_SHOT_MESSAGE,
|
||||
path: ["asNeeded"],
|
||||
})
|
||||
.refine(
|
||||
(b) =>
|
||||
b.asNeeded !== true || !b.schedules || b.schedules.length === 0,
|
||||
{
|
||||
message: AS_NEEDED_SCHEDULES_MESSAGE,
|
||||
path: ["schedules"],
|
||||
},
|
||||
)
|
||||
.refine(
|
||||
// An empty replace-list is only legal on the as-needed path — for a
|
||||
// scheduled medication it would wipe every schedule and strand the
|
||||
// row in a state no surface can reason about.
|
||||
(b) => b.asNeeded === true || !b.schedules || b.schedules.length >= 1,
|
||||
{
|
||||
message: "Mindestens ein Zeitfenster",
|
||||
path: ["schedules"],
|
||||
},
|
||||
)
|
||||
.meta({
|
||||
id: "UpdateMedicationRequest",
|
||||
description:
|
||||
"Update-medication body. Every field is optional; omitted fields are left untouched. Supplying `schedules` REPLACES the medication's full schedule list (the route deletes existing rows before re-creating). Flipping `active` to false records the current timestamp on `pausedAt`; flipping back to true clears it. v1.5 invariants on the `schedules` array match the create path.",
|
||||
"Update-medication body. Every field is optional; omitted fields are left untouched. Supplying `schedules` REPLACES the medication's full schedule list (the route deletes existing rows before re-creating). Flipping `active` to false records the current timestamp on `pausedAt`; flipping back to true clears it. v1.5 invariants on the `schedules` array match the create path. v1.16.11 — `asNeeded: true` requires the medication to end schedule-less: supply `schedules: []` to clear an existing plan (any schedule entry is a 422); an empty `schedules` array without `asNeeded: true` is likewise a 422.",
|
||||
});
|
||||
|
||||
export const intakeSchema = z
|
||||
|
||||
Reference in new issue
Block a user