liveCleanup.mjs
2.5 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
/**
* @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
}