mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
Let a medication have several courses
A medication taken now and then (#1024) keeps one row and gains course rows: calendar spans, both ends inclusive, an optional encrypted note, no schedule or dose of their own. Courses never overlap and every course but the latest has ended, so the latest course is always the one the medication's startsOn/endsOn project. src/lib/medications/courses.ts is the only writer of those two columns for a medication with courses; it writes under a per-medication advisory lock and re-projects in the same transaction, so reminders, the next-due line and intakeActionable keep reading the columns and stay right. - Migration 0368 adds medication_courses and backfills one course per medication window (an end-only window starts on the creation day, or on its end day when that lies earlier); a medication without a window stays course-less. Idempotent, data-preserving. - GET/POST /api/medications/{id}/courses and PATCH/DELETE .../courses/{courseId} (owner-only); create seeds the first course from a window; the medication PUT edits the latest course and refuses a window that would break the rules (medications.course.*). - List, detail, create and update carry courses, courseCount, previousCourseEndedOn and canStartCourse, resolved on the server. - Compliance expands over the span of all courses and drops the slots between them; every compliance read selects the courses. A rolling cadence is not anchored by an intake from a previous course. - The card names the last course's end and the running course's number; the detail Lifecycle group lists the courses with start, edit and delete. The Coach compliance block, the MCP resource, the doctor report window and table, the clinician view and FHIR (one MedicationStatement per course with effectivePeriod and status) read the courses. - Backup carries courses per medication and the restore writes them and re-projects; an older file derives the one course its window describes. Wipe plan, encrypted columns, rotation and OpenAPI follow.
This commit is contained in:
1 parent
9b71231010
commit
a14174fe4d
71 files changed
+3635
-90
No files matched your search
@@ -190,6 +190,23 @@ function makePrisma() {
|
||||
createdAt: new Date("2026-07-15T08:01:00.000Z"),
|
||||
},
|
||||
],
|
||||
// v1.40 (#1024) — one ended course with a note, one running.
|
||||
courses: [
|
||||
{
|
||||
id: "course-march",
|
||||
startsOn: new Date("2026-03-01T00:00:00.000Z"),
|
||||
endsOn: new Date("2026-03-07T00:00:00.000Z"),
|
||||
noteEncrypted: encryptToBytes("the March flu"),
|
||||
createdAt: new Date("2026-03-01T08:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "course-june",
|
||||
startsOn: new Date("2026-06-10T00:00:00.000Z"),
|
||||
endsOn: null,
|
||||
noteEncrypted: null,
|
||||
createdAt: new Date("2026-06-10T08:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
// A two-step ramp, one row carrying an encrypted note and one
|
||||
// without, so both arms of the note contract are exercised.
|
||||
doseChanges: [
|
||||
@@ -743,6 +760,35 @@ describe("buildFullBackupPayload disaster-recovery mode", () => {
|
||||
* into a portable export and losing the note are opposite failures of the same
|
||||
* decision.
|
||||
*/
|
||||
describe("buildFullBackupPayload — medication courses (v1.40, #1024)", () => {
|
||||
it.each(["portable-export", "disaster-recovery"] as const)(
|
||||
"carries every course with its note readable in a %s file",
|
||||
async (purpose) => {
|
||||
installSectionMocks();
|
||||
const { payload } = await buildFullBackupPayload(
|
||||
makePrisma() as never,
|
||||
"user-1",
|
||||
{ purpose, exportedAt: new Date("2026-07-20T00:00:00.000Z") },
|
||||
);
|
||||
const parsed = parseBackupPayload(payload);
|
||||
expect(parsed.medications[0].courses).toEqual([
|
||||
{
|
||||
startsOn: "2026-03-01",
|
||||
endsOn: "2026-03-07",
|
||||
note: "the March flu",
|
||||
createdAt: "2026-03-01T08:00:00.000Z",
|
||||
},
|
||||
{
|
||||
startsOn: "2026-06-10",
|
||||
endsOn: null,
|
||||
note: null,
|
||||
createdAt: "2026-06-10T08:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("buildFullBackupPayload — medication side effects", () => {
|
||||
it("decrypts the note and emits no ciphertext in a portable export", async () => {
|
||||
installSectionMocks();
|
||||
|
||||
@@ -86,6 +86,9 @@ export const BACKED_UP_MODELS = [
|
||||
// The categories the person named themselves (v1.40, #1041). A medication
|
||||
// filed under one carries its key; without the row the key reads as Other.
|
||||
"MedicationCategoryLabel",
|
||||
// The courses (v1.40, #1024). Once a second one exists the earlier spans
|
||||
// live here and nowhere else; the medication row keeps only the latest.
|
||||
"MedicationCourse",
|
||||
|
||||
// ── Mood ──────────────────────────────────────────────────────────────────
|
||||
"MoodEntry",
|
||||
@@ -314,6 +317,7 @@ export const TWO_ENDED_MODELS = [
|
||||
"MedicationDoseChange",
|
||||
"MedicationCategoryAssignment",
|
||||
"MedicationCategoryLabel",
|
||||
"MedicationCourse",
|
||||
"MoodEntry",
|
||||
"MoodContext",
|
||||
"MoodEntryTagLink",
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
* one reaches the other; the integration suite pins the two outputs byte for
|
||||
* byte rather than trusting that sentence.
|
||||
*/
|
||||
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
|
||||
import { dayKeyOfDate } from "@/lib/medications/course-window";
|
||||
import { Buffer } from "node:buffer";
|
||||
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
|
||||
import { readNote } from "@/lib/crypto/note-cipher";
|
||||
@@ -735,6 +737,7 @@ export async function buildFullBackupPayload(
|
||||
schedules: true,
|
||||
sideEffects: { orderBy: { occurredAt: "desc" } },
|
||||
pauseEras: { orderBy: { pausedAt: "asc" } },
|
||||
courses: { orderBy: { startsOn: "asc" } },
|
||||
doseChanges: { orderBy: { effectiveFrom: "asc" } },
|
||||
inventoryItems: { orderBy: { createdAt: "asc" } },
|
||||
inventoryEvents: { orderBy: { occurredAt: "asc" } },
|
||||
@@ -1119,6 +1122,15 @@ export async function buildFullBackupPayload(
|
||||
resumedAt: p.resumedAt ? p.resumedAt.toISOString() : null,
|
||||
createdAt: p.createdAt.toISOString(),
|
||||
})),
|
||||
// v1.40 (#1024) — the courses: "when did I last take this" lives here
|
||||
// and nowhere else once a second course exists. The medication's own
|
||||
// window above is the projection of the latest one.
|
||||
courses: m.courses.map((c) => ({
|
||||
startsOn: dayKeyOfDate(c.startsOn),
|
||||
endsOn: c.endsOn ? dayKeyOfDate(c.endsOn) : null,
|
||||
note: c.noteEncrypted ? decryptFromBytes(c.noteEncrypted) : null,
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
})),
|
||||
// Titration: when the dose moved, to what, and why. The drug comes
|
||||
// back at today's dose either way; without these the ramp that led to
|
||||
// it is gone, and that ramp is what a prescriber asks about.
|
||||
|
||||
@@ -27,6 +27,11 @@
|
||||
* replacement is still one transaction, so a failure part-way leaves the
|
||||
* account exactly as it was.
|
||||
*/
|
||||
import {
|
||||
dateOfDayKey,
|
||||
dayKeyOfDate,
|
||||
projectCourseWindow,
|
||||
} from "@/lib/medications/course-window";
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { prisma, toJson } from "@/lib/db";
|
||||
@@ -1301,6 +1306,59 @@ export async function restoreBackup(
|
||||
);
|
||||
}
|
||||
|
||||
// v1.40 (#1024) — the courses, then the window they project. A file
|
||||
// written before courses existed carries none; the medication's own
|
||||
// window then describes its one course, derived exactly as the
|
||||
// migration's backfill did (an end-only window runs from creation,
|
||||
// or from its end day when that lies earlier).
|
||||
const courseRows: Array<{
|
||||
startsOn: Date;
|
||||
endsOn: Date | null;
|
||||
note: string | null;
|
||||
createdAt?: Date;
|
||||
}> =
|
||||
m.courses !== undefined
|
||||
? m.courses.map((c) => ({
|
||||
startsOn: dateOfDayKey(c.startsOn),
|
||||
endsOn: c.endsOn ? dateOfDayKey(c.endsOn) : null,
|
||||
note: c.note ?? null,
|
||||
...(c.createdAt ? { createdAt: new Date(c.createdAt) } : {}),
|
||||
}))
|
||||
: created.startsOn || created.endsOn
|
||||
? [
|
||||
{
|
||||
startsOn:
|
||||
created.startsOn ??
|
||||
(created.endsOn &&
|
||||
created.endsOn.getTime() <
|
||||
dateOfDayKey(
|
||||
dayKeyOfDate(created.createdAt),
|
||||
).getTime()
|
||||
? created.endsOn
|
||||
: dateOfDayKey(dayKeyOfDate(created.createdAt))),
|
||||
endsOn: created.endsOn,
|
||||
note: null,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
if (courseRows.length > 0) {
|
||||
await tx.medicationCourse.createMany({
|
||||
data: courseRows.map((c) => ({
|
||||
medicationId: created.id,
|
||||
userId: ownerId,
|
||||
startsOn: c.startsOn,
|
||||
endsOn: c.endsOn,
|
||||
noteEncrypted: c.note ? encryptToBytes(c.note) : null,
|
||||
...(c.createdAt ? { createdAt: c.createdAt } : {}),
|
||||
})),
|
||||
});
|
||||
const window = projectCourseWindow(courseRows);
|
||||
await tx.medication.update({
|
||||
where: { id: created.id },
|
||||
data: { startsOn: window.startsOn, endsOn: window.endsOn },
|
||||
});
|
||||
}
|
||||
|
||||
// ── The archived schedule eras, in two passes ────────────────
|
||||
//
|
||||
// An era carries `supersededByRevisionId`, the pointer from a
|
||||
|
||||
Reference in new issue
Block a user