simpleQuotationCheckout.workflow.test.mjs 16.1 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
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'

import {
  checkSimpleQuotationDailyReport,
  completeSimpleQuotationContract,
  recordSimpleQuotationOrder,
  submitSimpleQuotationCheckout
} from '../pages/carQuotation/services/simpleQuotationCheckout.workflow.js'

const LIST_NAVIGATION = {
  type: 'reLaunch',
  alias: 'packageEquity.equityPage',
  params: { tabIndex: 1 }
}

/**
 * 用真实 Promise.race 区分正常结束与异步悬挂。
 *
 * @param {Promise<unknown>} promise 被测 workflow Promise
 * @returns {Promise<{state:'resolved'|'rejected'|'timeout',value?:unknown,error?:unknown}>}
 */
function settleWithinDeadline(promise) {
  return Promise.race([
    promise.then(
      value => ({ state: 'resolved', value }),
      error => ({ state: 'rejected', error })
    ),
    new Promise(resolve => {
      setTimeout(() => resolve({ state: 'timeout' }), 80)
    })
  ])
}

function createCheckoutDependencies(overrides = {}) {
  return {
    quotationAdd: async () => ({ code: 0, data: 71 }),
    updateQuotation: async () => ({ code: 0, data: 72 }),
    errorOrderById: async () => ({ code: 0, data: 73 }),
    quotationRecording: async () => ({ code: 0, data: 74 }),
    checkZyPayFlag: async () => ({ code: 0, data: false }),
    checkRecord: async () => ({ code: 0, data: false }),
    quotationUpgrade: async () => ({
      code: 0,
      data: { orderId: 'payment-order-1' }
    }),
    getQuotationInfoById: async () => ({
      code: 0,
      data: {
        id: 74,
        orderId: 'order-74',
        referrer: '销售甲',
        referrerId: 'sales-1'
      }
    }),
    updateCustomerInfo: async () => ({ code: 0, data: true }),
    ...overrides
  }
}

describe('simpleQuotationCheckout.workflow', () => {
  it('IT-EQ-SIMPLE-CHECKOUT-001: maps the daily-report request and previous report date without page effects', async () => {
    let received
    const result = await checkSimpleQuotationDailyReport(
      {
        userInfo: {
          shopMerchantId: 'shop-1',
          merchantId: 'equity-1',
          uuid: 'staff-1'
        },
        now: new Date('2026-09-08T12:00:00+08:00')
      },
      async payload => {
        received = payload
        return { code: 0, data: true }
      }
    )

    assert.deepEqual(received, {
      merchantId: 'shop-1',
      yqMerchantId: 'equity-1',
      staffUuid: 'staff-1',
      sceneType: 0
    })
    assert.deepEqual(result, {
      blocked: true,
      reportDate: '2026-09-07'
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-002: returns a payment-document effect before recording or submitting', async () => {
    const result = await submitSimpleQuotationCheckout(
      {
        action: 'add',
        merchantId: 'merchant-1',
        orderInfo: {
          payType: 2,
          transactionNo: '',
          paymentDocList: []
        }
      },
      createCheckoutDependencies({
        quotationAdd: async () => assert.fail('must not submit')
      })
    )

    assert.deepEqual(result, {
      status: 'need-payment-documents',
      patch: { showPopup: true }
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-003: records an additional order and returns either contract upload or the list', async () => {
    const orderInfo = {
      orderType: 1,
      outTradeNo: 'trade-1',
      vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
    }
    const snapshot = structuredClone(orderInfo)

    const needContract = await recordSimpleQuotationOrder(
      { orderInfo, merchantId: 'merchant-1' },
      createCheckoutDependencies({
        quotationRecording: async payload => {
          assert.deepEqual(payload, { ...snapshot, check: true })
          return { code: 0, data: 74 }
        },
        checkZyPayFlag: async payload => {
          assert.deepEqual(payload, {
            goodsIds: ['goods-1'],
            merchantId: 'merchant-1'
          })
          return { code: 0, data: true }
        }
      })
    )
    assert.deepEqual(needContract, {
      status: 'need-contract',
      supplementaryOrderId: 74,
      patch: { showPopup: false, showZyPopup: true }
    })
    assert.deepEqual(orderInfo, snapshot)

    const noContract = await recordSimpleQuotationOrder(
      {
        orderInfo: { ...orderInfo, orderType: 3 },
        merchantId: 'merchant-1'
      },
      createCheckoutDependencies({
        checkZyPayFlag: async () => assert.fail('gift orders skip contract check')
      })
    )
    assert.deepEqual(noContract, {
      status: 'list',
      supplementaryOrderId: 74,
      patch: { showPopup: false },
      navigation: LIST_NAVIGATION
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-004: selects add, update and correction APIs and returns the list for direct-payment outcomes', async () => {
    for (const fixture of [
      { action: 'add', dependency: 'quotationAdd', id: 71, extra: {} },
      {
        action: 'update',
        dependency: 'updateQuotation',
        id: 72,
        extra: { id: 12 }
      },
      {
        action: 'correct',
        dependency: 'errorOrderById',
        id: 73,
        extra: { id: 13, resetOrder: true }
      }
    ]) {
      const calls = []
      const orderInfo = {
        ...fixture.extra,
        payType: 5,
        transactionNo: 'trade-1',
        paymentDocList: [{ paymentDocUrl: 'https://example.test/pay.png' }],
        zyPayUrl: 'https://example.test/contract.pdf'
      }
      const dependencies = createCheckoutDependencies(
        Object.fromEntries(
          ['quotationAdd', 'updateQuotation', 'errorOrderById'].map(name => [
            name,
            async payload => {
              calls.push([name, payload])
              return { code: 0, data: fixture.id }
            }
          ])
        )
      )

      const result = await submitSimpleQuotationCheckout(
        { action: fixture.action, orderInfo, merchantId: 'merchant-1' },
        dependencies
      )

      const normalizedOrderInfo = {
        ...orderInfo,
        paymentDocList: [
          { paymentDocUrl: 'https://example.test/pay.png', type: 1 }
        ]
      }
      const expectedPayload = fixture.action === 'correct'
        ? {
            ...normalizedOrderInfo,
            zyPayUrl: '',
            payType: 5,
            payee: 0,
            oldQuotationId: 13,
            transactionNo: 'trade-1,'
          }
        : normalizedOrderInfo
      assert.deepEqual(calls, [[fixture.dependency, expectedPayload]])
      assert.deepEqual(result, {
        status: 'list',
        quotationId: fixture.id,
        navigation: LIST_NAVIGATION
      })
    }
  })

  it('IT-EQ-SIMPLE-CHECKOUT-005: routes every supported offline collection type directly to the list', async () => {
    for (const payType of [2, 5, 6, 7]) {
      const result = await submitSimpleQuotationCheckout(
        {
          action: 'add',
          merchantId: 'merchant-1',
          orderInfo: {
            payType,
            transactionNo: 'trade-1',
            paymentDocList: [{ paymentDocUrl: 'https://example.test/pay.png' }],
            zyPayUrl: 'https://example.test/contract.pdf'
          }
        },
        createCheckoutDependencies()
      )

      assert.equal(result.status, 'list')
      assert.deepEqual(result.navigation, LIST_NAVIGATION)
    }
  })

  it('IT-EQ-SIMPLE-CHECKOUT-006: returns a pay navigation with contract-voucher status after online submission', async () => {
    const result = await submitSimpleQuotationCheckout(
      {
        action: 'add',
        merchantId: 'merchant-1',
        orderInfo: {
          payType: 1,
          orderType: 1,
          vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
        }
      },
      createCheckoutDependencies({
        checkZyPayFlag: async payload => {
          assert.deepEqual(payload, {
            goodsIds: ['goods-1'],
            merchantId: 'merchant-1'
          })
          return { code: 0, data: true }
        }
      })
    )

    assert.deepEqual(result, {
      status: 'pay',
      quotationId: 71,
      navigation: {
        type: 'redirectTo',
        alias: 'CarQuotationPay',
        params: {
          id: 71,
          orderId: 'payment-order-1',
          zyVoucherStatus: 1
        }
      }
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-007: separates required-contract, blocked and business-error outcomes', async () => {
    const contractInput = {
      action: 'add',
      merchantId: 'merchant-1',
      orderInfo: {
        payType: 2,
        orderType: 1,
        transactionNo: 'trade-1',
        paymentDocList: [{ paymentDocUrl: 'https://example.test/pay.png' }],
        vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
      }
    }

    const needContract = await submitSimpleQuotationCheckout(
      contractInput,
      createCheckoutDependencies({
        checkZyPayFlag: async () => ({ code: 0, data: true }),
        checkRecord: async () => ({ code: 0, data: false }),
        quotationAdd: async () => assert.fail('must wait for contract')
      })
    )
    assert.deepEqual(needContract, {
      status: 'need-contract',
      patch: { showPopup: false, showZyPopup: true }
    })

    const blocked = await submitSimpleQuotationCheckout(
      contractInput,
      createCheckoutDependencies({
        checkZyPayFlag: async () => ({ code: 9, message: '合同校验失败' }),
        quotationAdd: async () => assert.fail('must not submit')
      })
    )
    assert.deepEqual(blocked, {
      status: 'blocked',
      message: '合同校验失败'
    })

    const response = { code: 8, message: '库存不足' }
    const businessError = await submitSimpleQuotationCheckout(
      {
        action: 'add',
        merchantId: 'merchant-1',
        orderInfo: { payType: 1, orderType: 3 }
      },
      createCheckoutDependencies({ quotationAdd: async () => response })
    )
    assert.deepEqual(businessError, {
      status: 'business-error',
      response
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-008: completes uploaded contract material and returns the list', async () => {
    let updatePayload
    const result = await completeSimpleQuotationContract(
      {
        quotationId: 74,
        zyPayUrls: [
          'https://example.test/contract-1.png',
          'https://example.test/contract-2.png'
        ],
        merchant4s: {
          merchantId: 'merchant-1',
          merchantName: '测试门店'
        }
      },
      createCheckoutDependencies({
        updateCustomerInfo: async payload => {
          updatePayload = payload
          return { code: 0, data: true }
        }
      })
    )

    assert.deepEqual(updatePayload, {
      check: true,
      id: 74,
      orderId: 'order-74',
      merchantId4s: 'merchant-1',
      merchantName4s: '测试门店',
      referrer: '销售甲',
      referrerId: 'sales-1',
      zyPayUrl:
        'https://example.test/contract-1.png,https://example.test/contract-2.png'
    })
    assert.deepEqual(result, {
      status: 'list',
      navigation: LIST_NAVIGATION
    })
  })

  it('IT-EQ-SIMPLE-CHECKOUT-009: every rejected checkout API settles before the timeout', async () => {
    const rejectionCases = [
      {
        name: 'staffDailyReportMerchantValid',
        run: error =>
          checkSimpleQuotationDailyReport(
            {
              userInfo: {
                shopMerchantId: 'shop-1',
                merchantId: 'equity-1',
                uuid: 'staff-1'
              },
              now: new Date('2026-09-08T12:00:00+08:00')
            },
            async () => {
              throw error
            }
          )
      },
      ...['quotationAdd', 'updateQuotation', 'errorOrderById'].map(
        (dependency, index) => ({
          name: dependency,
          run: error =>
            submitSimpleQuotationCheckout(
              {
                action: ['add', 'update', 'correct'][index],
                merchantId: 'merchant-1',
                orderInfo: {
                  id: index ? index : undefined,
                  resetOrder: index === 2,
                  payType: 5,
                  transactionNo: 'trade-1',
                  paymentDocList: [
                    { paymentDocUrl: 'https://example.test/pay.png' }
                  ],
                  zyPayUrl: 'https://example.test/contract.pdf'
                }
              },
              createCheckoutDependencies({
                [dependency]: async () => {
                  throw error
                }
              })
            )
        })
      ),
      {
        name: 'quotationRecording',
        run: error =>
          recordSimpleQuotationOrder(
            { orderInfo: { orderType: 3 }, merchantId: 'merchant-1' },
            createCheckoutDependencies({
              quotationRecording: async () => {
                throw error
              }
            })
          )
      },
      {
        name: 'checkZyPayFlag',
        run: error =>
          submitSimpleQuotationCheckout(
            {
              action: 'add',
              merchantId: 'merchant-1',
              orderInfo: {
                payType: 2,
                transactionNo: 'trade-1',
                paymentDocList: [
                  { paymentDocUrl: 'https://example.test/pay.png' }
                ],
                vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
              }
            },
            createCheckoutDependencies({
              checkZyPayFlag: async () => {
                throw error
              }
            })
          )
      },
      {
        name: 'checkRecord',
        run: error =>
          submitSimpleQuotationCheckout(
            {
              action: 'add',
              merchantId: 'merchant-1',
              orderInfo: {
                payType: 2,
                transactionNo: 'trade-1',
                paymentDocList: [
                  { paymentDocUrl: 'https://example.test/pay.png' }
                ],
                vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
              }
            },
            createCheckoutDependencies({
              checkZyPayFlag: async () => ({ code: 0, data: true }),
              checkRecord: async () => {
                throw error
              }
            })
          )
      },
      {
        name: 'quotationUpgrade',
        run: error =>
          submitSimpleQuotationCheckout(
            {
              action: 'add',
              merchantId: 'merchant-1',
              orderInfo: { payType: 1, orderType: 3 }
            },
            createCheckoutDependencies({
              quotationUpgrade: async () => {
                throw error
              }
            })
          )
      },
      ...['getQuotationInfoById', 'updateCustomerInfo'].map(dependency => ({
        name: dependency,
        run: error =>
          completeSimpleQuotationContract(
            {
              quotationId: 74,
              zyPayUrls: ['https://example.test/contract.png'],
              merchant4s: {
                merchantId: 'merchant-1',
                merchantName: '测试门店'
              }
            },
            createCheckoutDependencies({
              [dependency]: async () => {
                throw error
              }
            })
          )
      }))
    ]

    for (const fixture of rejectionCases) {
      const rejection = new Error(`${fixture.name} unavailable`)
      const settled = await settleWithinDeadline(fixture.run(rejection))
      assert.notEqual(settled.state, 'timeout', fixture.name)
      assert.equal(settled.state, 'rejected', fixture.name)
      assert.equal(settled.error, rejection, fixture.name)
    }
  })

  it('IT-EQ-SIMPLE-CHECKOUT-010: keeps the pay route after a post-submit contract business failure', async () => {
    const result = await submitSimpleQuotationCheckout(
      {
        action: 'add',
        merchantId: 'merchant-1',
        orderInfo: {
          payType: 1,
          orderType: 1,
          vdQuotationGoodsList: [{ goodsId: 'goods-1' }]
        }
      },
      createCheckoutDependencies({
        checkZyPayFlag: async () => ({
          code: 9,
          message: '合同服务暂不可用'
        })
      })
    )

    assert.deepEqual(result, {
      status: 'pay',
      quotationId: 71,
      navigation: {
        type: 'redirectTo',
        alias: 'CarQuotationPay',
        params: {
          id: 71,
          orderId: 'payment-order-1',
          zyVoucherStatus: 0
        }
      }
    })
  })
})