Files
HealthLog/src/lib/medications/inventory/service.ts
T
Marc-André Bombeck f4dec8c28f feat(medications): fractional dosing via decimal units per dose (#316)
A dose can now consume a fraction of a unit — a half, third or quarter
tablet for a split pill. The wizard offers a curated fraction set beside
the whole numbers (the most error-resistant input); units-per-dose and the
per-container counts widen from Int to Decimal, so a 30-tablet pack dosed
at a half reads 29.5 after one dose and the days-left projection follows.
The consumption ledger stamps and refunds the exact fraction, and existing
whole-number doses are untouched. OpenAPI regenerated — the three unit
fields move from integer to number — and the units-per-dose hint is
updated across the six locales.

Also anchors a first-use date relative to now in an inventory route test
that had aged past its 30-day in-use window.
2026-06-13 16:07:50 +02:00

103 lines
3.4 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"`.
*/
export function serializeInventoryItem<
T extends { unitsTotal: unknown; unitsRemaining: unknown },
>(
item: T,
): Omit<T, "unitsTotal" | "unitsRemaining"> & {
unitsTotal: number;
unitsRemaining: number;
} {
return {
...item,
unitsTotal: Number(item.unitsTotal),
unitsRemaining: Number(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,
};
}