feat: replace hardcoded package assumptions with profile abstraction (#379)

This commit is contained in:
Daniel Volz
2026-03-04 21:15:05 +01:00
committed by GitHub
parent 6672fb78c9
commit 4936929849
23 changed files with 440 additions and 289 deletions
+3 -3
View File
@@ -120,10 +120,10 @@ Share your medication schedule with others via a public link.
</details>
### Smart Inventory
- Track exact stock: packs, blisters, bottles, and loose pills
- Track exact stock with package profiles (blister, bottle, tube, liquid container)
- Display remaining days of supply
- Automatic calculation based on intake schedule
- Manual stock correction supports partial blisters and loose pills
- Manual stock correction supports profile-specific stock semantics (sealed units + loose stock for blister, amount-based stock for bottle/tube/liquid)
### Medication Refill
- One-click refill with pack or loose pill options
@@ -141,7 +141,7 @@ Share your medication schedule with others via a public link.
- Intake reminders via push notifications
### Trip Planner
- Calculate how many pills you need for a trip or date range
- Calculate medication demand for a trip or date range with package-aware units
- Plan ahead for vacations, business trips, or hospital stays
- Send demand reports via email or push notification
+4 -3
View File
@@ -10,6 +10,7 @@ import { doseTracking, medications, refillHistory, shareTokens, userSettings } f
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js";
import { normalizePackageType, PACKAGE_TYPES } from "../utils/package-profiles.js";
import { parseIntakesJson, parseTakenByJson } from "../utils/scheduler-utils.js";
const IMAGES_DIR = resolve(getDataDir(), "images");
@@ -39,7 +40,7 @@ const inventorySchema = z.object({
totalPills: z.number().int().nullable().optional(), // For bottle type: total capacity
looseTablets: z.number().int().min(0).default(0),
stockAdjustment: z.number().int().default(0), // Manual stock correction
packageType: z.enum(["blister", "bottle", "tube", "liquid_container"]).default("blister"),
packageType: z.enum(PACKAGE_TYPES).default("blister"),
packageAmountValue: z.number().int().min(0).default(0),
packageAmountUnit: z.enum(["ml", "g"]).default("ml"),
});
@@ -319,7 +320,7 @@ export async function exportRoutes(app: FastifyInstance) {
totalPills: med.totalPills ?? null,
looseTablets: med.looseTablets ?? 0,
stockAdjustment: med.stockAdjustment ?? 0,
packageType: med.packageType ?? "blister",
packageType: normalizePackageType(med.packageType),
packageAmountValue: med.packageAmountValue ?? 0,
packageAmountUnit: (med.packageAmountUnit ?? "ml") as "ml" | "g",
},
@@ -595,7 +596,7 @@ export async function exportRoutes(app: FastifyInstance) {
medicationForm: med.medicationForm ?? "tablet",
pillForm: med.pillForm || null,
lifecycleCategory: med.lifecycleCategory ?? "refill_when_empty",
packageType: med.inventory.packageType ?? "blister",
packageType: normalizePackageType(med.inventory.packageType),
packageAmountValue: med.inventory.packageAmountValue ?? 0,
packageAmountUnit: med.inventory.packageAmountUnit ?? "ml",
packCount: med.inventory.packCount,
+24 -18
View File
@@ -14,6 +14,13 @@ import {
streamToBuffer,
writeOptimizedImageSet,
} from "../utils/image-upload.js";
import {
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
normalizePackageType,
PACKAGE_TYPES,
} from "../utils/package-profiles.js";
import {
type Intake,
normalizeIntakeUsageForStock,
@@ -75,7 +82,7 @@ const blisterSchema = z.object({
start: z.string().datetime({ local: true }),
});
const packageTypeSchema = z.enum(["blister", "bottle", "tube", "liquid_container"]).default("blister");
const packageTypeSchema = z.enum(PACKAGE_TYPES).default("blister");
const medicationFormSchema = z.enum(["capsule", "tablet", "liquid", "topical"]).default("tablet");
const pillFormSchema = z.enum(["capsule", "tablet"]);
const lifecycleCategorySchema = z.enum(["refill_when_empty", "treatment_period"]).default("refill_when_empty");
@@ -163,7 +170,7 @@ const medicationSchema = z
.refine(
(data) => {
if (data.medicationForm === "topical") {
return data.packageType === "tube";
return isTubePackageType(data.packageType);
}
return true;
},
@@ -175,7 +182,7 @@ const medicationSchema = z
.refine(
(data) => {
if (data.medicationForm === "liquid") {
return data.packageType === "liquid_container";
return isLiquidContainerPackageType(data.packageType);
}
return true;
},
@@ -187,7 +194,7 @@ const medicationSchema = z
.refine(
(data) => {
if (data.medicationForm === "capsule" || data.medicationForm === "tablet") {
return data.packageType !== "tube" && data.packageType !== "liquid_container";
return !isTubePackageType(data.packageType) && !isLiquidContainerPackageType(data.packageType);
}
return true;
},
@@ -294,7 +301,7 @@ export async function medicationRoutes(app: FastifyInstance) {
medicationForm: row.medicationForm ?? "tablet",
pillForm: row.pillForm ?? null,
lifecycleCategory: row.lifecycleCategory ?? "refill_when_empty",
packageType: row.packageType ?? "blister",
packageType: normalizePackageType(row.packageType),
packCount: row.packCount ?? 1,
blistersPerPack: row.blistersPerPack ?? 1,
pillsPerBlister: row.pillsPerBlister ?? 1,
@@ -412,7 +419,7 @@ export async function medicationRoutes(app: FastifyInstance) {
medicationForm: medicationForm ?? "tablet",
pillForm: normalizedPillForm,
lifecycleCategory: lifecycleCategory ?? "refill_when_empty",
packageType: packageType ?? "blister",
packageType: normalizePackageType(packageType),
packCount,
blistersPerPack,
pillsPerBlister,
@@ -448,7 +455,7 @@ export async function medicationRoutes(app: FastifyInstance) {
medicationForm: inserted.medicationForm ?? "tablet",
pillForm: inserted.pillForm ?? null,
lifecycleCategory: inserted.lifecycleCategory ?? "refill_when_empty",
packageType: inserted.packageType ?? "blister",
packageType: normalizePackageType(inserted.packageType),
packCount: inserted.packCount,
blistersPerPack: inserted.blistersPerPack,
pillsPerBlister: inserted.pillsPerBlister,
@@ -583,7 +590,7 @@ export async function medicationRoutes(app: FastifyInstance) {
medicationForm: medicationForm ?? "tablet",
pillForm: normalizedPillForm,
lifecycleCategory: lifecycleCategory ?? "refill_when_empty",
packageType: packageType ?? "blister",
packageType: normalizePackageType(packageType),
packCount,
blistersPerPack,
pillsPerBlister,
@@ -743,7 +750,7 @@ export async function medicationRoutes(app: FastifyInstance) {
medicationForm: result[0].medicationForm ?? "tablet",
pillForm: result[0].pillForm ?? null,
lifecycleCategory: result[0].lifecycleCategory ?? "refill_when_empty",
packageType: result[0].packageType ?? "blister",
packageType: normalizePackageType(result[0].packageType),
packCount: result[0].packCount,
blistersPerPack: result[0].blistersPerPack,
pillsPerBlister: result[0].pillsPerBlister,
@@ -901,8 +908,8 @@ export async function medicationRoutes(app: FastifyInstance) {
updatedAt: new Date(),
};
const packageType = existing.packageType ?? "blister";
const allowsAmountBaseUpdate = packageType === "tube" || packageType === "liquid_container";
const packageType = normalizePackageType(existing.packageType);
const allowsAmountBaseUpdate = isTubePackageType(packageType) || isLiquidContainerPackageType(packageType);
if (allowsAmountBaseUpdate) {
if (totalPills !== undefined) updateFields.totalPills = totalPills;
if (looseTablets !== undefined) updateFields.looseTablets = looseTablets;
@@ -1097,14 +1104,13 @@ export async function medicationRoutes(app: FastifyInstance) {
const blistersPerPack = row.blistersPerPack ?? 1;
const looseTablets = row.looseTablets ?? 0;
const stockAdjustment = row.stockAdjustment ?? 0;
const packageType = row.packageType ?? "blister";
const packageType = normalizePackageType(row.packageType);
// For bottle type, looseTablets IS the current stock (no blister math)
const isTopical = medForm === "topical" || packageType === "tube";
const originalTotalPills =
packageType === "bottle" || packageType === "liquid_container"
? looseTablets + stockAdjustment
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
const isTopical = medForm === "topical" || isTubePackageType(packageType);
const originalTotalPills = isAmountBasedPackageType(packageType)
? looseTablets + stockAdjustment
: packCount * blistersPerPack * pillsPerBlister + looseTablets + stockAdjustment;
// Calculate consumption with the same automatic/manual behavior as frontend coverage.
const stockCorrectionCutoff = row.lastStockCorrectionAt ? new Date(row.lastStockCorrectionAt).getTime() : 0;
@@ -1232,7 +1238,7 @@ export async function medicationRoutes(app: FastifyInstance) {
let fullBlisters: number;
let loosePills: number;
if (packageType === "bottle" || packageType === "tube" || packageType === "liquid_container") {
if (isAmountBasedPackageType(packageType)) {
// Bottle type: no blisters, everything is loose pills
fullBlisters = 0;
loosePills = availableAfterPeriod;
+12 -5
View File
@@ -15,6 +15,12 @@ import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import { updateReminderSentTime, updateUserReminderSentTime } from "../services/reminder-scheduler.js";
import type { AuthUser } from "../types/fastify.js";
import {
getPlannerUnitKind,
isAmountBasedPackageType,
isTubePackageType,
normalizePackageType,
} from "../utils/package-profiles.js";
import { loadUserSettings, sendShoutrrrNotification } from "./settings.js";
// Escape HTML to prevent XSS in email templates
@@ -80,12 +86,13 @@ type PlannerRow = {
};
function isContainerPackage(packageType?: string): boolean {
return packageType === "bottle" || packageType === "tube" || packageType === "liquid_container";
return isAmountBasedPackageType(packageType);
}
function getPlannerUnit(packageType: string | undefined, tr: ReturnType<typeof getTranslations>): string {
if (packageType === "tube") return tr.common.units;
if (packageType === "liquid_container") return tr.common.ml;
const unitKind = getPlannerUnitKind(packageType);
if (unitKind === "units") return tr.common.units;
if (unitKind === "ml") return tr.common.ml;
return tr.common.pills;
}
@@ -481,13 +488,13 @@ ${getFooterPlain(language)}`;
.where(and(eq(medications.userId, userId), eq(medications.isObsolete, false)));
const activeMedicationByName = new Map(
activeMeds
.map((med) => [med.name || med.genericName || "", med.packageType ?? "blister"] as const)
.map((med) => [med.name || med.genericName || "", normalizePackageType(med.packageType)] as const)
.filter(([name]) => name.length > 0)
);
const filteredLowStock = lowStock.filter((item) => {
const packageType = activeMedicationByName.get(item.name);
if (!packageType) return false;
if (packageType === "tube") return false;
if (isTubePackageType(packageType)) return false;
return true;
});
if (filteredLowStock.length === 0) {
+5 -7
View File
@@ -7,6 +7,7 @@ import { medications, shareTokens, userSettings, users } from "../db/schema.js";
import { getAnonymousUserId, requireAuth } from "../plugins/auth.js";
import { env } from "../plugins/env.js";
import type { AuthUser } from "../types/fastify.js";
import { isAmountBasedPackageType, normalizePackageType } from "../utils/package-profiles.js";
import {
getAllTakenByForMedication,
parseIntakesJson,
@@ -119,12 +120,9 @@ export async function shareRoutes(app: FastifyInstance) {
// Parse takenBy JSON array
const takenByArray = parseTakenByJson(med.takenByJson);
const totalPills =
(med.packageType ?? "blister") === "bottle" ||
(med.packageType ?? "blister") === "tube" ||
(med.packageType ?? "blister") === "liquid_container"
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
const totalPills = isAmountBasedPackageType(med.packageType)
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
return {
id: med.id,
name: med.name,
@@ -133,7 +131,7 @@ export async function shareRoutes(app: FastifyInstance) {
doseUnit: med.doseUnit ?? "mg",
imageUrl: med.imageUrl,
totalPills,
packageType: med.packageType ?? "blister",
packageType: normalizePackageType(med.packageType),
packCount: med.packCount,
blistersPerPack: med.blistersPerPack,
looseTablets: med.looseTablets,
+12 -6
View File
@@ -8,6 +8,12 @@ import { doseTracking, medications, userSettings } from "../db/schema.js";
import { getFooterHtml, getFooterPlain, getTranslations, type Language, t } from "../i18n/translations.js";
import { getAllUserSettings, sendShoutrrrNotification, type UserSettings } from "../routes/settings.js";
import type { ServiceLogger } from "../utils/logger.js";
import {
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
normalizePackageType,
} from "../utils/package-profiles.js";
// Import shared utilities
import {
type Blister,
@@ -268,9 +274,10 @@ async function getMedicationsNeedingReminder(
const msPerDay = 86_400_000;
for (const row of rows) {
const packageType = normalizePackageType(row.packageType);
// Tube stock reminders are intentionally disabled:
// topical usage in grams cannot be mapped reliably to schedule events.
if ((row.packageType ?? "blister") === "tube") continue;
if (isTubePackageType(packageType)) continue;
const intakes = parseIntakesJson(
row.intakesJson,
@@ -283,10 +290,9 @@ async function getMedicationsNeedingReminder(
start: i.start,
}));
const originalTotalPills =
(row.packageType ?? "blister") === "bottle"
? row.looseTablets + (row.stockAdjustment ?? 0)
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
const originalTotalPills = isAmountBasedPackageType(packageType)
? row.looseTablets + (row.stockAdjustment ?? 0)
: row.packCount * row.blistersPerPack * row.pillsPerBlister + row.looseTablets + (row.stockAdjustment ?? 0);
const stockCorrectionCutoff = row.lastStockCorrectionAt ? new Date(row.lastStockCorrectionAt).getTime() : 0;
const takenDoseIds = takenDoseIdsByMed.get(row.id) ?? new Set<string>();
@@ -393,7 +399,7 @@ async function getMedicationsNeedingReminder(
if (daysLeft === null) continue;
const isLiquid = (row.packageType ?? "blister") === "liquid_container";
const isLiquid = isLiquidContainerPackageType(packageType);
const { lowDays, criticalDays } = isLiquid
? getLiquidReminderThresholds(reminderDaysBefore)
: { lowDays: lowStockDays, criticalDays: reminderDaysBefore };
+32
View File
@@ -0,0 +1,32 @@
export const PACKAGE_TYPES = ["blister", "bottle", "tube", "liquid_container"] as const;
export type PackageType = (typeof PACKAGE_TYPES)[number];
const PACKAGE_TYPE_SET = new Set<string>(PACKAGE_TYPES);
export function normalizePackageType(packageType?: string | null): PackageType {
if (packageType && PACKAGE_TYPE_SET.has(packageType)) {
return packageType as PackageType;
}
return "blister";
}
export function isTubePackageType(packageType?: string | null): boolean {
return normalizePackageType(packageType) === "tube";
}
export function isLiquidContainerPackageType(packageType?: string | null): boolean {
return normalizePackageType(packageType) === "liquid_container";
}
export function isAmountBasedPackageType(packageType?: string | null): boolean {
const normalized = normalizePackageType(packageType);
return normalized === "bottle" || normalized === "tube" || normalized === "liquid_container";
}
export function getPlannerUnitKind(packageType?: string | null): "pills" | "ml" | "units" {
const normalized = normalizePackageType(packageType);
if (normalized === "tube") return "units";
if (normalized === "liquid_container") return "ml";
return "pills";
}
+3 -2
View File
@@ -4,6 +4,7 @@
*/
import { getDateLocale, type Language } from "../i18n/translations.js";
import { isLiquidContainerPackageType, isTubePackageType } from "./package-profiles.js";
// Legacy type - individual blister schedule (DEPRECATED: use Intake instead)
export type Blister = { usage: number; every: number; start: string };
@@ -36,9 +37,9 @@ export function normalizeIntakeUsageForStock(
): number {
const usage = Number(intake.usage);
if (!Number.isFinite(usage) || usage <= 0) return 0;
if (packageType === "tube") return 0;
if (isTubePackageType(packageType)) return 0;
const isLiquidStock = packageType === "liquid_container" || medicationForm === "liquid";
const isLiquidStock = isLiquidContainerPackageType(packageType) || medicationForm === "liquid";
if (!isLiquidStock) return usage;
if (intake.intakeUnit === "tsp") return usage * 5;
+49 -56
View File
@@ -15,7 +15,14 @@ import { useTranslation } from "react-i18next";
import { Lightbox, MedicationAvatar } from "../components";
import { useEscapeKey } from "../hooks";
import type { Coverage, Medication, RefillEntry, StockThresholds } from "../types";
import { getMedDisplayName, getMedTotal, getPackageSize } from "../types";
import {
getMedDisplayName,
getMedTotal,
getPackageSize,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
} from "../types";
import { formatNumber, generateICS, getExpiryClass, getSystemLocale } from "../utils";
import { getStockStatus } from "../utils/schedule";
import { splitCurrentBlisterStock } from "../utils/stock";
@@ -170,7 +177,7 @@ export function MedDetailModal({
}, [showEditStockModal]);
const remainingPrescriptionRefills = Math.max(0, Number(selectedMed?.prescriptionRemainingRefills) || 0);
const prescriptionPackCapEnabled = selectedMed?.packageType === "blister" && usePrescriptionRefill;
const prescriptionPackCapEnabled = !isAmountBasedPackageType(selectedMed?.packageType) && usePrescriptionRefill;
const cappedRefillPacks = prescriptionPackCapEnabled
? Math.min(refillPacks, remainingPrescriptionRefills)
: refillPacks;
@@ -179,7 +186,7 @@ export function MedDetailModal({
useEffect(() => {
if (!selectedMed) return;
if (!showRefillModal) return;
if (selectedMed.packageType !== "blister" || !usePrescriptionRefill) return;
if (isAmountBasedPackageType(selectedMed.packageType) || !usePrescriptionRefill) return;
if (refillPacks <= remainingPrescriptionRefills) return;
onRefillPacksChange(remainingPrescriptionRefills);
}, [
@@ -192,9 +199,10 @@ export function MedDetailModal({
]);
if (!selectedMed) return null;
const isAmountPackage = selectedMed.packageType === "tube" || selectedMed.packageType === "liquid_container";
const isAmountPackage =
isTubePackageType(selectedMed.packageType) || isLiquidContainerPackageType(selectedMed.packageType);
const amountUnitLabel =
selectedMed.packageType === "liquid_container" || selectedMed.medicationForm === "liquid"
isLiquidContainerPackageType(selectedMed.packageType) || selectedMed.medicationForm === "liquid"
? t("form.packageAmountUnitMl")
: t("form.packageAmountUnitG");
const stockUnitLabel = isAmountPackage ? amountUnitLabel : null;
@@ -202,12 +210,9 @@ export function MedDetailModal({
const medCoverage = coverage.all.find((c) => c.name === getMedDisplayName(selectedMed));
const packageSize = getPackageSize(selectedMed);
// Structural max = sealed package capacity only (excludes pre-existing looseTablets).
const structuralMax =
selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container"
? (selectedMed.totalPills ?? packageSize)
: selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister;
const structuralMax = isAmountBasedPackageType(selectedMed.packageType)
? (selectedMed.totalPills ?? packageSize)
: selectedMed.packCount * selectedMed.blistersPerPack * selectedMed.pillsPerBlister;
const currentStock = medCoverage ? Math.round(medCoverage.medsLeft) : getMedTotal(selectedMed);
const status = medCoverage ? getStockStatus(medCoverage.daysLeft, medCoverage.medsLeft, settings) : null;
const fallbackTextClass = status?.className === "warning" ? "warning-text" : "success-text";
@@ -216,12 +221,9 @@ export function MedDetailModal({
const currentFullBlisters = Math.max(0, stock.fullBlisters);
const currentPartialPills = Math.max(0, stock.openBlisterPills);
const currentLoosePills = Math.max(0, stock.loosePills);
const stockDisplayTotal =
selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container"
? (selectedMed.totalPills ?? packageSize)
: Math.max(0, structuralMax);
const stockDisplayTotal = isAmountBasedPackageType(selectedMed.packageType)
? (selectedMed.totalPills ?? packageSize)
: Math.max(0, structuralMax);
const packageCount = Math.max(1, Number(selectedMed.packCount) || 1);
const amountPerPackage = (() => {
const configured = Number(selectedMed.packageAmountValue ?? 0);
@@ -244,7 +246,7 @@ export function MedDetailModal({
const decrementLabel = t("editStock.decreaseValue");
const incrementLabel = t("editStock.increaseValue");
const getScheduleUsageLabel = (usage: number, intakeUnit?: "ml" | "tsp" | "tbsp" | null) => {
if (selectedMed.packageType === "liquid_container") {
if (isLiquidContainerPackageType(selectedMed.packageType)) {
if (intakeUnit === "tsp") {
return `${usage} ${t("form.blisters.teaspoons", { count: Math.abs(usage) })}`;
}
@@ -253,7 +255,7 @@ export function MedDetailModal({
}
return `${usage} ${t("form.packageAmountUnitMl")}`;
}
if (selectedMed.packageType === "tube") {
if (isTubePackageType(selectedMed.packageType)) {
return `${usage} ${t("form.blisters.applications", { count: Math.abs(usage) })}`;
}
return `${usage} ${usage !== 1 ? t("common.pills") : t("common.pill")}`;
@@ -400,7 +402,7 @@ export function MedDetailModal({
const renderEditStockModal = () => {
if (!showEditStockModal) return null;
const isLiquidPackage = selectedMed.packageType === "liquid_container";
const isLiquidPackage = isLiquidContainerPackageType(selectedMed.packageType);
const liquidBottleCount = Math.max(1, editStockFullBlisters);
const liquidAmountPerBottle = Math.max(1, Number.isFinite(amountPerPackage) ? amountPerPackage : 1);
const liquidCapacity = Math.max(1, Math.round(liquidBottleCount * liquidAmountPerBottle));
@@ -439,7 +441,7 @@ export function MedDetailModal({
<h2>{t("editStock.title")}</h2>
<p className="edit-stock-med-name">{getMedDisplayName(selectedMed)}</p>
<p className="edit-stock-hint">{t("editStock.hint")}</p>
{selectedMed.packageType === "blister" && (
{!isAmountBasedPackageType(selectedMed.packageType) && (
<p className="edit-stock-cap-info edit-stock-live-breakdown">
{t("editStock.currentComposition", {
fullBlisters: currentFullBlisters,
@@ -449,10 +451,10 @@ export function MedDetailModal({
})}
</p>
)}
{selectedMed.packageType === "bottle" && (
{isAmountBasedPackageType(selectedMed.packageType) && !isTubePackageType(selectedMed.packageType) && (
<p className="edit-stock-cap-info">{t("editStock.packageSize", { count: structuralMax })}</p>
)}
{(selectedMed.packageType === "tube" || selectedMed.packageType === "liquid_container") && (
{(isTubePackageType(selectedMed.packageType) || isLiquidContainerPackageType(selectedMed.packageType)) && (
<p className="edit-stock-cap-info">
{t("form.totalAmount")}: {formatNumber(isLiquidPackage ? liquidCapacity : structuralMax)}{" "}
{amountUnitLabel}
@@ -465,10 +467,7 @@ export function MedDetailModal({
{(() => {
const dbTotal = getMedTotal(selectedMed);
const currentTotal = medCoverage ? Math.round(medCoverage.medsLeft) : dbTotal;
const isBottle =
selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container";
const isBottle = isAmountBasedPackageType(selectedMed.packageType);
const enteredTotal = isLiquidPackage
? Math.min(liquidCapacity, editStockPartialBlisterPills)
: isBottle
@@ -813,7 +812,7 @@ export function MedDetailModal({
<div className="med-detail-section">
<h3>{t("modal.stockInfo")}</h3>
<div className="med-detail-grid">
{selectedMed.packageType === "blister" && (
{!isAmountBasedPackageType(selectedMed.packageType) && (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("table.fullBlisters")}</span>
@@ -832,7 +831,7 @@ export function MedDetailModal({
</div>
</>
)}
<div className={`med-detail-item ${selectedMed.packageType === "bottle" ? "full-width" : "full-width"}`}>
<div className="med-detail-item full-width">
<span className="med-detail-label">
{isAmountPackage ? t("form.currentAmount") : t("modal.currentStock")}
</span>
@@ -858,27 +857,27 @@ export function MedDetailModal({
<div className="med-detail-section">
<h3>
{t("modal.packageDetails")} (
{selectedMed.packageType === "bottle"
? t("form.packageTypeBottle")
: selectedMed.packageType === "tube"
? t("form.packageTypeTube")
: selectedMed.packageType === "liquid_container"
? t("form.packageTypeLiquidContainer")
{isTubePackageType(selectedMed.packageType)
? t("form.packageTypeTube")
: isLiquidContainerPackageType(selectedMed.packageType)
? t("form.packageTypeLiquidContainer")
: isAmountBasedPackageType(selectedMed.packageType)
? t("form.packageTypeBottle")
: t("form.packageTypeBlister")}
)
{selectedMed.packageType === "tube" && (
{isTubePackageType(selectedMed.packageType) && (
<span className="info-tooltip small" data-tooltip={t("modal.packageTypeTubeHint")}>
</span>
)}
{selectedMed.packageType === "liquid_container" && (
{isLiquidContainerPackageType(selectedMed.packageType) && (
<span className="info-tooltip small" data-tooltip={t("modal.packageTypeLiquidHint")}>
</span>
)}
</h3>
<div className="med-detail-grid">
{selectedMed.packageType === "blister" ? (
{!isAmountBasedPackageType(selectedMed.packageType) ? (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("modal.packs")}</span>
@@ -893,7 +892,7 @@ export function MedDetailModal({
<span className="med-detail-value">{selectedMed.pillsPerBlister}</span>
</div>
</>
) : selectedMed.packageType === "liquid_container" ? (
) : isLiquidContainerPackageType(selectedMed.packageType) ? (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("form.bottles")}</span>
@@ -912,7 +911,7 @@ export function MedDetailModal({
</span>
</div>
</>
) : selectedMed.packageType === "tube" ? (
) : isTubePackageType(selectedMed.packageType) ? (
<>
<div className="med-detail-item">
<span className="med-detail-label">{t("form.tubes")}</span>
@@ -1115,13 +1114,10 @@ export function MedDetailModal({
</span>
<span className="refill-amount">
{(() => {
const total =
selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container"
? entry.loosePillsAdded
: entry.packsAdded * selectedMed.blistersPerPack * selectedMed.pillsPerBlister +
entry.loosePillsAdded;
const total = isAmountBasedPackageType(selectedMed.packageType)
? entry.loosePillsAdded
: entry.packsAdded * selectedMed.blistersPerPack * selectedMed.pillsPerBlister +
entry.loosePillsAdded;
return `+${total}${isAmountPackage ? ` ${stockUnitLabel}` : ` ${total === 1 ? t("common.pill") : t("common.pills")}`}`;
})()}
{entry.usedPrescription && (
@@ -1221,7 +1217,7 @@ export function MedDetailModal({
<p className="refill-med-name">{getMedDisplayName(selectedMed)}</p>
<div className="refill-form">
{selectedMed.packageType === "blister" ? (
{!isAmountBasedPackageType(selectedMed.packageType) ? (
<>
<label>
{t("refill.packs")}
@@ -1265,7 +1261,7 @@ export function MedDetailModal({
onUsePrescriptionRefillChange(checked);
if (
checked &&
selectedMed.packageType === "blister" &&
!isAmountBasedPackageType(selectedMed.packageType) &&
refillPacks > remainingPrescriptionRefills
) {
onRefillPacksChange(remainingPrescriptionRefills);
@@ -1291,9 +1287,7 @@ export function MedDetailModal({
className="success"
onClick={() => onSubmitRefill(selectedMed.id, usePrescriptionRefill)}
disabled={
(selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container"
(isAmountBasedPackageType(selectedMed.packageType)
? refillLoose < 1
: cappedRefillPacks < 1 && refillLoose < 1) ||
exceedsPrescriptionPackLimit ||
@@ -1303,10 +1297,9 @@ export function MedDetailModal({
{refillSaving ? t("common.saving") : t("refill.button")}
</button>
{(() => {
const totalRefill =
selectedMed.packageType === "blister"
? cappedRefillPacks * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + refillLoose
: refillLoose;
const totalRefill = !isAmountBasedPackageType(selectedMed.packageType)
? cappedRefillPacks * selectedMed.blistersPerPack * selectedMed.pillsPerBlister + refillLoose
: refillLoose;
return totalRefill > 0 ? (
<span className="refill-preview">
+{totalRefill}
+28 -20
View File
@@ -10,7 +10,14 @@ import { useTranslation } from "react-i18next";
import { useEscapeKey } from "../hooks/useEscapeKey";
import { useScrollLock } from "../hooks/useScrollLock";
import type { DoseUnit, FieldErrors, FormBlister, FormIntake, FormState, Medication } from "../types";
import { DOSE_UNITS } from "../types";
import {
allowsPillFormSelection,
DOSE_UNITS,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
PACKAGE_PROFILES,
} from "../types";
import { deriveTotal } from "../utils";
import { DateInput } from "./DateInput";
import { FormNumberStepper } from "./FormNumberStepper";
@@ -68,7 +75,7 @@ export interface MobileEditModalProps {
/** Calculate total pills from form state */
function deriveTotalFromForm(form: FormState) {
if (form.packageType === "bottle" || form.packageType === "tube" || form.packageType === "liquid_container") {
if (isAmountBasedPackageType(form.packageType)) {
// For bottle type, looseTablets is the current stock
return Number(form.looseTablets) || 0;
}
@@ -126,19 +133,19 @@ export function MobileEditModal({
const activeTabIndexRef = useRef(0);
const allowFractionalIntake = useMemo(() => {
if (form.packageType === "liquid_container") return true;
if (form.packageType === "tube") return form.medicationForm === "liquid";
if (isLiquidContainerPackageType(form.packageType)) return true;
if (isTubePackageType(form.packageType)) return form.medicationForm === "liquid";
return form.pillForm === "tablet";
}, [form.packageType, form.medicationForm, form.pillForm]);
const getUsageLabel = useCallback(
(intake: (typeof form.intakes)[number]) => {
if (form.packageType === "liquid_container") {
if (isLiquidContainerPackageType(form.packageType)) {
if (intake.intakeUnit === "tsp") return t("form.blisters.usageTsp");
if (intake.intakeUnit === "tbsp") return t("form.blisters.usageTbsp");
return t("form.blisters.usageMl");
}
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
return form.medicationForm === "liquid" ? t("form.blisters.usageMl") : t("form.blisters.usageApplication");
}
if (form.pillForm === "capsule") return t("form.blisters.usageCapsules");
@@ -147,7 +154,7 @@ export function MobileEditModal({
[form.packageType, form.medicationForm, form.pillForm, t]
);
const usesAmountLabels = form.packageType === "tube" || form.packageType === "liquid_container";
const usesAmountLabels = isTubePackageType(form.packageType) || isLiquidContainerPackageType(form.packageType);
const totalCapacityLabel = usesAmountLabels ? t("form.totalAmount") : t("form.totalCapacity");
const currentStockLabel = usesAmountLabels ? t("form.currentAmount") : t("form.currentPills");
const totalLabel = usesAmountLabels ? t("form.totalAmountLabel") : t("form.total");
@@ -432,10 +439,11 @@ export function MobileEditModal({
value={form.packageType}
onChange={(e) => onHandleValueChange("packageType", e.target.value as FormState["packageType"])}
>
<option value="blister">{t("form.packageTypeBlister")}</option>
<option value="bottle">{t("form.packageTypeBottle")}</option>
<option value="tube">{t("form.packageTypeTube")}</option>
<option value="liquid_container">{t("form.packageTypeLiquidContainer")}</option>
{PACKAGE_PROFILES.map((profile) => (
<option key={profile.value} value={profile.value}>
{t(profile.labelKey)}
</option>
))}
</select>
</label>
<label className="full">
@@ -446,7 +454,7 @@ export function MobileEditModal({
placeholder={t("common.optional")}
/>
</label>
{form.packageType !== "tube" && form.packageType !== "liquid_container" && (
{allowsPillFormSelection(form.packageType) && (
<label className="full">
{t("form.pillForm")}
<select
@@ -458,7 +466,7 @@ export function MobileEditModal({
</select>
</label>
)}
{form.packageType === "tube" && (
{isTubePackageType(form.packageType) && (
<label className="full">
{t("form.medicationForm")}
<select value={"topical"} onChange={() => onHandleValueChange("medicationForm", "topical")}>
@@ -466,7 +474,7 @@ export function MobileEditModal({
</select>
</label>
)}
{form.packageType === "liquid_container" && (
{isLiquidContainerPackageType(form.packageType) && (
<label className="full">
{t("form.medicationForm")}
<select value={"liquid"} onChange={() => onHandleValueChange("medicationForm", "liquid")}>
@@ -560,7 +568,7 @@ export function MobileEditModal({
<div className="full form-category">
<h4 className="form-category-title">{t("form.sections.stock")}</h4>
{(() => {
if (form.packageType === "blister") {
if (!isAmountBasedPackageType(form.packageType)) {
return (
<>
<label>
@@ -601,7 +609,7 @@ export function MobileEditModal({
);
}
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
return (
<>
<label>
@@ -640,7 +648,7 @@ export function MobileEditModal({
);
}
if (form.packageType === "liquid_container") {
if (isLiquidContainerPackageType(form.packageType)) {
return (
<>
<label>
@@ -710,7 +718,7 @@ export function MobileEditModal({
</>
);
})()}
{form.packageType === "bottle" && (
{isAmountBasedPackageType(form.packageType) && !isTubePackageType(form.packageType) && (
<div className="full stock-total-row">
<div className="stock-total-field">
<p className="sub">
@@ -720,7 +728,7 @@ export function MobileEditModal({
</div>
</div>
)}
{form.packageType !== "tube" && form.packageType !== "liquid_container" && (
{allowsPillFormSelection(form.packageType) && (
<label className="full">
{t("form.pillWeight")} ({form.doseUnit})
<div className="dose-input-group">
@@ -837,7 +845,7 @@ export function MobileEditModal({
onChange={(e) => onSetIntakeValue(idx, "startTime", e.target.value)}
/>
</label>
{form.packageType === "liquid_container" && (
{isLiquidContainerPackageType(form.packageType) && (
<label className="compact full-row">
<span>{t("form.blisters.intakeUnit")}</span>
<select
+20 -14
View File
@@ -3,7 +3,13 @@ import { useTranslation } from "react-i18next";
import { useEscapeKey } from "../hooks/useEscapeKey";
import { useScrollLock } from "../hooks/useScrollLock";
import type { Medication } from "../types";
import { getMedDisplayName, getPackageSize } from "../types";
import {
getMedDisplayName,
getPackageSize,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
} from "../types";
import { MedicationAvatar } from "./MedicationAvatar";
type ReportFormat = "txt" | "md" | "pdf";
@@ -299,35 +305,35 @@ function fmtDateTime(iso: string | null | undefined): string {
}
function getTubeUnitKey(med: Medication): "form.ml" | "blisters.applications" {
if (med.packageType === "liquid_container") return "form.ml";
if (isLiquidContainerPackageType(med.packageType)) return "form.ml";
return med.medicationForm === "liquid" ? "form.ml" : "blisters.applications";
}
function getUsageText(med: Medication, usage: number, t: TFn): string {
if (med.packageType === "tube" || med.packageType === "liquid_container") {
if (isTubePackageType(med.packageType) || isLiquidContainerPackageType(med.packageType)) {
return `${usage} ${t(getTubeUnitKey(med))}`;
}
return `${usage} ${usage === 1 ? t("common.pill") : t("common.pills")}`;
}
function getTotalCapacityLabel(med: Medication, t: TFn): string {
if (med.packageType === "tube" || med.packageType === "liquid_container") {
if (isTubePackageType(med.packageType) || isLiquidContainerPackageType(med.packageType)) {
return t("form.totalAmountLabel", { unit: t(getTubeUnitKey(med)) });
}
return t("report.docTotalCapacity");
}
function getCurrentStockText(med: Medication, t: TFn): string {
if (med.packageType === "tube" || med.packageType === "liquid_container") {
if (isTubePackageType(med.packageType) || isLiquidContainerPackageType(med.packageType)) {
return `${getPackageSize(med)} ${t(getTubeUnitKey(med))}`;
}
return `${getPackageSize(med)} ${t("common.pills")}`;
}
function getReportPackageTypeLabel(med: Medication, t: TFn): string {
if (med.packageType === "bottle") return t("report.docBottle");
if (med.packageType === "tube") return t("report.docTube");
if (med.packageType === "liquid_container") return t("form.packageTypeLiquidContainer");
if (isTubePackageType(med.packageType)) return t("report.docTube");
if (isLiquidContainerPackageType(med.packageType)) return t("form.packageTypeLiquidContainer");
if (isAmountBasedPackageType(med.packageType)) return t("report.docBottle");
return t("report.docBlister");
}
@@ -374,7 +380,7 @@ function generateTextReport(
// Package / Stock
lines.push(h3(t("report.docPackage")));
lines.push(item(t("report.docPackageType"), getReportPackageTypeLabel(med, t)));
if (med.packageType === "blister") {
if (!isAmountBasedPackageType(med.packageType)) {
lines.push(item(t("report.docPacks"), String(med.packCount)));
lines.push(item(t("report.docBlistersPerPack"), String(med.blistersPerPack)));
lines.push(item(t("report.docPillsPerBlister"), String(med.pillsPerBlister)));
@@ -383,7 +389,7 @@ function generateTextReport(
lines.push(item(getTotalCapacityLabel(med, t), String(med.totalPills ?? med.looseTablets)));
}
lines.push(item(t("report.docCurrentStock"), getCurrentStockText(med, t)));
if (med.packageType !== "tube" && med.packageType !== "liquid_container" && med.pillWeightMg)
if (!isTubePackageType(med.packageType) && !isLiquidContainerPackageType(med.packageType) && med.pillWeightMg)
lines.push(item(t("report.docDosePerPill"), `${med.pillWeightMg} ${med.doseUnit ?? "mg"}`));
if (med.expiryDate) lines.push(item(t("report.docExpiryDate"), fmtDate(med.expiryDate)));
if (med.notes) lines.push(item(t("report.docNotes"), med.notes));
@@ -439,7 +445,7 @@ function generateTextReport(
if (data.refills.length > 0) {
lines.push(h3(t("report.docRefillHistory")));
for (const r of data.refills) {
let entry = `${fmtDate(r.refillDate)}: +${r.packsAdded} ${t("report.docPacks")}, +${r.loosePillsAdded} ${med.packageType === "tube" || med.packageType === "liquid_container" ? t(getTubeUnitKey(med)) : t("common.pills")}`;
let entry = `${fmtDate(r.refillDate)}: +${r.packsAdded} ${t("report.docPacks")}, +${r.loosePillsAdded} ${isTubePackageType(med.packageType) || isLiquidContainerPackageType(med.packageType) ? t(getTubeUnitKey(med)) : t("common.pills")}`;
if (r.usedPrescription) entry += ` ${t("report.docRefillPrescription")}`;
lines.push(fmt === "md" ? `- ${entry}` : `${entry}`);
}
@@ -572,7 +578,7 @@ function buildPrintHtml(
s += `<h3>${escHtml(t("report.docPackage"))}</h3>`;
s += `<table><tbody>`;
s += `<tr><td class="label">${escHtml(t("report.docPackageType"))}</td><td>${escHtml(getReportPackageTypeLabel(med, t))}</td></tr>`;
if (med.packageType === "blister") {
if (!isAmountBasedPackageType(med.packageType)) {
s += `<tr><td class="label">${escHtml(t("report.docPacks"))}</td><td>${med.packCount}</td></tr>`;
s += `<tr><td class="label">${escHtml(t("report.docBlistersPerPack"))}</td><td>${med.blistersPerPack}</td></tr>`;
s += `<tr><td class="label">${escHtml(t("report.docPillsPerBlister"))}</td><td>${med.pillsPerBlister}</td></tr>`;
@@ -582,7 +588,7 @@ function buildPrintHtml(
s += `<tr><td class="label">${escHtml(getTotalCapacityLabel(med, t))}</td><td>${med.totalPills ?? med.looseTablets}</td></tr>`;
}
s += `<tr><td class="label">${escHtml(t("report.docCurrentStock"))}</td><td>${escHtml(getCurrentStockText(med, t))}</td></tr>`;
if (med.packageType !== "tube" && med.packageType !== "liquid_container" && med.pillWeightMg)
if (!isTubePackageType(med.packageType) && !isLiquidContainerPackageType(med.packageType) && med.pillWeightMg)
s += `<tr><td class="label">${escHtml(t("report.docDosePerPill"))}</td><td>${med.pillWeightMg} ${escHtml(med.doseUnit ?? "mg")}</td></tr>`;
if (med.expiryDate)
s += `<tr><td class="label">${escHtml(t("report.docExpiryDate"))}</td><td>${fmtDate(med.expiryDate)}</td></tr>`;
@@ -646,7 +652,7 @@ function buildPrintHtml(
s += `<h3>${escHtml(t("report.docRefillHistory"))}</h3>`;
s += `<ul>`;
for (const r of data.refills) {
let entry = `${fmtDate(r.refillDate)}: +${r.packsAdded} ${escHtml(t("report.docPacks"))}, +${r.loosePillsAdded} ${escHtml(med.packageType === "tube" || med.packageType === "liquid_container" ? t(getTubeUnitKey(med)) : t("common.pills"))}`;
let entry = `${fmtDate(r.refillDate)}: +${r.packsAdded} ${escHtml(t("report.docPacks"))}, +${r.loosePillsAdded} ${escHtml(isTubePackageType(med.packageType) || isLiquidContainerPackageType(med.packageType) ? t(getTubeUnitKey(med)) : t("common.pills"))}`;
if (r.usedPrescription) entry += ` <em>${escHtml(t("report.docRefillPrescription"))}</em>`;
s += `<li>${entry}</li>`;
}
+6 -6
View File
@@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { useEscapeKey } from "../hooks";
import type { ExpiredLinkData, SharedScheduleData } from "../types";
import { getMedDisplayName, getMedTotal } from "../types";
import { getMedDisplayName, getMedTotal, isLiquidContainerPackageType, isTubePackageType } from "../types";
import { getSystemLocale } from "../utils/formatters";
import { isDoseDismissed } from "../utils/schedule";
import { loadCollapsedDaysFromStorage } from "../utils/storage";
@@ -24,10 +24,10 @@ function getStockStatus(
thresholds: { lowStockDays: number; normalStockDays: number; highStockDays: number; criticalStockDays: number },
packageType?: string
) {
if (packageType === "tube") return { className: "success", label: "status.noSchedule" };
if (isTubePackageType(packageType)) return { className: "success", label: "status.noSchedule" };
if (medsLeft <= 0 || daysLeft === 0) return { className: "danger", label: "status.outOfStock" };
if (daysLeft === null) return { className: "success", label: "status.noSchedule" };
if (packageType === "liquid_container") {
if (isLiquidContainerPackageType(packageType)) {
const lowDays = Math.max(1, Math.floor(thresholds.criticalStockDays));
const criticalDays = Math.max(1, Math.ceil(lowDays / 2));
if (daysLeft <= criticalDays) return { className: "danger", label: "status.criticalStock" };
@@ -54,7 +54,7 @@ export function SharedSchedule() {
const [showFutureDays, setShowFutureDays] = useState(false);
const isLiquidContainerMed = (med: SharedScheduleData["medications"][number] | undefined) =>
med?.packageType === "liquid_container";
isLiquidContainerPackageType(med?.packageType);
const convertLiquidUsageToMl = (usage: number, unit: "ml" | "tsp" | "tbsp" | null | undefined): number => {
if (unit === "tsp") return usage * 5;
@@ -67,7 +67,7 @@ export function SharedSchedule() {
med: SharedScheduleData["medications"][number] | undefined,
unit: "ml" | "tsp" | "tbsp" | null | undefined
): number => {
if (med?.packageType === "tube") return 0;
if (isTubePackageType(med?.packageType)) return 0;
if (!isLiquidContainerMed(med)) return usage;
return convertLiquidUsageToMl(usage, unit);
};
@@ -140,7 +140,7 @@ export function SharedSchedule() {
const shouldHideNoScheduleStatusForTube = (
med: SharedScheduleData["medications"][number] | undefined,
status: { className: string; label: string } | null
) => med?.packageType === "tube" && status?.label === "status.noSchedule";
) => isTubePackageType(med?.packageType) && status?.label === "status.noSchedule";
const getVisibleStockStatus = (
med: SharedScheduleData["medications"][number] | undefined,
+23 -20
View File
@@ -1,7 +1,13 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { FieldErrors, FormBlister, FormIntake, FormState, Medication } from "../types";
import { FIELD_LIMITS } from "../types";
import {
FIELD_LIMITS,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
normalizePackageType,
} from "../types";
import { toDateValue, toTimeValue } from "../utils/formatters";
export const defaultBlister = (): FormBlister => {
@@ -230,18 +236,19 @@ export function useMedicationForm(): UseMedicationFormReturn {
const authorizedRefills = Math.max(0, med.prescriptionAuthorizedRefills ?? 0);
const remainingRefills = Math.min(Math.max(0, med.prescriptionRemainingRefills ?? 0), authorizedRefills);
const lowRefillThreshold = Math.min(Math.max(0, med.prescriptionLowRefillThreshold ?? 1), authorizedRefills);
const isTubeOrLiquidPackage = med.packageType === "tube" || med.packageType === "liquid_container";
const packageType = normalizePackageType(med.packageType);
const isTubeOrLiquidPackage = isTubePackageType(packageType) || isLiquidContainerPackageType(packageType);
let normalizedPackCount = String(med.packCount);
let normalizedPackageAmountValue = String(med.packageAmountValue ?? 0);
if (isTubeOrLiquidPackage) {
const safePackCount = med.packageType === "tube" ? 1 : Math.max(1, med.packCount || 1);
const safePackCount = isTubePackageType(packageType) ? 1 : Math.max(1, med.packCount || 1);
normalizedPackCount = String(safePackCount);
const rawPackageAmount = Number(med.packageAmountValue ?? 0);
const legacyKnownAmount = Math.max(0, Number(med.totalPills ?? 0), Number(med.looseTablets ?? 0));
if (med.packageType === "tube") {
if (isTubePackageType(packageType)) {
normalizedPackageAmountValue = String(
legacyKnownAmount > 0 ? legacyKnownAmount : Math.max(1, rawPackageAmount)
);
@@ -256,16 +263,12 @@ export function useMedicationForm(): UseMedicationFormReturn {
? Math.max(0, (Number(normalizedPackCount) || 0) * (Number(normalizedPackageAmountValue) || 0))
: null;
const bottleTotalPills =
(med.packageType === "bottle" || med.packageType === "tube" || med.packageType === "liquid_container") &&
med.looseTablets
? String(med.looseTablets)
: "";
const bottleTotalPills = isAmountBasedPackageType(packageType) && med.looseTablets ? String(med.looseTablets) : "";
let resolvedForm = med.medicationForm;
if (!resolvedForm) {
if (med.packageType === "tube") {
if (isTubePackageType(packageType)) {
resolvedForm = "topical";
} else if (med.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(packageType)) {
resolvedForm = "liquid";
} else {
resolvedForm = med.pillForm ?? "tablet";
@@ -273,9 +276,9 @@ export function useMedicationForm(): UseMedicationFormReturn {
}
const resolvedPillForm = med.pillForm ?? (resolvedForm === "capsule" ? "capsule" : "tablet");
let normalizedPackageAmountUnit = med.packageAmountUnit ?? "ml";
if (med.packageType === "tube") {
if (isTubePackageType(packageType)) {
normalizedPackageAmountUnit = "g";
} else if (med.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(packageType)) {
normalizedPackageAmountUnit = "ml";
}
let resolvedTotalPills = bottleTotalPills;
@@ -291,7 +294,7 @@ export function useMedicationForm(): UseMedicationFormReturn {
medicationForm: resolvedForm,
pillForm: resolvedPillForm,
lifecycleCategory: med.lifecycleCategory ?? "refill_when_empty",
packageType: med.packageType ?? "blister",
packageType,
packCount: normalizedPackCount,
blistersPerPack: String(med.blistersPerPack),
pillsPerBlister: String(med.pillsPerBlister),
@@ -347,14 +350,14 @@ export function useMedicationForm(): UseMedicationFormReturn {
const next = { ...prev, [key]: value } as FormState;
if (key === "packageType") {
if (value === "tube") {
if (isTubePackageType(value)) {
next.packCount = "1";
next.packageAmountValue = String(Math.max(1, Number(next.packageAmountValue) || 0));
next.medicationForm = "topical";
next.lifecycleCategory = "treatment_period";
next.doseUnit = "units";
next.packageAmountUnit = "g";
} else if (value === "liquid_container") {
} else if (isLiquidContainerPackageType(value)) {
next.packCount = String(Math.max(1, Number(next.packCount) || 1));
next.packageAmountValue = String(Math.max(1, Number(next.packageAmountValue) || 0));
next.medicationForm = "liquid";
@@ -369,12 +372,12 @@ export function useMedicationForm(): UseMedicationFormReturn {
}
if (key === "medicationForm") {
if (next.packageType === "tube") {
if (isTubePackageType(next.packageType)) {
next.medicationForm = "topical";
next.lifecycleCategory = "treatment_period";
next.doseUnit = "units";
next.packageAmountUnit = "g";
} else if (next.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(next.packageType)) {
next.medicationForm = "liquid";
next.lifecycleCategory = "refill_when_empty";
next.doseUnit = "ml";
@@ -383,10 +386,10 @@ export function useMedicationForm(): UseMedicationFormReturn {
}
}
if (next.packageType === "tube") {
if (isTubePackageType(next.packageType)) {
next.packCount = "1";
next.packageAmountUnit = "g";
} else if (next.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(next.packageType)) {
next.packageAmountUnit = "ml";
}
+12 -10
View File
@@ -1,6 +1,12 @@
import { useCallback, useEffect, useState } from "react";
import type { Coverage, FormState, Medication, RefillEntry } from "../types";
import { getMedTotal, getPackageSize } from "../types";
import {
getMedTotal,
getPackageSize,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
} from "../types";
export interface UseRefillReturn {
// Refill state
@@ -137,10 +143,9 @@ export function useRefill(): UseRefillReturn {
if (!selectedMed) return;
setEditStockSaving(true);
try {
const isTubePackage = selectedMed.packageType === "tube";
const isBottlePackage = selectedMed.packageType === "bottle";
const isLiquidPackage = selectedMed.packageType === "liquid_container";
const isAmountPackage = isBottlePackage || isTubePackage || isLiquidPackage;
const isTubePackage = isTubePackageType(selectedMed.packageType);
const isLiquidPackage = isLiquidContainerPackageType(selectedMed.packageType);
const isAmountPackage = isAmountBasedPackageType(selectedMed.packageType);
const liquidAmountPerBottle = Math.max(
1,
Number.isFinite(Number(selectedMed.packageAmountValue)) && Number(selectedMed.packageAmountValue) > 0
@@ -268,10 +273,7 @@ export function useRefill(): UseRefillReturn {
const openEditStockModal = useCallback((selectedMed: Medication, coverage: { all: Coverage[] }) => {
if (!selectedMed) return;
setEditStockMedication(selectedMed);
const isAmountPackage =
selectedMed.packageType === "bottle" ||
selectedMed.packageType === "tube" ||
selectedMed.packageType === "liquid_container";
const isAmountPackage = isAmountBasedPackageType(selectedMed.packageType);
// Get current stock from coverage (after consumption)
const medCoverage = coverage.all.find((c) => c.name === selectedMed.name);
const dbTotal = getMedTotal(selectedMed);
@@ -282,7 +284,7 @@ export function useRefill(): UseRefillReturn {
const knownLoose = Math.min(currentStock, Math.max(0, selectedMed.looseTablets));
const sealedPills = Math.max(0, currentStock - knownLoose);
let fullBlisters: number;
if (selectedMed.packageType === "liquid_container") {
if (isLiquidContainerPackageType(selectedMed.packageType)) {
fullBlisters = Math.max(1, selectedMed.packCount);
} else if (isAmountPackage) {
fullBlisters = 0;
+31 -34
View File
@@ -6,7 +6,14 @@ import { ConfirmModal, MedicationAvatar } from "../components";
import { useAuth } from "../components/Auth";
import { useAppContext } from "../context";
import { useModalHistory } from "../hooks";
import { type Coverage, getMedDisplayName } from "../types";
import {
allowsPillFormSelection,
type Coverage,
getMedDisplayName,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
} from "../types";
import { formatNumber, getExpiryClass, getSystemLocale } from "../utils/formatters";
import { expandDoseIds, getStockStatus, isDoseDismissed } from "../utils/schedule";
import {
@@ -132,15 +139,15 @@ export function DashboardPage() {
const prescriptionEmptyCount = prescriptionLowMeds.filter((med) => med.remainingRefills <= 0).length;
const getTubeUnitLabel = (med: (typeof meds)[number] | undefined, value: number) =>
med?.packageType === "liquid_container" || med?.medicationForm === "liquid"
isLiquidContainerPackageType(med?.packageType) || med?.medicationForm === "liquid"
? t("form.packageAmountUnitMl")
: t("form.blisters.applications", { count: Math.abs(value) });
const formatStockLabel = (med: (typeof meds)[number] | undefined, medsLeft: number) => {
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
return `${formatNumber(medsLeft)} ${t("form.packageAmountUnitMl")}`;
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return `${formatNumber(medsLeft)} ${getTubeUnitLabel(med, medsLeft)}`;
}
return t("table.pillsCount", { count: Math.round(medsLeft) });
@@ -177,10 +184,10 @@ export function DashboardPage() {
usage: number,
intakeUnit?: "ml" | "tsp" | "tbsp" | null
) => {
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
return formatLiquidUsageLabel(usage, intakeUnit);
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return `${usage} ${getTubeUnitLabel(med, usage)}`;
}
return `${usage} ${usage !== 1 ? t("common.pills") : t("common.pill")}`;
@@ -192,7 +199,7 @@ export function DashboardPage() {
intakeUnit?: "ml" | "tsp" | "tbsp" | null,
doses?: Array<{ usage: number; intakeUnit?: "ml" | "tsp" | "tbsp" | null }>
) => {
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
if (doses && doses.length > 0) {
const normalizedDoses = doses.filter((dose) => Number.isFinite(Number(dose.usage)) && Number(dose.usage) > 0);
if (normalizedDoses.length > 0) {
@@ -214,7 +221,7 @@ export function DashboardPage() {
return formatLiquidUsageLabel(total, intakeUnit);
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return `${total} ${getTubeUnitLabel(med, total)}`;
}
return t("common.pillsTotal", { count: total });
@@ -245,7 +252,7 @@ export function DashboardPage() {
const personMultiplier = hasPerIntakeTakenBy ? 1 : Math.max(1, med.takenBy?.length ?? 0);
const normalizedUsage = (usage * personMultiplier) / every;
if (med.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med.packageType)) {
dailyTotal += convertLiquidUsageToMl(normalizedUsage, intake.intakeUnit ?? "ml");
} else {
dailyTotal += normalizedUsage;
@@ -254,11 +261,11 @@ export function DashboardPage() {
if (dailyTotal <= 0) return "-";
if (med.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med.packageType)) {
return t("table.perDayWithUnit", { value: formatNumber(dailyTotal), unit: t("form.packageAmountUnitMl") });
}
if (med.packageType === "tube") {
if (isTubePackageType(med.packageType)) {
const tubeUnit =
med.medicationForm === "liquid"
? t("form.packageAmountUnitMl")
@@ -273,7 +280,7 @@ export function DashboardPage() {
const shouldHideNoScheduleStatusForTube = (
med: (typeof meds)[number] | undefined,
status: { className: string; label: string } | null
) => med?.packageType === "tube" && status?.label === "status.noSchedule";
) => isTubePackageType(med?.packageType) && status?.label === "status.noSchedule";
const getVisibleStockStatus = (
med: (typeof meds)[number] | undefined,
@@ -746,9 +753,7 @@ export function DashboardPage() {
</span>
</span>
<span data-label={t("table.stock")} className={textClass}>
{med?.packageType === "bottle" ||
med?.packageType === "tube" ||
med?.packageType === "liquid_container"
{isAmountBasedPackageType(med?.packageType)
? formatStockLabel(med, row.medsLeft)
: formatFullBlisters(stock.fullBlisters, t)}
</span>
@@ -757,11 +762,9 @@ export function DashboardPage() {
</span>
<span
data-label={t("table.stockDetails")}
className={`${textClass}${med?.packageType === "bottle" || med?.packageType === "tube" || med?.packageType === "liquid_container" ? " hide-on-card" : ""}`}
className={`${textClass}${isAmountBasedPackageType(med?.packageType) ? " hide-on-card" : ""}`}
>
{med?.packageType === "bottle" ||
med?.packageType === "tube" ||
med?.packageType === "liquid_container"
{isAmountBasedPackageType(med?.packageType)
? "—"
: formatOpenBlisterAndLoose(
stock.openBlisterPills,
@@ -958,11 +961,9 @@ export function DashboardPage() {
<span className="dose-usage-main">
{formatDoseUsageLabel(med, dose.usage, dose.intakeUnit)}
</span>
{med?.packageType !== "tube" &&
med?.packageType !== "liquid_container" &&
med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
{allowsPillFormSelection(med?.packageType) && med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
</span>
{dose.intakeRemindersEnabled && (
<span
@@ -1241,11 +1242,9 @@ export function DashboardPage() {
<span className="dose-usage-main">
{formatDoseUsageLabel(med, dose.usage, dose.intakeUnit)}
</span>
{med?.packageType !== "tube" &&
med?.packageType !== "liquid_container" &&
med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
{allowsPillFormSelection(med?.packageType) && med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
</span>
{dose.intakeRemindersEnabled && (
<span
@@ -1487,11 +1486,9 @@ export function DashboardPage() {
<span className="dose-usage-main">
{formatDoseUsageLabel(med, dose.usage, dose.intakeUnit)}
</span>
{med?.packageType !== "tube" &&
med?.packageType !== "liquid_container" &&
med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
{allowsPillFormSelection(med?.packageType) && med?.pillWeightMg && (
<span className="dose-usage-weight">{`${dose.usage * med.pillWeightMg} ${med.doseUnit ?? "mg"}`}</span>
)}
</span>
{dose.intakeRemindersEnabled && (
<span
+60 -48
View File
@@ -17,8 +17,20 @@ import {
import { useAuth } from "../components/Auth";
import { useAppContext, useUnsavedChanges } from "../context";
import { useMedicationForm, useModalHistory, useUnsavedChangesWarning } from "../hooks";
import type { DoseUnit, FormState, Medication } from "../types";
import { DOSE_UNITS, FIELD_LIMITS, getMedDisplayName, getPackageSize } from "../types";
import type { DoseUnit, FormState, Medication, PackageType } from "../types";
import {
allowsPillFormSelection,
DOSE_UNITS,
FIELD_LIMITS,
getMedDisplayName,
getPackageProfile,
getPackageSize,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
normalizePackageType,
PACKAGE_PROFILES,
} from "../types";
import { combineDateAndTime, formatDate, formatDateTime, formatNumber } from "../utils/formatters";
import { MAX_IMAGE_UPLOAD_BYTES, resolveImageUploadError } from "../utils/image-upload";
import { log } from "../utils/logger";
@@ -239,7 +251,7 @@ export function MedicationsPage() {
// Calculate total tablets
const totalTablets = useMemo(() => {
if (form.packageType === "bottle" || form.packageType === "tube" || form.packageType === "liquid_container") {
if (isAmountBasedPackageType(form.packageType)) {
// For bottle type, looseTablets is the current stock
return Number(form.looseTablets) || 0;
}
@@ -274,19 +286,19 @@ export function MedicationsPage() {
}, [form.medicationStartDate, form.medicationEndDate, form.intakes, t]);
const allowFractionalIntake = useMemo(() => {
if (form.packageType === "liquid_container") return true;
if (form.packageType === "tube") return form.medicationForm === "liquid";
if (isLiquidContainerPackageType(form.packageType)) return true;
if (isTubePackageType(form.packageType)) return form.medicationForm === "liquid";
return form.pillForm === "tablet";
}, [form.packageType, form.medicationForm, form.pillForm]);
const getUsageLabel = useCallback(
(intakeUnit: "ml" | "tsp" | "tbsp") => {
if (form.packageType === "liquid_container") {
if (isLiquidContainerPackageType(form.packageType)) {
if (intakeUnit === "tsp") return t("form.blisters.usageTsp");
if (intakeUnit === "tbsp") return t("form.blisters.usageTbsp");
return t("form.blisters.usageMl");
}
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
return form.medicationForm === "liquid" ? t("form.blisters.usageMl") : t("form.blisters.usageApplication");
}
if (form.pillForm === "capsule") return t("form.blisters.usageCapsules");
@@ -295,25 +307,22 @@ export function MedicationsPage() {
[form.packageType, form.medicationForm, form.pillForm, t]
);
const usesAmountLabels = form.packageType === "tube" || form.packageType === "liquid_container";
const usesAmountLabels = isTubePackageType(form.packageType) || isLiquidContainerPackageType(form.packageType);
const totalCapacityLabel = usesAmountLabels ? t("form.totalAmount") : t("form.totalCapacity");
const currentStockLabel = usesAmountLabels ? t("form.currentAmount") : t("form.currentPills");
const totalLabel = usesAmountLabels ? t("form.totalAmountLabel") : t("form.total");
const getMedicationPackageTypeLabel = useCallback(
(med: Medication) => {
if (med.packageType === "bottle") return t("form.packageTypeBottle");
if (med.packageType === "tube") return t("form.packageTypeTube");
if (med.packageType === "liquid_container") return t("form.packageTypeLiquidContainer");
return t("form.packageTypeBlister");
return t(getPackageProfile(med.packageType).labelKey);
},
[t]
);
const getMedicationStockSuffix = useCallback(
(med: Medication) => {
if (med.packageType === "tube") return "";
if (med.packageType === "liquid_container") return " ml";
if (isTubePackageType(med.packageType)) return "";
if (isLiquidContainerPackageType(med.packageType)) return " ml";
return ` ${getPackageSize(med) === 1 ? t("common.pill") : t("common.pills")}`;
},
[t]
@@ -321,10 +330,10 @@ export function MedicationsPage() {
const getMedicationUsageUnitLabel = useCallback(
(med: Medication, usage: number) => {
if (med.packageType === "tube") {
if (isTubePackageType(med.packageType)) {
return med.medicationForm === "liquid" ? "ml" : t("form.blisters.usageApplication");
}
if (med.packageType === "liquid_container") return "ml";
if (isLiquidContainerPackageType(med.packageType)) return "ml";
if (usage === 1) return t("common.pill");
return t("common.pills");
},
@@ -527,7 +536,7 @@ export function MedicationsPage() {
usage: Number(intake.usage) || 1,
every: Number(intake.every) || 1,
start: combineDateAndTime(intake.startDate, intake.startTime),
intakeUnit: form.packageType === "liquid_container" ? intake.intakeUnit : null,
intakeUnit: isLiquidContainerPackageType(form.packageType) ? intake.intakeUnit : null,
takenBy: intake.takenBy.trim() || null, // Empty string becomes null
intakeRemindersEnabled: intake.intakeRemindersEnabled,
}));
@@ -544,22 +553,23 @@ export function MedicationsPage() {
const lowRefillThreshold = Math.min(Number(form.prescriptionLowRefillThreshold || 1), authorizedRefills);
let derivedMedicationForm: string;
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
derivedMedicationForm =
form.medicationForm === "liquid" || form.medicationForm === "topical" ? form.medicationForm : "topical";
} else if (form.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(form.packageType)) {
derivedMedicationForm = "liquid";
} else {
derivedMedicationForm = form.pillForm;
}
const tubeTotalAmount =
form.packageType === "tube" ? (Number(form.packCount) || 0) * (Number(form.packageAmountValue ?? 0) || 0) : null;
const tubeTotalAmount = isTubePackageType(form.packageType)
? (Number(form.packCount) || 0) * (Number(form.packageAmountValue ?? 0) || 0)
: null;
let packageAmountUnit = form.packageAmountUnit ?? "ml";
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
packageAmountUnit = "g";
} else if (form.packageType === "liquid_container") {
} else if (isLiquidContainerPackageType(form.packageType)) {
packageAmountUnit = "ml";
}
@@ -568,16 +578,19 @@ export function MedicationsPage() {
genericName: form.genericName.trim() || null,
takenBy: form.takenBy.length > 0 ? form.takenBy : [],
medicationForm: derivedMedicationForm,
pillForm: form.packageType === "tube" || form.packageType === "liquid_container" ? null : form.pillForm,
pillForm:
isTubePackageType(form.packageType) || isLiquidContainerPackageType(form.packageType) ? null : form.pillForm,
lifecycleCategory: form.lifecycleCategory,
packageType: form.packageType,
packCount: form.packageType === "tube" ? Math.max(1, Number(form.packCount) || 1) : Number(form.packCount) || 0,
blistersPerPack: form.packageType === "tube" ? 1 : Number(form.blistersPerPack) || 1,
pillsPerBlister: form.packageType === "tube" ? 1 : Number(form.pillsPerBlister) || 1,
packageType: normalizePackageType(form.packageType),
packCount: isTubePackageType(form.packageType)
? Math.max(1, Number(form.packCount) || 1)
: Number(form.packCount) || 0,
blistersPerPack: isTubePackageType(form.packageType) ? 1 : Number(form.blistersPerPack) || 1,
pillsPerBlister: isTubePackageType(form.packageType) ? 1 : Number(form.pillsPerBlister) || 1,
packageAmountValue: Number(form.packageAmountValue ?? 0) || 0,
packageAmountUnit,
totalPills: form.packageType === "tube" ? tubeTotalAmount : Number(form.totalPills) || null,
looseTablets: form.packageType === "tube" ? tubeTotalAmount || 0 : Number(form.looseTablets) || 0,
totalPills: isTubePackageType(form.packageType) ? tubeTotalAmount : Number(form.totalPills) || null,
looseTablets: isTubePackageType(form.packageType) ? tubeTotalAmount || 0 : Number(form.looseTablets) || 0,
pillWeightMg: Number(form.pillWeightMg) || null,
doseUnit: form.doseUnit,
medicationStartDate: form.medicationStartDate || null,
@@ -981,7 +994,7 @@ export function MedicationsPage() {
<span>
{t("medications.details.type")}: <strong>{getMedicationPackageTypeLabel(med)}</strong>
</span>
{med.packageType === "blister" ? (
{!isAmountBasedPackageType(med.packageType) ? (
<>
<span>
{t("medications.details.packs")}: <strong>{med.packCount}</strong>
@@ -1014,7 +1027,7 @@ export function MedicationsPage() {
? Math.round(coverageByMed[getMedDisplayName(med)].medsLeft)
: getPackageSize(med)}{" "}
/ {getPackageSize(med)}
{med.packageType === "tube" ? "" : getMedicationStockSuffix(med)}
{getMedicationStockSuffix(med)}
{(coverageByMed[getMedDisplayName(med)]
? Math.round(coverageByMed[getMedDisplayName(med)].medsLeft)
: getPackageSize(med)) > getPackageSize(med) && (
@@ -1250,14 +1263,13 @@ export function MedicationsPage() {
<select
className="package-type-select"
value={form.packageType}
onChange={(e) =>
handleValueChange("packageType", e.target.value as import("../types").PackageType)
}
onChange={(e) => handleValueChange("packageType", e.target.value as PackageType)}
>
<option value="blister">{t("form.packageTypeBlister")}</option>
<option value="bottle">{t("form.packageTypeBottle")}</option>
<option value="tube">{t("form.packageTypeTube")}</option>
<option value="liquid_container">{t("form.packageTypeLiquidContainer")}</option>
{PACKAGE_PROFILES.map((profile) => (
<option key={profile.value} value={profile.value}>
{t(profile.labelKey)}
</option>
))}
</select>
</label>
<label>
@@ -1268,7 +1280,7 @@ export function MedicationsPage() {
placeholder={t("common.optional")}
/>
</label>
{form.packageType !== "tube" && form.packageType !== "liquid_container" && (
{allowsPillFormSelection(form.packageType) && (
<label>
{t("form.pillForm")}
<select
@@ -1280,7 +1292,7 @@ export function MedicationsPage() {
</select>
</label>
)}
{form.packageType === "tube" && (
{isTubePackageType(form.packageType) && (
<label>
{t("form.medicationForm")}
<select value={"topical"} onChange={() => handleValueChange("medicationForm", "topical")}>
@@ -1288,7 +1300,7 @@ export function MedicationsPage() {
</select>
</label>
)}
{form.packageType === "liquid_container" && (
{isLiquidContainerPackageType(form.packageType) && (
<label>
{t("form.medicationForm")}
<select value={"liquid"} onChange={() => handleValueChange("medicationForm", "liquid")}>
@@ -1423,7 +1435,7 @@ export function MedicationsPage() {
<div className="full form-category">
<h4 className="form-category-title">{t("form.sections.stock")}</h4>
{(() => {
if (form.packageType === "blister") {
if (!isAmountBasedPackageType(form.packageType)) {
return (
<>
<label>
@@ -1464,7 +1476,7 @@ export function MedicationsPage() {
);
}
if (form.packageType === "tube") {
if (isTubePackageType(form.packageType)) {
return (
<>
<label>
@@ -1536,7 +1548,7 @@ export function MedicationsPage() {
</>
);
})()}
{form.packageType !== "tube" && form.packageType !== "liquid_container" && (
{allowsPillFormSelection(form.packageType) && (
<label className="full">
{t("form.pillWeight")} ({form.doseUnit})
<div className="dose-input-group">
@@ -1562,7 +1574,7 @@ export function MedicationsPage() {
</div>
</label>
)}
{(form.packageType === "bottle" || form.packageType === "liquid_container") && (
{isAmountBasedPackageType(form.packageType) && !isTubePackageType(form.packageType) && (
<div className="full stock-total-row">
<label className="stock-total-field">
{totalLabel}
@@ -1570,7 +1582,7 @@ export function MedicationsPage() {
</label>
</div>
)}
{form.packageType === "liquid_container" && (
{isLiquidContainerPackageType(form.packageType) && (
<label className="full">
{t("form.packageAmount")}
<div className="dose-input-group">
@@ -1744,7 +1756,7 @@ export function MedicationsPage() {
onChange={(e) => setIntakeValue(idx, "startTime", e.target.value)}
/>
</label>
{form.packageType === "liquid_container" && (
{isLiquidContainerPackageType(form.packageType) && (
<label>
{t("form.blisters.intakeUnit")}
<select
+7 -13
View File
@@ -5,7 +5,7 @@ import { DateTimeInput, MedicationAvatar } from "../components";
import { useAuth } from "../components/Auth";
import { useAppContext } from "../context";
import type { PlannerRow } from "../types";
import { getMedDisplayName } from "../types";
import { getMedDisplayName, isAmountBasedPackageType, isLiquidContainerPackageType, isTubePackageType } from "../types";
import { toInputValue } from "../utils/formatters";
// Date helpers
@@ -124,10 +124,10 @@ export function PlannerPage() {
const getUsageUnitLabel = (medicationId: number, count: number): string => {
const med = meds.find((m) => m.id === medicationId);
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
return t("form.ml");
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return med.medicationForm === "liquid" ? t("form.ml") : t("blisters.applications");
}
return count === 1 ? t("common.pill") : t("common.pills");
@@ -136,10 +136,10 @@ export function PlannerPage() {
const getAvailableLabel = (medicationId: number, loosePills: number): string => {
const med = meds.find((m) => m.id === medicationId);
const roundedLoose = Math.round(loosePills * 10) / 10;
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
return `${roundedLoose} ${t("form.ml")}`;
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
const unit = med.medicationForm === "liquid" ? t("form.ml") : t("blisters.applications");
return `${roundedLoose} ${unit}`;
}
@@ -254,17 +254,11 @@ export function PlannerPage() {
</span>
</span>
<span data-label={t("planner.table.blisters")}>
{row.packageType === "bottle" ||
row.packageType === "tube" ||
row.packageType === "liquid_container"
? ""
: `${row.blistersNeeded} × ${row.blisterSize}`}
{isAmountBasedPackageType(row.packageType) ? "" : `${row.blistersNeeded} × ${row.blisterSize}`}
</span>
<span data-label={t("planner.table.prescriptionRefills")}>{remainingRefills ?? ""}</span>
<span data-label={t("planner.table.available")}>
{row.packageType === "bottle" ||
row.packageType === "tube" ||
row.packageType === "liquid_container" ? (
{isAmountBasedPackageType(row.packageType) ? (
getAvailableLabel(row.medicationId, row.loosePills)
) : (
<>
+9 -9
View File
@@ -5,7 +5,7 @@ import { MedicationAvatar } from "../components";
import { useAuth } from "../components/Auth";
import { useAppContext } from "../context";
import type { Coverage } from "../types";
import { getMedDisplayName } from "../types";
import { getMedDisplayName, isLiquidContainerPackageType, isTubePackageType } from "../types";
import { formatNumber } from "../utils/formatters";
import { expandDoseIds, isDoseDismissed } from "../utils/schedule";
@@ -21,12 +21,12 @@ function getStockStatus(
settings: { lowStockDays: number; normalStockDays: number; highStockDays: number; reminderDaysBefore: number },
packageType?: string
) {
if (packageType === "tube") return { className: "success", label: "status.noSchedule" };
if (isTubePackageType(packageType)) return { className: "success", label: "status.noSchedule" };
// Out of stock or completely depleted = danger (red)
if (medsLeft <= 0 || daysLeft === 0) return { className: "danger", label: "status.outOfStock" };
// No schedule, but has stock = normal
if (daysLeft === null) return { className: "success", label: "status.noSchedule" };
if (packageType === "liquid_container") {
if (isLiquidContainerPackageType(packageType)) {
const lowDays = Math.max(1, Math.floor(settings.reminderDaysBefore));
const criticalDays = Math.max(1, Math.ceil(lowDays / 2));
if (daysLeft <= criticalDays) return { className: "danger", label: "status.criticalStock" };
@@ -95,10 +95,10 @@ export function SchedulePage() {
const shouldHideNoScheduleStatusForTube = (
med: (typeof meds)[number] | undefined,
status: { className: string; label: string } | null
) => med?.packageType === "tube" && status?.label === "status.noSchedule";
) => isTubePackageType(med?.packageType) && status?.label === "status.noSchedule";
const getTubeUnitLabel = (med: (typeof meds)[number] | undefined, value: number) =>
med?.packageType === "liquid_container" || med?.medicationForm === "liquid"
isLiquidContainerPackageType(med?.packageType) || med?.medicationForm === "liquid"
? t("form.packageAmountUnitMl")
: t("form.blisters.applications", { count: Math.abs(value) });
@@ -133,10 +133,10 @@ export function SchedulePage() {
usage: number,
intakeUnit?: "ml" | "tsp" | "tbsp" | null
) => {
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
return formatLiquidUsageLabel(usage, intakeUnit);
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return `${usage} ${getTubeUnitLabel(med, usage)}`;
}
return `${usage} ${usage !== 1 ? t("common.pills") : t("common.pill")}`;
@@ -147,7 +147,7 @@ export function SchedulePage() {
total: number,
doses?: Array<{ usage: number; intakeUnit?: "ml" | "tsp" | "tbsp" | null }>
) => {
if (med?.packageType === "liquid_container") {
if (isLiquidContainerPackageType(med?.packageType)) {
if (doses && doses.length > 0) {
const normalizedDoses = doses.filter((dose) => Number.isFinite(Number(dose.usage)) && Number(dose.usage) > 0);
if (normalizedDoses.length > 0) {
@@ -167,7 +167,7 @@ export function SchedulePage() {
}
return `${formatNumber(total)} ${t("form.packageAmountUnitMl")}`;
}
if (med?.packageType === "tube") {
if (isTubePackageType(med?.packageType)) {
return `${total} ${getTubeUnitLabel(med, total)}`;
}
return t("common.pillsTotal", { count: total });
+3 -3
View File
@@ -1,5 +1,5 @@
import type { Coverage, Medication, PackageType } from "../types";
import { getMedTotal as getMedTotalFromTypes } from "../types";
import { getMedTotal as getMedTotalFromTypes, isLiquidContainerPackageType, isTubePackageType } from "../types";
import { splitCurrentBlisterStock } from "../utils/stock";
export function userStorageKey(userId: number | undefined, key: string): string {
@@ -78,7 +78,7 @@ export function getReminderStatusData(
for (const c of allCoverage) {
const med = medByName.get(c.name);
if (med?.packageType === "tube") continue;
if (isTubePackageType(med?.packageType)) continue;
if (c.medsLeft <= 0) {
lowStockMap.set(c.name, { name: c.name, daysLeft: 0, isCritical: true });
@@ -88,7 +88,7 @@ export function getReminderStatusData(
if (c.daysLeft === null) continue;
const roundedDaysLeft = Math.round(c.daysLeft);
const isLiquid = med?.packageType === "liquid_container";
const isLiquid = isLiquidContainerPackageType(med?.packageType);
const liquidLowDays = Math.max(1, Math.floor(reminderDaysBefore));
const liquidCriticalDays = Math.max(1, Math.ceil(liquidLowDays / 2));
const isCritical = isLiquid ? c.daysLeft <= liquidCriticalDays : c.daysLeft <= reminderDaysBefore;
+16 -3
View File
@@ -2,7 +2,20 @@
// Core Types for MedAssist
// =============================================================================
export type PackageType = "blister" | "bottle" | "tube" | "liquid_container";
export type { PackageProfile, PackageType } from "./package-profiles";
export {
allowsPillFormSelection,
getPackageProfile,
isAmountBasedPackageType,
isLiquidContainerPackageType,
isTubePackageType,
normalizePackageType,
PACKAGE_PROFILES,
PACKAGE_TYPES,
} from "./package-profiles";
import type { PackageType } from "./package-profiles";
import { isAmountBasedPackageType } from "./package-profiles";
// Common medication dose units
export type DoseUnit = "mg" | "g" | "mcg" | "ml" | "units";
@@ -280,7 +293,7 @@ type MedLike = Pick<Medication, "packCount" | "blistersPerPack" | "pillsPerBlist
export function getMedTotal(med: MedLike): number {
// Amount-based package types store their current base stock directly
// in totalPills (fallback looseTablets for legacy rows).
if (med.packageType === "bottle" || med.packageType === "tube" || med.packageType === "liquid_container") {
if (isAmountBasedPackageType(med.packageType)) {
const baseStock = med.totalPills ?? med.looseTablets;
return baseStock + (med.stockAdjustment ?? 0);
}
@@ -291,7 +304,7 @@ export function getMedTotal(med: MedLike): number {
/** Get the base package size (without stockAdjustment) */
export function getPackageSize(med: MedLike): number {
// Amount-based package types use totalPills as base capacity
if (med.packageType === "bottle" || med.packageType === "tube" || med.packageType === "liquid_container") {
if (isAmountBasedPackageType(med.packageType)) {
return med.totalPills ?? med.looseTablets;
}
// For blister type, calculate from packs + loose
+72
View File
@@ -0,0 +1,72 @@
export const PACKAGE_TYPES = ["blister", "bottle", "tube", "liquid_container"] as const;
export type PackageType = (typeof PACKAGE_TYPES)[number];
export type PackageProfile = {
value: PackageType;
labelKey: string;
amountBased: boolean;
plannerUnitKind: "pills" | "ml" | "units";
allowsPillFormSelection: boolean;
};
export const PACKAGE_PROFILES: PackageProfile[] = [
{
value: "blister",
labelKey: "form.packageTypeBlister",
amountBased: false,
plannerUnitKind: "pills",
allowsPillFormSelection: true,
},
{
value: "bottle",
labelKey: "form.packageTypeBottle",
amountBased: true,
plannerUnitKind: "pills",
allowsPillFormSelection: true,
},
{
value: "tube",
labelKey: "form.packageTypeTube",
amountBased: true,
plannerUnitKind: "units",
allowsPillFormSelection: false,
},
{
value: "liquid_container",
labelKey: "form.packageTypeLiquidContainer",
amountBased: true,
plannerUnitKind: "ml",
allowsPillFormSelection: false,
},
];
const PACKAGE_TYPE_SET = new Set<string>(PACKAGE_TYPES);
const PROFILE_BY_TYPE = new Map(PACKAGE_PROFILES.map((profile) => [profile.value, profile] as const));
export function normalizePackageType(packageType?: string | null): PackageType {
if (packageType && PACKAGE_TYPE_SET.has(packageType)) {
return packageType as PackageType;
}
return "blister";
}
export function getPackageProfile(packageType?: string | null): PackageProfile {
return PROFILE_BY_TYPE.get(normalizePackageType(packageType)) ?? PACKAGE_PROFILES[0];
}
export function isTubePackageType(packageType?: string | null): boolean {
return normalizePackageType(packageType) === "tube";
}
export function isLiquidContainerPackageType(packageType?: string | null): boolean {
return normalizePackageType(packageType) === "liquid_container";
}
export function isAmountBasedPackageType(packageType?: string | null): boolean {
return getPackageProfile(packageType).amountBased;
}
export function allowsPillFormSelection(packageType?: string | null): boolean {
return getPackageProfile(packageType).allowsPillFormSelection;
}
+5 -5
View File
@@ -12,14 +12,14 @@ import type {
StockStatus,
StockThresholds,
} from "../types";
import { getMedDisplayName, getMedTotal } from "../types";
import { getMedDisplayName, getMedTotal, isLiquidContainerPackageType, isTubePackageType } from "../types";
function normalizeIntakeUsageForStock(intake: Intake, med: Medication): number {
const usage = Number(intake.usage);
if (!Number.isFinite(usage) || usage <= 0) return 0;
if (med.packageType === "tube") return 0;
if (isTubePackageType(med.packageType)) return 0;
const isLiquidStock = med.packageType === "liquid_container" || med.medicationForm === "liquid";
const isLiquidStock = isLiquidContainerPackageType(med.packageType) || med.medicationForm === "liquid";
if (!isLiquidStock) return usage;
if (intake.intakeUnit === "tsp") return usage * 5;
@@ -344,7 +344,7 @@ export function getStockStatus(
}
// Tube has no stock reminder semantics.
if (packageType === "tube") {
if (isTubePackageType(packageType)) {
return { level: "normal", className: "success", label: "status.noSchedule" };
}
@@ -353,7 +353,7 @@ export function getStockStatus(
return { level: "normal", className: "success", label: "status.noSchedule" };
}
if (packageType === "liquid_container") {
if (isLiquidContainerPackageType(packageType)) {
const liquidThresholds = getLiquidDerivedThresholds(thresholds.criticalStockDays);
if (daysLeft <= liquidThresholds.criticalDays) {
return { level: "critical", className: "danger", label: "status.criticalStock" };
+4 -4
View File
@@ -1,4 +1,5 @@
import type { Medication } from "../types";
import { isAmountBasedPackageType } from "../types";
export type BlisterStockSplit = {
fullBlisters: number;
@@ -34,10 +35,9 @@ export function splitCurrentBlisterStock(
* Convenience helper when medication object already contains stock fields.
*/
export function getBlisterStockFromMedication(med: Medication): BlisterStockSplit {
const total =
med.packageType === "bottle" || med.packageType === "tube" || med.packageType === "liquid_container"
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
const total = isAmountBasedPackageType(med.packageType)
? med.looseTablets + (med.stockAdjustment ?? 0)
: med.packCount * med.blistersPerPack * med.pillsPerBlister + med.looseTablets + (med.stockAdjustment ?? 0);
return splitCurrentBlisterStock(total, med.pillsPerBlister, med.looseTablets);
}