liveCleanup.mjs 2.5 KB
/**
 * @file Live 订单测试的尽力清理边界;不在结果或诊断中暴露会话信息。
 */

import { ORDER_FLOW_METHODS, waitForOrderStatus } from './orderFlow.mjs'

/**
 * 尝试撤销一个测试订单并确认状态。
 *
 * @param {object} client ROP 客户端。
 * @param {object} context 登录上下文。
 * @param {string} orderCode 订单号。
 * @returns {Promise<{revoked: boolean, alreadyRevoked?: boolean, reason?: string}>} 清理结果。
 */
export async function bestEffortRevoke(client, context, orderCode) {
  try {
    const response = await client.post(ORDER_FLOW_METHODS.revoke, {
      orderCode,
      sessionId: context.sessionId,
    })
    if (Number(response?.code) !== 0) {
      const detailResponse = await client.post(ORDER_FLOW_METHODS.detail, {
        orderCode,
        sessionId: context.sessionId,
      })
      if (
        Number(detailResponse?.code) === 0 &&
        Number(detailResponse?.data?.status) === 9
      ) {
        return { revoked: true, alreadyRevoked: true }
      }
      return {
        revoked: false,
        reason: `business-code-${response?.code ?? 'missing'}`,
      }
    }
    await waitForOrderStatus({
      client,
      context,
      orderCode,
      expectedStatus: 9,
    })
    return { revoked: true }
  } catch {
    return { revoked: false, reason: 'request-or-status-check-failed' }
  }
}

/**
 * 逆序清理全部已跟踪订单;单个失败不会阻断后续订单。
 *
 * @param {{client: object, context: object, orders?: object[], tracker?: {orders: object[]}, label?: string, onDiagnostic?: Function, testContext?: {diagnostic: Function}}} options 清理依赖和诊断出口。
 * @returns {Promise<object[]>} 不含会话字段的逐订单结果。
 */
export async function cleanupTrackedOrders({
  client,
  context,
  orders,
  tracker,
  label = 'Live cleanup',
  onDiagnostic,
  testContext,
}) {
  const tracked = orders || tracker?.orders || []
  const diagnostic = onDiagnostic || ((message) => testContext?.diagnostic?.(message))
  const results = []
  for (const order of [...tracked].reverse()) {
    const cleanup = await bestEffortRevoke(client, context, order.orderCode)
    const result = {
      orderCode: order.orderCode,
      role: order.role,
      ...cleanup,
    }
    results.push(result)
    if (!cleanup.revoked) {
      diagnostic?.(
        `${label}: ${JSON.stringify({
          orderCode: order.orderCode,
          role: order.role,
          reason: cleanup.reason,
        })}`,
      )
    }
  }
  return results
}