submitStrategy.js 11.4 KB
import {
  checkDailyReport,
  checkStudyTask,
  checkOrderLockGate
} from '~/store/ModalToQueueControl'
import { buildAdditionRecordLockBypassContext } from '~/utils/abnormalFlowLock.helpers.js'
import api from '../../api'
import { prepareSubmitPayload } from './services/submitPayload.helpers.js'
import {
  isBoutiqueErrorOrderBalanced,
  isBoutiqueTotalAtLeastOneCent
} from './services/goodsPriceEdit.helpers.js'
import {
  buildSubmitUiResult,
  resolveBoutiqueSubmitAction,
  runValidationPipeline,
  runWithSubmitLock,
  submitBoutiqueOrder
} from './services/submitWorkflow.js'

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

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

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

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

// 1. 异步前置校验 (日报、学习任务、配置)
function AsyncPreCheckStrategy(page, context) {
  this.page = page
  this.context = context
}
AsyncPreCheckStrategy.prototype.validate = async function () {
  // 校验是否填写昨日日报
  let staffCheck = await checkDailyReport()
  if (staffCheck) return ValidationResult.failure(null) // checkDailyReport 自带提示或跳转

  // 校验学习中心开单限制
  let staffStudyTask = await checkStudyTask()
  if (staffStudyTask) return ValidationResult.failure(null)
  let lockCheck = await checkOrderLockGate(
    buildAdditionRecordLockBypassContext(this.page.data)
  )
  if (lockCheck) return ValidationResult.failure(null)
  // 判断手机号是否用配置的默认值
  this.page.checkPhoneUseConfig()

  return ValidationResult.success()
}

// 2. 状态与权限校验
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()
}

// 3. 必填项校验
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

  const result = this.page.checkRequired(save, orderObj)
  if (!result.ok) {
    return new ValidationResult(
      false,
      result.message,
      result.errorKey,
      result.presentation
    )
  }
  return ValidationResult.success()
}

// 4. 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()
}

// 5. 商品校验
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
  // 调用页面的 checkGoods 方法
  let goodsKey = this.page.checkGoods(save, goodsList, orderObj)

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

// 6. 错单金额校验
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 balance = isBoutiqueErrorOrderBalanced({
      originalPrice: orderObj.finalPrice,
      associatedFeeCents: totalFee,
      currentTotal: total
    })
    if (!balance.ok) {
      return ValidationResult.failure('订单金额格式不正确')
    }
    if (!balance.value) {
      return ValidationResult.failure(
        '原错误订单总价+关联交易流水必须等于商品总价'
      )
    }
  }
  return ValidationResult.success()
}

// 7. 总价校验
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 = isBoutiqueTotalAtLeastOneCent(data.total)
  if (!total.ok) {
    return ValidationResult.failure('订单金额格式不正确')
  }
  if (!total.value) {
    return ValidationResult.failure('订单总价不能小于0.01元')
  }
  return ValidationResult.success()
}

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

/**
 * 从页面事件进入精品提交,并在校验、组装、请求和异常提示期间持有提交锁。
 * @param {WechatMiniprogram.BaseEvent} event
 * @returns {Promise<{status:string,value?:*}>}
 */
SubmitContext.prototype.execute = async function (event) {
  const dataset = event.currentTarget.dataset
  const save = dataset.save
  const context = { save: save }

  return runWithSubmitLock(
    {
      isLocked: () => Boolean(this.page.data.submitStatus),
      setLocked: locked => this.page.setData({ submitStatus: locked })
    },
    async () => {
      try {
        return await this.executeUnlocked(context)
      } catch (error) {
        console.warn('精品开单提交失败', error)
        wx.showModal({
          title: '温馨提示',
          content: error?.message || '提交失败,请稍后重试',
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#347BFF'
        })
      } finally {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      }
    }
  )
}

/**
 * 执行锁内的精品校验、payload 构建与提交。
 * @param {{save:boolean}} context
 * @returns {Promise<*>}
 */
SubmitContext.prototype.executeUnlocked = async function (context) {
  const save = context.save

  // 1. 构建校验链
  const strategies = [
    new AsyncPreCheckStrategy(this.page, context),
    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. 执行校验
  const validation = await runValidationPipeline(strategies)
  if (!validation.ok) {
    if (validation.message) {
      if (validation.presentation === 'toast') {
        this.page.showToast(validation.message)
      } else {
        wx.showModal({
          title: '温馨提示',
          content: validation.message,
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#347BFF'
        })
      }
    }
    if (validation.errorKey) {
      this.page.handleRequiredError(validation.errorKey)
    }
    return
  }

  // 3. 准备并提交
  await this.finishSubmit(save)
}

/**
 * 构建提交参数并二次核对业务模式与 API 选择,防止重构后静默串接口。
 * @param {boolean} save 是否建档
 * @returns {Promise<void>}
 */
SubmitContext.prototype.finishSubmit = async function (save) {
  const preparedData = this.prepareSubmitData(save)
  const submitObj = preparedData.submitObj
  const action = resolveBoutiqueSubmitAction({
    save,
    isErrorOrder: this.page.data.isErrorOrder,
    isAlreadyExistOrder: this.page.data.isAlreadyExistOrder,
    orderCreateType: this.page.data.orderCreateType,
    selectPayType: submitObj.selectPayType
  })
  if (action.method !== preparedData.apiName) {
    throw new Error('精品提交接口选择不一致')
  }
  await this.doSubmit(submitObj, action)
}

/**
 * 从页面订单态生成精品 API payload,保留原契约字段和值。
 * @param {boolean} save 是否建档
 * @returns {{submitObj:object,apiName:string}}
 */
SubmitContext.prototype.prepareSubmitData = function (save) {
  const data = this.page.data
  return prepareSubmitPayload(data.orderObj, {
    save,
    isErrorOrder: data.isErrorOrder,
    orderCreateType: data.orderCreateType,
    scene: data.scene,
    merchantBrands: data.customerDailyFieldMerchantBrands
  })
}

/**
 * 执行已选定的精品 API,并只在页面层处理提示、刷新和语义路由。
 * @param {object} submitObj API payload
 * @param {{method:string,mode:string}} action 提交动作
 * @returns {Promise<void>}
 */
SubmitContext.prototype.doSubmit = async function (submitObj, action) {
  const page = this.page
  const outcome = await submitBoutiqueOrder(
    { method: action.method, payload: submitObj },
    api
  )
  const res = outcome.response
  const uiResult = buildSubmitUiResult({
    mode: action.mode,
    response: res,
    pageContext: page.data
  })

  if (outcome.status === 'success') {
    wx.disableAlertBeforeUnload && wx.disableAlertBeforeUnload() // 关闭页面返回询问对话框

    if (action.mode === 'prerecorded') {
      wx.showModal({
        title: '温馨提示',
        content: '保存成功',
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#347BFF',
        success: function (_res_) {
          if (_res_.confirm) {
            // 预录建档跳转到预约列表
            wx.$util.refreshPageData()
            wx.$router.go(uiResult.navigation.alias)
            wx.$util.pointRecord(30)
          }
        }
      })
    } else {
      // 状态更新需刷新工单列表和预约管理列表
      wx.$util.refreshPageData()
      wx.$router.redirectTo(
        uiResult.navigation.alias,
        uiResult.navigation.params
      )
    }
  } else {
    wx.showModal({
      title: '温馨提示',
      content: uiResult.message,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#347BFF'
    })
  }
}

export { SubmitContext }