orderApprovalFormat.js 2.57 KB
const orderFieldMaps = {
  djOrderType: {
    '': '订单类型',
    1: '正常订单',
    2: '打折策略',
    3: '买赠策略',
    4: '冲量活动',
    5: '组合付款',
    6: '内部结算'
  },
  lowPriceFlag: {
    1: '低价订单'
  }
}

function getFormattedFieldValue(value, format) {
  const fieldMap = orderFieldMaps[format]
  if (!fieldMap || value === undefined || value === null) return '-'
  return Object.prototype.hasOwnProperty.call(fieldMap, value) ? fieldMap[value] : '-'
}

const orderMoneyFields = [
  'finalPrice',
  'singleProductFinalPrice',
  'singleProductSalesPrice',
  'totalPrice',
  'upgradePrice'
]

function toMoneyCents(value) {
  if (value === null || value === undefined || value === '') return null
  const amount = Number(value)
  if (!Number.isFinite(amount)) return null
  const correction = amount < 0 ? -Number.EPSILON : Number.EPSILON
  return Math.round((amount + correction) * 100)
}

function normalizeMoney(value) {
  const cents = toMoneyCents(value)
  return cents === null ? value : cents / 100
}

function normalizeGoodsLine(line = {}) {
  return orderMoneyFields.reduce(
    (result, field) => {
      if (Object.prototype.hasOwnProperty.call(result, field)) {
        result[field] = normalizeMoney(result[field])
      }
      return result
    },
    { ...line }
  )
}

function sumFinalPrices(goodsList = []) {
  const totalCents = goodsList.reduce((total, goods) => {
    if (Number(goods.discountType) === 4) return total
    const cents = toMoneyCents(goods.finalPrice)
    return cents === null ? total : total + cents
  }, 0)
  return totalCents / 100
}

/**
 * 统一审批详情普通商品、套餐子商品和套餐汇总的金额精度。
 * 套餐总额直接累加非赠品子项的权威 finalPrice,不通过单价和数量反算。
 * @param {object} orderDTO 订单商品数据
 * @returns {object} 不修改源对象的金额展示数据
 */
function normalizeOrderGoodsPrices(orderDTO = {}) {
  const result = { ...orderDTO }
  if (Array.isArray(result.subOrderList)) {
    result.subOrderList = result.subOrderList.map(normalizeGoodsLine)
  }
  if (Array.isArray(result.packageGoodsList)) {
    result.packageGoodsList = result.packageGoodsList.map(pkg => {
      const packageGoodsOrderList = Array.isArray(pkg.packageGoodsOrderList)
        ? pkg.packageGoodsOrderList.map(normalizeGoodsLine)
        : []
      return {
        ...pkg,
        packageGoodsOrderList,
        packagePrice: sumFinalPrices(packageGoodsOrderList)
      }
    })
  }
  return result
}

module.exports = {
  getFormattedFieldValue,
  normalizeOrderGoodsPrices
}