mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
feat(medications,admin): the schedule's history is visible and invites count their uses
The schedule tab shows its eras as a collapsible timeline — current plan since its date, predecessors with their times and span — and a past era can be added manually for old history, with validation against overlaps and the live plan. Invite creation chooses one to fifty uses and the redemption list scrolls.
This commit is contained in:
1 parent
a62e00cfcd
commit
5639da4333
11 files changed
+1847
No files matched your search
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* v1.16.5 — DELETE /api/medications/[id]/schedule-revisions/[revisionId]
|
||||
*
|
||||
* Removes a MANUAL schedule era (one the owner appended through the
|
||||
* sibling POST). Write-path archives (`source: "ARCHIVED"`) are
|
||||
* immutable history — the wholesale-replace path minted them from rows
|
||||
* that actually existed, so deleting one would falsify the ledger; the
|
||||
* route refuses with 409.
|
||||
*
|
||||
* Auth: requireAuth() + medication ownership; a revision belonging to
|
||||
* another medication (or another user's medication) surfaces as 404,
|
||||
* existence channel sealed like every medication sub-route.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
import { enqueueUserMedicationComplianceBackfill } from "@/lib/rollups/medication-compliance-rollups";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string; revisionId: string }> };
|
||||
|
||||
export const DELETE = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
const { id, revisionId } = await params;
|
||||
|
||||
const guard = await assertMedicationOwnership(id, user.id);
|
||||
if (guard) return guard;
|
||||
|
||||
const revision = await prisma.medicationScheduleRevision.findUnique({
|
||||
where: { id: revisionId },
|
||||
select: { id: true, medicationId: true, source: true },
|
||||
});
|
||||
if (!revision || revision.medicationId !== id) {
|
||||
return apiError("Schedule revision not found", 404);
|
||||
}
|
||||
|
||||
if (revision.source !== "MANUAL") {
|
||||
return apiError(
|
||||
"Only manually added schedule eras can be deleted",
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.medicationScheduleRevision.delete({
|
||||
where: { id: revisionId },
|
||||
});
|
||||
|
||||
await auditLog("medication.schedule_revision.deleted", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, revisionId },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.schedule_revision.manual_deleted",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { revision_id: revisionId },
|
||||
});
|
||||
|
||||
// History re-segments without the era; refresh the pre-aggregated
|
||||
// compliance rollups asynchronously (best-effort).
|
||||
await enqueueUserMedicationComplianceBackfill(user.id);
|
||||
|
||||
return apiSuccess({ deleted: true });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,328 @@
|
||||
/**
|
||||
* v1.16.5 — schedule-era endpoints: ownership, validation, provenance.
|
||||
*
|
||||
* GET /api/medications/[id]/schedule-revisions
|
||||
* POST /api/medications/[id]/schedule-revisions
|
||||
* DELETE /api/medications/[id]/schedule-revisions/[revisionId]
|
||||
*
|
||||
* The POST guards are the contract under test: a manual era must end
|
||||
* at or before the start of the live plan, must not overlap an
|
||||
* archived era, and is always minted with `source: "MANUAL"`. The
|
||||
* DELETE refuses write-path archives (409) so the immutable history
|
||||
* the replace path mints can never be falsified through the API.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medication: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
medicationScheduleRevision: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
|
||||
enqueueUserMedicationComplianceBackfill: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ enqueued: true, error: null }),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { GET, POST } from "../route";
|
||||
import { DELETE } from "../[revisionId]/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { enqueueUserMedicationComplianceBackfill } from "@/lib/rollups/medication-compliance-rollups";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: { id: "user-1", username: "tester", role: "USER" as const },
|
||||
};
|
||||
|
||||
const ROUTE_CTX = { params: Promise.resolve({ id: "m1" }) };
|
||||
|
||||
function getReq(): NextRequest {
|
||||
return new NextRequest(
|
||||
"http://localhost/api/medications/m1/schedule-revisions",
|
||||
);
|
||||
}
|
||||
|
||||
function postReq(body: unknown): NextRequest {
|
||||
return new NextRequest(
|
||||
"http://localhost/api/medications/m1/schedule-revisions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function deleteReq(revisionId: string): NextRequest {
|
||||
return new NextRequest(
|
||||
`http://localhost/api/medications/m1/schedule-revisions/${revisionId}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
}
|
||||
|
||||
function deleteCtx(revisionId: string) {
|
||||
return { params: Promise.resolve({ id: "m1", revisionId }) };
|
||||
}
|
||||
|
||||
const MED_CREATED_AT = new Date("2026-01-10T08:00:00Z");
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
// Ownership guard + GET both read `medication.findUnique`; the guard
|
||||
// selects `{ id, userId }`, the GET selects `{ createdAt }` — one
|
||||
// superset row satisfies both.
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "m1",
|
||||
userId: "user-1",
|
||||
createdAt: MED_CREATED_AT,
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationScheduleRevision.findMany).mockResolvedValue(
|
||||
[] as never,
|
||||
);
|
||||
});
|
||||
|
||||
describe("GET /api/medications/[id]/schedule-revisions", () => {
|
||||
it("404s for another user's medication (existence sealed)", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "m1",
|
||||
userId: "someone-else",
|
||||
createdAt: MED_CREATED_AT,
|
||||
} as never);
|
||||
const res = await GET(getReq(), ROUTE_CTX);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns currentSince = createdAt when no revision exists", async () => {
|
||||
const res = await GET(getReq(), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
expect(json.data.currentSince).toBe(MED_CREATED_AT.toISOString());
|
||||
expect(json.data.revisions).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns currentSince = newest validUntil and summarised entries", async () => {
|
||||
vi.mocked(prisma.medicationScheduleRevision.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "rev-2",
|
||||
validFrom: new Date("2026-03-01T00:00:00Z"),
|
||||
validUntil: new Date("2026-05-01T00:00:00Z"),
|
||||
source: "ARCHIVED",
|
||||
payload: [
|
||||
{
|
||||
timesOfDay: ["07:00", "19:00"],
|
||||
label: "Morgens",
|
||||
dose: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "rev-1",
|
||||
validFrom: new Date("2026-01-10T08:00:00Z"),
|
||||
validUntil: new Date("2026-03-01T00:00:00Z"),
|
||||
source: "MANUAL",
|
||||
// Malformed payload must degrade, never throw on a read path.
|
||||
payload: { not: "an array" },
|
||||
},
|
||||
] as never);
|
||||
|
||||
const res = await GET(getReq(), ROUTE_CTX);
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
expect(json.data.currentSince).toBe("2026-05-01T00:00:00.000Z");
|
||||
expect(json.data.revisions).toHaveLength(2);
|
||||
expect(json.data.revisions[0].entries[0].timesOfDay).toEqual([
|
||||
"07:00",
|
||||
"19:00",
|
||||
]);
|
||||
expect(json.data.revisions[1].entries).toEqual([]);
|
||||
expect(json.data.revisions[1].source).toBe("MANUAL");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/medications/[id]/schedule-revisions", () => {
|
||||
const VALID_BODY = {
|
||||
validFrom: "2025-03-12T00:00:00.000Z",
|
||||
validUntil: "2025-06-01T00:00:00.000Z",
|
||||
timesOfDay: ["19:00", "07:00"],
|
||||
};
|
||||
|
||||
it("404s for another user's medication", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "m1",
|
||||
userId: "someone-else",
|
||||
createdAt: MED_CREATED_AT,
|
||||
} as never);
|
||||
const res = await POST(postReq(VALID_BODY), ROUTE_CTX);
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.medicationScheduleRevision.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("422s when validFrom is not before validUntil", async () => {
|
||||
const res = await POST(
|
||||
postReq({ ...VALID_BODY, validUntil: VALID_BODY.validFrom }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("422s on a malformed time literal", async () => {
|
||||
const res = await POST(
|
||||
postReq({ ...VALID_BODY, timesOfDay: ["25:99"] }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("422s when the era overlaps an archived era", async () => {
|
||||
vi.mocked(prisma.medicationScheduleRevision.findMany).mockResolvedValue([
|
||||
{
|
||||
validFrom: new Date("2025-05-01T00:00:00Z"),
|
||||
validUntil: new Date("2026-01-01T00:00:00Z"),
|
||||
},
|
||||
] as never);
|
||||
const res = await POST(postReq(VALID_BODY), ROUTE_CTX);
|
||||
expect(res.status).toBe(422);
|
||||
const json = await res.json();
|
||||
expect(json.error).toMatch(/overlap/i);
|
||||
});
|
||||
|
||||
it("422s when the era ends after the live plan began", async () => {
|
||||
vi.mocked(prisma.medicationScheduleRevision.findMany).mockResolvedValue([
|
||||
{
|
||||
validFrom: new Date("2025-01-01T00:00:00Z"),
|
||||
validUntil: new Date("2025-04-01T00:00:00Z"),
|
||||
},
|
||||
] as never);
|
||||
// Ends 2025-06-01 — after the live plan start (2025-04-01) — and
|
||||
// does NOT overlap the archived era; the boundary check must fire.
|
||||
const res = await POST(
|
||||
postReq({ ...VALID_BODY, validFrom: "2025-04-01T00:00:00.000Z" }),
|
||||
ROUTE_CTX,
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const json = await res.json();
|
||||
expect(json.error).toMatch(/current plan/i);
|
||||
});
|
||||
|
||||
it("creates a MANUAL revision with a daily snapshot entry", async () => {
|
||||
vi.mocked(prisma.medicationScheduleRevision.create).mockResolvedValue({
|
||||
id: "rev-new",
|
||||
validFrom: new Date(VALID_BODY.validFrom),
|
||||
validUntil: new Date(VALID_BODY.validUntil),
|
||||
source: "MANUAL",
|
||||
payload: [],
|
||||
} as never);
|
||||
|
||||
const res = await POST(postReq(VALID_BODY), ROUTE_CTX);
|
||||
expect(res.status).toBe(201);
|
||||
|
||||
const createArgs = vi.mocked(prisma.medicationScheduleRevision.create)
|
||||
.mock.calls[0][0] as unknown as {
|
||||
data: {
|
||||
medicationId: string;
|
||||
source: string;
|
||||
payload: Array<{
|
||||
timesOfDay: string[];
|
||||
rrule: string | null;
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
scheduleType: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
expect(createArgs.data.medicationId).toBe("m1");
|
||||
expect(createArgs.data.source).toBe("MANUAL");
|
||||
expect(createArgs.data.payload).toHaveLength(1);
|
||||
// Times sorted ascending; window pulled to their min/max; daily.
|
||||
expect(createArgs.data.payload[0].timesOfDay).toEqual(["07:00", "19:00"]);
|
||||
expect(createArgs.data.payload[0].windowStart).toBe("07:00");
|
||||
expect(createArgs.data.payload[0].windowEnd).toBe("19:00");
|
||||
expect(createArgs.data.payload[0].rrule).toBe("FREQ=DAILY");
|
||||
expect(createArgs.data.payload[0].scheduleType).toBe("SCHEDULED");
|
||||
|
||||
// History re-segmented — the rollup backfill must be enqueued.
|
||||
expect(enqueueUserMedicationComplianceBackfill).toHaveBeenCalledWith(
|
||||
"user-1",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/medications/[id]/schedule-revisions/[revisionId]", () => {
|
||||
it("404s when the revision belongs to another medication", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
id: "rev-x",
|
||||
medicationId: "other-med",
|
||||
source: "MANUAL",
|
||||
} as never);
|
||||
const res = await DELETE(deleteReq("rev-x"), deleteCtx("rev-x"));
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.medicationScheduleRevision.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("409s for a write-path archive", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
id: "rev-a",
|
||||
medicationId: "m1",
|
||||
source: "ARCHIVED",
|
||||
} as never);
|
||||
const res = await DELETE(deleteReq("rev-a"), deleteCtx("rev-a"));
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.medicationScheduleRevision.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes a MANUAL era and enqueues the rollup backfill", async () => {
|
||||
vi.mocked(
|
||||
prisma.medicationScheduleRevision.findUnique,
|
||||
).mockResolvedValue({
|
||||
id: "rev-m",
|
||||
medicationId: "m1",
|
||||
source: "MANUAL",
|
||||
} as never);
|
||||
vi.mocked(prisma.medicationScheduleRevision.delete).mockResolvedValue(
|
||||
{} as never,
|
||||
);
|
||||
const res = await DELETE(deleteReq("rev-m"), deleteCtx("rev-m"));
|
||||
expect(res.status).toBe(200);
|
||||
const json = await res.json();
|
||||
expect(json.data.deleted).toBe(true);
|
||||
expect(prisma.medicationScheduleRevision.delete).toHaveBeenCalledWith({
|
||||
where: { id: "rev-m" },
|
||||
});
|
||||
expect(enqueueUserMedicationComplianceBackfill).toHaveBeenCalledWith(
|
||||
"user-1",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* v1.16.5 — schedule-era management for the Zeitplan tab.
|
||||
*
|
||||
* GET /api/medications/[id]/schedule-revisions
|
||||
* - lists the medication's archived schedule eras (newest first)
|
||||
* plus `currentSince`, the instant the LIVE plan took over (the
|
||||
* newest revision's `validUntil`, or `medication.createdAt` when
|
||||
* no era has been archived yet).
|
||||
*
|
||||
* POST /api/medications/[id]/schedule-revisions
|
||||
* - appends a MANUAL era for pre-tracking history ("dosed at
|
||||
* 07:00/19:00 from March to June"). Validation: the era must end
|
||||
* at or before the start of the live era and must not overlap
|
||||
* any existing revision. The snapshot payload mirrors what the
|
||||
* write-path archive mints (`FREQ=DAILY`, window pulled to the
|
||||
* min/max of the times) so the era minter — ledger, compliance,
|
||||
* cadence chips — reads it like any other revision.
|
||||
*
|
||||
* Auth: cookie-session or Bearer via requireAuth(); the medication is
|
||||
* verified to belong to the caller before any read or write. Deleting
|
||||
* a manual era lives in the `[revisionId]` sub-route.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
|
||||
import { scheduleRevisionCreateSchema } from "@/lib/validations/schedule-revision";
|
||||
import {
|
||||
toRevisionPayloadEntry,
|
||||
type ScheduleRevisionEntry,
|
||||
} from "@/lib/medications/scheduling/schedule-eras";
|
||||
import { enqueueUserMedicationComplianceBackfill } from "@/lib/rollups/medication-compliance-rollups";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* Display projection of one archived schedule row. Defensive parsing —
|
||||
* a malformed payload entry degrades to an empty summary instead of
|
||||
* throwing on a read path (mirrors `canonicalSchedulesFromRevision`).
|
||||
*/
|
||||
function summariseEntries(payload: unknown): Array<{
|
||||
timesOfDay: string[];
|
||||
label: string | null;
|
||||
dose: string | null;
|
||||
scheduleType: string;
|
||||
}> {
|
||||
if (!Array.isArray(payload)) return [];
|
||||
return payload.map((raw) => {
|
||||
const e = (raw ?? {}) as Partial<ScheduleRevisionEntry>;
|
||||
return {
|
||||
timesOfDay: Array.isArray(e.timesOfDay)
|
||||
? e.timesOfDay.filter((t): t is string => typeof t === "string")
|
||||
: [],
|
||||
label: typeof e.label === "string" ? e.label : null,
|
||||
dose: typeof e.dose === "string" ? e.dose : null,
|
||||
scheduleType: typeof e.scheduleType === "string" ? e.scheduleType : "SCHEDULED",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (_request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
const { id } = await params;
|
||||
|
||||
const guard = await assertMedicationOwnership(id, user.id);
|
||||
if (guard) return guard;
|
||||
|
||||
const med = await prisma.medication.findUnique({
|
||||
where: { id },
|
||||
select: { createdAt: true },
|
||||
});
|
||||
if (!med) {
|
||||
return apiError("Medication not found", 404);
|
||||
}
|
||||
|
||||
const revisions = await prisma.medicationScheduleRevision.findMany({
|
||||
where: { medicationId: id },
|
||||
orderBy: { validFrom: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
validFrom: true,
|
||||
validUntil: true,
|
||||
source: true,
|
||||
payload: true,
|
||||
},
|
||||
});
|
||||
|
||||
// The live plan has been current since the newest archived era
|
||||
// ended; with no archive it has been current since creation.
|
||||
const currentSince =
|
||||
revisions.length > 0
|
||||
? revisions.reduce(
|
||||
(latest, r) => (r.validUntil > latest ? r.validUntil : latest),
|
||||
revisions[0].validUntil,
|
||||
)
|
||||
: med.createdAt;
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.schedule_revisions.list",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { revision_count: revisions.length },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
currentSince: currentSince.toISOString(),
|
||||
revisions: revisions.map((r) => ({
|
||||
id: r.id,
|
||||
validFrom: r.validFrom.toISOString(),
|
||||
validUntil: r.validUntil.toISOString(),
|
||||
source: r.source,
|
||||
entries: summariseEntries(r.payload),
|
||||
})),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const POST = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
const { id } = await params;
|
||||
|
||||
const guard = await assertMedicationOwnership(id, user.id);
|
||||
if (guard) return guard;
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 16 * 1024,
|
||||
});
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = scheduleRevisionCreateSchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
const validFrom = new Date(parsed.data.validFrom);
|
||||
const validUntil = new Date(parsed.data.validUntil);
|
||||
|
||||
// Sanity floor — a fat-fingered year ("0203") would otherwise mint
|
||||
// an era the timeline renders as antiquity.
|
||||
if (validFrom.getUTCFullYear() < 1900) {
|
||||
return apiError("validFrom must be a date after 1900", 422);
|
||||
}
|
||||
|
||||
const existing = await prisma.medicationScheduleRevision.findMany({
|
||||
where: { medicationId: id },
|
||||
select: { validFrom: true, validUntil: true },
|
||||
});
|
||||
|
||||
// "Before the current plan": the live era began at the newest
|
||||
// archived `validUntil`; with no archive it spans up to now, so a
|
||||
// manual era may cover anything up to this instant.
|
||||
const liveStart = existing.reduce(
|
||||
(latest, r) => (r.validUntil > latest ? r.validUntil : latest),
|
||||
new Date(0),
|
||||
);
|
||||
const liveBoundary = existing.length > 0 ? liveStart : new Date();
|
||||
if (validUntil.getTime() > liveBoundary.getTime()) {
|
||||
return apiError(
|
||||
"A manual era must end before the current plan begins",
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
// No overlap with any archived interval `[validFrom, validUntil)`.
|
||||
const overlaps = existing.some(
|
||||
(r) =>
|
||||
validFrom.getTime() < r.validUntil.getTime() &&
|
||||
validUntil.getTime() > r.validFrom.getTime(),
|
||||
);
|
||||
if (overlaps) {
|
||||
return apiError("The era overlaps an existing schedule era", 422);
|
||||
}
|
||||
|
||||
// Snapshot entry shaped exactly like the write-path archive: daily
|
||||
// recurrence at the given times, window pulled to their min/max.
|
||||
const times = [...parsed.data.timesOfDay].sort((a, b) =>
|
||||
a.localeCompare(b),
|
||||
);
|
||||
const entry = toRevisionPayloadEntry({
|
||||
timesOfDay: times,
|
||||
windowStart: times[0],
|
||||
windowEnd: times[times.length - 1],
|
||||
daysOfWeek: null,
|
||||
rrule: "FREQ=DAILY",
|
||||
rollingIntervalDays: null,
|
||||
scheduleType: "SCHEDULED",
|
||||
cyclicOnWeeks: null,
|
||||
cyclicOffWeeks: null,
|
||||
doseWindows: null,
|
||||
label: null,
|
||||
dose: null,
|
||||
reminderGraceMinutes: null,
|
||||
});
|
||||
|
||||
const revision = await prisma.medicationScheduleRevision.create({
|
||||
data: {
|
||||
medicationId: id,
|
||||
validFrom,
|
||||
validUntil,
|
||||
source: "MANUAL",
|
||||
payload: [entry] as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
validFrom: true,
|
||||
validUntil: true,
|
||||
source: true,
|
||||
payload: true,
|
||||
},
|
||||
});
|
||||
|
||||
await auditLog("medication.schedule_revision.created", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { medicationId: id, revisionId: revision.id },
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: {
|
||||
name: "medication.schedule_revision.manual_created",
|
||||
entity_type: "medication",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: {
|
||||
revision_id: revision.id,
|
||||
era_days: Math.round(
|
||||
(validUntil.getTime() - validFrom.getTime()) / 86_400_000,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
// The new era re-segments history the compliance rollups already
|
||||
// pre-aggregated; refresh them asynchronously. Best-effort like
|
||||
// every other rollup write-hook.
|
||||
await enqueueUserMedicationComplianceBackfill(user.id);
|
||||
|
||||
return apiSuccess(
|
||||
{
|
||||
id: revision.id,
|
||||
validFrom: revision.validFrom.toISOString(),
|
||||
validUntil: revision.validUntil.toISOString(),
|
||||
source: revision.source,
|
||||
entries: summariseEntries(revision.payload),
|
||||
},
|
||||
201,
|
||||
);
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user