The product/variant price, usdPrice, quantity, and uom fields.
The numeric price per base unit, or undefined when it can't be computed.
getUnitPrice({ usdPrice: 40, price: 40, quantity: 500, uom: "g" }); // => 0.08
getUnitPrice({ usdPrice: 20, price: 20, quantity: 1, uom: "kg" }); // => 0.02
getUnitPrice({ price: 10, quantity: 0, uom: "g" }); // => undefined
export function getUnitPrice(product: UnitPriceFields): number | undefined {
const { usdPrice, price, quantity, uom } = product;
const priceValue = usdPrice ?? price;
if (priceValue === undefined || quantity === undefined || uom === undefined) return undefined;
const base = toCostBaseQuantity(quantity, uom);
if (!base) return undefined;
return priceValue / base.quantity;
}
Computes a product's price per base unit as a currency-stable number for sorting and filtering — the USD price (or raw price when there's no USD anchor) divided by the quantity normalized to its cost base unit (grams for mass, millilitres for volume, pieces for countable units; see toCostBaseQuantity). Returns
undefinedwhen there's no price, no quantity, or the unit can't be converted, so the value never becomesNaN.Uses
usdPrice(mirroring the price column's sort) so per-unit values compare across currencies; formatUnitPrice handles display-currency conversion separately.