The question was asked previously but there was not any proper answer. The problem is I am developing a POS application for a Canadian client. I am stuck in a tax calculation and could not be able to find a solution. So here is my scenario, I have 2 items lets say item 1 = $10 and item 2 = $2. The item 2 is tax exempted means the taxes (13%) will not be apply on item 2 but before applying tax. I need to apply discount for example of $5. So how to apply discount on my total bill and calculate the total tax.
I NEED A TAX AMOUNT AFTER DISCOUNT . THE TAX IS 13%.
Item 1 is $10 item 2 is $2 (Tax Exempt)
Subtotal is $12 Discount is $5 Tax will be ?
Here's one way to do it:
const ITEMS = [
{ price: 2.00, taxExempt: true },
{ price: 10.00, taxExempt: false },
{ price: 8.25, taxExempt: false },
]
const DISCOUNT = 12
const TAX = 0.13
const applyDiscount = (items, discount) => {
// 1️⃣ sort by price, most expensive to least
items = items.slice().sort((a,b) => b.price - a.price)
// 2️⃣
return items.map(item => {
let price = item.price
const itemDiscount = Math.min(price, discount)
if (itemDiscount > 0) {
price -= itemDiscount
discount -= itemDiscount
}
return { ...item, price, origPrice: item.price, itemDiscount }
})
}
const itemsWithDiscount = applyDiscount(ITEMS, DISCOUNT)
const sumPrices = arr => arr.map(x => x.price).reduce((p,c) => p + c, 0)
const subtotal = sumPrices(itemsWithDiscount) // 3️⃣
const taxableAmt = sumPrices(itemsWithDiscount.filter(x => !x.taxExempt)) // 4️⃣
const total = subtotal + (taxableAmt * TAX) // 5️⃣
console.log('items after discount', itemsWithDiscount)
console.log('subtotal: $' + subtotal.toFixed(2) + ' (taxable: $' + taxableAmt.toFixed(2) + ')')
console.log('tax: $' + (taxableAmt * TAX).toFixed(2) + ' (' + (TAX * 100) + '%)')
console.log('total: $' + total.toFixed(2))