submitStrategy.js 11.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
import {
  checkDailyReport,
  checkStudyTask,
  checkAbnormalOrder
} from '~/store/ModalToQueueControl'
import api from '../../api'
import NP from 'number-precision'

// ----------------------------------------------------------------------
// 辅助构造函数:校验结果
// ----------------------------------------------------------------------
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 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 abnormalOrderCheck = await checkAbnormalOrder()
  if (abnormalOrderCheck) return false
  // 判断手机号是否用配置的默认值
  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

  // 调用页面的 checkRequired 方法
  let key = this.page.checkRequired(save, orderObj)
  if (key) {
    return ValidationResult.errorKey(key)
  }
  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
  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()
}

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

// 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 = 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.execute = async function (event) {
  const dataset = event.currentTarget.dataset
  const save = dataset.save
  const context = { save: 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. 执行校验
  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. 准备提交数据
  const preparedData = this.prepareSubmitData(save)
  const submitObj = preparedData.submitObj
  const apiName = preparedData.apiName

  // 4. 执行提交
  await this.doSubmit(submitObj, apiName, save)
}

SubmitContext.prototype.prepareSubmitData = function (save) {
  const data = this.page.data
  const orderObj = data.orderObj
  const scene = data.scene
  const isErrorOrder = data.isErrorOrder
  const orderCreateType = data.orderCreateType

  // 深拷贝
  let submitObj = JSON.parse(JSON.stringify(orderObj))

  // 数据清洗逻辑
  if (!scene) {
    if (!submitObj.orderCode) delete submitObj.orderCode
  }

  const propertiesToDelete = [
    'profitAllocatinList',
    'packageGoodsList',
    'expenseCategoryList',
    'merchantDistributionList',
    'baseSceneName',
    'orderTime',
    'createdBy',
    'createdDate',
    'updatedBy',
    'updatedDate'
  ]

  for (let i = 0; i < propertiesToDelete.length; i++) {
    const prop = propertiesToDelete[i]
    if (submitObj.hasOwnProperty(prop)) {
      delete submitObj[prop]
    }
  }

  if (submitObj.customer) {
    const customerPropertiesToDelete = ['buyTime', 'createdDate']
    for (let i = 0; i < customerPropertiesToDelete.length; i++) {
      const prop = customerPropertiesToDelete[i]
      if (submitObj.customer.hasOwnProperty(prop)) {
        delete submitObj.customer[prop]
      }
    }
  }

  // 场景参数:来自“当前选中的场景”存入的 orderObj.sceneType
  if (!submitObj.baseSceneCode) {
    delete submitObj.sceneType
  }

  if (isErrorOrder) submitObj.oldOrderCode = submitObj.associateOrderCode

  if (save) {
    // 建档删除卡券商品支付方式参数
    delete submitObj.subOrderList
    delete submitObj.customerCouponCode
    delete submitObj.selectPayType
  }

  if (submitObj.selectPayType == 0) {
    const deleteArr = ['plateNumber', 'standNo', 'carBrand']
    delete submitObj.remark
    submitObj.customer.experienceFlag = 'Y'
    deleteArr.forEach(function (element) {
      delete submitObj.customer[element]
    })
  }

  // 太阳膜下单入口
  submitObj.filmOrder = 0

  // 确定 API 名称
  let apiName =
    save && !isErrorOrder
      ? 'createPrerecordedOrder'
      : isErrorOrder
        ? 'correctionOrder'
        : 'createWithPay'

  apiName =
    orderCreateType == 'additionRecordOrder' ? 'supplementOrder' : apiName

  return { submitObj: submitObj, apiName: apiName }
}

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('pages.tabDateIndex')
                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 }