import _ from 'lodash' export default function calculateBatchItem ( item: IAppBatchItem, order: IAppOrder, ): IAppBatchItem { // 選擇 surcharge // 若 Order 有設定服務費優先使用,否則使用 merchant 的服務費設定 const surchargeModifier = order.deliveryType === 'table' ? order.surcharge : { percent: 0, amount: 0 } // 計算 optionsTotal (sum by options price * quantity) const optionsTotal = _.sumBy(item.options, option => option.price * option.quantity) // 計算基本的價格 不含折扣和服務費 let baseTotal = (item.price - item.discount + optionsTotal) // 整理 modifiers const modifiers = [...item.modifiers] // order.modifiers.forEach(modifier => { // if (!item.excludeOrderDiscount || (modifier.overrideItem ?? false)) { // modifiers.push(modifier) // } // }) if (order.deliveryType === 'table') { if (!item.excludedOrderSurcharge) { modifiers.push(surchargeModifier) } } // 計算 modifiers let totalDiscount = 0 // 統計全部折扣 let totalSurcharge = 0 // 統計全部費用 let total = modifiers.reduce((total, modifier) => { const newTotal = total * (100 + modifier.percent) / 100 + modifier.amount const diffAmount = newTotal - total if (diffAmount < 0) { // 折扣 totalDiscount += Math.abs(diffAmount) } else { // 費用 totalSurcharge += diffAmount } return newTotal }, baseTotal) const setItems = item.setItems.map((setItem) => calculateBatchItem(setItem, order)) const setItemsDiscountTotal = _.sumBy(setItems, 'totalDiscount') const setItemsSurcharge = _.sumBy(setItems, 'surcharge') const setItemsTotal = _.sumBy(setItems, 'total') totalDiscount += setItemsDiscountTotal totalSurcharge += setItemsSurcharge total += setItemsTotal // 計算 quantity const divisor = item.divisor != null && item.divisor !== 0 ? item.divisor : 1 totalDiscount *= item.quantity / divisor totalSurcharge *= item.quantity / divisor total *= item.quantity / divisor baseTotal *= item.quantity / divisor return { ...item, totalDiscount: totalDiscount, // 總折扣 (含 discount 和 modifiers),總共扣多少錢(不含套餐餐點) surcharge: totalSurcharge, // 算完折扣後,再算上 order surcharge 總共要多付多少錢(不含套餐餐點) total: item.cancelled ? 0 : total, // 包含折扣、服務費和套餐中餐點價格的總價 originalTotal: item.cancelled ? 0 : (baseTotal + totalSurcharge), setItems, } }