@jetthai/cuora 1.1.483 → 1.1.485-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.claude/commands/sync-ai-prompts.md +88 -1
  2. package/.claude/settings.local.json +3 -1
  3. package/.github/copilot-instructions.md +19 -10
  4. package/.husky/post-checkout +3 -3
  5. package/.husky/pre-push +1 -1
  6. package/.prettierignore +2 -1
  7. package/AGENTS.md +19 -10
  8. package/AI_PROMPT_SOURCE.md +19 -10
  9. package/CHANGELOG.md +386 -23
  10. package/CLAUDE.md +19 -10
  11. package/GEMINI.md +19 -10
  12. package/docs/my-claude/feat-sharon-JT-1790247240-socket/branch-transfer.md +14 -0
  13. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-preparation.json +40 -0
  14. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-verification.md +41 -0
  15. package/docs/my-claude/feat-sharon-JT-1790247240-socket/implementation-ledger.md +87 -0
  16. package/docs/my-claude/feat-sharon-JT-1790247240-socket/module-report.md +73 -0
  17. package/docs/my-claude/feat-sharon-JT-1790247240-socket/plan.md +309 -0
  18. package/docs/my-claude/feat-sharon-JT-1790247240-socket/test-cases.md +245 -0
  19. package/docs/my-claude/feat-sharon-JT-1791180540-onesignal/transfer.md +9 -0
  20. package/e2e/feature-map.md +61 -0
  21. package/package.json +1 -1
  22. package/prepare-for-pr/JT-1776243420.md +85 -0
  23. package/prepare-for-pr/TI-16026/STATE.md +17 -0
  24. package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
  25. package/prepare-for-pr/TI-16026/analysis.md +38 -0
  26. package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
  27. package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
  28. package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
  29. package/prepare-for-pr/TI-16026/bundle.json +18 -0
  30. package/prepare-for-pr/TI-16026/checklist.md +39 -0
  31. package/prepare-for-pr/TI-16026/claude-after-model +1 -0
  32. package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
  33. package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
  34. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
  35. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
  36. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
  37. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
  38. package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
  39. package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
  40. package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
  41. package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
  42. package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
  43. package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
  44. package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
  45. package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
  46. package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
  47. package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
  48. package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
  49. package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
  50. package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
  51. package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
  52. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
  53. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
  54. package/prepare-for-pr/TI-16026/commit-note.md +5 -0
  55. package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
  56. package/prepare-for-pr/TI-16026/harvest-redaction.out +1 -0
  57. package/prepare-for-pr/TI-16026/harvest.md +37 -0
  58. package/prepare-for-pr/TI-16026/lessons.md +5 -0
  59. package/prepare-for-pr/TI-16026/open-questions.md +6 -0
  60. package/prepare-for-pr/TI-16026/publish.md +28 -0
  61. package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
  62. package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
  63. package/prepare-for-pr/TI-16026/review-log.md +57 -0
  64. package/prepare-for-pr/TI-16026/review-notes.md +97 -0
  65. package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
  66. package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
  67. package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
  68. package/prepare-for-pr/TI-16026/state-log.md +35 -0
  69. package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
  70. package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
  71. package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
  72. package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
  73. package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
  74. package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
  75. package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
  76. package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
  77. package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
  78. package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
  79. package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
  80. package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
  81. package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
  82. package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
  83. package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
  84. package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
  85. package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
  86. package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
  87. package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
  88. package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
  89. package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
  90. package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
  91. package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
  92. package/prepare-for-pr/TI-16026/user-question.md +24 -0
  93. package/prepare-for-pr/TI-16026/verify-after.md +15 -0
  94. package/prepare-for-pr/TI-16026.md +408 -0
  95. package/scripts/auto-version.js +1 -0
  96. package/scripts/branch-auto-npm-publish.js +9 -2
  97. package/src/api/payment.js +1 -0
  98. package/src/machine/auth_otp_v3.js +59 -20
  99. package/src/machine/honor_board_cash.js +15 -18
  100. package/src/machine/reward_cash.js +2 -2
  101. package/src/machine/user_sign_up.js +3 -0
  102. package/src/machine/websocket.js +380 -311
  103. package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
  104. package/src/util/constant.js +4 -0
  105. package/src/util/socketPolicy.js +57 -0
  106. package/test/auth_otp_v3.test.js +323 -0
  107. package/test/withdraw_manual_cash.test.js +149 -0
  108. package/tests/websocket.test.mjs +779 -0
@@ -36,9 +36,8 @@ export default function (request, context) {
36
36
  target: 'checking',
37
37
  actions: 'setInitData',
38
38
  },
39
- onError: {
40
- target: 'loaded',
41
- },
39
+ // submitted 的 REFRESH 失敗時無法確認訂單已結束,保留原 Pending 畫面讓下次 REFRESH 可重試
40
+ onError: [{ target: 'submitted', cond: 'isProcessing' }, { target: 'loaded' }],
42
41
  },
43
42
  },
44
43
  checking: {
@@ -96,7 +95,11 @@ export default function (request, context) {
96
95
  },
97
96
  },
98
97
  },
99
- submitted: {},
98
+ submitted: {
99
+ on: {
100
+ REFRESH: { target: 'loading', internal: false },
101
+ },
102
+ },
100
103
  otp: {
101
104
  type: 'parallel',
102
105
  states: {
@@ -17,3 +17,7 @@ export const GAME_TYPE_LIST = [
17
17
  { typeId: 'TURBO', name: 'Turbo', gameTypeMappingId: 15 },
18
18
  { typeId: 'SPORT', name: 'Sports', gameTypeMappingId: 16 },
19
19
  ]
20
+
21
+ // OTP 自動驗證:主動打的 /self 未通過後,最多再等幾次 auth 例行輪詢的 /self、等待上限多久
22
+ export const AUTO_VERIFY_MAX_USER_INFO_UPDATES = 2
23
+ export const AUTO_VERIFY_WAIT_MS = 5000
@@ -0,0 +1,57 @@
1
+ export function decideNextStep({ event, reason, err, active, ready, rejection } = {}) {
2
+ if (event === 'kicked') return 'kicked'
3
+ if (event === 'disconnect' && reason === 'io client disconnect') return 'none'
4
+ if ((event === 'disconnect' && reason !== 'io server disconnect') || (event === 'connect_error' && active)) return 'socketio'
5
+ const info = rejection || err?.data
6
+ if (info) {
7
+ if (info.code === 'MAX_CONNECTIONS') return 'kicked'
8
+ if (info.code === 'SESSION_TOKEN_INVALID') return 'renew'
9
+ if (info.retryable === false) return 'stop'
10
+ if (info.retryable === true) return 'retry'
11
+ }
12
+ if (event === 'disconnect') return ready ? 'kicked' : 'retry'
13
+ if (err?.message === 'session rejected') return 'renew'
14
+ return 'retry'
15
+ }
16
+
17
+ export function canResume(state, currentToken, source = 'user', now = Date.now()) {
18
+ if (!currentToken) return false
19
+ if (currentToken !== state.lastToken) return true
20
+ if (!state.blocked) return true
21
+ if (state.blocked === 'stop') return false
22
+ if (state.blocked === 'kicked') return source === 'user'
23
+ if (state.blocked === 'exhausted') return source === 'user' || (source === 'auto' && now - state.lastAttemptAt >= 15000)
24
+ return false
25
+ }
26
+
27
+ export function nextRetryDelay(attempt, retryAfterMs) {
28
+ const count = Number.isFinite(attempt) ? Math.max(1, Math.floor(attempt)) : 1
29
+ const base = Math.min(30000, 1000 * 2 ** Math.min(count - 1, 30))
30
+ const floor = Number.isFinite(retryAfterMs) ? Math.max(0, retryAfterMs) : 0
31
+ return Math.max(floor, Math.round(base * (0.5 + Math.random())))
32
+ }
33
+
34
+ export function createPushDedupe({ max = 500, ttlMs = 600000 } = {}) {
35
+ const capacity = Number.isFinite(max) ? Math.max(1, Math.floor(max)) : 500
36
+ const ttl = Number.isFinite(ttlMs) ? Math.max(0, ttlMs) : 600000
37
+ const seen = new Map()
38
+ return (eventName, data, now = Date.now()) => {
39
+ for (const [key, timestamp] of seen) {
40
+ if (now - timestamp >= ttl) seen.delete(key)
41
+ }
42
+ const messageId = data?._meta?.messageId
43
+ const orderId = [data?.data?.applyId, data?.applyId, data?.data?.transactionId, data?.transactionId].find(
44
+ (id) => id !== undefined && id !== null && id !== ''
45
+ )
46
+ const businessEvent = [data?.event, data?.data?.event].find((event) => event !== undefined && event !== null && event !== '')
47
+ let key
48
+ if (messageId !== undefined && messageId !== null && messageId !== '') key = JSON.stringify(['message', messageId])
49
+ else if (eventName === 'payment-info' && businessEvent && orderId !== undefined && orderId !== null && orderId !== '')
50
+ key = JSON.stringify(['payment', eventName, businessEvent, String(orderId)])
51
+ if (!key) return false
52
+ if (seen.has(key)) return true
53
+ seen.set(key, now)
54
+ while (seen.size > capacity) seen.delete(seen.keys().next().value)
55
+ return false
56
+ }
57
+ }
@@ -0,0 +1,323 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { interpret } from 'xstate'
4
+ import authOtpV3 from '../src/machine/auth_otp_v3.js'
5
+
6
+ function waitForState(service, matches) {
7
+ if (service.state.matches(matches)) return Promise.resolve(service.state)
8
+ return new Promise((resolve, reject) => {
9
+ const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${matches}`)), 1000)
10
+ service.onTransition((state) => {
11
+ if (!state.matches(matches)) return
12
+ clearTimeout(timeout)
13
+ resolve(state)
14
+ })
15
+ })
16
+ }
17
+
18
+ test('phone entry skips OTP only after /self confirms phone verification', async () => {
19
+ let selfReads = 0
20
+ const requests = []
21
+ const request = {
22
+ async send(descriptor) {
23
+ requests.push(descriptor.url)
24
+ if (descriptor.url === 'self') {
25
+ selfReads++
26
+ return {
27
+ phone: selfReads === 1 ? null : '123456789',
28
+ phone_verification_status: selfReads > 1,
29
+ email: null,
30
+ email_verification_status: false,
31
+ }
32
+ }
33
+ if (descriptor.url === 'otp-verification-point/verify') return { needAcknowledge: false }
34
+ throw new Error(`Unexpected request: ${descriptor.url}`)
35
+ },
36
+ }
37
+ const service = interpret(authOtpV3(request)).start()
38
+ try {
39
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
40
+ await waitForState(service, 'notVerified.phone')
41
+ service.send({ type: 'SEND_PHONE', data: { countryCode: '886', phone: '123456789' } })
42
+ await waitForState(service, 'verified')
43
+ assert.equal(selfReads, 2)
44
+ assert.deepEqual(requests, ['self', 'otp-verification-point/verify', 'self'])
45
+ } finally {
46
+ service.stop()
47
+ }
48
+ })
49
+
50
+ test('email entry skips OTP only after /self confirms email verification', async () => {
51
+ let selfReads = 0
52
+ const request = {
53
+ async send(descriptor) {
54
+ if (descriptor.url === 'self') {
55
+ selfReads++
56
+ return {
57
+ phone: null,
58
+ phone_verification_status: false,
59
+ email: selfReads === 1 ? null : 'test@example.com',
60
+ email_verification_status: selfReads > 1,
61
+ }
62
+ }
63
+ if (descriptor.url === 'otp-verification-point/verify') return { needAcknowledge: false }
64
+ throw new Error(`Unexpected request: ${descriptor.url}`)
65
+ },
66
+ }
67
+ const service = interpret(authOtpV3(request)).start()
68
+ try {
69
+ service.send({ type: 'SET_STRATEGY', data: 'email' })
70
+ await waitForState(service, 'notVerified.email')
71
+ service.send({ type: 'SEND_EMAIL', data: { email: 'test@example.com' } })
72
+ await waitForState(service, 'verified')
73
+ assert.equal(selfReads, 2)
74
+ } finally {
75
+ service.stop()
76
+ }
77
+ })
78
+
79
+ test('existing phone auto verification checks /self before finishing', async () => {
80
+ let selfReads = 0
81
+ const request = {
82
+ async send(descriptor) {
83
+ if (descriptor.url === 'self') {
84
+ selfReads++
85
+ return {
86
+ phone: '123456789',
87
+ phone_verification_status: selfReads > 1,
88
+ email: null,
89
+ email_verification_status: false,
90
+ }
91
+ }
92
+ if (descriptor.url === 'otp-verification-point/verify') return { needAcknowledge: false }
93
+ throw new Error(`Unexpected request: ${descriptor.url}`)
94
+ },
95
+ }
96
+ const service = interpret(authOtpV3(request)).start()
97
+ try {
98
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
99
+ await waitForState(service, 'verified')
100
+ assert.equal(selfReads, 2)
101
+ } finally {
102
+ service.stop()
103
+ }
104
+ })
105
+
106
+ test('needAcknowledge false never grants verification when /self is still unverified', async () => {
107
+ let verifyCalls = 0
108
+ const request = {
109
+ async send(descriptor) {
110
+ if (descriptor.url === 'self') {
111
+ return { phone: null, phone_verification_status: false, email: null, email_verification_status: false }
112
+ }
113
+ if (descriptor.url === 'otp-verification-point/verify') {
114
+ verifyCalls++
115
+ return { needAcknowledge: false }
116
+ }
117
+ throw new Error(`Unexpected request: ${descriptor.url}`)
118
+ },
119
+ }
120
+ const service = interpret(authOtpV3(request)).start()
121
+ try {
122
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
123
+ await waitForState(service, 'notVerified.phone')
124
+ service.send({ type: 'SEND_PHONE', data: { countryCode: '886', phone: '123456789' } })
125
+ await waitForState(service, 'autoVerifyWaiting')
126
+ const stale = { phone: '123456789', phone_verification_status: false, email: null, email_verification_status: false }
127
+ service.send({ type: 'USER_INFO_UPDATED', data: stale })
128
+ assert.equal(service.state.matches('autoVerifyWaiting'), true)
129
+ service.send({ type: 'USER_INFO_UPDATED', data: stale })
130
+ assert.equal(service.state.matches('fail'), true)
131
+ assert.equal(verifyCalls, 1)
132
+ } finally {
133
+ service.stop()
134
+ }
135
+ })
136
+
137
+ const autoVerifyEntries = [
138
+ {
139
+ name: 'existing phone',
140
+ strategy: 'phone',
141
+ initialUser: { phone: '123456789', phone_verification_status: false },
142
+ },
143
+ {
144
+ name: 'filled phone',
145
+ strategy: 'phone',
146
+ initialUser: { phone: null, phone_verification_status: false },
147
+ fill: { type: 'SEND_PHONE', data: { countryCode: '886', phone: '123456789' } },
148
+ waitFor: 'notVerified.phone',
149
+ },
150
+ {
151
+ name: 'filled email',
152
+ strategy: 'email',
153
+ initialUser: { email: null, email_verification_status: false },
154
+ fill: { type: 'SEND_EMAIL', data: { email: 'test@example.com' } },
155
+ waitFor: 'notVerified.email',
156
+ },
157
+ ]
158
+
159
+ // 第 1 次 /self 為進入流程時抓的,第 2 次為 verify 後主動打的;兩次都尚未反映驗證結果
160
+ function staleSelfRequest(strategy, initialUser) {
161
+ const requests = []
162
+ const contact = strategy === 'phone' ? { phone: '123456789' } : { email: 'test@example.com' }
163
+ return {
164
+ requests,
165
+ contact,
166
+ async send(descriptor) {
167
+ requests.push(descriptor.url)
168
+ if (descriptor.url === 'self') {
169
+ return requests.filter((url) => url === 'self').length === 1 ? { ...initialUser } : { ...initialUser, ...contact }
170
+ }
171
+ if (descriptor.url === 'otp-verification-point/verify') return { needAcknowledge: false }
172
+ throw new Error(`Unexpected request: ${descriptor.url}`)
173
+ },
174
+ }
175
+ }
176
+
177
+ async function startAutoVerify(entry) {
178
+ const request = staleSelfRequest(entry.strategy, entry.initialUser)
179
+ const service = interpret(authOtpV3(request)).start()
180
+ service.send({ type: 'SET_STRATEGY', data: entry.strategy })
181
+ if (entry.fill) {
182
+ await waitForState(service, entry.waitFor)
183
+ service.send(entry.fill)
184
+ }
185
+ await waitForState(service, 'autoVerifyWaiting')
186
+ return { service, request }
187
+ }
188
+
189
+ for (const entry of autoVerifyEntries) {
190
+ test(`${entry.name}: stale /self waits and passes on a later polled /self`, async () => {
191
+ const { service, request } = await startAutoVerify(entry)
192
+ try {
193
+ const statusKey = `${entry.strategy}_verification_status`
194
+ service.send({ type: 'USER_INFO_UPDATED', data: { ...request.contact, [statusKey]: false } })
195
+ assert.equal(service.state.matches('autoVerifyWaiting'), true)
196
+ service.send({ type: 'USER_INFO_UPDATED', data: { ...request.contact, [statusKey]: true } })
197
+ assert.equal(service.state.matches('verified'), true)
198
+ assert.equal(service.state.context.userInfo[statusKey], true)
199
+ assert.deepEqual(request.requests, ['self', 'otp-verification-point/verify', 'self'])
200
+ } finally {
201
+ service.stop()
202
+ }
203
+ })
204
+
205
+ test(`${entry.name}: two stale polled /self responses fail`, async () => {
206
+ const { service, request } = await startAutoVerify(entry)
207
+ try {
208
+ const stale = { ...request.contact, [`${entry.strategy}_verification_status`]: false }
209
+ service.send({ type: 'USER_INFO_UPDATED', data: stale })
210
+ service.send({ type: 'USER_INFO_UPDATED', data: stale })
211
+ assert.equal(service.state.matches('fail'), true)
212
+ assert.deepEqual(request.requests, ['self', 'otp-verification-point/verify', 'self'])
213
+ } finally {
214
+ service.stop()
215
+ }
216
+ })
217
+ }
218
+
219
+ test('auto verify waiting fails after the 5 second limit without polled /self', async (t) => {
220
+ t.mock.timers.enable({ apis: ['setTimeout'] })
221
+ const { service } = await startAutoVerify(autoVerifyEntries[0])
222
+ try {
223
+ t.mock.timers.tick(4999)
224
+ assert.equal(service.state.matches('autoVerifyWaiting'), true)
225
+ t.mock.timers.tick(1)
226
+ assert.equal(service.state.matches('fail'), true)
227
+ } finally {
228
+ service.stop()
229
+ }
230
+ })
231
+
232
+ test('the 5 second limit is not reset by a stale polled /self', async (t) => {
233
+ t.mock.timers.enable({ apis: ['setTimeout'] })
234
+ const { service, request } = await startAutoVerify(autoVerifyEntries[0])
235
+ try {
236
+ t.mock.timers.tick(4000)
237
+ service.send({ type: 'USER_INFO_UPDATED', data: { ...request.contact, phone_verification_status: false } })
238
+ t.mock.timers.tick(1000)
239
+ assert.equal(service.state.matches('fail'), true)
240
+ } finally {
241
+ service.stop()
242
+ }
243
+ })
244
+
245
+ test('USER_INFO_UPDATED outside auto verify waiting does not change state', async () => {
246
+ const request = {
247
+ async send(descriptor) {
248
+ if (descriptor.url === 'self') return { phone: null, phone_verification_status: false }
249
+ throw new Error(`Unexpected request: ${descriptor.url}`)
250
+ },
251
+ }
252
+ const service = interpret(authOtpV3(request)).start()
253
+ try {
254
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
255
+ await waitForState(service, 'notVerified.phone')
256
+ service.send({ type: 'USER_INFO_UPDATED', data: { phone: '123456789', phone_verification_status: true } })
257
+ assert.equal(service.state.matches('notVerified.phone'), true)
258
+ } finally {
259
+ service.stop()
260
+ }
261
+ })
262
+
263
+ test('needAcknowledge true keeps the existing OTP input route', async () => {
264
+ const request = {
265
+ async send(descriptor) {
266
+ if (descriptor.url === 'self') {
267
+ return { phone: null, phone_verification_status: false, email: null, email_verification_status: false }
268
+ }
269
+ if (descriptor.url === 'otp-verification-point/verify') {
270
+ return { needAcknowledge: true, request_id: 'test-request', ttl: 60000, countryCode: '886', phone: '123456789' }
271
+ }
272
+ throw new Error(`Unexpected request: ${descriptor.url}`)
273
+ },
274
+ }
275
+ const service = interpret(authOtpV3(request)).start()
276
+ try {
277
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
278
+ await waitForState(service, 'notVerified.phone')
279
+ service.send({ type: 'SEND_PHONE', data: { countryCode: '886', phone: '123456789' } })
280
+ await waitForState(service, 'notVerified.otp')
281
+ assert.equal(service.state.context.requestId, 'test-request')
282
+ } finally {
283
+ service.stop()
284
+ }
285
+ })
286
+
287
+ test('email without an address still requires input even if its verification flag is true', async () => {
288
+ const request = {
289
+ async send(descriptor) {
290
+ if (descriptor.url === 'self') {
291
+ return { phone: '123456789', phone_verification_status: true, email: null, email_verification_status: true }
292
+ }
293
+ throw new Error(`Unexpected request: ${descriptor.url}`)
294
+ },
295
+ }
296
+ const service = interpret(authOtpV3(request)).start()
297
+ try {
298
+ service.send({ type: 'SET_STRATEGY', data: 'email' })
299
+ await waitForState(service, 'notVerified.email')
300
+ assert.equal(service.state.matches('verified'), false)
301
+ } finally {
302
+ service.stop()
303
+ }
304
+ })
305
+
306
+ test('phone without a number still requires input even if its verification flag is true', async () => {
307
+ const request = {
308
+ async send(descriptor) {
309
+ if (descriptor.url === 'self') {
310
+ return { phone: null, phone_verification_status: true, email: 'test@example.com', email_verification_status: true }
311
+ }
312
+ throw new Error(`Unexpected request: ${descriptor.url}`)
313
+ },
314
+ }
315
+ const service = interpret(authOtpV3(request)).start()
316
+ try {
317
+ service.send({ type: 'SET_STRATEGY', data: 'phone' })
318
+ await waitForState(service, 'notVerified.phone')
319
+ assert.equal(service.state.matches('verified'), false)
320
+ } finally {
321
+ service.stop()
322
+ }
323
+ })
@@ -0,0 +1,149 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { interpret } from 'xstate'
4
+ import withdrawManualCash from '../src/machine/withdraw/withdraw_manual_cash.js'
5
+
6
+ function waitForState(service, matches) {
7
+ if (service.state.matches(matches)) return Promise.resolve(service.state)
8
+ return new Promise((resolve, reject) => {
9
+ const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${matches}`)), 1000)
10
+ service.onTransition((state) => {
11
+ if (!state.matches(matches)) return
12
+ clearTimeout(timeout)
13
+ resolve(state)
14
+ })
15
+ })
16
+ }
17
+
18
+ const context = {
19
+ doubleWalletWithdrawLimitCheck: '0',
20
+ paymentDetail: [{ category: 'manual', transferType: 'withdraw', method: 'MANUAL', minimum: 100, maximum: 10000 }],
21
+ }
22
+
23
+ const boundBank = { bankCode: 'BANK', accountNumber: '0001', holderName: 'holder' }
24
+
25
+ // pendingOrders[i] 為第 i+1 次 pendingOrder 的回應;Error 代表該次 reject
26
+ function stubRequest(pendingOrders) {
27
+ const calls = { pendingOrder: 0 }
28
+ return {
29
+ calls,
30
+ async send(descriptor) {
31
+ if (descriptor.url === 'payment/v2/getBindingPaymentInfo') return { bankList: [boundBank], ewalletList: [], cryptoList: [] }
32
+ if (descriptor.url === 'payment/v2/withdrawRule') return { enableWithdraw: true }
33
+ if (descriptor.url === 'payment/v2/pendingOrder') {
34
+ const response = pendingOrders[calls.pendingOrder++] ?? []
35
+ if (response instanceof Error) throw response
36
+ return response
37
+ }
38
+ throw new Error(`Unexpected request: ${descriptor.url}`)
39
+ },
40
+ }
41
+ }
42
+
43
+ function waitForPendingOrderCalls(request, count) {
44
+ return new Promise((resolve, reject) => {
45
+ const started = Date.now()
46
+ const poll = () => {
47
+ if (request.calls.pendingOrder >= count) return resolve()
48
+ if (Date.now() - started > 1000) return reject(new Error(`Timed out waiting for ${count} pendingOrder calls`))
49
+ setTimeout(poll, 5)
50
+ }
51
+ poll()
52
+ })
53
+ }
54
+
55
+ const firstOrder = { applyId: 'W-1', amount: 500 }
56
+ const secondOrder = { applyId: 'W-2', amount: 800 }
57
+
58
+ test('REFRESH in submitted re-runs loading and fetches the pending order again', async () => {
59
+ const request = stubRequest([[firstOrder], []])
60
+ const service = interpret(withdrawManualCash(request, context)).start()
61
+ try {
62
+ await waitForState(service, 'submitted')
63
+ assert.equal(request.calls.pendingOrder, 1)
64
+ service.send({ type: 'REFRESH' })
65
+ assert.equal(service.state.matches('loading'), true)
66
+ await waitForPendingOrderCalls(request, 2)
67
+ } finally {
68
+ service.stop()
69
+ }
70
+ })
71
+
72
+ test('REFRESH in submitted returns to the form when no order is pending', async () => {
73
+ const request = stubRequest([[firstOrder], []])
74
+ const service = interpret(withdrawManualCash(request, context)).start()
75
+ try {
76
+ await waitForState(service, 'submitted')
77
+ service.send({ type: 'REFRESH' })
78
+ const state = await waitForState(service, 'loaded')
79
+ assert.equal(request.calls.pendingOrder, 2)
80
+ assert.equal(state.context.processing, undefined)
81
+ } finally {
82
+ service.stop()
83
+ }
84
+ })
85
+
86
+ test('REFRESH in submitted keeps submitted with the updated order when one is still pending', async () => {
87
+ const request = stubRequest([[firstOrder], [secondOrder]])
88
+ const service = interpret(withdrawManualCash(request, context)).start()
89
+ try {
90
+ await waitForState(service, 'submitted')
91
+ assert.equal(service.state.context.processing.applyId, 'W-1')
92
+ service.send({ type: 'REFRESH' })
93
+ await waitForPendingOrderCalls(request, 2)
94
+ const state = await waitForState(service, 'submitted')
95
+ assert.equal(request.calls.pendingOrder, 2)
96
+ assert.deepEqual(state.context.processing, secondOrder)
97
+ } finally {
98
+ service.stop()
99
+ }
100
+ })
101
+
102
+ function networkError() {
103
+ return Object.assign(new Error('Network Error'), { code: 'ERR_998' })
104
+ }
105
+
106
+ test('a failed refresh in submitted keeps the pending order and a later REFRESH retries', async () => {
107
+ const request = stubRequest([[firstOrder], networkError(), []])
108
+ const service = interpret(withdrawManualCash(request, context)).start()
109
+ try {
110
+ await waitForState(service, 'submitted')
111
+ service.send({ type: 'REFRESH' })
112
+ await waitForPendingOrderCalls(request, 2)
113
+ const state = await waitForState(service, 'submitted')
114
+ assert.deepEqual(state.context.processing, firstOrder)
115
+ service.send({ type: 'REFRESH' })
116
+ await waitForState(service, 'loaded')
117
+ assert.equal(request.calls.pendingOrder, 3)
118
+ } finally {
119
+ service.stop()
120
+ }
121
+ })
122
+
123
+ test('a failed first load without a pending order still shows the form', async () => {
124
+ const request = stubRequest([networkError()])
125
+ const service = interpret(withdrawManualCash(request, context)).start()
126
+ try {
127
+ await waitForState(service, 'loaded')
128
+ assert.equal(request.calls.pendingOrder, 1)
129
+ assert.equal(service.state.context.processing, null)
130
+ } finally {
131
+ service.stop()
132
+ }
133
+ })
134
+
135
+ test('REFRESH in loaded with a bound bank is still ignored', async () => {
136
+ const request = stubRequest([[]])
137
+ const service = interpret(withdrawManualCash(request, context)).start()
138
+ try {
139
+ await waitForState(service, 'loaded')
140
+ assert.equal(request.calls.pendingOrder, 1)
141
+ service.send({ type: 'REFRESH' })
142
+ assert.equal(service.state.matches('loaded'), true)
143
+ await new Promise((resolve) => setTimeout(resolve, 20))
144
+ assert.equal(request.calls.pendingOrder, 1)
145
+ assert.equal(service.state.matches('loaded'), true)
146
+ } finally {
147
+ service.stop()
148
+ }
149
+ })