mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
Merge branch 'feat/v146-server-meds' into feat/v146-server
This commit is contained in:
commit
f942389a4b
53 files changed
+26036
-902
No files matched your search
@@ -1,8 +1,6 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { overwriteDetails } from "@/lib/sharing/audit-details";
|
||||
import {
|
||||
apiSuccess,
|
||||
apiError,
|
||||
@@ -13,22 +11,14 @@ import {
|
||||
} from "@/lib/api-response";
|
||||
import { updateIntakeEventSchema } from "@/lib/validations/medication";
|
||||
import {
|
||||
consumeForIntake,
|
||||
restoreForIntake,
|
||||
} from "@/lib/medications/inventory/consumption";
|
||||
import { reconcileOneShotState } from "@/lib/medications/lifecycle";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { queueMedicationIntakeSync } from "@/lib/notifications/medication-intake-sync";
|
||||
import { refreshDoseSlot } from "@/lib/medications/dose-day-refresh";
|
||||
import { dayKeyForUserTz } from "@/lib/measurements/consolidation-tz";
|
||||
findEditableIntakeEvent,
|
||||
updateIntakeEvent,
|
||||
} from "@/lib/medications/update-intake-event";
|
||||
import {
|
||||
applyCanonicalSlotWrite,
|
||||
findPinConflict,
|
||||
resolveForcedSlotForWrite,
|
||||
resolveSlotForWriteByBand,
|
||||
} from "@/lib/medications/scheduling/slot-upsert";
|
||||
deleteIntakeEvent,
|
||||
findDeletableIntakeEvent,
|
||||
} from "@/lib/medications/delete-intake-event";
|
||||
import { NextRequest } from "next/server";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string; eventId: string }> };
|
||||
|
||||
@@ -41,13 +31,12 @@ export const PUT = apiHandler(
|
||||
|
||||
const { id, eventId } = await params;
|
||||
|
||||
// v1.7.0 sync — a tombstoned event 404s on PUT; the `deletedAt: null`
|
||||
// filter refuses to resurrect-edit a soft-deleted intake.
|
||||
const event = await prisma.medicationIntakeEvent.findFirst({
|
||||
where: { id: eventId, deletedAt: null },
|
||||
const event = await findEditableIntakeEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
eventId,
|
||||
});
|
||||
|
||||
if (!event || event.userId !== user.id || event.medicationId !== id) {
|
||||
if (!event) {
|
||||
return apiError("Intake not found", 404);
|
||||
}
|
||||
|
||||
@@ -87,341 +76,20 @@ export const PUT = apiHandler(
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
|
||||
// v1.15.19 — start-date guard on an edited `takenAt` (audit P0-4). The
|
||||
// schema bounds the instant to a plausible absolute range; this check
|
||||
// adds the per-medication floor: a take cannot predate the day the
|
||||
// medication starts (calendar-day comparison in the user's timezone, so
|
||||
// a take in the early hours of the start day never false-rejects).
|
||||
if (data.takenAt instanceof Date) {
|
||||
const medication = await prisma.medication.findFirst({
|
||||
where: { id, userId: user.id },
|
||||
select: { startsOn: true },
|
||||
});
|
||||
if (medication?.startsOn) {
|
||||
const takenDay = dayKeyForUserTz(data.takenAt, user.timezone);
|
||||
const startsOnDay = dateOnlyKey(medication.startsOn);
|
||||
if (takenDay < startsOnDay) {
|
||||
annotate({
|
||||
action: {
|
||||
name: "medications.intake.event.update.before-start-date",
|
||||
},
|
||||
meta: { medication_id: id, event_id: eventId },
|
||||
});
|
||||
return apiError(
|
||||
"takenAt is before the medication's start date",
|
||||
422,
|
||||
{ errorCode: "medications.intake.taken_at.before_start" },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The post-edit state of the row (current values where the body omits a
|
||||
// field) — drives the re-attribution decision.
|
||||
const nextTakenAt =
|
||||
data.takenAt !== undefined ? data.takenAt : event.takenAt;
|
||||
const nextSkipped =
|
||||
data.skipped !== undefined ? data.skipped : event.skipped;
|
||||
const takenOrSkippedChanged =
|
||||
(data.takenAt !== undefined &&
|
||||
data.takenAt?.getTime() !== event.takenAt?.getTime()) ||
|
||||
(data.skipped !== undefined && data.skipped !== event.skipped);
|
||||
|
||||
// v1.15.18 — re-run window-band attribution when the edit moves `takenAt`
|
||||
// or `skipped`, so an edited time re-binds to the correct slot instead of
|
||||
// leaving `scheduledFor` stale (audit HIGH-4). Precedence:
|
||||
// 1. an explicit `scheduledFor` in the body wins (deliberate override);
|
||||
// 2. else `forceSlotInstant` pins onto a named real slot (422 if it is
|
||||
// not a slot of this med) — v1.15.20: standalone too, no takenAt /
|
||||
// skipped change required ("Slot zuordnen" from the ledger kebab),
|
||||
// and the row is stamped USER_PIN so the read ledger binds it by
|
||||
// anchor instead of degrading the off-window take back to ad-hoc;
|
||||
// 3. else an explicit `forceSlotInstant: null` UNPINS (v1.15.20,
|
||||
// "Zuordnung lösen"): re-attribute the take by band on its takenAt
|
||||
// (ad-hoc when no band matches). v1.16.0 — the release is itself a
|
||||
// deliberate binding decision, so the row KEEPS `USER_PIN`
|
||||
// provenance ("attribution user-fixed": onto a slot OR deliberately
|
||||
// ad-hoc). The persisted marker is what keeps the nightly slot
|
||||
// dedup from snapping the released row back into the cluster the
|
||||
// user just detached it from;
|
||||
// 4. else a taken edit attributes by band (slot anchor on match, the
|
||||
// take's own time on a miss → ad-hoc), provenance AUTO;
|
||||
// 5. a skip / pending edit keeps the existing `scheduledFor` anchor.
|
||||
let resolvedScheduledFor: Date | undefined = data.scheduledFor;
|
||||
let attributionSource: "AUTO" | "USER_PIN" | undefined;
|
||||
if (resolvedScheduledFor === undefined) {
|
||||
if (
|
||||
data.forceSlotInstant !== undefined &&
|
||||
data.forceSlotInstant !== null
|
||||
) {
|
||||
const forced = await resolveForcedSlotForWrite({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
userTz: user.timezone,
|
||||
slotInstant: data.forceSlotInstant,
|
||||
});
|
||||
if (forced === null) {
|
||||
annotate({
|
||||
action: { name: "medication.intake.force_slot.invalid" },
|
||||
meta: { medication_id: id, event_id: eventId },
|
||||
});
|
||||
return apiError(
|
||||
"forceSlotInstant is not a scheduled slot of this medication",
|
||||
422,
|
||||
{ errorCode: "medications.intake.force_slot.invalid" },
|
||||
);
|
||||
}
|
||||
// v1.16.0 — refuse to pin onto a slot another recorded action
|
||||
// already serves (excluding the row being edited): the explicit-
|
||||
// write last-write-wins rule would silently overwrite that dose
|
||||
// record. The ledger UI only offers the pin for unserved slots,
|
||||
// so this only fires for stale clients / raw API calls.
|
||||
if (
|
||||
await findPinConflict({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
canonicalSlot: forced,
|
||||
incomingTakenAt: nextSkipped ? null : nextTakenAt,
|
||||
excludeEventId: eventId,
|
||||
})
|
||||
) {
|
||||
annotate({
|
||||
action: { name: "medication.intake.force_slot.occupied" },
|
||||
meta: { medication_id: id, event_id: eventId },
|
||||
});
|
||||
return apiError(
|
||||
"forceSlotInstant already carries a recorded dose action",
|
||||
422,
|
||||
{ errorCode: "medications.intake.force_slot.occupied" },
|
||||
);
|
||||
}
|
||||
resolvedScheduledFor = forced;
|
||||
attributionSource = "USER_PIN";
|
||||
} else if (
|
||||
(data.forceSlotInstant === null || takenOrSkippedChanged) &&
|
||||
nextTakenAt !== null &&
|
||||
!nextSkipped
|
||||
) {
|
||||
const attribution = await resolveSlotForWriteByBand({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
userTz: user.timezone,
|
||||
takenAt: nextTakenAt,
|
||||
});
|
||||
// band.at on match; the take's own time on a miss (ad-hoc).
|
||||
resolvedScheduledFor = attribution.slotInstant ?? nextTakenAt;
|
||||
// v1.16.0 — an explicit unpin stays user-fixed (USER_PIN) even on
|
||||
// the released row; a plain taken/skipped edit re-attributes AUTO.
|
||||
attributionSource =
|
||||
data.forceSlotInstant === null ? "USER_PIN" : "AUTO";
|
||||
} else if (data.forceSlotInstant === null) {
|
||||
// Unpin on a row that is not a confirmed take (skip / pending):
|
||||
// nothing to re-attribute, but the provenance still resets — a
|
||||
// skip / pending row anchors on its slot by construction, so there
|
||||
// is no user-fixed ad-hoc decision to persist.
|
||||
attributionSource = "AUTO";
|
||||
}
|
||||
// skip / pending edits leave `scheduledFor` on the existing anchor.
|
||||
}
|
||||
|
||||
const targetScheduledFor = resolvedScheduledFor ?? event.scheduledFor;
|
||||
const slotMoved =
|
||||
targetScheduledFor.getTime() !== event.scheduledFor.getTime();
|
||||
|
||||
// v1.16.10 — transition gate for the inventory hooks below. Only an
|
||||
// edit moving the row INTO taken may consume; a row that was
|
||||
// already taken keeps its stamp frozen (a stamped row would no-op
|
||||
// anyway, and a pre-v1.16.10 taken row — NULL stamp, stock already
|
||||
// moved by the legacy hook at take time — must never retro-consume
|
||||
// on a time correction).
|
||||
const wasTaken = event.takenAt !== null && !event.skipped;
|
||||
|
||||
let updated;
|
||||
if (!slotMoved) {
|
||||
// The slot is unchanged — a bare in-place update can never collide with
|
||||
// a sibling row (it is its own slot).
|
||||
updated = await prisma.medicationIntakeEvent.update({
|
||||
where: { id: eventId },
|
||||
data: {
|
||||
...(data.takenAt !== undefined && { takenAt: data.takenAt }),
|
||||
...(data.skipped !== undefined && { skipped: data.skipped }),
|
||||
// v1.15.20 — binding provenance: pin / unpin / band re-attribution
|
||||
// stamps it even when the anchor itself did not move (e.g. a pin
|
||||
// onto the slot the row already sits on, or an unpin whose band
|
||||
// re-attribution lands on the same anchor).
|
||||
...(attributionSource !== undefined && { attributionSource }),
|
||||
// v1.42.2 — an edit of the outcome is the person's own record.
|
||||
...((data.takenAt !== undefined || data.skipped !== undefined) && {
|
||||
autoRecorded: false,
|
||||
}),
|
||||
// v1.7.0 sync — bump the reconciliation counter on every
|
||||
// server-side mutation so the `/api/sync/changes` feed echoes a
|
||||
// monotonic value to paired clients.
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
// v1.16.10 — inventory follows the post-edit state: an edit that
|
||||
// moves the row INTO taken consumes; a row that stays taken keeps
|
||||
// its stamp untouched (the stamp freezes what the original take
|
||||
// pulled, even when `unitsPerDose` changed since, and a pre-stamp
|
||||
// legacy row must not retro-consume); a row edited out of taken
|
||||
// (skip flip, takenAt cleared) refunds its stamp.
|
||||
if (nextTakenAt !== null && !nextSkipped) {
|
||||
if (!wasTaken) {
|
||||
await consumeForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
eventId,
|
||||
intakeAt: nextTakenAt,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await restoreForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
eventId,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// The edit moved the dose to a different slot. Tombstone the original
|
||||
// row (the iOS "a correction is a tombstone + re-insert" model the
|
||||
// DELETE handler documents) and route the corrected dose through the
|
||||
// shared canonical-slot upsert, which converges onto any row already at
|
||||
// the target slot (a pending REMINDER row) rather than bare-updating
|
||||
// into an occupied slot and risking a P2002 (audit HIGH-4).
|
||||
//
|
||||
// v1.16.10 — refund the source row's consumption stamp BEFORE the
|
||||
// tombstone; the consume on the converged row below nets the move
|
||||
// to exactly one consumption.
|
||||
await restoreForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
eventId,
|
||||
});
|
||||
await prisma.medicationIntakeEvent.update({
|
||||
where: { id: eventId },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
const applied = await applyCanonicalSlotWrite({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
canonicalSlot: targetScheduledFor,
|
||||
takenAt: nextSkipped ? null : nextTakenAt,
|
||||
skipped: nextSkipped,
|
||||
isExplicitTaken: !nextSkipped && nextTakenAt !== null,
|
||||
isExplicitSkip: nextSkipped,
|
||||
idempotencyKey: null,
|
||||
// The converged row keeps the ORIGINAL's provenance. This used
|
||||
// to be a hardcoded `"WEB"`, which said "somebody typed this in the
|
||||
// browser" about an Apple Health dose whose time was corrected. Under
|
||||
// MANAGE the sentence would be wrong about a second person as well.
|
||||
createSource: event.source,
|
||||
attributionSource,
|
||||
// v1.16.9 — a slot move is a re-binding, not a new dose: the
|
||||
// original row's recorded injection site and dose override ride
|
||||
// along onto the converged row instead of being tombstoned away.
|
||||
injectionSite: event.injectionSite,
|
||||
doseTaken: event.doseTaken,
|
||||
});
|
||||
updated = applied.row;
|
||||
// A taken source WITHOUT a stamp is a pre-v1.16.10 row whose
|
||||
// stock moved through the legacy hook: the refund above was a
|
||||
// no-op, so consuming on the converged row would double-charge —
|
||||
// skip it. Every other taken outcome nets the move to exactly one
|
||||
// consumption.
|
||||
if (
|
||||
nextTakenAt !== null &&
|
||||
!nextSkipped &&
|
||||
(!wasTaken || event.inventoryConsumption !== null)
|
||||
) {
|
||||
await consumeForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
eventId: applied.row.id,
|
||||
intakeAt: nextTakenAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await auditLog("medication.intake.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
// What the correction moved. A dose edit changes when a dose is
|
||||
// recorded as taken, which is exactly what a clinician reads back.
|
||||
details: {
|
||||
eventId,
|
||||
medicationId: id,
|
||||
...overwriteDetails({
|
||||
before: {
|
||||
scheduledFor: event.scheduledFor,
|
||||
takenAt: event.takenAt,
|
||||
skipped: event.skipped,
|
||||
},
|
||||
// The slot-write result carries the canonical four. The injection
|
||||
// site and the dose override are not compared here because the move
|
||||
// path copies them onto the converged row by construction — there is
|
||||
// no edit of them to report.
|
||||
after: {
|
||||
scheduledFor: updated.scheduledFor,
|
||||
takenAt: updated.takenAt,
|
||||
skipped: updated.skipped,
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.update",
|
||||
entity_type: "intake_event",
|
||||
entity_id: eventId,
|
||||
},
|
||||
meta: { medication_id: id },
|
||||
});
|
||||
|
||||
// v1.4.34 — bust per-user medications + compliance + achievement
|
||||
// caches so the next read reflects the edited event.
|
||||
invalidateUserMedications(user.id, { evict: true });
|
||||
|
||||
// v1.4.39 — refresh the rollup row for both the old + new
|
||||
// scheduledFor day-keys when the dose moved across a day boundary
|
||||
// (band re-attribution can move it as well as an explicit edit); if the
|
||||
// slot is unchanged the second call collapses to a no-op upsert.
|
||||
await refreshDoseSlot({
|
||||
userId: user.id,
|
||||
const outcome = await updateIntakeEvent({
|
||||
user,
|
||||
medicationId: id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
if (slotMoved) {
|
||||
await refreshDoseSlot({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
scheduledFor: targetScheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
}
|
||||
|
||||
// v1.5.0 — re-evaluate the one-shot active flag. A skip-flip on the
|
||||
// single live intake of a one-shot medication should reactivate it
|
||||
// (the dose is no longer logged), and the reverse case should
|
||||
// deactivate again. No-op for non-one-shot medications.
|
||||
await reconcileOneShotState(prisma, id, user.id);
|
||||
|
||||
// (#22) — silent cross-device intake sync: an edited dose must
|
||||
// reconcile on the user's other iOS devices too. Coalesced per user,
|
||||
// best-effort — never affects the response.
|
||||
queueMedicationIntakeSync({
|
||||
userId: user.id,
|
||||
eventId,
|
||||
event,
|
||||
data: parsed.data,
|
||||
ipAddress: getClientIp(request),
|
||||
originDeviceToken: request.headers.get("x-device-id"),
|
||||
});
|
||||
if (!outcome.ok) {
|
||||
return apiError(outcome.message, 422, { errorCode: outcome.errorCode });
|
||||
}
|
||||
|
||||
return apiSuccess(updated);
|
||||
return apiSuccess(outcome.row);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -433,80 +101,21 @@ export const DELETE = apiHandler(
|
||||
|
||||
const { id, eventId } = await params;
|
||||
|
||||
const event = await prisma.medicationIntakeEvent.findUnique({
|
||||
where: { id: eventId },
|
||||
const event = await findDeletableIntakeEvent({
|
||||
userId: user.id,
|
||||
medicationId: id,
|
||||
eventId,
|
||||
});
|
||||
|
||||
if (!event || event.userId !== user.id || event.medicationId !== id) {
|
||||
if (!event) {
|
||||
return apiError("Intake not found", 404);
|
||||
}
|
||||
|
||||
// v1.16.10 — a deleted dose record refunds its consumption stamp
|
||||
// (no-op for a never-consumed row; a re-delete finds it cleared).
|
||||
await restoreForIntake({
|
||||
client: prisma,
|
||||
userId: user.id,
|
||||
eventId,
|
||||
});
|
||||
|
||||
// v1.7.0 sync — soft-delete instead of a hard `delete`. An intake is
|
||||
// an immutable fact, so a "correction" is a tombstone + re-insert
|
||||
// (never an in-place edit). Setting `deletedAt` (+ bumping
|
||||
// `syncVersion`) leaves the row in place so the `/api/sync/changes`
|
||||
// feed surfaces the deletion as a tombstone keyed on the server `id`
|
||||
// to paired clients offline at delete time. Every today / compliance
|
||||
// / list read filters `deletedAt: null`, so the row is invisible to
|
||||
// normal reads from here on. A re-delete re-bumps harmlessly.
|
||||
await prisma.medicationIntakeEvent.update({
|
||||
where: { id: eventId },
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
const ip = getClientIp(request) ?? "unknown";
|
||||
await auditLog("medication.intake.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: ip,
|
||||
details: { eventId, medicationId: id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.intake.delete",
|
||||
entity_type: "intake_event",
|
||||
entity_id: eventId,
|
||||
},
|
||||
meta: { medication_id: id },
|
||||
});
|
||||
|
||||
// v1.4.34 — bust per-user medications + compliance + achievement
|
||||
// caches so the next read reflects the deletion.
|
||||
invalidateUserMedications(user.id, { evict: true });
|
||||
|
||||
// v1.4.39 — refresh the rollup row for the day the deleted
|
||||
// event sat on. When that day now holds zero events the helper
|
||||
// drops the rollup row entirely.
|
||||
await refreshDoseSlot({
|
||||
userId: user.id,
|
||||
await deleteIntakeEvent({
|
||||
user,
|
||||
medicationId: id,
|
||||
scheduledFor: event.scheduledFor,
|
||||
tz: user.timezone,
|
||||
});
|
||||
|
||||
// v1.5.0 — re-evaluate the one-shot active flag. Deleting the
|
||||
// single live intake of a one-shot medication reactivates it so
|
||||
// the dashboard / lists / worker pick it back up. No-op for
|
||||
// non-one-shot medications.
|
||||
await reconcileOneShotState(prisma, id, user.id);
|
||||
|
||||
// (#22) — silent cross-device intake sync: an undone dose must
|
||||
// reconcile on the user's other iOS devices (the widget count and a
|
||||
// pending Live Activity both change). Coalesced per user,
|
||||
// best-effort — never affects the response.
|
||||
queueMedicationIntakeSync({
|
||||
userId: user.id,
|
||||
eventId,
|
||||
event,
|
||||
ipAddress: getClientIp(request) ?? "unknown",
|
||||
originDeviceToken: request.headers.get("x-device-id"),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
@@ -10,45 +7,15 @@ import {
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import {
|
||||
courseRefusalResponse,
|
||||
resolveCourseFields,
|
||||
} from "@/lib/medications/courses";
|
||||
import {
|
||||
dateOfDayKey,
|
||||
dayKeyOfDate,
|
||||
validateCourses,
|
||||
} from "@/lib/medications/course-window";
|
||||
import { DEFAULT_TIMEZONE, userDayKey } from "@/lib/tz/format";
|
||||
import {
|
||||
createMedicationSchema,
|
||||
isCustomMedicationCategoryKey,
|
||||
} from "@/lib/validations/medication";
|
||||
import { createMedicationSchema } from "@/lib/validations/medication";
|
||||
import {
|
||||
unstableExternalIdMeta,
|
||||
unstableExternalIdShape,
|
||||
} from "@/lib/validations/external-id";
|
||||
import {
|
||||
isAssignableCategory,
|
||||
resolveMedicationCategories,
|
||||
setMedicationCategory,
|
||||
} from "@/lib/medication-category";
|
||||
import { serializeScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { invalidateUserMedications } from "@/lib/cache/invalidate";
|
||||
import { readMedicationsListCached } from "@/lib/medications/list-read";
|
||||
import { serializeScheduleUnitsPerDose } from "@/lib/medications/schedule-units-dto";
|
||||
import { createMedication } from "@/lib/medications/create-medication";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { NextRequest } from "next/server";
|
||||
import { scheduleWireFields } from "@/lib/medications/intake-tracking";
|
||||
|
||||
// v1.32.25 — blast-radius cap on externally-mirrored medications per user.
|
||||
// A client that mints a fresh `externalId` for the same source concept on
|
||||
// every sync sweep (a known iOS unstable-key bug class) never matches the
|
||||
// idempotency triple, so each sweep would otherwise create a new mirror
|
||||
// row unbounded. Apple's own medication list makes >30 genuinely distinct
|
||||
// meds implausible, so this caps the damage a buggy client can do without
|
||||
// breaking any legitimate use.
|
||||
const APPLE_HEALTH_MIRROR_CAP = 30;
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireRecordAuth("read", "medications");
|
||||
@@ -73,66 +40,12 @@ export const GET = apiHandler(async () => {
|
||||
return apiSuccess(result);
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.28 — idempotent response for a re-mirrored medication. The create
|
||||
* route returns the EXISTING row (status 200, vs 201 for a fresh create)
|
||||
* when the caller re-posts a `(externalSource, externalId)` pair this
|
||||
* user already mirrors — the iOS re-sync replays its full HealthKit
|
||||
* medication list, and a replay must neither duplicate nor 500. Response
|
||||
* shape mirrors the fresh-create envelope (schedules included, category
|
||||
* joined, Decimal unwrapped); no audit row and no cache eviction because
|
||||
* nothing was written.
|
||||
*/
|
||||
async function respondWithExistingMirror(
|
||||
medication: Record<string, unknown> & {
|
||||
id: string;
|
||||
unitsPerDose: unknown;
|
||||
trackIntake: boolean;
|
||||
schedules: Array<{ unitsPerDose: Prisma.Decimal | null }>;
|
||||
},
|
||||
): Promise<Response> {
|
||||
let category = "OTHER";
|
||||
let categoryLabel: string | null = null;
|
||||
try {
|
||||
const categories = await resolveMedicationCategories([medication.id]);
|
||||
category = categories[medication.id]?.category ?? "OTHER";
|
||||
categoryLabel = categories[medication.id]?.categoryLabel ?? null;
|
||||
} catch {
|
||||
getEvent()?.addWarning("Medication categories could not be loaded");
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.create",
|
||||
entity_type: "medication",
|
||||
entity_id: medication.id,
|
||||
},
|
||||
meta: { idempotent_replay: true },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
...medication,
|
||||
unitsPerDose: Number(medication.unitsPerDose),
|
||||
// #219 — Decimal → number for the per-schedule column too.
|
||||
// v1.39.1 (#1033) — record-only medications ship `schedules: []`.
|
||||
...scheduleWireFields(
|
||||
medication.trackIntake,
|
||||
serializeScheduleUnitsPerDose(
|
||||
medication.schedules,
|
||||
Number(medication.unitsPerDose),
|
||||
),
|
||||
),
|
||||
category,
|
||||
categoryLabel,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The create is wrapped in `withIdempotency` so a client replaying its offline
|
||||
* outbox after a lost success response replays the first answer instead of
|
||||
* minting a second medication. The `(externalSource, externalId)` dedupe below
|
||||
* only ever covered a MIRRORED create; a manually entered medication carries
|
||||
* neither field and had nothing to collapse a retry onto.
|
||||
* minting a second medication. The `(externalSource, externalId)` dedupe in
|
||||
* `createMedication` only ever covered a MIRRORED create; a manually entered
|
||||
* medication carries neither field and had nothing to collapse a retry onto.
|
||||
*/
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postMedication));
|
||||
|
||||
@@ -165,377 +78,17 @@ async function postMedication(request: NextRequest): Promise<Response> {
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
const {
|
||||
name,
|
||||
dose,
|
||||
category,
|
||||
treatmentClass,
|
||||
dosesPerUnit,
|
||||
unitsPerDose,
|
||||
reorderLeadDays,
|
||||
deliveryForm,
|
||||
trackInjectionSites,
|
||||
allowedInjectionSites,
|
||||
notificationsEnabled,
|
||||
liveActivityEnabled,
|
||||
criticalAlarmEnabled,
|
||||
atcCode,
|
||||
rxNormCode,
|
||||
externalSource,
|
||||
externalId,
|
||||
schedules,
|
||||
startsOn,
|
||||
endsOn,
|
||||
oneShot,
|
||||
asNeeded,
|
||||
trackIntake,
|
||||
autoMarkTaken,
|
||||
} = parsed.data;
|
||||
|
||||
// v1.40 (#1041) — a custom category must be one of this record's own.
|
||||
if (
|
||||
category !== undefined &&
|
||||
!(await isAssignableCategory(user.id, category))
|
||||
) {
|
||||
return apiError("Unknown medication category", 422, {
|
||||
errorCode: "medications.category.unknown",
|
||||
});
|
||||
}
|
||||
|
||||
// v1.28 — idempotent mirror create. A mirrored medication (Apple
|
||||
// Health) is keyed by the `(userId, externalSource, externalId)`
|
||||
// unique; a re-post of the same concept id (iOS re-sync, retry after a
|
||||
// dropped response) returns the EXISTING medication with 200 instead
|
||||
// of minting a duplicate or 500-ing on P2002. The pre-query covers the
|
||||
// common replay; the P2002 catch around the create below covers the
|
||||
// concurrent race.
|
||||
if (externalSource !== undefined && externalId !== undefined) {
|
||||
const existing = await prisma.medication.findFirst({
|
||||
where: { userId: user.id, externalSource, externalId },
|
||||
include: { schedules: true },
|
||||
});
|
||||
if (existing) {
|
||||
return respondWithExistingMirror(existing);
|
||||
}
|
||||
|
||||
// v1.32.25 — growth guard. This point is only reached when the
|
||||
// idempotency lookup MISSED, i.e. this is a genuinely NEW mirror row,
|
||||
// not a replay of one the user already holds (a replay returned 200
|
||||
// above). An idempotent re-post of an existing mirror is therefore
|
||||
// never blocked, even for a user already at the cap. Refuse only the
|
||||
// minting of a fresh row once the user already holds the cap of
|
||||
// Apple-Health-mirrored medications, so a client feeding a rotating
|
||||
// key can no longer fill the list with duplicates. The count runs on
|
||||
// the mirror-create-miss path only; native creates (no
|
||||
// `externalSource`) never reach this branch and pay nothing.
|
||||
const mirroredCount = await prisma.medication.count({
|
||||
where: { userId: user.id, externalSource: "APPLE_HEALTH" },
|
||||
});
|
||||
if (mirroredCount >= APPLE_HEALTH_MIRROR_CAP) {
|
||||
annotate({
|
||||
action: { name: "medication.mirror.limit_exceeded" },
|
||||
meta: { existing: mirroredCount },
|
||||
});
|
||||
return apiError(
|
||||
"This account already mirrors the maximum number of medications from an external source",
|
||||
422,
|
||||
{ errorCode: "medications.mirror.limit_exceeded" },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── v1.5 route invariants for the new scheduling primitives ───────
|
||||
//
|
||||
// The Zod layer already enforces `rrule` xor `rollingIntervalDays`
|
||||
// (scheduleSchema.refine). The route layer enforces the cross-field
|
||||
// invariants that span medication + schedules:
|
||||
//
|
||||
// 1. **One-shot consistency** — when `oneShot === true`:
|
||||
// a. The medication has at most ONE schedule.
|
||||
// b. The single schedule carries neither `rrule` nor
|
||||
// `rollingIntervalDays` (a one-shot dose IS the schedule).
|
||||
// c. `endsOn` is normalised to equal `startsOn` on write so the
|
||||
// worker's date-range cap matches the one-and-only slot.
|
||||
//
|
||||
// 2. **Recurring default** — when `oneShot !== true` AND the
|
||||
// schedule has no `rrule`, no `rollingIntervalDays`, and no
|
||||
// legacy `daysOfWeek`, the route stamps `rrule = "FREQ=DAILY"`
|
||||
// so the canonical recurrence engine has a clean shape going
|
||||
// forward instead of falling through to the legacy parser.
|
||||
//
|
||||
// 3. **iOS contract dual-write** — when `timesOfDay` is absent or
|
||||
// empty, the route stamps `[windowStart]` so the new engine
|
||||
// always sees a populated `timesOfDay` while legacy iOS clients
|
||||
// (v0.6.x) keep encoding the `windowStart` / `windowEnd` /
|
||||
// `daysOfWeek` shape. Both shapes coexist through v1.5.x.
|
||||
// 4. **As-needed (v1.16.11, #316)** — when `asNeeded === true` the
|
||||
// medication carries ZERO schedules (the Zod refine already
|
||||
// rejects a populated array, mutual exclusion with `oneShot`
|
||||
// included). Every "never due / never reminded / never scored"
|
||||
// surface follows structurally from the empty schedule list.
|
||||
const scheduleInputs = schedules ?? [];
|
||||
if (oneShot === true) {
|
||||
if (scheduleInputs.length > 1) {
|
||||
return apiError(
|
||||
"A one-shot medication can have at most one schedule",
|
||||
422,
|
||||
);
|
||||
}
|
||||
const s = scheduleInputs[0];
|
||||
if (s && (s.rrule !== undefined || s.rollingIntervalDays !== undefined)) {
|
||||
return apiError(
|
||||
"A one-shot medication cannot have a recurrence (rrule or rollingIntervalDays)",
|
||||
422,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Normalise endsOn for one-shot. Zod gives us `Date | null | undefined`.
|
||||
const normalisedEndsOn =
|
||||
oneShot === true && startsOn ? startsOn : (endsOn ?? undefined);
|
||||
|
||||
// v1.40 (#1024) — a medication created with a window starts with one
|
||||
// course; the row projects it. An end without a start has always meant
|
||||
// "running since creation", so the course starts today (or on the end day,
|
||||
// when that lies earlier). No window: no course, chronic since creation.
|
||||
let initialCourse: { startsOn: Date; endsOn: Date | null } | null = null;
|
||||
if (startsOn || normalisedEndsOn) {
|
||||
const todayKey = userDayKey(new Date(), user.timezone || DEFAULT_TIMEZONE);
|
||||
const endKey = normalisedEndsOn ? dayKeyOfDate(normalisedEndsOn) : null;
|
||||
initialCourse = {
|
||||
startsOn:
|
||||
startsOn ??
|
||||
dateOfDayKey(endKey && endKey < todayKey ? endKey : todayKey),
|
||||
endsOn: normalisedEndsOn ?? null,
|
||||
};
|
||||
const refusal = validateCourses(
|
||||
[initialCourse],
|
||||
todayKey,
|
||||
oneShot === true,
|
||||
);
|
||||
if (refusal) {
|
||||
const r = courseRefusalResponse(refusal);
|
||||
return apiError(r.message, r.status, { errorCode: r.errorCode });
|
||||
}
|
||||
}
|
||||
|
||||
const createMedication = () =>
|
||||
prisma.medication.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
name,
|
||||
dose,
|
||||
// v1.4.25 — treatmentClass + dosesPerUnit are optional in the
|
||||
// wire schema; Prisma fills the default GENERIC when omitted.
|
||||
...(treatmentClass !== undefined && { treatmentClass }),
|
||||
...(dosesPerUnit !== undefined && { dosesPerUnit }),
|
||||
// v1.16.10 — units consumed per dose; Prisma defaults to 1 when omitted.
|
||||
...(unitsPerDose !== undefined && { unitsPerDose }),
|
||||
// v1.17.0 — optional reorder lead override; null/omitted = inherit
|
||||
// the user-level default in the low-stock alert.
|
||||
...(reorderLeadDays !== undefined && { reorderLeadDays }),
|
||||
// v1.6.0 — route of administration; Prisma defaults to ORAL when omitted.
|
||||
...(deliveryForm !== undefined && { deliveryForm }),
|
||||
// v1.8.5 — injection-site tracking opt-in + per-medication allowed
|
||||
// sites; Prisma defaults to false / [] when omitted.
|
||||
...(trackInjectionSites !== undefined && { trackInjectionSites }),
|
||||
...(allowedInjectionSites !== undefined && { allowedInjectionSites }),
|
||||
// v1.7.0 — iOS reminder flags; Prisma defaults both to false.
|
||||
...(liveActivityEnabled !== undefined && { liveActivityEnabled }),
|
||||
...(criticalAlarmEnabled !== undefined && { criticalAlarmEnabled }),
|
||||
// v1.9.0 — optional drug-classification codes (ATC / RxNorm).
|
||||
// Validated for format by Zod; stored verbatim when present.
|
||||
...(atcCode !== undefined && { atcCode }),
|
||||
...(rxNormCode !== undefined && { rxNormCode }),
|
||||
// v1.28 — mirrored-medication provenance (Apple Health). Zod
|
||||
// enforces the both-or-neither pairing; field-by-field like every
|
||||
// other column.
|
||||
...(externalSource !== undefined && { externalSource }),
|
||||
...(externalId !== undefined && { externalId }),
|
||||
// v1.5 — wizard's reminders toggle now ships through the create
|
||||
// payload (was orphaned in the initial diff). Prisma defaults to
|
||||
// true when omitted, matching the legacy form's behaviour.
|
||||
...(notificationsEnabled !== undefined && { notificationsEnabled }),
|
||||
// v1.5 scheduling primitives — pass-through when supplied.
|
||||
...(startsOn !== undefined && { startsOn }),
|
||||
...(normalisedEndsOn !== undefined && { endsOn: normalisedEndsOn }),
|
||||
...(initialCourse && {
|
||||
startsOn: initialCourse.startsOn,
|
||||
endsOn: initialCourse.endsOn,
|
||||
courses: {
|
||||
create: {
|
||||
userId: user.id,
|
||||
startsOn: initialCourse.startsOn,
|
||||
endsOn: initialCourse.endsOn,
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(oneShot !== undefined && { oneShot }),
|
||||
// v1.16.11 — as-needed flag, field-by-field. An asNeeded create
|
||||
// carries an empty `scheduleInputs`, so the nested create below
|
||||
// persists zero schedule rows.
|
||||
...(asNeeded !== undefined && { asNeeded }),
|
||||
// v1.39.1 (#1033) — intake tracking, field-by-field. Created off,
|
||||
// the schedule is stored as a record from the start; the column
|
||||
// default (true) covers every caller that does not send it.
|
||||
...(trackIntake !== undefined && { trackIntake }),
|
||||
// v1.42.2 — auto-mark-taken, field-by-field. Created on, the
|
||||
// auto-take job fills slots from this moment only.
|
||||
...(autoMarkTaken !== undefined && {
|
||||
autoMarkTaken,
|
||||
autoMarkTakenSince: autoMarkTaken ? new Date() : null,
|
||||
}),
|
||||
schedules: {
|
||||
create: scheduleInputs.map((s) => {
|
||||
// Invariant 2 — default to FREQ=DAILY when nothing else is set.
|
||||
// v1.7.0 — PRN schedules carry no cadence, so never default
|
||||
// them to FREQ=DAILY (they would otherwise project + remind).
|
||||
const hasLegacyDays = (s.daysOfWeek?.length ?? 0) > 0;
|
||||
const isPrn = s.scheduleType === "PRN";
|
||||
const defaultedRrule =
|
||||
!oneShot &&
|
||||
!isPrn &&
|
||||
s.rrule === undefined &&
|
||||
s.rollingIntervalDays === undefined &&
|
||||
!hasLegacyDays
|
||||
? "FREQ=DAILY"
|
||||
: s.rrule;
|
||||
|
||||
// Invariant 3 — dual-write `timesOfDay` from windowStart when
|
||||
// the legacy-shape iOS client doesn't send the new field.
|
||||
const effectiveTimesOfDay =
|
||||
s.timesOfDay && s.timesOfDay.length > 0
|
||||
? s.timesOfDay
|
||||
: [s.windowStart];
|
||||
|
||||
return {
|
||||
windowStart: s.windowStart,
|
||||
windowEnd: s.windowEnd,
|
||||
label: s.label ?? null,
|
||||
dose: s.dose ?? null,
|
||||
// #219 — per-schedule inventory units. Field-by-field (no mass
|
||||
// assignment); absent leaves the column NULL so the consume
|
||||
// hook inherits the medication-level units_per_dose.
|
||||
...(s.unitsPerDose !== undefined && {
|
||||
unitsPerDose: s.unitsPerDose,
|
||||
}),
|
||||
daysOfWeek: serializeScheduleRecurrence({
|
||||
daysOfWeek: s.daysOfWeek ?? [],
|
||||
intervalWeeks: s.intervalWeeks ?? 1,
|
||||
}),
|
||||
// v1.5 first-class times-of-day.
|
||||
timesOfDay: effectiveTimesOfDay,
|
||||
...(s.reminderGraceMinutes !== undefined && {
|
||||
reminderGraceMinutes: s.reminderGraceMinutes,
|
||||
}),
|
||||
...(defaultedRrule !== undefined && { rrule: defaultedRrule }),
|
||||
...(s.rollingIntervalDays !== undefined && {
|
||||
rollingIntervalDays: s.rollingIntervalDays,
|
||||
}),
|
||||
// v1.7.0 — schedule type + cyclic weeks, field-by-field.
|
||||
...(s.scheduleType !== undefined && {
|
||||
scheduleType: s.scheduleType,
|
||||
}),
|
||||
...(s.cyclicOnWeeks !== undefined && {
|
||||
cyclicOnWeeks: s.cyclicOnWeeks,
|
||||
}),
|
||||
...(s.cyclicOffWeeks !== undefined && {
|
||||
cyclicOffWeeks: s.cyclicOffWeeks,
|
||||
}),
|
||||
// v1.15.18 — per-dose configurable on-time windows. Stored as the
|
||||
// validated `{ timeOfDay, start, end }[]` JSON; absent leaves the
|
||||
// column NULL (every slot on the default ±1h derivation).
|
||||
...(s.doseWindows !== undefined && {
|
||||
doseWindows: s.doseWindows,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
include: { schedules: true },
|
||||
});
|
||||
|
||||
let medication: Awaited<ReturnType<typeof createMedication>>;
|
||||
try {
|
||||
medication = await createMedication();
|
||||
} catch (err: unknown) {
|
||||
// v1.28 — P2002 on the mirror triple: a concurrent create of the
|
||||
// same `(userId, externalSource, externalId)` won the race between
|
||||
// the pre-query above and this insert. Resolve to the winning row
|
||||
// and answer idempotently instead of 500-ing. Any other unique
|
||||
// violation (there is none on this table today) rethrows.
|
||||
const isP2002 =
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "P2002";
|
||||
if (isP2002 && externalSource !== undefined && externalId !== undefined) {
|
||||
const winner = await prisma.medication.findFirst({
|
||||
where: { userId: user.id, externalSource, externalId },
|
||||
include: { schedules: true },
|
||||
});
|
||||
if (winner) return respondWithExistingMirror(winner);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const normalizedCategory = await setMedicationCategory(
|
||||
medication.id,
|
||||
category,
|
||||
);
|
||||
const categoryLabel = isCustomMedicationCategoryKey(normalizedCategory)
|
||||
? ((await resolveMedicationCategories([medication.id]))[medication.id]
|
||||
?.categoryLabel ?? null)
|
||||
: null;
|
||||
|
||||
await auditLog("medication.create", {
|
||||
userId: user.id,
|
||||
const outcome = await createMedication({
|
||||
user,
|
||||
data: parsed.data,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
medicationId: medication.id,
|
||||
name,
|
||||
// v1.42.2 — a medication created with its doses recorded
|
||||
// automatically says so in its audit row.
|
||||
autoMarkTaken: medication.autoMarkTaken,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.create",
|
||||
entity_type: "medication",
|
||||
entity_id: medication.id,
|
||||
},
|
||||
});
|
||||
|
||||
// v1.4.34 — bust per-user medications + compliance + achievement
|
||||
// caches so the next read reflects the new schedule.
|
||||
invalidateUserMedications(user.id, { evict: true });
|
||||
|
||||
return apiSuccess(
|
||||
{
|
||||
...medication,
|
||||
unitsPerDose: Number(medication.unitsPerDose),
|
||||
// #219 — Decimal → number for the per-schedule column too.
|
||||
// v1.39.1 (#1033) — record-only medications ship `schedules: []`.
|
||||
...scheduleWireFields(
|
||||
medication.trackIntake,
|
||||
serializeScheduleUnitsPerDose(
|
||||
medication.schedules,
|
||||
medication.unitsPerDose,
|
||||
),
|
||||
),
|
||||
category: normalizedCategory,
|
||||
categoryLabel,
|
||||
// v1.40 (#1024) — the courses, as every medication read carries them.
|
||||
...(
|
||||
await resolveCourseFields(
|
||||
[medication],
|
||||
new Date(),
|
||||
user.timezone || DEFAULT_TIMEZONE,
|
||||
)
|
||||
).get(medication.id),
|
||||
},
|
||||
201,
|
||||
);
|
||||
switch (outcome.kind) {
|
||||
case "refused":
|
||||
return apiError(outcome.message, outcome.status, outcome.meta);
|
||||
case "existing":
|
||||
return apiSuccess(outcome.body);
|
||||
case "created":
|
||||
return apiSuccess(outcome.body, 201);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user