Files
HealthLog/src/lib/medications/inventory/service.ts
T
Marc-André Bombeck b132244c03 fix(medications): serialise unknown inventory as null, not 0
An inventory item's unit count comes from a non-null Decimal column, but a
corrupt or legacy row could hold a missing or non-finite value. The
serialiser ran `Number(item.unitsTotal)`, and `Number(null) === 0` (and
`Number("corrupt") === NaN`), so an unknown count went out on the wire as a
fabricated 0 that a client could decrement into negatives.

Serialise a genuinely-unknown count (null / non-finite) as `null` so clients
render "unknown" instead. A real tracked 0 stays 0. No model change — the
distinction is serialisation-only.

The supply tab now renders an unknown-units row as "—", pre-fills the
correction editor empty, drops the capacity ceiling when total is unknown,
and keeps such a row out of the pooled available-supply headline. The
low-stock alert already excludes non-usable rows, so it does not fire on
unknown stock. OpenAPI marks both unit fields nullable.
2026-06-17 14:09:04 +02:00

120 lines
4.3 KiB
TypeScript

/**
* v1.4.25 W19b — inventory persistence helpers.
*
* Thin layer on top of Prisma that the route handlers compose. Keeps
* the state-machine math (pure) separate from the I/O (here), so unit
* tests on the math don't need a DB.
*
* v1.16.10 — the per-intake consumption hook moved to
* `./consumption.ts` (multi-unit, FEFO, spillover, stamped on the
* intake event); this module keeps the expire cron and the
* create-input builder.
*/
import { prisma } from "@/lib/db";
import type { MedicationContainerType } from "@/generated/prisma/client";
import { computeExpiresAt } from "./state-machine";
/**
* Daily cron pass — flip any IN_USE rows whose 30-day window has
* elapsed into EXPIRED. Returns the count of transitions for logging.
*
* Optionally scoped to a single user — useful for the per-user
* trigger path. Cron with `userId: null` sweeps every user.
*/
export async function expireStaleInUseItems(input: {
userId?: string;
nowMs: number;
}): Promise<number> {
const { userId, nowMs } = input;
const now = new Date(nowMs);
// Candidates: IN_USE rows whose `expiresAt` has lapsed. The
// selector + state-machine semantics line up here — every row that
// matches `state = IN_USE AND expiresAt < now` is also a row that
// `computeInventoryState` would classify EXPIRED (clause 2 or 3),
// because IN_USE implies `unitsRemaining > 0` (the consumption hook
// flips an empty container to USED_UP) and the `expiresAt` filter
// already proves the printed-expiry-or-window deadline has lapsed.
// EXPIRED rows are already terminal; USED_UP rows are off-window by
// definition. Use a single `updateMany` instead of one update per
// row — the daily cron sweep ran N round-trips for nothing.
const result = await prisma.medicationInventoryItem.updateMany({
where: {
state: "IN_USE",
expiresAt: { lt: now },
...(userId ? { userId } : {}),
},
data: { state: "EXPIRED" },
});
return result.count;
}
/**
* v1.16.12 (#316) — Prisma serialises a Decimal column to a JSON STRING,
* but the API contract (and the iOS client) read an inventory item's
* `unitsTotal` / `unitsRemaining` as numbers. Convert at every response
* boundary that returns an item, so a fractional remainder (29.5 after a
* half-tablet dose) lands as a JSON number, never `"29.5"`.
*
* v1.18.3 (iOS#31) — serialise a genuinely-unknown unit count as `null`,
* not `0`. A well-formed row always carries both Decimals, but a corrupt
* or legacy row could hold null / NaN / Infinity; `Number(null) === 0`
* (and `Number("x") === NaN`) would otherwise fabricate a misleading `0`
* that the client decrements into negatives. `null` lets the client
* render "unbekannt" instead. A real tracked `0` stays `0`.
*/
function toFiniteUnit(value: unknown): number | null {
// `Number(null) === 0` and `Number("") === 0`, so reject the empty /
// nullish cases up front — a genuinely-absent count must read as null,
// not a fabricated 0. Anything else goes through the finiteness gate
// (NaN / Infinity from a corrupt string also fall to null).
if (value === null || value === undefined || value === "") return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
export function serializeInventoryItem<
T extends { unitsTotal: unknown; unitsRemaining: unknown },
>(
item: T,
): Omit<T, "unitsTotal" | "unitsRemaining"> & {
unitsTotal: number | null;
unitsRemaining: number | null;
} {
return {
...item,
unitsTotal: toFiniteUnit(item.unitsTotal),
unitsRemaining: toFiniteUnit(item.unitsRemaining),
};
}
/**
* Helper for the POST /[medId]/inventory route. Composes the
* Prisma-create with the computed `expiresAt` so the caller doesn't
* have to re-derive it.
*/
export function buildCreateInventoryInput(input: {
userId: string;
medicationId: string;
unitsTotal: number;
containerType: MedicationContainerType;
printedExpiry: Date | null;
purchasedAt: Date | null;
notes: string | null;
}) {
return {
userId: input.userId,
medicationId: input.medicationId,
state: "ACTIVE" as const,
containerType: input.containerType,
unitsTotal: input.unitsTotal,
unitsRemaining: input.unitsTotal,
firstUseAt: null,
printedExpiry: input.printedExpiry,
purchasedAt: input.purchasedAt,
expiresAt: computeExpiresAt(null, input.printedExpiry),
notes: input.notes,
};
}