Merge branch 'fix/meds-ended-and-mental-health' into release/v1.39.4

This commit is contained in:
Marc-André Bombeck committed 2026-09-27 14:18:09 +02:00
commit 206da07e8c
42 files changed
+1075 -34

No files matched your search

@@ -12,6 +12,13 @@ const mocks = vi.hoisted(() => ({
buildRecordsBackupSection: vi.fn(),
}));
// The category side table is raw SQL on the shared client; the round trip
// through it is proven in tests/integration/backup-round-trip.test.ts.
vi.mock("@/lib/medication-category", () => ({
ensureMedicationCategoryTable: vi.fn(async () => {}),
getMedicationCategories: vi.fn(async () => ({})),
setMedicationCategory: vi.fn(async () => "OTHER"),
}));
vi.mock("@/lib/export/paged-measurements", () => ({
iterateMeasurementPages: mocks.iterateMeasurementPages,
}));
@@ -31,6 +31,13 @@ const mocks = vi.hoisted(() => ({
transaction: vi.fn(),
}));
// The category side table is raw SQL on the shared client; the round trip
// through it is proven in tests/integration/backup-round-trip.test.ts.
vi.mock("@/lib/medication-category", () => ({
ensureMedicationCategoryTable: vi.fn(async () => {}),
getMedicationCategories: vi.fn(async () => ({})),
setMedicationCategory: vi.fn(async () => "OTHER"),
}));
vi.mock("@/lib/db", () => ({
prisma: {
dataBackup: { findUnique: vi.fn() },
+18
View File
@@ -706,6 +706,24 @@ export const NOT_IN_BACKUP_MODELS: Readonly<Record<string, string>> = {
"Feedback on generated recommendations that are themselves DERIVED. Restoring the feedback without the item it judged leaves an orphan.",
};
/**
* Tables created with raw SQL at runtime rather than declared in the schema.
* Every check above walks `schema.prisma`, so a table outside it is invisible
* to all of them — which is how the medication category went missing from
* every backup until v1.39.4. The guard beside this file finds each
* `CREATE TABLE IF NOT EXISTS` in the source and demands a verdict here, or a
* schema model mapped to the same name.
*/
export const RAW_SQL_TABLES: Readonly<
Record<string, { verdict: "BACKED_UP" | "NOT_IN_BACKUP"; reason: string }>
> = {
medication_categories: {
verdict: "BACKED_UP",
reason:
"The clinical category the person chose for each medication. Carried inside its medication in both backup formats and written back in the restore transaction; without it every restored medication reads as Other.",
},
};
/** Auth material: not user data, and excluded from the wipe for the same reason. */
export const AUTH_MODELS_OUT_OF_SCOPE: readonly string[] = [
"Session",
+11
View File
@@ -118,6 +118,7 @@ import {
type OnboardingBackupCounts,
type OnboardingBackupSection,
} from "@/lib/export/onboarding-backup";
import { getMedicationCategories } from "@/lib/medication-category";
export interface FullBackupCounts
extends
@@ -943,6 +944,14 @@ export async function buildFullBackupPayload(
: moodEntries!,
};
// The clinical category lives in a raw side table rather than on the
// medication row, so no Prisma include reaches it. Before v1.39.4 no backup
// carried it and every restored medication came back as "Other".
const categoryByMedication = await getMedicationCategories(
medications.map((m) => m.id),
prisma,
);
// Where each archived era sits in its OWN drug's ordered list. Built once
// here rather than per row, and scoped per medication because the supersede
// pointer never crosses a drug — every route that writes it scopes the
@@ -1008,6 +1017,8 @@ export async function buildFullBackupPayload(
// record only. Both purposes carry it: a restore that dropped it would
// start reminding them about a medication they chose not to track.
trackIntake: m.trackIntake,
// Both purposes: the category is something the person chose.
category: categoryByMedication[m.id] ?? "OTHER",
// Both purposes carry the creation instant: it is the floor of the
// medication's expected slots, so a restore stamped with the restore
// time would read the whole restored history as predating the
+14
View File
@@ -101,6 +101,10 @@ import { restoreAwardsData } from "@/lib/export/awards-backup";
import { restoreEnvironmentData } from "@/lib/export/environment-backup";
import { restoreEcgData } from "@/lib/export/ecg-backup";
import { restoredMedicationCreatedAt } from "@/lib/export/medication-created-at";
import {
ensureMedicationCategoryTable,
setMedicationCategory,
} from "@/lib/medication-category";
import { invalidateUserData } from "@/lib/cache/invalidate";
import { TOMBSTONE_RETENTION_DAYS } from "@/lib/auth/native-client";
import { stampSyncReset } from "@/lib/sync/reset";
@@ -671,6 +675,10 @@ export async function restoreBackup(
cleared: RestoreResponse["cleared"];
skipped: RestoreSkipSummary;
};
// The category side table is created lazily. Doing that here, before the
// transaction, keeps its DDL (which takes a table lock) out of a
// transaction that already holds row locks on the same table.
await ensureMedicationCategoryTable();
try {
report("clearing");
outcome = await prisma.$transaction(
@@ -1245,6 +1253,12 @@ export async function restoreBackup(
});
restoredMedicationIds.add(created.id);
if (!medByName.has(m.name)) medByName.set(m.name, created.id);
// v1.39.4 — the clinical category lives in a side table keyed on the
// medication id, so it is written after the row exists and inside the
// same transaction. OTHER is what a missing row already reads as.
if (m.category && m.category !== "OTHER") {
await setMedicationCategory(created.id, m.category, tx);
}
// ── The archived schedule eras, in two passes ────────────────
//
+16 -3
View File
@@ -7,6 +7,17 @@ export type MedicationCategory = (typeof MEDICATION_CATEGORIES)[number];
const DEFAULT_CATEGORY: MedicationCategory = "OTHER";
/**
* The raw-SQL surface the helpers below need. The default is the shared
* client; the backup builder and the restore pass their own (the restore's
* transaction client, so a category row lands in the same transaction as
* the medication it points at and its foreign key can see that row).
*/
type RawSqlClient = Pick<
typeof prisma,
"$queryRawUnsafe" | "$executeRawUnsafe"
>;
let ensureTablePromise: Promise<void> | null = null;
function normalizeCategory(input: unknown): MedicationCategory {
@@ -16,7 +27,7 @@ function normalizeCategory(input: unknown): MedicationCategory {
: DEFAULT_CATEGORY;
}
async function ensureMedicationCategoryTable() {
export async function ensureMedicationCategoryTable() {
if (!ensureTablePromise) {
ensureTablePromise = (async () => {
await prisma.$executeRawUnsafe(`
@@ -42,11 +53,12 @@ async function ensureMedicationCategoryTable() {
export async function getMedicationCategories(
medicationIds: string[],
client: RawSqlClient = prisma,
): Promise<Record<string, MedicationCategory>> {
if (medicationIds.length === 0) return {};
await ensureMedicationCategoryTable();
const rows = await prisma.$queryRawUnsafe<
const rows = await client.$queryRawUnsafe<
Array<{ medication_id: string; category: string }>
>(
`
@@ -70,11 +82,12 @@ export async function getMedicationCategories(
export async function setMedicationCategory(
medicationId: string,
category: unknown,
client: RawSqlClient = prisma,
) {
await ensureMedicationCategoryTable();
const normalized = normalizeCategory(category);
await prisma.$executeRawUnsafe(
await client.$executeRawUnsafe(
`
INSERT INTO medication_categories (medication_id, category, updated_at)
VALUES ($1, $2, NOW())
@@ -0,0 +1,103 @@
/**
* #1040 — a medication whose course has ended must not offer a dose.
* The course bounds are calendar dates (UTC midnight of the date); only
* `now` is read on the user's clock. A course that ends today stays
* actionable for the whole local day, east and west of UTC.
*/
import { describe, expect, it } from "vitest";
import { zonedWallClockToUtc } from "@/lib/tz/wall-clock";
import { resolveIntakeActionability } from "../intake-actionable";
const ZONES = [
"America/Los_Angeles",
"America/New_York",
"Europe/Berlin",
"Asia/Tokyo",
"Pacific/Auckland",
] as const;
const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
function at(tz: string, d: number, hour: number, minute = 0): Date {
return zonedWallClockToUtc(
{ year: 2026, month: 9, day: d, hour, minute },
tz,
);
}
const base = {
active: true,
trackIntake: true,
startsOn: day("2026-09-01"),
endsOn: day("2026-09-20"),
};
describe.each(ZONES)("course window in %s", (tz) => {
it("is actionable on the last course day, from local midnight to 23:59", () => {
for (const [h, m] of [
[0, 0],
[8, 0],
[23, 59],
] as const) {
const r = resolveIntakeActionability(base, at(tz, 20, h, m), tz);
expect(r).toEqual({ courseStatus: "CURRENT", intakeActionable: true });
}
});
it("is ended from local midnight of the day after endsOn", () => {
const r = resolveIntakeActionability(base, at(tz, 21, 0, 0), tz);
expect(r).toEqual({ courseStatus: "ENDED", intakeActionable: false });
});
it("is upcoming until local midnight of startsOn", () => {
const med = { ...base, startsOn: day("2026-09-25"), endsOn: null };
expect(resolveIntakeActionability(med, at(tz, 24, 23, 59), tz)).toEqual({
courseStatus: "UPCOMING",
intakeActionable: false,
});
expect(resolveIntakeActionability(med, at(tz, 25, 0, 0), tz)).toEqual({
courseStatus: "CURRENT",
intakeActionable: true,
});
});
});
describe("resolveIntakeActionability", () => {
const tz = "Europe/Berlin";
const now = at(tz, 10, 9);
it("treats an open-ended course as current", () => {
expect(
resolveIntakeActionability(
{ ...base, startsOn: null, endsOn: null },
now,
tz,
).intakeActionable,
).toBe(true);
});
it("refuses a paused or archived medication inside its course", () => {
const r = resolveIntakeActionability({ ...base, active: false }, now, tz);
expect(r).toEqual({ courseStatus: "CURRENT", intakeActionable: false });
});
it("refuses a record-only medication inside its course", () => {
const r = resolveIntakeActionability(
{ ...base, trackIntake: false },
now,
tz,
);
expect(r).toEqual({ courseStatus: "CURRENT", intakeActionable: false });
});
it("reports ENDED for a course that is also paused", () => {
const r = resolveIntakeActionability(
{ ...base, active: false },
at(tz, 22, 9),
tz,
);
expect(r.courseStatus).toBe("ENDED");
});
});
+1
View File
@@ -34,6 +34,7 @@ const MEDICATION_CATEGORY_KEYS: Record<string, string> = {
SLEEP_AID: "medications.categorySleepAid",
DIABETES: "medications.categoryDiabetes",
ANTIBIOTIC: "medications.categoryAntibiotic",
MENTAL_HEALTH: "medications.categoryMentalHealth",
OTHER: "medications.categoryOther",
};
+55
View File
@@ -0,0 +1,55 @@
/**
* v1.39.4 (#1040) — whether a medication offers "taken" / "skip" today.
*
* One rule, resolved on the server and published on the medication read
* wire as `intakeActionable` (with the `courseStatus` it derives from), so
* the web cards, the table, the take-all flow and the iOS app all answer
* the same question the same way instead of each re-deriving it:
*
* - the medication is active (not paused or archived),
* - its intake is tracked (`trackIntake`, see `intake-tracking.ts`), and
* - its course includes today on the user's clock (`courseStatusAt`:
* `startsOn <= today <= endsOn`, calendar days, both ends inclusive).
*
* The due-slot question is already the schedule engine's: it caps every
* slot at `endsOn` and floors it at `startsOn`, so the reminder worker, the
* dashboard doses card and the today list never mint a dose outside the
* course. What was missing was the action row on the medication itself,
* which only looked at `active` and so kept offering a dose for a course
* that had ended. Within the course the row stays available between slots
* on purpose: taking a dose early is a supported flow with its own
* double-dose guard.
*
* 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.
*/
import {
courseStatusAt,
type CourseStatus,
} from "@/lib/medications/scheduling/recurrence";
import { isRecordOnly } from "@/lib/medications/intake-tracking";
export interface IntakeActionability {
courseStatus: CourseStatus;
intakeActionable: boolean;
}
export function resolveIntakeActionability(
medication: {
active: boolean;
trackIntake: boolean;
startsOn: Date | null;
endsOn: Date | null;
},
now: Date,
timeZone: string,
): IntakeActionability {
const courseStatus = courseStatusAt(medication, now, timeZone);
return {
courseStatus,
intakeActionable:
medication.active &&
!isRecordOnly(medication) &&
courseStatus === "CURRENT",
};
}
+5
View File
@@ -35,6 +35,7 @@ import {
} from "@/lib/medications/intake-tracking";
import { liveEraStartsByMedication } from "@/lib/medications/scheduling/live-era";
import { floorWhole } from "@/lib/medications/units-per-dose";
import { resolveIntakeActionability } from "@/lib/medications/intake-actionable";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
export type MedicationsListResult = Array<Record<string, unknown>>;
@@ -312,6 +313,10 @@ export async function buildMedicationsList(
nextDueAt: display ? display.at.toISOString() : null,
nextDueOverdue: display?.overdue ?? false,
nextDueScheduleId: display?.scheduleId ?? null,
// v1.39.4 (#1040) — whether the card offers taken / skip today, and
// the course position it derives from. Resolved here so no client
// re-derives the calendar-day rule.
...resolveIntakeActionability(m, now, userTz),
stockUnitsRemaining,
stockDosesRemaining,
runwayDays,
@@ -182,6 +182,31 @@ const ONE_MINUTE_MS = 60_000;
// Public API
// ────────────────────────────────────────────────────────────────────
/**
* Where `now` sits relative to a medication's course, in calendar days on
* the user's clock. `startsOn` / `endsOn` are calendar dates and are read as
* such (never shifted through `timeZone`); only `now` is converted to the
* local day it falls on. Both ends are inclusive: a course that ends today
* is CURRENT for the whole of today, one that starts today is CURRENT from
* local midnight.
*/
export type CourseStatus = "UPCOMING" | "CURRENT" | "ENDED";
export function courseStatusAt(
course: { startsOn: Date | null; endsOn: Date | null },
now: Date,
timeZone: string,
): CourseStatus {
const today = civilDayOfInstant(now, timeZone).getTime();
if (course.startsOn && today < civilDayOfDate(course.startsOn).getTime()) {
return "UPCOMING";
}
if (course.endsOn && today > civilDayOfDate(course.endsOn).getTime()) {
return "ENDED";
}
return "CURRENT";
}
/**
* Emit every occurrence in `[from, to]` (inclusive of both ends) in
* chronological order. Pure: no DB access, no side effects.
@@ -262,6 +262,16 @@ export const medicationListEntry = medicationResource
// even though the shared base leaves them optional for the write paths.
nextDueAt: z.iso.datetime({ offset: true }).nullable(),
nextDueOverdue: z.boolean(),
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. 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.",
),
lastTakenAt: z.iso
.datetime({ offset: true })
.nullable()
@@ -305,6 +315,16 @@ export const medicationListEntry = medicationResource
export const medicationDetailEntry = medicationResource
.extend({
category: medicationCategoryEnum,
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. 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.",
),
stockUnitsRemaining: z
.number()
.nullable()
+5
View File
@@ -358,6 +358,11 @@ const medicationSchema = z
// v1.39.1 (#1033) — absent in a backup written before the field existed;
// the restore defaults it to tracking on, the behaviour those had.
trackIntake: z.boolean().optional(),
// v1.39.4 — the clinical category. Absent in older files. A string, not
// the enum: a file from a newer server may name a category this one does
// not know, and the restore reads that as OTHER rather than refusing the
// whole file.
category: z.string().max(64).optional(),
deliveryForm: z.enum(MedicationDeliveryForm).optional(),
trackInjectionSites: z.boolean().optional(),
allowedInjectionSites: z.array(z.enum(InjectionSite)).optional(),
+4 -1
View File
@@ -68,7 +68,9 @@ export const rxNormCodeField = z
* wizard's Step 2 taxonomy can write a first-class bucket for those
* two rows instead of collapsing them into `OTHER`. The column is a
* plain TEXT field — no Prisma enum exists to migrate; the Zod values
* list is the only enforcement layer.
* list is the only enforcement layer. v1.39.4 adds `MENTAL_HEALTH`
* (antidepressants, anxiolytics, mood stabilisers, ADHD medication), again
* without a migration.
*/
export const MEDICATION_CATEGORY_VALUES = [
"BLOOD_PRESSURE",
@@ -83,6 +85,7 @@ export const MEDICATION_CATEGORY_VALUES = [
"SLEEP_AID",
"DIABETES",
"ANTIBIOTIC",
"MENTAL_HEALTH",
"OTHER",
] as const;
export type MedicationCategoryValue =