60 lines
1.5 KiB
TypeScript
60 lines
1.5 KiB
TypeScript
|
|
import { MoneyValue, Percentage, Quantity } from "@shared/contexts";
|
||
|
|
import { IMoney, IPercentage, IQuantity } from "./types";
|
||
|
|
|
||
|
|
export const calculateItemTotals = (item: {
|
||
|
|
quantity?: IQuantity;
|
||
|
|
retail_price?: IMoney;
|
||
|
|
discount?: IPercentage;
|
||
|
|
}): {
|
||
|
|
quantity: Quantity;
|
||
|
|
retailPrice: MoneyValue;
|
||
|
|
price: MoneyValue;
|
||
|
|
discount: Percentage;
|
||
|
|
total: MoneyValue;
|
||
|
|
} => {
|
||
|
|
const { quantity: quantityValue, retail_price: retailPriceValue, discount: discountValue } = item;
|
||
|
|
|
||
|
|
console.log({
|
||
|
|
quantityValue,
|
||
|
|
retailPriceValue,
|
||
|
|
discountValue,
|
||
|
|
});
|
||
|
|
|
||
|
|
const quantityOrError = Quantity.create(quantityValue);
|
||
|
|
if (quantityOrError.isFailure) {
|
||
|
|
throw quantityOrError.error;
|
||
|
|
}
|
||
|
|
const quantity = quantityOrError.object;
|
||
|
|
|
||
|
|
const retailPriceOrError = MoneyValue.create(retailPriceValue);
|
||
|
|
if (retailPriceOrError.isFailure) {
|
||
|
|
throw retailPriceOrError.error;
|
||
|
|
}
|
||
|
|
const retailPrice = retailPriceOrError.object;
|
||
|
|
|
||
|
|
const discountOrError = Percentage.create(discountValue);
|
||
|
|
if (discountOrError.isFailure) {
|
||
|
|
throw discountOrError.error;
|
||
|
|
}
|
||
|
|
const discount = discountOrError.object;
|
||
|
|
|
||
|
|
const price = retailPrice.multiply(quantity.toNumber());
|
||
|
|
const total = price.subtract(price.percentage(discount.toNumber()));
|
||
|
|
|
||
|
|
return {
|
||
|
|
quantity,
|
||
|
|
retailPrice,
|
||
|
|
price,
|
||
|
|
discount,
|
||
|
|
total,
|
||
|
|
};
|
||
|
|
|
||
|
|
/*return {
|
||
|
|
quantity: quantity.toObject(),
|
||
|
|
retail_price: retailPrice.toObject(),
|
||
|
|
price: price.toObject(),
|
||
|
|
discount: discount.toObject(),
|
||
|
|
total: total.toObject(),
|
||
|
|
};*/
|
||
|
|
};
|