Skip to content

Instantly share code, notes, and snippets.

@NSLog0
Created May 26, 2021 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NSLog0/f76f4610a7cc57fa10d516574bce49eb to your computer and use it in GitHub Desktop.
Save NSLog0/f76f4610a7cc57fa10d516574bce49eb to your computer and use it in GitHub Desktop.
const priceValidator = ({
products = [],
tax = 0,
deliveryFee = 0,
limitDeliveryFee = 0,
pointToDiscount = 0,
pointToDiscountRate = 10
}: IPriceValidator) => {
const PRICE_OFFSET = 100
let totalPrice = 0
let totalPriceWithTax = 0
let vat = tax / PRICE_OFFSET
let totalDiscount = 0
let totalQuantity = 0
let totalDiscountPrice = 0
products.map(({ variants: { price: { cents } }, quantity }) => { totalPrice += cents * quantity })
products.map(({ quantity }) => { totalQuantity += quantity })
totalDiscount = (Math.floor(pointToDiscount / pointToDiscountRate) * PRICE_OFFSET)
const totalPriceInCent = totalPrice / PRICE_OFFSET
const totalVat = Math.round((totalPriceInCent * vat) * PRICE_OFFSET) / PRICE_OFFSET
totalPriceWithTax = totalPrice + (totalVat * PRICE_OFFSET)
totalDiscountPrice = totalPriceWithTax - totalDiscount
if(limitDeliveryFee === 0 || limitDeliveryFee > totalDiscountPrice) {
totalDiscountPrice += deliveryFee
}
return {
totalPriceWithVatFee: totalDiscountPrice,
totalPrice,
totalQuantity,
totalDiscount,
totalDeliveryFee: deliveryFee / PRICE_OFFSET,
totalVat,
totalUsagePoint: pointToDiscount,
totalDiscountPrice,
vat,
tax,
deliveryFeeRate: deliveryFee,
}
}
export default priceValidator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment