financialCalculationDialog.vue 18.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 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
<!-- 分账测试(3 步向导) -->
<template>
  <d2-dialog
    title="分账测试"
    :is-visible="verificationCodeVisible"
    class="verificationCode division-test-dialog"
    width="960px"
    :is-show-footer="false"
    no-cancel
    @closeDialog="handleClose"
  >
    <div class="division-test">
      <p class="edit-sub-title channel-subtitle">
        测试渠道:{{ testObj.paymentChannelName }}
      </p>

      <DivisionTestStepper
        :max-reached-step="maxReachedStep"
        :view-step="viewStep"
        :step-completed-flags="stepCompletedFlags"
        @step-click="onStepClick"
      />

      <div class="step-content">
        <DivisionTestStep1Pay
          v-show="viewStep === 1"
          :step1-paid="step1ShowOrderLinked"
          :order-code="testOrderCode"
          :qr-code-u-r-l="qrCodeURL"
          :pay-amount="payAmount"
          :read-only="isStepReadOnly(1)"
          @retest="handleRetest"
        />
        <DivisionTestStep2Allocate
          v-show="viewStep === 2"
          :merchants="step2Merchants"
        />
        <DivisionTestStep3Verify
          v-show="viewStep === 3"
          ref="step3"
          :merchants="step3Merchants"
          :read-only="isStepReadOnly(3)"
        />
      </div>
    </div>

    <template #btn-start>
      <el-button @click="handleClose">关闭</el-button>
    </template>
    <template #btn-end>
      <el-button
        v-if="viewStep < 3"
        type="primary"
        :disabled="nextButtonDisabled"
        :loading="actionLoading"
        @click="handleNext"
      >
        下一步
      </el-button>
      <el-button
        v-else
        type="primary"
        :loading="actionLoading"
        :disabled="isStepReadOnly(3)"
        @click="handleCompleteTest"
      >
        完成测试
      </el-button>
    </template>
  </d2-dialog>
</template>

<script>
import { createWeappQrcode } from '@api/serviceManage'
import {
  getWsUrlApi,
  divisionRuleTestGet,
  divisionRuleTestMoneyValid,
  divisionRuleTestRetest,
  divisionRuleTestUpdateMainProgress
} from '@api/merchant'
import { resolveBaseSceneCodeFromRouter } from '@/common/sceneBaseSceneCode'
import {
  mapSubProgressToUi,
  buildStepCompletedFlags,
  resolveInitialWizardSteps,
  canNavigateToStep,
  isStepReadOnly as checkStepReadOnly,
  isDivisionTestPassed,
  shouldShowStep1OrderLinked,
  shouldSyncWizardStepsFromProgress,
  DIVISION_TEST_SUB_PROGRESS_IN_PROGRESS
} from '../utils/divisionTestStepProgress'
import {
  buildStep2DisplayMerchants,
  buildStep3VerifyMerchants
} from '../utils/buildStep2DisplayMerchants'
import {
  buildStep3SubmitMerchants,
  isStep3AmountTotalConsistent
} from '../utils/validateStep3Amounts'
import {
  buildDivisionRuleTestParams,
  buildDivisionRuleTestRetestParams,
  buildDivisionRuleTestMoneyValidParams,
  buildDivisionRuleTestUpdateMainProgressParams
} from '../utils/buildDivisionRuleTestParams'
import {
  resolveDivisionTestOrderCode,
  resolveDivisionTestOutTradeNo,
  resolveDivisionTestSubProgress,
  resolveDivisionTestProgress,
  resolveDivisionTestMerchantDivisions,
  normalizeDivisionTestPayload
} from '../utils/resolveDivisionTestOrderCode'
import { buildWebSocketUrl } from '../utils/buildWebSocketUrl'
import DivisionTestStepper from './divisionTestDialog/DivisionTestStepper.vue'
import DivisionTestStep1Pay from './divisionTestDialog/DivisionTestStep1Pay.vue'
import DivisionTestStep2Allocate from './divisionTestDialog/DivisionTestStep2Allocate.vue'
import DivisionTestStep3Verify from './divisionTestDialog/DivisionTestStep3Verify.vue'

export default {
  name: 'FinancialCalculationDialog',
  components: {
    DivisionTestStepper,
    DivisionTestStep1Pay,
    DivisionTestStep2Allocate,
    DivisionTestStep3Verify
  },
  inject: {
    financialRulesEnv: { default: () => ({}) }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    financialCalculationObj: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      testObj: {},
      subProgress: 0,
      viewStep: 1,
      maxReachedStep: 1,
      uiState: {
        step1Paid: false
      },
      qrCodeURL: '',
      wsUrl: '',
      socket: null,
      actionLoading: false,
      step2Merchants: [],
      step3Merchants: [],
      step2AllocationCache: {},
      lastSyncedProgress: null
    }
  },
  computed: {
    verificationCodeVisible: {
      get() {
        return this.visible
      },
      set() {
        this.$emit('update:visible', false)
      }
    },
    payAmount() {
      return this.testObj.testGoodsPrice || 3.5
    },
    nextButtonDisabled() {
      if (this.viewStep === 1) return !this.step1ShowOrderLinked
      return false
    },
    testOrderCode() {
      return resolveDivisionTestOrderCode(this.testObj)
    },
    testOutTradeNo() {
      return resolveDivisionTestOutTradeNo(this.testObj)
    },
    step1ShowOrderLinked() {
      return shouldShowStep1OrderLinked({
        step1Paid: this.uiState.step1Paid,
        subProgress: this.subProgress,
        outTradeNo: this.testOutTradeNo,
        maxReachedStep: this.maxReachedStep,
        viewStep: this.viewStep
      })
    },
    stepCompletedFlags() {
      return buildStepCompletedFlags(
        this.uiState.step1Paid,
        this.maxReachedStep,
        Number(this.subProgress) === 31
      )
    },
    navigationState() {
      return {
        maxReachedStep: this.maxReachedStep,
        step1Paid: this.uiState.step1Paid
      }
    },
    /** 与父页财务详情一致,唯一来源(financialRulesEnv) */
    divisionRuleId() {
      return this.financialRulesEnv.divisionRuleId
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.bootstrapFromProps()
        if (!this.step1ShowOrderLinked && this.testOrderCode) {
          this.initQrCode()
        }
        this.refreshTestData()
        this.getWsUrl()
      } else {
        this.teardownWs()
        this.lastSyncedProgress = null
      }
    },
    financialCalculationObj: {
      deep: true,
      handler() {
        if (!this.visible) return
        this.testObj = this.normalizeTestObjPayload(this.financialCalculationObj)
        this.applySubProgress(this.testObj.subProgress, this.testObj)
        this.syncViewStepFromServerProgress()
      }
    }
  },
  mounted() {
    if (this.visible) {
      this.bootstrapFromProps()
      this.refreshTestData()
      this.getWsUrl()
    }
  },
  beforeDestroy() {
    this.teardownWs()
  },
  methods: {
    normalizeTestObjPayload(payload = {}) {
      const id = this.divisionRuleId
      const merged = id != null && id !== ''
        ? { ...payload, divisionRuleId: id }
        : payload
      return normalizeDivisionTestPayload(merged)
    },
    setViewStep(step) {
      const target = Number(step)
      if (target < 1 || target > 3) return
      this.viewStep = target
      this.syncUpdateMainProgress(target)
    },
    syncUpdateMainProgress(progress) {
      if (!this.visible) return
      const p = Number(progress)
      if (p < 1 || p > 3) return
      if (this.lastSyncedProgress === p) return

      const paymentChannelId = this.testObj.paymentChannelId
      const params = buildDivisionRuleTestUpdateMainProgressParams({
        divisionRuleId: this.divisionRuleId,
        paymentChannelId,
        progress: p
      })
      if (
        params.divisionRuleId == null
        || params.divisionRuleId === ''
        || params.paymentChannelId == null
        || params.paymentChannelId === ''
        || params.progress == null
      ) {
        return
      }

      divisionRuleTestUpdateMainProgress(params)
        .then(() => {
          this.lastSyncedProgress = p
        })
        .catch((err) => {
          console.error('[FinancialCalculationDialog] updateMainProgress', err)
        })
    },
    resetWizardNavigation(subProgress) {
      const sp = subProgress != null && subProgress !== ''
        ? Number(subProgress) || 0
        : Number(this.subProgress) || 0
      const progress = resolveDivisionTestProgress(this.testObj, this.testObj.progress)
      const { viewStep, maxReachedStep } = resolveInitialWizardSteps(sp, progress)
      this.maxReachedStep = maxReachedStep
      this.setViewStep(viewStep)
    },
    bootstrapFromProps() {
      this.testObj = this.normalizeTestObjPayload(this.financialCalculationObj)
      const sp = resolveDivisionTestSubProgress(this.testObj, this.testObj.subProgress)
      this.resetWizardNavigation(sp)
      this.applySubProgress(sp, this.testObj)
    },
    syncViewStepFromServerProgress() {
      if (!shouldSyncWizardStepsFromProgress(this.subProgress)) return
      const progress = resolveDivisionTestProgress(this.testObj, this.testObj.progress)
      const { viewStep, maxReachedStep } = resolveInitialWizardSteps(this.subProgress, progress)
      this.maxReachedStep = maxReachedStep
      this.setViewStep(viewStep)
    },
    applySubProgress(subProgress, payload = this.testObj) {
      const prevPaid = this.uiState.step1Paid
      this.subProgress = resolveDivisionTestSubProgress(payload, subProgress)
      const ui = mapSubProgressToUi(this.subProgress, {
        orderPaid: payload.orderPaid,
        payStatus: payload.payStatus,
        paymentSuccess: payload.paymentSuccess,
        outTradeNo: resolveDivisionTestOutTradeNo(payload)
      })
      let step1Paid = ui.step1Paid
      if (prevPaid && resolveDivisionTestOrderCode(payload) && !step1Paid) {
        step1Paid = true
      }
      this.uiState = { step1Paid }
      this.rebuildMerchantLists()
    },
    rebuildMerchantLists() {
      const list = resolveDivisionTestMerchantDivisions(this.testObj)
      this.step2Merchants = buildStep2DisplayMerchants(list, {
        cachedAllocations: this.step2AllocationCache
      })
      this.step2Merchants.forEach((m) => {
        const key = String(m.merchantId ?? m.merchantName ?? '')
        if (!m.testCompleted && m.displayDivisionMoney != null && m.displayDivisionMoney !== '') {
          this.$set(this.step2AllocationCache, key, m.displayDivisionMoney)
        }
      })
      this.step3Merchants = buildStep3VerifyMerchants(list)
    },
    buildBaseParams() {
      const routerInfo = this.financialRulesEnv.routerInfo || {}
      const { merchantId, scene: sceneType } = routerInfo
      const baseSceneCode = resolveBaseSceneCodeFromRouter(routerInfo)
      return buildDivisionRuleTestParams({
        merchantId,
        sceneType,
        paymentChannelId: this.testObj.paymentChannelId,
        divisionRuleId: this.divisionRuleId,
        baseSceneCode
      })
    },
    buildRetestParams() {
      return buildDivisionRuleTestRetestParams({
        divisionRuleId: this.divisionRuleId,
        paymentChannelId: this.testObj.paymentChannelId
      })
    },
    refreshTestData() {
      const params = this.buildBaseParams()
      if (
        !params.merchantId
        || params.paymentChannelId == null
        || params.divisionRuleId == null
        || params.divisionRuleId === ''
      ) {
        return Promise.resolve()
      }
      return divisionRuleTestGet(params).then((result) => {
        if (!result) return
        this.testObj = this.normalizeTestObjPayload({ ...this.testObj, ...result })
        this.applySubProgress(result.subProgress, this.testObj)
        this.syncViewStepFromServerProgress()
        if (!this.step1ShowOrderLinked && this.testOrderCode) {
          this.initQrCode()
        }
        if (isDivisionTestPassed(result.subProgress)) {
          this.handleClose()
          this.$emit('checkSuccess')
        }
      }).catch((err) => {
        console.error('[FinancialCalculationDialog] refreshTestData', err)
      })
    },
    initQrCode() {
      const orderCode = this.testOrderCode
      if (!orderCode) return
      const oParams = {
        channelType: 1,
        appId: this.testObj.payPlatform === 'allinpay'
          ? 'wx3d2ee7f8bda398cc'
          : 'wx06d1198e751435d1',
        qrcodeType: 'QR_WXA_UNLIMIT',
        path: 'packagesPayment/pages/payment/index',
        scene: `orderCode=${orderCode}&workWxSessionId=11`
      }
      createWeappQrcode(oParams).then((res) => {
        this.qrCodeURL = res
      })
    },
    getWsUrl() {
      if (this.socket) return
      getWsUrlApi({}).then((res) => {
        this.wsUrl = res
        this.initWs()
      })
    },
    initWs() {
      if (!this.wsUrl || this.socket) return
      const url = buildWebSocketUrl(this.wsUrl)
      if (!url) return
      try {
        this.socket = new WebSocket(url)
        this.socket.onmessage = this.getMessage
      } catch (err) {
        console.error('[FinancialCalculationDialog] initWs', err)
      }
    },
    teardownWs() {
      if (this.socket) {
        try {
          this.socket.close()
        } catch (e) { /* ignore */ }
        this.socket = null
      }
    },
    getMessage(msg) {
      let data
      try {
        data = JSON.parse(msg.data)
      } catch (e) {
        return
      }
      if (
        data.type === 'TEST_PAY_SUCCESS'
        && data.content === this.testOrderCode
      ) {
        this.uiState.step1Paid = true
        this.refreshTestData()
      }
    },
    isStepReadOnly(step) {
      return checkStepReadOnly(step, this.navigationState)
    },
    onStepClick(stepNum) {
      const target = Number(stepNum)
      if (!canNavigateToStep(target, this.navigationState)) {
        if (target > this.maxReachedStep && !this.uiState.step1Paid) {
          this.$message.warning('请先完成扫码支付')
        }
        return
      }
      this.setViewStep(target)
    },
    handleClose() {
      this.verificationCodeVisible = false
    },
    handleRetest() {
      const params = this.buildRetestParams()
      if (!params.divisionRuleId || params.paymentChannelId == null) {
        this.$message.warning('缺少分账规则或渠道信息,无法重新测试')
        return
      }
      this.actionLoading = true
      divisionRuleTestRetest(params)
        .then((result) => {
          if (result) {
            this.testObj = this.normalizeTestObjPayload({ ...this.testObj, ...result })
          }
          this.step2AllocationCache = {}
          this.uiState.step1Paid = false
          this.subProgress = 34
          this.resetWizardNavigation(34)
          this.qrCodeURL = ''
          this.applySubProgress(34, this.testObj)
          this.initQrCode()
        })
        .catch((err) => {
          const msg = err?.message || err?.msg || ''
          if (msg.includes('404') || msg.includes('method')) {
            this.mockRetestLocal()
          } else {
            console.error('[FinancialCalculationDialog] retest', err)
            this.$message.error(msg || '重新测试失败')
          }
        })
        .finally(() => {
          this.actionLoading = false
        })
    },
    mockRetestLocal() {
      this.step2AllocationCache = {}
      this.uiState.step1Paid = false
      this.subProgress = 34
      this.resetWizardNavigation(34)
      const mockCode = this.testOrderCode || `TEST${Date.now()}`
      this.testObj = this.normalizeTestObjPayload({
        ...this.testObj,
        orderCode: mockCode,
        divisionRuleTestItem: {
          ...(this.testObj.divisionRuleTestItem || {}),
          orderCode: mockCode
        }
      })
      this.qrCodeURL = ''
      this.initQrCode()
      this.rebuildMerchantLists(this.testObj.testMerchantDivisions)
    },
    handleNext() {
      if (this.viewStep === 1) {
        if (!this.step1ShowOrderLinked) {
          this.$message.warning('请先完成扫码支付')
          return
        }
        this.maxReachedStep = Math.max(this.maxReachedStep, 2)
        this.setViewStep(2)
        return
      }
      if (this.viewStep === 2) {
        this.maxReachedStep = 3
        this.setViewStep(3)
      }
    },
    async handleCompleteTest() {
      if (this.isStepReadOnly(3)) return
      const step3 = this.$refs.step3
      if (!step3) return
      const valid = await step3.validate()
      if (!valid) return

      const rawList = resolveDivisionTestMerchantDivisions(this.testObj)
      const formMerchants = step3.getSubmitMerchants()
      if (!isStep3AmountTotalConsistent(formMerchants, rawList)) {
        this.$message.warning('金额不一致,请确认后重新操作')
        return
      }
      const testMerchantDivisions = buildStep3SubmitMerchants(rawList, formMerchants)
      const params = buildDivisionRuleTestMoneyValidParams({
        testObj: this.testObj,
        testMerchantDivisions,
        divisionRuleId: this.divisionRuleId
      })
      if (params.divisionRuleId == null || params.divisionRuleId === '') {
        this.$message.warning('缺少分账规则 ID,请刷新后重试')
        return
      }
      if (params.paymentChannelId == null || params.paymentChannelId === '') {
        this.$message.warning('缺少支付渠道,请刷新后重试')
        return
      }

      this.actionLoading = true
      divisionRuleTestMoneyValid(params)
        .then((result) => {
          const sp = result?.subProgress ?? result
          this.subProgress = sp
          if (!DIVISION_TEST_SUB_PROGRESS_IN_PROGRESS.includes(Number(sp))) {
            this.$notify.success({
              title: '提示',
              message: '测试通过'
            })
            this.handleClose()
            this.$emit('checkSuccess')
          } else {
            this.testObj = this.normalizeTestObjPayload({ ...this.testObj, ...result })
            this.applySubProgress(sp, this.testObj)
            this.syncViewStepFromServerProgress()
          }
        })
        .catch((err) => {
          console.error('[FinancialCalculationDialog] completeTest', err)
        })
        .finally(() => {
          this.actionLoading = false
        })
    }
  }
}
</script>

<style lang="scss">
.division-test-dialog {
  .division-test {
    .channel-subtitle {
      font-size: 14px;
      color: #666;
      margin: 0 0 20px;
    }

    .step-content {
      min-height: 300px;
    }
  }
}
</style>