submitStrategy.js 10.7 KB
import api from '../../api'
import NP from 'number-precision'
import { buildSubmitGoodsSnapshot } from './services/submitGoodsSnapshot'
import { prepareSubmitPayload } from './services/submitPayload.helpers.js'
import { buildMinPriceApprovalList } from './services/minPriceApproval.js'
import { shouldUseMinPriceApprovalFlow } from './services/orderMerchantConfig.js'
import { applyLowPriceDefaultScene } from './services/lowPriceOrderContext.helpers.js'

// ----------------------------------------------------------------------
// 辅助构造函数:校验结果
// ----------------------------------------------------------------------
function ValidationResult(isValid, message, errorKey) {
  this.isValid = isValid
  this.message = message || null
  this.errorKey = errorKey || null
}

ValidationResult.success = function () {
  return new ValidationResult(true)
}

ValidationResult.failure = function (message) {
  return new ValidationResult(false, message)
}

ValidationResult.errorKey = function (key) {
  return new ValidationResult(false, null, key)
}

// ----------------------------------------------------------------------
// 策略基类 (模拟)
// ----------------------------------------------------------------------
// 实际上不需要复杂的继承结构,只需确保每个策略对象都有 validate 方法即可。
// 这里使用工厂函数模式来创建策略对象。

// 1. 状态与权限校验
function StatePermissionStrategy(page, context) {
  this.page = page
  this.context = context
}
StatePermissionStrategy.prototype.validate = async function () {
  const save = this.context.save
  const data = this.page.data
  const isErrorOrder = data.isErrorOrder
  const isAlreadyExistOrder = data.isAlreadyExistOrder
  const orderCreateType = data.orderCreateType

  // 如果是错单补录 禁用掉保存功能 或待跟进订单/预约订单 或补录工单 禁用建档
  if (
    (isErrorOrder && save) ||
    (isAlreadyExistOrder && save) ||
    (orderCreateType == 'additionRecordOrder' && save)
  ) {
    return ValidationResult.failure(null)
  }
  return ValidationResult.success()
}

// 2. 必填项校验
function RequiredFieldStrategy(page, context) {
  this.page = page
  this.context = context
}
RequiredFieldStrategy.prototype.validate = async function () {
  const save = this.context.save
  const orderObj = this.page.data.orderObj

  // 调用页面的 checkRequired 方法
  let key = this.page.checkRequired(save, orderObj)
  if (key) {
    return ValidationResult.errorKey(key)
  }
  return ValidationResult.success()
}

// 3. VIN码校验
function VinValidationStrategy(page, context) {
  this.page = page
  this.context = context
}
VinValidationStrategy.prototype.validate = async function () {
  const data = this.page.data
  const orderObj = data.orderObj
  const vinValid = data.vinValid
  const carVin = orderObj.customer.standNo

  if (carVin) {
    if (carVin.length !== 17) {
      return ValidationResult.failure(
        '请输入 17 位有效字符(支持大写 A-H/J-N/P-Z、0-9)'
      )
    }
    if (!vinValid) {
      return ValidationResult.failure('车架号校验不匹配,请核对后重新输入')
    }
  }
  return ValidationResult.success()
}

// 4. 商品校验
function GoodsValidationStrategy(page, context) {
  this.page = page
  this.context = context
}
GoodsValidationStrategy.prototype.validate = async function () {
  const save = this.context.save
  const data = this.page.data
  const goodsList = data.goodsList
  const orderObj = data.orderObj
  let subOrderList = []
  let priceDisabled = true

  // 调用页面的 checkGoods 方法
  let goodsKey = this.page.checkGoods(
    save,
    subOrderList,
    priceDisabled,
    goodsList,
    orderObj
  )

  if (goodsKey) {
    return ValidationResult.failure(goodsKey)
  }
  return ValidationResult.success()
}

// 5. 错单金额校验
function ErrorOrderPriceStrategy(page, context) {
  this.page = page
  this.context = context
}
ErrorOrderPriceStrategy.prototype.validate = async function () {
  const data = this.page.data
  const isErrorOrder = data.isErrorOrder
  const totalFee = data.totalFee
  const total = data.total
  const orderObj = data.orderObj

  if (isErrorOrder) {
    const originalPrice = Number(orderObj.finalPrice || 0)
    const associatedPrice = NP.divide(Number(totalFee || 0), 100)
    const currentTotal = Number(total || 0)

    console.log('Validation:', {
      originalPrice: originalPrice,
      associatedPrice: associatedPrice,
      currentTotal: currentTotal
    })

    if (NP.minus(NP.plus(originalPrice, associatedPrice), currentTotal) !== 0) {
      return ValidationResult.failure(
        '原错误订单总价+关联交易流水必须等于商品总价'
      )
    }
  }
  return ValidationResult.success()
}

// 6. 总价校验
function TotalPriceStrategy(page, context) {
  this.page = page
  this.context = context
}
TotalPriceStrategy.prototype.validate = async function () {
  const save = this.context.save
  const data = this.page.data
  const orderObj = data.orderObj

  // 建档或战败单不校验
  if (save || orderObj.selectPayType == 0) {
    return ValidationResult.success()
  }

  const total = Number(data.total || 0)
  if (total < 0.01) {
    return ValidationResult.failure('订单总价不能小于0.01元')
  }
  return ValidationResult.success()
}

// ----------------------------------------------------------------------
// 提交上下文 (Main Entry)
// ----------------------------------------------------------------------
function SubmitContext(page) {
  this.page = page
}

SubmitContext.prototype.isLowPriceOrder = function () {
  if (typeof this.page.isLowPriceOrder === 'function') {
    return this.page.isLowPriceOrder()
  }
  return Number(this.page.data.orderObj?.lowPriceFlag) === 1
}

SubmitContext.prototype.ensureLowPriceOrderScene = function () {
  if (!this.isLowPriceOrder()) return

  const orderObj = applyLowPriceDefaultScene({
    ...(this.page.data.orderObj || {}),
    lowPriceFlag: 1
  })
  this.page.setData({ orderObj })
}

SubmitContext.prototype.execute = async function (event) {
  const dataset = event.currentTarget.dataset
  const save = dataset.save
  const context = { save }

  // 低价单页面的订单对象可能被路由/档案回显整对象替换;校验前恢复页面固定标识,
  // 并仅在场景不完整时补默认值,完整的真实场景保持不变。
  this.ensureLowPriceOrderScene()

  // 手机号默认值属于页面配置,保留在订单数据校验之前处理。
  this.page.checkPhoneUseConfig()

  // 1. 构建校验链
  const strategies = [
    new StatePermissionStrategy(this.page, context),
    new GoodsValidationStrategy(this.page, context),
    new RequiredFieldStrategy(this.page, context),
    new VinValidationStrategy(this.page, context),
    new ErrorOrderPriceStrategy(this.page, context),
    new TotalPriceStrategy(this.page, context)
  ]

  // 2. 执行校验
  for (let i = 0; i < strategies.length; i++) {
    const strategy = strategies[i]
    const result = await strategy.validate()
    if (!result.isValid) {
      if (result.message) {
        wx.showModal({
          title: '温馨提示',
          content: result.message,
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#347BFF'
        })
      }
      if (result.errorKey) {
        this.page.handleRequiredError(result.errorKey)
      }
      return
    }
  }

  // 3. 准备并提交(含低于最低价审批弹层)
  await this.finishSubmit(save)
}

/**
 * 审批弹层确认后跳过二次弹层直接提交
 * @param {{ save?: boolean }} options
 */
SubmitContext.prototype.executeAfterApproval = async function (options = {}) {
  // 审批弹层期间页面状态仍可能变化,真正发请求前再次保证低价单场景完整。
  this.ensureLowPriceOrderScene()
  await this.finishSubmit(options.save, true)
}

/**
 * @param {boolean} save 是否建档
 * @param {boolean} [skipApprovalSheet] 已在审批弹层确认
 */
SubmitContext.prototype.finishSubmit = async function (
  save,
  skipApprovalSheet
) {
  const approvalItems = buildMinPriceApprovalList(this.page.data.goodsList)
  console.log(
    '[createOrder submit goods]',
    buildSubmitGoodsSnapshot(this.page.data, { approvalItems })
  )

  if (
    !save &&
    !skipApprovalSheet &&
    shouldUseMinPriceApprovalFlow(this.page.data.orderObj?.lowPriceFlag) &&
    approvalItems.length
  ) {
    this.page.openMinPriceApprovalSheet(approvalItems, save)
    return
  }

  const preparedData = this.prepareSubmitData(save)
  const submitObj = preparedData.submitObj
  const apiName = preparedData.apiName
  await this.doSubmit(submitObj, apiName, save)
}

SubmitContext.prototype.prepareSubmitData = function (save) {
  const data = this.page.data
  return prepareSubmitPayload(data.orderObj, {
    save,
    isErrorOrder: data.isErrorOrder,
    orderCreateType: data.orderCreateType,
    scene: data.scene
  })
}

SubmitContext.prototype.doSubmit = async function (submitObj, apiName, save) {
  const page = this.page
  const data = page.data
  const submitStatus = data.submitStatus
  const isErrorOrder = data.isErrorOrder

  // 防止重复提交
  if (submitStatus) return

  page.setData({
    submitStatus: true
  })
  // console.log(submitObj, 'submitObj');
  // return;
  try {
    const res = await api[apiName](submitObj)
    let code = res.code
    let resData = res.data
    let message = res.message

    if (code == 0) {
      wx.disableAlertBeforeUnload && wx.disableAlertBeforeUnload() //关闭小程序页面返回询问对话框

      if (save) {
        wx.showModal({
          title: '温馨提示',
          content: '保存成功',
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#347BFF',
          success: function (_res_) {
            if (_res_.confirm) {
              if (apiName == 'createPrerecordedOrder') {
                // 预录建档跳转到预约列表
                wx.$util.refreshPageData()
                wx.$router.go('/tabWorkOrder/pages/index/index')
                wx.$util.pointRecord(30)
              } else {
                wx.$router.back(function (p) {
                  p.search && p.search()
                })
              }
            }
          }
        })
      } else {
        // 状态更新 需刷新工单列表和预约管理列表
        wx.$util.refreshPageData()
        if (isErrorOrder) resData.isErrorOrder = true
        wx.$router.redirectTo('confirmOrder', resData)
      }
    } else {
      wx.showModal({
        title: '温馨提示',
        content: message,
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#347BFF'
      })
    }
  } finally {
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    page.setData({
      submitStatus: false
    })
  }
}

export { SubmitContext }