feat(medications): end a course now through its own action

"End course" now posts to `POST /api/medications/{id}/courses/end`, which
ends the running course at that moment: its last day becomes today on the
person's clock and the instant is stored as `endedAt`, so a dose later today
is not due, not reminded and never missed, while one taken earlier still
counts. Pending placeholders already minted for later slots are tombstoned.
A medication without dates gets the course its window describes, ended now.

End stays its own verb instead of `PUT { endsOn }`: an end date set through
the PUT or the course editor keeps meaning the whole day, and the PUT keeps
accepting it on any course, since moving an end is a legitimate edit.

The list and detail reads serve `canEndCourse`, true exactly while a course
is running, and the action refuses with 409 `medications.course.notRunning`
when it is false, so no client can reopen an ended course or invent a
one-day course from a planned one by ending it. The web controls render End
from the served flag; the contributed tests keep their cases against it.

Refs #1280
This commit is contained in:
Marc-André Bombeck committed 2026-10-24 22:24:15 +02:00
1 parent 23a67f61e6
commit 275367f6e9
15 files changed
+990 -124

No files matched your search

@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import {
canEndCourse,
canStartCourse,
courseEndNow,
courseFromWindow,
courseStatusAt,
courseStatusOn,
@@ -186,6 +188,29 @@ describe("ending a course now (#1280)", () => {
expect(at("2026-06-12T22:00:00.000Z")).toBe("ENDED");
});
it("offers End only while a course runs", () => {
expect(canEndCourse("CURRENT")).toBe(true);
expect(canEndCourse("ENDED")).toBe(false);
expect(canEndCourse("UPCOMING")).toBe(false);
// No dates at all is running.
expect(
canEndCourse(
courseStatusAt({ startsOn: null, endsOn: null }, ENDED_AT, "UTC"),
),
).toBe(true);
});
it("ends on the person's own day, at the moment itself", () => {
const late = new Date("2026-06-11T23:30:00.000Z");
expect(courseEndNow(late, "Europe/Warsaw")).toEqual({
endsOn: d("2026-06-12"),
endedAt: late,
});
expect(courseEndNow(late, "America/New_York").endsOn).toEqual(
d("2026-06-11"),
);
});
it("lets a new course start once the ended one is behind it", () => {
const base = { active: true, oneShot: false, todayKey: "2026-06-12" };
expect(canStartCourse({ ...base, courses: [MARCH, ended] })).toBe(true);
@@ -46,6 +46,7 @@ describe.each(ZONES)("course window in %s", (tz) => {
expect(r).toEqual({
courseStatus: "CURRENT",
intakeActionable: true,
canEndCourse: true,
});
}
});
@@ -55,6 +56,7 @@ describe.each(ZONES)("course window in %s", (tz) => {
expect(r).toEqual({
courseStatus: "ENDED",
intakeActionable: false,
canEndCourse: false,
});
});
@@ -63,10 +65,12 @@ describe.each(ZONES)("course window in %s", (tz) => {
expect(resolveIntakeActionability(med, at(tz, 24, 23, 59), tz)).toEqual({
courseStatus: "UPCOMING",
intakeActionable: false,
canEndCourse: false,
});
expect(resolveIntakeActionability(med, at(tz, 25, 0, 0), tz)).toEqual({
courseStatus: "CURRENT",
intakeActionable: true,
canEndCourse: true,
});
});
});
@@ -90,6 +94,7 @@ describe("resolveIntakeActionability", () => {
expect(r).toEqual({
courseStatus: "CURRENT",
intakeActionable: false,
canEndCourse: true,
});
});
@@ -102,6 +107,7 @@ describe("resolveIntakeActionability", () => {
expect(r).toEqual({
courseStatus: "CURRENT",
intakeActionable: false,
canEndCourse: true,
});
});
@@ -131,6 +137,7 @@ describe("a course ended with End course (#1280)", () => {
expect(before).toEqual({
courseStatus: "CURRENT",
intakeActionable: true,
canEndCourse: true,
});
const after = resolveIntakeActionability(
ended,
@@ -140,6 +147,7 @@ describe("a course ended with End course (#1280)", () => {
expect(after).toEqual({
courseStatus: "ENDED",
intakeActionable: false,
canEndCourse: false,
});
});
});
+23
View File
@@ -143,6 +143,29 @@ export function courseStatusAt(
return "CURRENT";
}
/**
* #1280 — the end "End course" writes: the person's own calendar day as the
* course's last day (never the UTC one, a day off around midnight), and the
* moment itself as `endedAt`.
*/
export function courseEndNow(
now: Date,
timeZone: string,
): { endsOn: Date; endedAt: Date } {
return { endsOn: dateOfDayKey(userDayKey(now, timeZone)), endedAt: now };
}
/**
* #1280 — whether "End course" may be pressed: a course is running now. On
* a course that has ended, ending it again would reopen it up to today; on
* one that has not started, it would turn into a one-day course today. The
* medication read wire publishes the answer as `canEndCourse`, and the End
* action refuses when it is false.
*/
export function canEndCourse(courseStatus: CourseStatus): boolean {
return courseStatus === "CURRENT";
}
export type CourseRefusal =
/** `endsOn` before `startsOn`. */
| "invalidRange"
+98 -4
View File
@@ -10,16 +10,21 @@
* and `intakeActionable` — which read the columns — can never disagree with
* the course list.
*
* #1280 — a course may carry `endedAt`, the instant it was ended at. Every
* write that moves a course's `endsOn` clears it: an end date chosen in the
* editor means the whole day.
* #1280 — "End course" (`endCurrentCourse`) ends the running course at the
* moment it is pressed: `endsOn` becomes today and `endedAt` records the
* instant, so no slot after it is due, reminded or expected. Every other
* write that moves a course's `endsOn` clears `endedAt`: an end date chosen
* in the editor means the whole day.
*/
import type { Prisma } from "@/generated/prisma/client";
import { decryptFromBytes, encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { prisma } from "@/lib/db";
import {
canEndCourse,
canStartCourse,
courseEndNow,
courseFromWindow,
courseStatusAt,
courseStatusOn,
dateOfDayKey,
dayKeyOfDate,
@@ -43,7 +48,9 @@ export type CourseWriteRefusal =
/** Clearing the window of a medication that has several courses. */
| "windowRequired"
/** The course or the medication is not the caller's. */
| "notFound";
| "notFound"
/** #1280 — "End course" on a medication with no course running now. */
| "notRunning";
export class CourseWriteError extends Error {
constructor(readonly refusal: CourseWriteRefusal) {
@@ -89,6 +96,12 @@ export function courseRefusalResponse(refusal: CourseWriteRefusal): {
errorCode: "medications.course.invalidRange",
message: "A course cannot end before it starts",
};
case "notRunning":
return {
status: 409,
errorCode: "medications.course.notRunning",
message: "No course is running to end",
};
case "windowRequired":
return {
status: 422,
@@ -450,6 +463,87 @@ function keptEndedAt(
: null;
}
/**
* #1280 — "End course": end the running course now.
*
* The course's last day becomes today on the person's clock and `endedAt`
* records the moment. Doses earlier today stay inside the course and count;
* a slot later today is not due, not reminded and not expected, and the
* course reads as ENDED at once (`courseStatusAt`). A medication without a
* course row (chronic since creation, or a window never materialised) gets
* the course its window describes, ended now.
*
* The pending placeholders already minted for slots at or after that moment
* (the today projector mints the whole day) are tombstoned, as a schedule
* replace does, so no list shows them and the auto-miss pass never stamps
* them a miss. An actioned row is history and stays.
*
* Refused with `notRunning` unless a course is running now
* (`canEndCourse`): ending an ended course would reopen it up to today, and
* ending one that has not started would invent a one-day course.
*/
export async function endCurrentCourse(
args: WriteContext,
): Promise<ProjectedWindow> {
const now = args.now ?? new Date();
const todayKey = userDayKey(now, args.timeZone);
const { endsOn: today, endedAt } = courseEndNow(now, args.timeZone);
return prisma.$transaction(async (tx) => {
await lockMedication(tx, args.medicationId);
const { medication, courses } = await loadOwned(
tx,
args.userId,
args.medicationId,
);
if (!canEndCourse(courseStatusAt(medication, now, args.timeZone))) {
throw new CourseWriteError("notRunning");
}
const latest = sortCourses(courses).at(-1);
if (latest) {
const ended = { startsOn: latest.startsOn, endsOn: today, endedAt };
refuseIfInvalid(
courses.map((c) => (c.id === latest.id ? ended : c)),
todayKey,
medication.oneShot,
);
await tx.medicationCourse.update({
where: { id: latest.id },
data: { endsOn: today, endedAt },
});
} else {
const implicit = windowAsCourse(
medication.startsOn,
today,
undefined,
medication.createdAt,
args.timeZone,
);
refuseIfInvalid([implicit], todayKey, medication.oneShot);
await tx.medicationCourse.create({
data: {
medicationId: args.medicationId,
userId: args.userId,
...implicit,
endedAt,
},
});
}
await tx.medicationIntakeEvent.updateMany({
where: {
userId: args.userId,
medicationId: args.medicationId,
deletedAt: null,
takenAt: null,
skipped: false,
autoMissed: false,
scheduledFor: { gte: now },
},
data: { deletedAt: now, syncVersion: { increment: 1 } },
});
return project(tx, args.medicationId);
});
}
/**
* Whether the window a PUT is about to write would be refused. Checked
* BEFORE the medication row is updated, so a refused window leaves the row
+7 -2
View File
@@ -23,10 +23,13 @@
* Logging a past dose from the history is a different verb and is not
* gated here; an ended course can still be completed after the fact.
*
* #1280 — a course ended at an instant (`endedAt`) is ENDED from it, so the
* action row goes away at once instead of at midnight.
* #1280 — `canEndCourse` rides along: "End course" is offered exactly while
* the course is CURRENT, from the same resolution. A course ended with it is
* ENDED from that instant (`endedAt`), so the action row and the End button
* go away at once instead of at midnight.
*/
import {
canEndCourse,
courseStatusAt,
type CourseStatus,
} from "@/lib/medications/course-window";
@@ -35,6 +38,7 @@ import { isRecordOnly } from "@/lib/medications/intake-tracking";
export interface IntakeActionability {
courseStatus: CourseStatus;
intakeActionable: boolean;
canEndCourse: boolean;
}
export function resolveIntakeActionability(
@@ -55,5 +59,6 @@ export function resolveIntakeActionability(
medication.active &&
!isRecordOnly(medication) &&
courseStatus === "CURRENT",
canEndCourse: canEndCourse(courseStatus),
};
}
+1
View File
@@ -312,6 +312,7 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
"medications.course.invalid",
"medications.course.invalidRange",
"medications.course.notFound",
"medications.course.notRunning",
"medications.course.oneShot",
"medications.course.overlap",
"medications.course.windowRequired",
@@ -1178,6 +1178,45 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/medications/{id}/courses/end": {
post: {
parameters: [idempotencyKeyParameter],
tags: ["Medications"],
summary: "End the running course now",
description:
"#1280 — \"End course\". No body. The running course's last day becomes today on the person's clock and the moment is stored as its `endedAt`: a dose slot later today is not due, not reminded and not expected by compliance, a dose taken earlier today still counts, and `courseStatus` reads ENDED at once. Pending placeholders for slots at or after the moment are removed (tombstoned for sync). A medication with no dates gets the course its window describes, from creation to today. An end date set through `PUT /api/medications/{id}` or the course editor keeps meaning the whole day; only this action ends a course at an instant. Refused with 409 `medications.course.notRunning` while no course is running — the rule the reads publish as `canEndCourse`. Owner-only.",
requestParams: { path: z.object({ id: z.string() }) },
responses: {
...idempotentWrite(),
"200": {
description: "The medication's window after ending.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
startsOn: z.iso.date().nullable(),
endsOn: z.iso.date().nullable(),
endedAt: isoDateTime().nullable(),
}),
"EndMedicationCourseResponse",
),
},
},
},
"404": {
description:
"Medication not found (`medications.course.notFound`), or another user's.",
content: { "application/json": { schema: errorEnvelope } },
},
"409": {
description:
"No course is running now (`medications.course.notRunning`): it has ended already or has not started.",
content: { "application/json": { schema: errorEnvelope } },
},
...stdResponses,
},
},
},
"/api/medications/{id}/courses/{courseId}": {
patch: {
tags: ["Medications"],
+14 -4
View File
@@ -69,7 +69,7 @@ export const medicationCourseResource = z
endedAt: isoDateTime()
.nullable()
.describe(
'#1280 — the instant "End course" ended this course, on its `endsOn` day. No dose slot at or after it is due, reminded or expected, and the course is ENDED from it on. NULL when the whole `endsOn` day counts (an end date set in the editor). Any edit that moves `endsOn` clears it.',
"#1280 — the instant `POST /api/medications/{id}/courses/end` ended this course, on its `endsOn` day. No dose slot at or after it is due, reminded or expected, and the course is ENDED from it on. NULL when the whole `endsOn` day counts (an end date set in the editor). Any edit that moves `endsOn` clears it.",
),
status: z
.enum(["UPCOMING", "CURRENT", "ENDED"])
@@ -375,7 +375,7 @@ export const medicationResource = z
.nullable()
.optional()
.describe(
'#1280 — the instant the latest course was ended with "End course" (the course\'s own `endedAt`). From it on no dose is due or reminded and `courseStatus` is ENDED; NULL when the course runs to the end of `endsOn`. Read-only — written by the course writer only.',
"#1280 — the instant the latest course was ended with `POST /api/medications/{id}/courses/end` (the course's own `endedAt`). From it on no dose is due or reminded and `courseStatus` is ENDED; NULL when the course runs to the end of `endsOn`. Read-only — written by the course writer only.",
),
oneShot: z
.boolean()
@@ -453,13 +453,18 @@ export const medicationListEntry = medicationResource
courseStatus: z
.enum(["UPCOMING", "CURRENT", "ENDED"])
.describe(
'v1.39.4 — where today (on the user\'s clock) sits in the course: UPCOMING before `startsOn`, ENDED after `endsOn`, CURRENT otherwise. Calendar days, both ends inclusive, so a course that ends today is CURRENT all day, unless it was ended with "End course": then it is ENDED from that instant (`endedAt`). Read-only — computed, not stored.',
"v1.39.4 — where today (on the user's clock) sits in the course: UPCOMING before `startsOn`, ENDED after `endsOn`, CURRENT otherwise. Calendar days, both ends inclusive, so a course that ends today is CURRENT all day, unless it was ended with `POST /api/medications/{id}/courses/end`: then it is ENDED from that instant (`endedAt`). Read-only — computed, not stored.",
),
intakeActionable: z
.boolean()
.describe(
"v1.39.4 — whether the medication offers taken / skip today: true only when it is `active`, its intake is tracked (`trackIntake`) and `courseStatus` is CURRENT. Clients render the dose actions from this and do not re-derive it. Logging a past dose from the history is not gated by it. Read-only — computed, not stored.",
),
canEndCourse: z
.boolean()
.describe(
'#1280 — whether `POST /api/medications/{id}/courses/end` may end the course now: true exactly while a course is running (`courseStatus` CURRENT; a medication with no dates is running). Clients offer "End course" from this and do not re-derive it; the action refuses with 409 `medications.course.notRunning` when it is false. Read-only — computed, not stored.',
),
lastTakenAt: isoDateTime()
.nullable()
.describe(
@@ -519,13 +524,18 @@ export const medicationDetailEntry = medicationResource
courseStatus: z
.enum(["UPCOMING", "CURRENT", "ENDED"])
.describe(
'v1.39.4 — where today (on the user\'s clock) sits in the course: UPCOMING before `startsOn`, ENDED after `endsOn`, CURRENT otherwise. Calendar days, both ends inclusive, so a course that ends today is CURRENT all day, unless it was ended with "End course": then it is ENDED from that instant (`endedAt`). Read-only — computed, not stored.',
"v1.39.4 — where today (on the user's clock) sits in the course: UPCOMING before `startsOn`, ENDED after `endsOn`, CURRENT otherwise. Calendar days, both ends inclusive, so a course that ends today is CURRENT all day, unless it was ended with `POST /api/medications/{id}/courses/end`: then it is ENDED from that instant (`endedAt`). Read-only — computed, not stored.",
),
intakeActionable: z
.boolean()
.describe(
"v1.39.4 — whether the medication offers taken / skip today: true only when it is `active`, its intake is tracked (`trackIntake`) and `courseStatus` is CURRENT. Clients render the dose actions from this and do not re-derive it. Logging a past dose from the history is not gated by it. Read-only — computed, not stored.",
),
canEndCourse: z
.boolean()
.describe(
'#1280 — whether `POST /api/medications/{id}/courses/end` may end the course now: true exactly while a course is running (`courseStatus` CURRENT; a medication with no dates is running). Clients offer "End course" from this and do not re-derive it; the action refuses with 409 `medications.course.notRunning` when it is false. Read-only — computed, not stored.',
),
stockUnitsRemaining: z
.number()
.nullable()