mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Publish the resolved per-slot dose units and a slot-aware runway on the medication wire
A medication whose slots carry different doses (a whole tablet in the morning, a half at noon — #219) was consumed correctly but reported wrongly: the wire shipped only the raw nullable per-slot column (clients had to derive the inheritance), stockDosesRemaining divided by the medication-level units alone, and no runway figure existed outside the low-stock push. - Every schedule now carries resolvedUnitsPerDose, resolved server-side exactly like the intake consumption resolver. - stockDosesRemaining divides the units pool by the schedule-weighted average units per dose. - runwayDays (whole days of supply under the slot-aware burn rate) rides the list AND detail payloads; the detail GET also gains the stock aggregates the list already had. - The low-stock engine runs the same slot-aware math, so the push and the wire cannot disagree; the web cards, table, and detail Übersicht prefer the server figure over their client estimate. - OpenAPI regenerated with the new fields.
This commit is contained in:
1 parent
542ca91be5
commit
4b009c3a45
15 files changed
+510
-85
No files matched your search
@@ -57,6 +57,7 @@
|
||||
import type { PrismaClient } from "@/generated/prisma/client";
|
||||
import {
|
||||
classifyLowStockState,
|
||||
effectiveUnitsPerDose,
|
||||
estimateDailyDoseCount,
|
||||
estimateRunwayDays,
|
||||
lowStockTriggerDays,
|
||||
@@ -125,7 +126,12 @@ export function evaluateMedicationRunway(
|
||||
unitsPerDose: number,
|
||||
schedules: RunwaySchedule[],
|
||||
): LowStockEvaluation {
|
||||
const supply = summariseSupply(items, unitsPerDose);
|
||||
// v1.37.19 — divide the pool by the schedule-weighted average units per
|
||||
// dose, so a per-slot medication's doses/runway match the wire figures.
|
||||
const supply = summariseSupply(
|
||||
items,
|
||||
effectiveUnitsPerDose(schedules, unitsPerDose),
|
||||
);
|
||||
// v1.18.11 (#31) — server-side observability for the central stock clamp.
|
||||
// `summariseSupply` floors a corrupt/legacy negative pool to zero; this is
|
||||
// the request-scoped seam that records the underflow so the data defect
|
||||
@@ -411,6 +417,8 @@ export async function runMedicationLowStockTick(
|
||||
timesOfDay: true,
|
||||
rrule: true,
|
||||
rollingIntervalDays: true,
|
||||
// v1.37.19 — per-slot units feed the slot-aware burn rate.
|
||||
unitsPerDose: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -419,6 +427,16 @@ export async function runMedicationLowStockTick(
|
||||
for (const med of medications) {
|
||||
summary.medicationsEvaluated += 1;
|
||||
|
||||
// Decimal → number for the per-slot units so the runway math and
|
||||
// the wire's `runwayDays` read the identical shape.
|
||||
const runwaySchedules: RunwaySchedule[] = med.schedules.map(
|
||||
(sched) => ({
|
||||
...sched,
|
||||
unitsPerDose:
|
||||
sched.unitsPerDose === null ? null : Number(sched.unitsPerDose),
|
||||
}),
|
||||
);
|
||||
|
||||
const evaluation = evaluateMedicationRunway(
|
||||
// v1.16.12 — Decimal columns → JS numbers for the runway math.
|
||||
med.inventoryItems.map((it) => ({
|
||||
@@ -427,7 +445,7 @@ export async function runMedicationLowStockTick(
|
||||
unitsRemaining: Number(it.unitsRemaining),
|
||||
})),
|
||||
Number(med.unitsPerDose),
|
||||
med.schedules,
|
||||
runwaySchedules,
|
||||
);
|
||||
|
||||
// v1.17.0 — effective reorder lead (per-med override beats the
|
||||
@@ -441,7 +459,7 @@ export async function runMedicationLowStockTick(
|
||||
const triggerDays = lowStockTriggerDays({
|
||||
lowStockRunwayDays: thresholdDays,
|
||||
leadDays,
|
||||
schedules: med.schedules,
|
||||
schedules: runwaySchedules,
|
||||
});
|
||||
|
||||
const decision = decideLowStockAction({
|
||||
@@ -494,7 +512,7 @@ export async function runMedicationLowStockTick(
|
||||
expiredUnits: evaluation.expiredUnits,
|
||||
leadDays,
|
||||
triggerDays,
|
||||
schedules: med.schedules,
|
||||
schedules: runwaySchedules,
|
||||
today: now,
|
||||
});
|
||||
const renderForRecipient = (locale: Locale) => {
|
||||
@@ -506,7 +524,7 @@ export async function runMedicationLowStockTick(
|
||||
expiredUnits: evaluation.expiredUnits,
|
||||
leadDays,
|
||||
triggerDays,
|
||||
schedules: med.schedules,
|
||||
schedules: runwaySchedules,
|
||||
today: now,
|
||||
});
|
||||
return { title: rendered.title, message: rendered.body };
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* #219 / iOS #25 — the per-schedule units wire shape.
|
||||
*
|
||||
* Watched red: with `resolvedUnitsPerDose` falling back to the raw value
|
||||
* alone (no medication-level inheritance) the NULL-slot case below fails —
|
||||
* the pre-v1.37.19 wire shipped only the raw nullable column and told the
|
||||
* client to derive the inheritance itself.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
|
||||
import { serializeScheduleUnitsPerDose } from "../schedule-units-dto";
|
||||
|
||||
describe("serializeScheduleUnitsPerDose", () => {
|
||||
it("keeps the raw column and adds the server-resolved effective value", () => {
|
||||
const [explicit, inherited] = serializeScheduleUnitsPerDose(
|
||||
[
|
||||
{ id: "s1", unitsPerDose: new Prisma.Decimal("0.5") },
|
||||
{ id: "s2", unitsPerDose: null },
|
||||
],
|
||||
new Prisma.Decimal("2"),
|
||||
);
|
||||
// Explicit slot: raw stays, resolved equals it.
|
||||
expect(explicit.unitsPerDose).toBe(0.5);
|
||||
expect(explicit.resolvedUnitsPerDose).toBe(0.5);
|
||||
// Inheriting slot: raw stays NULL (the edit surface needs the
|
||||
// distinction), resolved carries the medication level.
|
||||
expect(inherited.unitsPerDose).toBeNull();
|
||||
expect(inherited.resolvedUnitsPerDose).toBe(2);
|
||||
});
|
||||
|
||||
it("serialises Decimals to plain JSON numbers", () => {
|
||||
const [row] = serializeScheduleUnitsPerDose(
|
||||
[{ unitsPerDose: new Prisma.Decimal("0.3333") }],
|
||||
1,
|
||||
);
|
||||
expect(typeof row.unitsPerDose).toBe("number");
|
||||
expect(typeof row.resolvedUnitsPerDose).toBe("number");
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,10 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { getMedicationCategories } from "@/lib/medication-category";
|
||||
import {
|
||||
effectiveUnitsPerDose,
|
||||
estimateUnitsRunwayDays,
|
||||
} from "@/components/medications/detail/supply-runway";
|
||||
import { serializeScheduleUnitsPerDose } from "@/lib/medications/schedule-units-dto";
|
||||
import {
|
||||
computeDisplayDue,
|
||||
@@ -247,17 +251,42 @@ export async function buildMedicationsList(
|
||||
const stockUnitsRemaining = tracksInventory
|
||||
? (usableUnitsByMedId.get(m.id) ?? 0)
|
||||
: null;
|
||||
// #219 / iOS #25 — schedules on the wire carry both the raw nullable
|
||||
// per-slot units AND the server-resolved effective value.
|
||||
const schedulesDto = serializeScheduleUnitsPerDose(
|
||||
m.schedules,
|
||||
m.unitsPerDose,
|
||||
);
|
||||
// v1.37.19 — slot-aware doses figure: divide the units pool by the
|
||||
// schedule-weighted average units per dose, not the medication-level
|
||||
// column alone (wrong for any per-slot medication). Falls back to the
|
||||
// medication level when no schedule derives a consumption rate.
|
||||
const stockDosesRemaining =
|
||||
stockUnitsRemaining === null
|
||||
? null
|
||||
: Math.floor(stockUnitsRemaining / (Number(m.unitsPerDose) || 1));
|
||||
: Math.floor(
|
||||
stockUnitsRemaining /
|
||||
effectiveUnitsPerDose(schedulesDto, Number(m.unitsPerDose)),
|
||||
);
|
||||
// v1.37.19 — projected runway in whole days on the wire (the low-stock
|
||||
// engine's burn-rate math, slot-aware). NULL when inventory tracking is
|
||||
// off or no schedule derives a consumption rate; 0 when the supply ran
|
||||
// out. Published resolved so no client re-derives the cadence math.
|
||||
const runwayDays =
|
||||
stockUnitsRemaining === null
|
||||
? null
|
||||
: estimateUnitsRunwayDays(
|
||||
stockUnitsRemaining,
|
||||
schedulesDto,
|
||||
Number(m.unitsPerDose),
|
||||
);
|
||||
return {
|
||||
...m,
|
||||
// v1.16.12 — Decimal → number so the wire stays a JSON number, not
|
||||
// the string Prisma would otherwise serialise a Decimal to.
|
||||
unitsPerDose: Number(m.unitsPerDose),
|
||||
// #219 — same Decimal → number unwrap for the per-schedule column.
|
||||
schedules: serializeScheduleUnitsPerDose(m.schedules),
|
||||
schedules: schedulesDto,
|
||||
category: categoryMap[m.id] ?? "OTHER",
|
||||
// v1.32.25 — provenance echo. Surfacing the mirror source lets the
|
||||
// web UI and an operator tell an externally-mirrored row (today only
|
||||
@@ -273,6 +302,7 @@ export async function buildMedicationsList(
|
||||
nextDueScheduleId: display?.scheduleId ?? null,
|
||||
stockUnitsRemaining,
|
||||
stockDosesRemaining,
|
||||
runwayDays,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,6 +8,14 @@
|
||||
* column: convert to a number, keep NULL as NULL (NULL means "inherit the
|
||||
* medication level"). One helper so the five medication read/write responses
|
||||
* cannot drift on the shape.
|
||||
*
|
||||
* v1.37.19 (iOS #25 parity) — every schedule additionally carries
|
||||
* `resolvedUnitsPerDose`: the EFFECTIVE units this slot consumes, resolved
|
||||
* server-side (`schedule.unitsPerDose ?? medication.unitsPerDose`, matching
|
||||
* the consumption resolver's >0 guard). Publish the resolved value; no
|
||||
* client re-derives the inheritance rule. The raw nullable `unitsPerDose`
|
||||
* stays beside it because the edit surface must distinguish "explicit"
|
||||
* from "inherits".
|
||||
*/
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
|
||||
@@ -15,10 +23,21 @@ type ScheduleWithUnits = { unitsPerDose: Prisma.Decimal | null };
|
||||
|
||||
export function serializeScheduleUnitsPerDose<T extends ScheduleWithUnits>(
|
||||
schedules: readonly T[],
|
||||
): Array<Omit<T, "unitsPerDose"> & { unitsPerDose: number | null }> {
|
||||
return schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
unitsPerDose:
|
||||
schedule.unitsPerDose === null ? null : Number(schedule.unitsPerDose),
|
||||
}));
|
||||
medicationUnitsPerDose: Prisma.Decimal | number,
|
||||
): Array<
|
||||
Omit<T, "unitsPerDose"> & {
|
||||
unitsPerDose: number | null;
|
||||
resolvedUnitsPerDose: number;
|
||||
}
|
||||
> {
|
||||
const fallback = Number(medicationUnitsPerDose);
|
||||
return schedules.map((schedule) => {
|
||||
const raw =
|
||||
schedule.unitsPerDose === null ? null : Number(schedule.unitsPerDose);
|
||||
return {
|
||||
...schedule,
|
||||
unitsPerDose: raw,
|
||||
resolvedUnitsPerDose: raw !== null && raw > 0 ? raw : fallback,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -68,6 +68,17 @@ export const medicationScheduleResource = z
|
||||
.describe(
|
||||
"Per-schedule dose override. NULL means the schedule inherits `Medication.dose`.",
|
||||
),
|
||||
unitsPerDose: z
|
||||
.number()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.37.10 (#219) — per-slot inventory-units override (may be a split-pill fraction). NULL means the schedule inherits the medication-level `unitsPerDose`. Kept raw so an edit surface can distinguish an explicit value from inheritance; consumers wanting the effective figure read `resolvedUnitsPerDose`.",
|
||||
),
|
||||
resolvedUnitsPerDose: z
|
||||
.number()
|
||||
.describe(
|
||||
"v1.37.19 — the EFFECTIVE units one dose of this slot consumes, resolved server-side (`schedule.unitsPerDose ?? medication.unitsPerDose`, matching the intake consumption resolver). Always present; clients never re-derive the inheritance rule.",
|
||||
),
|
||||
daysOfWeek: z
|
||||
.string()
|
||||
.nullable()
|
||||
@@ -260,7 +271,14 @@ export const medicationListEntry = medicationResource
|
||||
.int()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.16.10 — dose-derived stock: `floor(stockUnitsRemaining / unitsPerDose)`, where `unitsPerDose` may be a fraction (½ tablet ⇒ twice the doses). Stays a whole-dose count. NULL when inventory tracking is off. Drives the table view's Bestand column. Read-only — aggregated, not stored.",
|
||||
"v1.16.10 — dose-derived stock as a whole-dose count. v1.37.19 — slot-aware: the divisor is the schedule-weighted average units per dose (each slot's `resolvedUnitsPerDose` weighted by its cadence share), falling back to the medication-level `unitsPerDose` when no schedule derives a consumption rate. `unitsPerDose` may be a fraction (½ tablet ⇒ twice the doses). NULL when inventory tracking is off. Drives the table view's Bestand column. Read-only — aggregated, not stored.",
|
||||
),
|
||||
runwayDays: z
|
||||
.number()
|
||||
.int()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.37.19 — projected whole days the usable stock covers under the slot-aware burn rate (the same math the low-stock notification engine runs, so the wire and the push can never disagree). NULL = inventory tracking off or no consuming cadence derivable; 0 = tracking on, supply ran out. Read-only — computed, not stored.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
@@ -272,6 +290,26 @@ export const medicationListEntry = medicationResource
|
||||
export const medicationDetailEntry = medicationResource
|
||||
.extend({
|
||||
category: medicationCategoryEnum,
|
||||
stockUnitsRemaining: z
|
||||
.number()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.37.19 — usable inventory units left (same semantics as the list entry's field): NULL = inventory tracking off; 0 = tracking on, supply ran out.",
|
||||
),
|
||||
stockDosesRemaining: z
|
||||
.number()
|
||||
.int()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.37.19 — slot-aware dose-derived stock, mirroring the list entry's field.",
|
||||
),
|
||||
runwayDays: z
|
||||
.number()
|
||||
.int()
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.37.19 — projected whole days the usable stock covers under the slot-aware burn rate; NULL = tracking off or no consuming cadence.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "MedicationDetail",
|
||||
|
||||
Reference in new issue
Block a user