feat(medications): accept units per dose like 1.5 and let the editor enter them

A medication's units per dose, a schedule's override and a restored
backup now accept any value above 0 and at most 100 with at most four
decimal places, which is exactly what the Decimal(10,4) column stores.
Before, only whole numbers 1-100 and the fractions 1/4, 1/3, 1/2, 2/3,
3/4 passed, so one and a half tablets could not be recorded. A restore
now refuses a value no write route would accept.

The medication editor keeps its buttons and adds an Other field that
reads 1.5, 1,5, 1 1/2 and 1½, holds the step while the text does not
read, and previews the value it will save. The supply tab's packaging
dialog uses the same reader; it refused every non-whole value before,
so a medication at half a tablet could not have its packaging saved.
Cards and the supply tab show a whole number plus a fraction as 1½.

The rule, the input reader and the display format live in one module
without imports so the editor and the validators share them.

Refs #1034
This commit is contained in:
Marc-André Bombeck committed 2026-09-25 09:58:55 +02:00
1 parent e03cf7c2c8
commit 1e040605be
33 files changed
+1030 -276

No files matched your search

@@ -611,3 +611,43 @@ describe("backupPayloadSchema — database enum boundaries", () => {
expect(parsed.success).toBe(false);
});
});
// #1034 — a restore applies the same units-per-dose rule as the write
// routes, on the medication and on each schedule, so a hand-edited file
// cannot put a value into the database that no route would accept.
describe("backupPayloadSchema — unitsPerDose", () => {
function withMedication(med: Record<string, unknown>) {
return backupPayloadSchema.safeParse({
schemaVersion: "1",
exportedAt: "2026-09-25T07:00:00.000Z",
userId: "u1",
measurements: [],
intakeEvents: [],
medications: [{ name: "Example", dose: "5 mg", ...med }],
});
}
it("accepts the Decimal strings a backup carries, mixed values included", () => {
for (const v of ["1", "0.5", "1.5", "2.25", "1.3333", "1.2"]) {
expect(withMedication({ unitsPerDose: v }).success).toBe(true);
}
});
it("refuses a medication value the write routes would refuse", () => {
for (const v of ["0", "-1", "101", "abc", "1.23456"]) {
expect(withMedication({ unitsPerDose: v }).success).toBe(false);
}
});
it("applies the rule to the per-schedule override, string or number", () => {
const schedule = (unitsPerDose: unknown) => ({
schedules: [{ windowStart: "08:00", windowEnd: "08:00", unitsPerDose }],
});
expect(withMedication(schedule("1.5")).success).toBe(true);
expect(withMedication(schedule(2.25)).success).toBe(true);
expect(withMedication(schedule(null)).success).toBe(true);
expect(withMedication(schedule("0")).success).toBe(false);
expect(withMedication(schedule(150)).success).toBe(false);
expect(withMedication(schedule("x")).success).toBe(false);
});
});
@@ -123,3 +123,22 @@ describe("scheduleSchema doseWindows", () => {
expect(r.success).toBe(true);
});
});
// #1034 — the per-slot override follows the medication-level rule.
describe("scheduleSchema unitsPerDose", () => {
it("accepts a whole number plus a fraction and a free decimal", () => {
for (const v of [1.5, 2.25, 1.3333, 0.8]) {
expect(
scheduleSchema.safeParse(baseSchedule({ unitsPerDose: v })).success,
).toBe(true);
}
});
it("refuses zero, above 100, and more than four decimal places", () => {
for (const v of [0, 100.5, 1.23456]) {
expect(
scheduleSchema.safeParse(baseSchedule({ unitsPerDose: v })).success,
).toBe(false);
}
});
});
@@ -139,7 +139,7 @@ describe("medication schemas — dosesPerUnit cap 1000 + unitsPerDose 1–100",
expect(
createMedicationSchema.safeParse({
...MINIMAL_MEDICATION,
unitsPerDose: 1.5,
unitsPerDose: 100.5,
}).success,
).toBe(false);
});
@@ -157,8 +157,7 @@ describe("medication schemas — dosesPerUnit cap 1000 + unitsPerDose 1–100",
});
// v1.16.12 (#316) — fractional dosing: a curated set of split-pill
// fractions is accepted alongside the whole numbers; an arbitrary
// decimal is NOT (the UI only ever sends a curated value).
// fractions is accepted alongside the whole numbers.
it("accepts every curated unitsPerDose fraction on create + update", () => {
for (const v of [0.25, 0.3333, 0.5, 0.6667, 0.75]) {
expect(
@@ -173,13 +172,32 @@ describe("medication schemas — dosesPerUnit cap 1000 + unitsPerDose 1–100",
}
});
it("rejects an uncurated fractional unitsPerDose", () => {
for (const v of [0.333, 0.1, 0.4, 1.5, 2.5]) {
// #1034 — a whole number plus a fraction (1½, 2¼), and any other value
// the Decimal(10,4) column stores exactly, is accepted on create + update.
it("accepts a mixed or free decimal unitsPerDose with up to four places", () => {
for (const v of [1.5, 2.25, 1.3333, 3.75, 0.1, 0.4, 1.2, 99.5]) {
expect(
createMedicationSchema.safeParse({
...MINIMAL_MEDICATION,
unitsPerDose: v,
}).success,
).toBe(true);
expect(
updateMedicationSchema.safeParse({ unitsPerDose: v }).success,
).toBe(true);
}
});
it("rejects a unitsPerDose with more than four decimal places", () => {
for (const v of [1.23456, 0.33333, 0.00001]) {
expect(
createMedicationSchema.safeParse({
...MINIMAL_MEDICATION,
unitsPerDose: v,
}).success,
).toBe(false);
expect(
updateMedicationSchema.safeParse({ unitsPerDose: v }).success,
).toBe(false);
}
});
+21 -2
View File
@@ -82,6 +82,10 @@ import {
organDonorStatusSchema,
} from "@/lib/validations/emergency-profile";
import { REMINDER_EVENT_SOURCES } from "@/lib/measurement-reminders/satisfy";
import {
UNITS_PER_DOSE_MESSAGE,
isSupportedUnitsPerDose,
} from "@/lib/medications/units-per-dose";
export const BACKUP_SCHEMA_VERSION = "2" as const;
const LEGACY_BACKUP_SCHEMA_VERSION = "1" as const;
@@ -132,6 +136,15 @@ const measurementSchema = z
})
.passthrough();
// #1034 — the restore applies the write routes' units-per-dose rule. A
// backup carries the Decimal column as a string ("1.5"); a hand-authored
// file may carry a number. `Number("")` is 0, so an empty string fails too.
const unitsPerDoseValue = z
.union([z.string(), z.number()])
.refine((v) => isSupportedUnitsPerDose(Number(v)), {
message: UNITS_PER_DOSE_MESSAGE,
});
const medicationScheduleSchema = z
.object({
id: z.string().min(1).optional(),
@@ -141,7 +154,7 @@ const medicationScheduleSchema = z
dose: z.string().nullable().optional(),
// #219 — per-schedule units per dose. Serialised as a Decimal string in a
// DR file (or a number in a hand-authored one); NULL means inherit.
unitsPerDose: z.union([z.string(), z.number()]).nullable().optional(),
unitsPerDose: unitsPerDoseValue.nullable().optional(),
daysOfWeek: z.string().nullable().optional(),
timesOfDay: z.array(z.string()).optional(),
reminderGraceMinutes: z.number().int().nullable().optional(),
@@ -321,7 +334,13 @@ const medicationSchema = z
dose: z.string(),
treatmentClass: z.enum(MedicationCategory).optional(),
dosesPerUnit: z.number().int().nullable().optional(),
unitsPerDose: z.string().min(1).optional(),
unitsPerDose: z
.string()
.min(1)
.refine((v) => isSupportedUnitsPerDose(Number(v)), {
message: UNITS_PER_DOSE_MESSAGE,
})
.optional(),
active: z.boolean().optional(),
notificationsEnabled: z.boolean().optional(),
pausedAt: isoDateTime.nullable().optional(),
-28
View File
@@ -100,34 +100,6 @@ export const MEDICATION_TREATMENT_CLASS_VALUES = ["GENERIC", "GLP1"] as const;
export type MedicationTreatmentClass =
(typeof MEDICATION_TREATMENT_CLASS_VALUES)[number];
/**
* v1.16.12 (#316) — fractional dosing. A dose may consume a sub-unit
* fraction of a tablet (split pills). The UI offers a CURATED set of
* common fractions (¼ ⅓ ½ ⅔ ¾), stored as their decimal value; thirds
* are inexact in decimal (⅓ ≈ 0.3333, ⅔ ≈ 0.6667) — the @db.Decimal(10,4)
* column and the runway floor absorb the sub-0.0001 drift. Whole numbers
* 1..100 (multi-tablet doses, the pre-v1.16.12 contract) stay valid
* alongside the fractions. One source of truth — the UI selector and the
* tests import this set so the allowed values can never drift from the
* validator.
*/
export const UNITS_PER_DOSE_FRACTIONS = [
0.25, 0.3333, 0.5, 0.6667, 0.75,
] as const;
export const UNITS_PER_DOSE_MAX_WHOLE = 100;
export function isSupportedUnitsPerDose(value: number): boolean {
if ((UNITS_PER_DOSE_FRACTIONS as readonly number[]).includes(value)) {
return true;
}
return (
Number.isInteger(value) && value >= 1 && value <= UNITS_PER_DOSE_MAX_WHOLE
);
}
export const UNITS_PER_DOSE_MESSAGE =
"unitsPerDose must be a whole number 1–100 or a supported fraction (¼, ⅓, ½, ⅔, ¾)";
/**
* v1.6.0 — route of administration. Decoupled from `treatmentClass`:
* the injection-site picker surfaces for any `INJECTION` dose, and a
@@ -4,14 +4,16 @@ import {
MEDICATION_CATEGORY_VALUES,
MEDICATION_DELIVERY_FORM_VALUES,
MEDICATION_TREATMENT_CLASS_VALUES,
UNITS_PER_DOSE_MESSAGE,
atcCodeField,
injectionSiteEnum,
isSupportedUnitsPerDose,
INJECTION_SITE_VALUES,
rxNormCodeField,
} from "./base";
import { scheduleSchema } from "./schedule";
import {
UNITS_PER_DOSE_MESSAGE,
isSupportedUnitsPerDose,
} from "@/lib/medications/units-per-dose";
import { assertStableExternalId } from "@/lib/validations/external-id";
/**
@@ -113,7 +115,7 @@ export const createMedicationSchema = z
.refine(isSupportedUnitsPerDose, { message: UNITS_PER_DOSE_MESSAGE })
.optional()
.describe(
"Inventory units consumed per dose. A whole number 1–100 (e.g. 2 tablets of 2 mg for a 4 mg dose) or a supported fraction for a split pill (¼ / ⅓ / ½ / ⅔ / ¾). Default 1. The intake consumption hook decrements this many units per taken dose; dose-derived readouts divide unit counts by it.",
"Inventory units consumed per dose: above 0 and at most 100, with at most 4 decimal places. A whole number (2 tablets of 2 mg for a 4 mg dose), a split pill (0.5, thirds as 0.3333 / 0.6667), a whole number plus a fraction (1.5, 2.25) or a measured amount (0.8). Default 1. The intake consumption hook decrements this many units per taken dose; dose-derived readouts divide unit counts by it.",
),
/**
* v1.17.0 — optional per-medication reorder lead time in days. The
@@ -269,13 +271,13 @@ export const updateMedicationSchema = z
treatmentClass: z.enum(MEDICATION_TREATMENT_CLASS_VALUES).optional(),
dosesPerUnit: z.number().int().min(1).max(1000).nullable().optional(),
/** v1.16.10 — inventory units one dose consumes. Default 1.
* v1.16.12 — whole number 1–100 or a curated fraction (½ / ⅓ / ¼ …). */
* #1034 — any value above 0 and at most 100 with up to 4 decimals. */
unitsPerDose: z
.number()
.refine(isSupportedUnitsPerDose, { message: UNITS_PER_DOSE_MESSAGE })
.optional()
.describe(
"Inventory units consumed per dose — a whole number 1–100 or a supported split-pill fraction (¼ / ⅓ / ½ / ⅔ / ¾). The intake consumption hook decrements this many units per taken dose; already-stamped intake events keep their recorded consumption.",
"Inventory units consumed per dose: above 0 and at most 100, with at most 4 decimal places (1, 0.5, 1.5, 2.25). The intake consumption hook decrements this many units per taken dose; already-stamped intake events keep their recorded consumption.",
),
/**
* v1.17.0 — per-medication reorder lead time in days (0–60). `null`
+3 -5
View File
@@ -1,13 +1,11 @@
import { z } from "zod/v4";
import { SCHEDULE_TYPES } from "@/lib/medications/scheduling/recurrence";
import { RRULE_PROPS, doseWindowEntrySchema, timeRegex } from "./base";
import {
RRULE_PROPS,
UNITS_PER_DOSE_MESSAGE,
doseWindowEntrySchema,
isSupportedUnitsPerDose,
timeRegex,
} from "./base";
} from "@/lib/medications/units-per-dose";
export const scheduleSchema = z
.object({
@@ -40,7 +38,7 @@ export const scheduleSchema = z
.refine(isSupportedUnitsPerDose, { message: UNITS_PER_DOSE_MESSAGE })
.optional()
.describe(
"Per-schedule inventory units consumed per dose (#219). A whole number 1-100 or a supported fraction (¼ / ⅓ / ½ / ⅔ / ¾) for a split pill. Omitted / NULL means the schedule inherits `Medication.unitsPerDose`. Lets one medication decrement a different tablet count at different times of day (a whole tablet in the morning, a half at noon).",
"Per-schedule inventory units consumed per dose (#219). Above 0 and at most 100 with at most 4 decimal places (1, 0.5, 1.5). Omitted / NULL means the schedule inherits `Medication.unitsPerDose`. Lets one medication decrement a different tablet count at different times of day (a whole tablet in the morning, a half at noon).",
),
daysOfWeek: z
.array(z.number().int().min(0).max(6))