@vicacha-devs/medusa-payment-bold 0.0.0-stage → 0.1.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 (155) hide show
  1. package/.medusa/server/src/admin/index.cjs +1732 -0
  2. package/.medusa/server/src/admin/index.js +1732 -0
  3. package/.medusa/server/src/api/admin/bold/banks/route.js +15 -0
  4. package/.medusa/server/src/api/admin/bold/payment-button/route.js +44 -0
  5. package/.medusa/server/src/api/admin/bold/payment-link/route.js +61 -0
  6. package/.medusa/server/src/api/admin/bold/payment-link-methods/route.js +16 -0
  7. package/.medusa/server/src/api/admin/bold/payment-methods/route.js +17 -0
  8. package/.medusa/server/src/api/admin/bold/payment-qr/route.js +53 -0
  9. package/.medusa/server/src/api/admin/bold/payment-status/route.js +37 -0
  10. package/.medusa/server/src/api/admin/bold/payment-stream/route.js +103 -0
  11. package/.medusa/server/src/api/admin/bold/pos-push/route.js +46 -0
  12. package/.medusa/server/src/api/admin/bold/refund/route.js +37 -0
  13. package/.medusa/server/src/api/admin/bold/terminals/route.js +16 -0
  14. package/.medusa/server/src/api/admin/plugin/route.js +10 -0
  15. package/.medusa/server/src/api/hooks/payment/bold/route.js +104 -0
  16. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  17. package/.medusa/server/src/hooks/index.js +10 -0
  18. package/.medusa/server/src/hooks/use-bold-checkout-handler.js +135 -0
  19. package/.medusa/server/src/hooks/use-bold-payment-methods.js +20 -0
  20. package/.medusa/server/src/hooks/use-bold-payment-status-stream.js +19 -0
  21. package/.medusa/server/src/hooks/use-bold-refund.js +19 -0
  22. package/.medusa/server/src/hooks/use-bold-terminals.js +13 -0
  23. package/.medusa/server/src/hooks/use-create-bold-button.js +19 -0
  24. package/.medusa/server/src/hooks/use-create-bold-link.js +19 -0
  25. package/.medusa/server/src/hooks/use-create-bold-qr.js +19 -0
  26. package/.medusa/server/src/hooks/use-create-bold-terminal.js +19 -0
  27. package/.medusa/server/src/index.js +21 -0
  28. package/.medusa/server/src/lib/error-utils.js +25 -0
  29. package/.medusa/server/src/lib/get-active-providers.js +34 -0
  30. package/.medusa/server/src/lib/get-provider-options.js +20 -0
  31. package/.medusa/server/src/lib/index.js +4 -0
  32. package/.medusa/server/src/lib/session-helpers.js +11 -0
  33. package/.medusa/server/src/providers/bold-button/index.js +157 -0
  34. package/.medusa/server/src/providers/bold-link/index.js +249 -0
  35. package/.medusa/server/src/providers/bold-online/index.js +169 -0
  36. package/.medusa/server/src/providers/bold-terminal/index.js +170 -0
  37. package/.medusa/server/src/rbac.js +58 -0
  38. package/.medusa/server/src/sdk/client.js +112 -0
  39. package/.medusa/server/src/sdk/query-keys.js +13 -0
  40. package/.medusa/server/src/services/bold-client.js +304 -0
  41. package/.medusa/server/src/services/integrity.js +54 -0
  42. package/.medusa/server/src/types/constants.js +55 -0
  43. package/.medusa/server/src/types/enums.js +15 -0
  44. package/.medusa/server/src/types/errors.js +80 -0
  45. package/.medusa/server/src/types/index.js +3 -0
  46. package/.medusa/server/src/workflows/create-bold-payment-link.js +7 -0
  47. package/.medusa/server/src/workflows/create-bold-refund.js +7 -0
  48. package/.medusa/server/src/workflows/get-bold-payment-methods.js +7 -0
  49. package/.medusa/server/src/workflows/get-integration-api-payment-methods.js +7 -0
  50. package/.medusa/server/src/workflows/get-payment-link-methods.js +7 -0
  51. package/.medusa/server/src/workflows/get-terminals.js +7 -0
  52. package/.medusa/server/src/workflows/index.js +7 -0
  53. package/.medusa/server/src/workflows/steps/create-bold-link.js +43 -0
  54. package/.medusa/server/src/workflows/steps/get-bold-payment-methods.js +12 -0
  55. package/.medusa/server/src/workflows/steps/get-payment-link-methods.js +12 -0
  56. package/.medusa/server/src/workflows/steps/get-terminals.js +13 -0
  57. package/.medusa/server/src/workflows/steps/refund-bold-payment.js +15 -0
  58. package/README.md +106 -2
  59. package/package.json +120 -3
  60. package/src/__tests__/bold-contract.spec.ts +40 -0
  61. package/src/__tests__/bold-qa-emulator.ts +582 -0
  62. package/src/__tests__/bold-use-cases.spec.ts +773 -0
  63. package/src/__tests__/medusa-payment-shim.mjs +334 -0
  64. package/src/__tests__/register-ts-resolver.mjs +101 -0
  65. package/src/admin/README.md +70 -0
  66. package/src/admin/components/bold-terminal-status.tsx +166 -0
  67. package/src/admin/components/icons/bold-fav.tsx +45 -0
  68. package/src/admin/components/icons/copy.tsx +23 -0
  69. package/src/admin/components/icons/index.ts +3 -0
  70. package/src/admin/components/icons/qr-code.tsx +33 -0
  71. package/src/admin/components/icons/smart-phone.tsx +23 -0
  72. package/src/admin/components/index.ts +4 -0
  73. package/src/admin/components/logos/bold.tsx +45 -0
  74. package/src/admin/components/method-item.tsx +19 -0
  75. package/src/admin/components/provider-card.tsx +21 -0
  76. package/src/admin/components/section.tsx +23 -0
  77. package/src/admin/i18n/README.md +58 -0
  78. package/src/admin/i18n/index.ts +11 -0
  79. package/src/admin/i18n/json/ar.json +99 -0
  80. package/src/admin/i18n/json/en.json +99 -0
  81. package/src/admin/i18n/json/es.json +99 -0
  82. package/src/admin/i18n/json/tr.json +99 -0
  83. package/src/admin/routes/settings/bold/components/bold-methods-sidebar.tsx +96 -0
  84. package/src/admin/routes/settings/bold/components/bold-providers-section.tsx +67 -0
  85. package/src/admin/routes/settings/bold/components/index.ts +2 -0
  86. package/src/admin/routes/settings/bold/page.tsx +109 -0
  87. package/src/admin/tsconfig.json +24 -0
  88. package/src/admin/vite-env.d.ts +1 -0
  89. package/src/admin/widgets/bold-audit-timeline.tsx +155 -0
  90. package/src/admin/widgets/bold-payment-actions/bold-payment-actions.tsx +114 -0
  91. package/src/admin/widgets/bold-payment-actions/components/bold-payment-tabs.tsx +127 -0
  92. package/src/admin/widgets/bold-payment-actions/components/bold-remote-payment-panel.tsx +104 -0
  93. package/src/admin/widgets/bold-payment-actions/components/bold-terminal-section.tsx +71 -0
  94. package/src/admin/widgets/bold-payment-actions/hooks/bold-order-balance.ts +126 -0
  95. package/src/admin/widgets/bold-payment-actions/hooks/use-bold-widget-state.tsx +181 -0
  96. package/src/admin/widgets/bold-refund-actions.tsx +151 -0
  97. package/src/admin/widgets/index.ts +12 -0
  98. package/src/api/README.md +37 -0
  99. package/src/api/admin/bold/banks/route.ts +23 -0
  100. package/src/api/admin/bold/payment-button/route.ts +57 -0
  101. package/src/api/admin/bold/payment-link/route.ts +68 -0
  102. package/src/api/admin/bold/payment-link-methods/route.ts +24 -0
  103. package/src/api/admin/bold/payment-methods/route.ts +27 -0
  104. package/src/api/admin/bold/payment-qr/route.ts +68 -0
  105. package/src/api/admin/bold/payment-status/route.ts +48 -0
  106. package/src/api/admin/bold/payment-stream/route.ts +161 -0
  107. package/src/api/admin/bold/pos-push/route.ts +59 -0
  108. package/src/api/admin/bold/refund/route.ts +51 -0
  109. package/src/api/admin/bold/terminals/route.ts +26 -0
  110. package/src/api/admin/plugin/route.ts +14 -0
  111. package/src/api/hooks/payment/bold/route.ts +156 -0
  112. package/src/api/store/plugin/route.ts +5 -0
  113. package/src/hooks/index.ts +9 -0
  114. package/src/hooks/use-bold-checkout-handler.ts +172 -0
  115. package/src/hooks/use-bold-payment-methods.ts +36 -0
  116. package/src/hooks/use-bold-payment-status-stream.ts +55 -0
  117. package/src/hooks/use-bold-refund.ts +33 -0
  118. package/src/hooks/use-bold-terminals.ts +22 -0
  119. package/src/hooks/use-create-bold-button.ts +34 -0
  120. package/src/hooks/use-create-bold-link.ts +33 -0
  121. package/src/hooks/use-create-bold-qr.ts +33 -0
  122. package/src/hooks/use-create-bold-terminal.ts +37 -0
  123. package/src/index.ts +31 -0
  124. package/src/lib/error-utils.ts +29 -0
  125. package/src/lib/get-active-providers.ts +52 -0
  126. package/src/lib/get-provider-options.ts +54 -0
  127. package/src/lib/index.ts +3 -0
  128. package/src/lib/session-helpers.ts +16 -0
  129. package/src/providers/README.md +30 -0
  130. package/src/providers/bold-button/index.ts +244 -0
  131. package/src/providers/bold-link/index.ts +350 -0
  132. package/src/providers/bold-online/index.ts +254 -0
  133. package/src/providers/bold-terminal/index.ts +258 -0
  134. package/src/rbac.ts +72 -0
  135. package/src/sdk/client.ts +157 -0
  136. package/src/sdk/query-keys.ts +13 -0
  137. package/src/services/bold-client.ts +470 -0
  138. package/src/services/integrity.ts +74 -0
  139. package/src/types/constants.ts +63 -0
  140. package/src/types/enums.ts +13 -0
  141. package/src/types/errors.ts +88 -0
  142. package/src/types/index.ts +517 -0
  143. package/src/workflows/create-bold-payment-link.ts +16 -0
  144. package/src/workflows/create-bold-refund.ts +16 -0
  145. package/src/workflows/get-bold-payment-methods.ts +13 -0
  146. package/src/workflows/get-integration-api-payment-methods.ts +13 -0
  147. package/src/workflows/get-payment-link-methods.ts +13 -0
  148. package/src/workflows/get-terminals.ts +10 -0
  149. package/src/workflows/index.ts +6 -0
  150. package/src/workflows/steps/create-bold-link.ts +74 -0
  151. package/src/workflows/steps/get-bold-payment-methods.ts +21 -0
  152. package/src/workflows/steps/get-payment-link-methods.ts +19 -0
  153. package/src/workflows/steps/get-terminals.ts +20 -0
  154. package/src/workflows/steps/refund-bold-payment.ts +28 -0
  155. package/tsconfig.json +41 -0
@@ -0,0 +1,773 @@
1
+ import assert from "node:assert/strict"
2
+ import crypto from "node:crypto"
3
+ import { EventEmitter } from "node:events"
4
+ import { after, before, beforeEach, describe, it } from "node:test"
5
+
6
+ import { GET as getPaymentStatusRoute } from "../api/admin/bold/payment-status/route"
7
+ import { GET as streamPaymentRoute } from "../api/admin/bold/payment-stream/route"
8
+ import { POST as createButtonRoute } from "../api/admin/bold/payment-button/route"
9
+ import { POST as createLinkRoute } from "../api/admin/bold/payment-link/route"
10
+ import { POST as createQrRoute } from "../api/admin/bold/payment-qr/route"
11
+ import { POST as posPushRoute } from "../api/admin/bold/pos-push/route"
12
+ import { POST as refundRoute } from "../api/admin/bold/refund/route"
13
+ import { GET as getTerminalsRoute } from "../api/admin/bold/terminals/route"
14
+ import { POST as webhookRoute } from "../api/hooks/payment/bold/route"
15
+ import { BoldButtonPaymentProviderService } from "../providers/bold-button/index"
16
+ import { BoldLinkPaymentProviderService } from "../providers/bold-link/index"
17
+ import { BoldOnlinePaymentProviderService } from "../providers/bold-online/index"
18
+ import { BoldTerminalPaymentProviderService } from "../providers/bold-terminal/index"
19
+ import { BoldHttpClient } from "../services/bold-client"
20
+ import { BoldIntegrityService } from "../services/integrity"
21
+ import { EMedusaFormatBoldPaymentProvider } from "../types/enums"
22
+ import { BoldQaEmulator, signBoldWebhook } from "./bold-qa-emulator"
23
+
24
+ interface MockSession {
25
+ id: string
26
+ payment_collection_id: string
27
+ provider_id: string
28
+ amount: number
29
+ currency_code: string
30
+ status: string
31
+ data: Record<string, unknown>
32
+ }
33
+
34
+ interface MockPayment {
35
+ id: string
36
+ session_id: string
37
+ provider_id: string
38
+ amount: number
39
+ currency_code: string
40
+ data: Record<string, unknown>
41
+ captured_at?: string
42
+ }
43
+
44
+ function createSilentLogger() {
45
+ return {
46
+ debug: () => {},
47
+ info: () => {},
48
+ warn: () => {},
49
+ error: () => {},
50
+ } as any
51
+ }
52
+
53
+ function createMockRes() {
54
+ const headers: Record<string, string> = {}
55
+ const chunks: string[] = []
56
+ let statusCode = 200
57
+ let jsonBody: unknown = null
58
+ let ended = false
59
+ let endResolve: (() => void) | null = null
60
+ const done = new Promise<void>((resolve) => {
61
+ endResolve = resolve
62
+ })
63
+
64
+ const res = {
65
+ setHeader(k: string, v: string) {
66
+ headers[k.toLowerCase()] = v
67
+ },
68
+ status(code: number) {
69
+ statusCode = code
70
+ return res
71
+ },
72
+ json(payload: unknown) {
73
+ jsonBody = payload
74
+ ended = true
75
+ endResolve?.()
76
+ return res
77
+ },
78
+ write(chunk: string) {
79
+ chunks.push(chunk)
80
+ return true
81
+ },
82
+ end() {
83
+ ended = true
84
+ endResolve?.()
85
+ },
86
+ get statusCode() {
87
+ return statusCode
88
+ },
89
+ get jsonBody() {
90
+ return jsonBody
91
+ },
92
+ get headers() {
93
+ return headers
94
+ },
95
+ get chunks() {
96
+ return chunks
97
+ },
98
+ get ended() {
99
+ return ended
100
+ },
101
+ done,
102
+ }
103
+ return res
104
+ }
105
+
106
+ function createMedusaTestHarness(emulator: BoldQaEmulator) {
107
+ const logger = createSilentLogger()
108
+ const options = emulator.clientOptions
109
+
110
+ const linkProvider = new BoldLinkPaymentProviderService({ logger }, options)
111
+ const onlineProvider = new BoldOnlinePaymentProviderService(
112
+ { logger },
113
+ options
114
+ )
115
+ const buttonProvider = new BoldButtonPaymentProviderService(
116
+ { logger },
117
+ options
118
+ )
119
+ const terminalProvider = new BoldTerminalPaymentProviderService(
120
+ { logger },
121
+ options
122
+ )
123
+
124
+ const providersById = new Map<string, any>([
125
+ [EMedusaFormatBoldPaymentProvider.LINK, linkProvider],
126
+ [EMedusaFormatBoldPaymentProvider.ONLINE, onlineProvider],
127
+ [EMedusaFormatBoldPaymentProvider.BUTTON, buttonProvider],
128
+ [EMedusaFormatBoldPaymentProvider.TERMINAL, terminalProvider],
129
+ ])
130
+
131
+ const collections = new Map<
132
+ string,
133
+ { id: string; amount: number; currency_code: string }
134
+ >()
135
+ const sessions = new Map<string, MockSession>()
136
+ const payments = new Map<string, MockPayment>()
137
+ let seq = 1
138
+
139
+ const paymentModule = {
140
+ async createPaymentCollections(input: {
141
+ amount: number
142
+ currency_code: string
143
+ }) {
144
+ const col = { id: `pay_col_${seq++}`, ...input }
145
+ collections.set(col.id, col)
146
+ return col
147
+ },
148
+ async retrievePaymentCollection(id: string) {
149
+ return collections.get(id)
150
+ },
151
+ async deletePaymentCollections(ids: string[]) {
152
+ for (const id of ids) collections.delete(id)
153
+ },
154
+ getPaymentProvider(providerId: string) {
155
+ return providersById.get(providerId)
156
+ },
157
+ async createPaymentSession(
158
+ collectionId: string,
159
+ input: {
160
+ provider_id: string
161
+ amount: number
162
+ currency_code: string
163
+ data: Record<string, unknown>
164
+ }
165
+ ) {
166
+ const provider = providersById.get(input.provider_id)
167
+ if (!provider) {
168
+ throw new Error(`Unknown provider_id: ${input.provider_id}`)
169
+ }
170
+ const initOut = await provider.initiatePayment({
171
+ amount: input.amount,
172
+ currency_code: input.currency_code,
173
+ data: input.data,
174
+ })
175
+ const session: MockSession = {
176
+ id: `payses_${seq++}`,
177
+ payment_collection_id: collectionId,
178
+ provider_id: input.provider_id,
179
+ amount: input.amount,
180
+ currency_code: input.currency_code,
181
+ status: "pending",
182
+ data: initOut.data as Record<string, unknown>,
183
+ }
184
+ sessions.set(session.id, session)
185
+ return session
186
+ },
187
+ async listPaymentSessions(filter: { status?: string } = {}) {
188
+ const all = [...sessions.values()]
189
+ return filter.status ? all.filter((s) => s.status === filter.status) : all
190
+ },
191
+ async retrievePaymentSession(id: string) {
192
+ const s = sessions.get(id)
193
+ if (!s) throw new Error(`Session ${id} not found`)
194
+ return s
195
+ },
196
+ async authorizePaymentSession(id: string) {
197
+ const session = sessions.get(id)
198
+ if (!session) throw new Error(`Session ${id} not found`)
199
+ const provider = providersById.get(session.provider_id)
200
+ const auth = await provider.authorizePayment({ data: session.data })
201
+ session.status = auth.status
202
+ session.data = auth.data as Record<string, unknown>
203
+ const payment: MockPayment = {
204
+ id: `pay_${seq++}`,
205
+ session_id: session.id,
206
+ provider_id: session.provider_id,
207
+ amount: session.amount,
208
+ currency_code: session.currency_code,
209
+ data: { ...session.data },
210
+ }
211
+ payments.set(payment.id, payment)
212
+ return payment
213
+ },
214
+ async capturePayment(input: { payment_id: string }) {
215
+ const payment = payments.get(input.payment_id)
216
+ if (!payment) throw new Error(`Payment ${input.payment_id} not found`)
217
+ const provider = providersById.get(payment.provider_id)
218
+ const captured = await provider.capturePayment({ data: payment.data })
219
+ payment.data = captured.data as Record<string, unknown>
220
+ payment.captured_at = new Date().toISOString()
221
+ const session = sessions.get(payment.session_id)
222
+ if (session) session.status = "captured"
223
+ return payment
224
+ },
225
+ async refundPayment(input: {
226
+ payment_id: string
227
+ amount: number
228
+ note?: string
229
+ }) {
230
+ const payment = payments.get(input.payment_id)
231
+ if (!payment) throw new Error(`Payment ${input.payment_id} not found`)
232
+ const provider = providersById.get(payment.provider_id)
233
+ const refunded = await provider.refundPayment({
234
+ data: payment.data,
235
+ amount: input.amount,
236
+ })
237
+ payment.data = refunded.data as Record<string, unknown>
238
+ return {
239
+ id: refunded.data.refund_id,
240
+ amount: input.amount,
241
+ note: input.note,
242
+ }
243
+ },
244
+ }
245
+
246
+ const scope = {
247
+ resolve(key: string) {
248
+ if (key === "logger") return logger
249
+ if (key === "payment") return paymentModule
250
+ if (key === "remoteQuery") return async () => []
251
+ if (key === "configModule") {
252
+ return {
253
+ modules: {
254
+ payment: {
255
+ options: {
256
+ providers: [
257
+ { id: "pp_bold-link_bold", resolve: "bold-link", options },
258
+ ],
259
+ },
260
+ },
261
+ },
262
+ }
263
+ }
264
+ if (providersById.has(key)) return providersById.get(key)
265
+ throw new Error(`Unregistered container dependency: ${key}`)
266
+ },
267
+ }
268
+
269
+ return {
270
+ scope,
271
+ paymentModule,
272
+ providers: {
273
+ linkProvider,
274
+ onlineProvider,
275
+ buttonProvider,
276
+ terminalProvider,
277
+ },
278
+ sessions,
279
+ payments,
280
+ }
281
+ }
282
+
283
+ describe("@vicacha-devs/medusa-payment-bold — Automated 4-Channel Use-Case Suite", () => {
284
+ const integrationApiKey = `int_qa_${crypto.randomBytes(8).toString("hex")}`
285
+ const buttonApiKey = `btn_qa_${crypto.randomBytes(8).toString("hex")}`
286
+ const webhookSecret = `whsec_qa_${crypto.randomBytes(16).toString("hex")}`
287
+
288
+ const emulator = new BoldQaEmulator({
289
+ integrationApiKey,
290
+ buttonApiKey,
291
+ webhookSecret,
292
+ })
293
+
294
+ before(async () => {
295
+ await emulator.start(0)
296
+ })
297
+
298
+ after(async () => {
299
+ await emulator.stop()
300
+ })
301
+
302
+ beforeEach(() => {
303
+ emulator.reset()
304
+ })
305
+
306
+ it("Use Case 1 (Payment Link): validates input, creates link with VAT, authorizes via signed webhook & processes partial refund", async () => {
307
+ const harness = createMedusaTestHarness(emulator)
308
+
309
+ // 1a. Reject invalid payload via Zod
310
+ const badRes = createMockRes()
311
+ await createLinkRoute(
312
+ {
313
+ scope: harness.scope,
314
+ body: {
315
+ amount: -500,
316
+ currency: "COP",
317
+ reference: "ORD-BAD",
318
+ description: "Invalid",
319
+ email: "not-an-email",
320
+ callbackUrl: "javascript:alert(1)",
321
+ },
322
+ } as any,
323
+ badRes as any
324
+ )
325
+ assert.equal(badRes.statusCode, 400)
326
+
327
+ // 1b. Create valid Payment Link
328
+ const linkRes = createMockRes()
329
+ await createLinkRoute(
330
+ {
331
+ scope: harness.scope,
332
+ body: {
333
+ amount: 119000,
334
+ vatAmount: 19000,
335
+ currency: "cop",
336
+ reference: "ORD-LINK-1001",
337
+ description: "Bogota Tour Package",
338
+ email: "traveler@example.com",
339
+ callbackUrl: "https://vicachatravels.com/checkout/return",
340
+ },
341
+ } as any,
342
+ linkRes as any
343
+ )
344
+ assert.equal(linkRes.statusCode, 200)
345
+ const created = linkRes.jsonBody as { paymentSession: MockSession }
346
+ assert.equal(created.paymentSession.status, "pending")
347
+ assert.ok(
348
+ String(created.paymentSession.data.payment_url).includes(
349
+ "/checkout/LNK_QA_"
350
+ )
351
+ )
352
+
353
+ // Verify exact Bold HTTP payload sent over TCP
354
+ const boldReq = emulator.requests.find((r) => r.path === "/online/link/v1")
355
+ assert.ok(boldReq, "Bold /online/link/v1 was called")
356
+ assert.equal(boldReq.authorization, `x-api-key ${integrationApiKey}`)
357
+ const sentAmount = boldReq.body?.amount as {
358
+ currency: string
359
+ total_amount: number
360
+ taxes: Array<{ type: string; base: number; value: number }>
361
+ }
362
+ assert.equal(sentAmount.currency, "COP")
363
+ assert.equal(sentAmount.total_amount, 119000)
364
+ assert.deepEqual(sentAmount.taxes, [
365
+ { type: "VAT", base: 100000, value: 19000 },
366
+ ])
367
+
368
+ // 1c. Simulate customer completing link + fire real HMAC-SHA256 webhook
369
+ const webhook = emulator.simulatePaymentOutcome("ORD-LINK-1001", "APPROVED")
370
+ const hookRes = createMockRes()
371
+ await webhookRoute(
372
+ {
373
+ scope: harness.scope,
374
+ headers: webhook.headers,
375
+ body: webhook.payload,
376
+ rawBody: webhook.rawBody,
377
+ } as any,
378
+ hookRes as any
379
+ )
380
+ assert.equal(hookRes.statusCode, 200)
381
+ assert.equal(created.paymentSession.status, "authorized")
382
+
383
+ // 1d. Execute partial refund via Admin Refund route & verify over-refund rejection
384
+ const payment = [...harness.payments.values()][0]
385
+ assert.ok(payment, "Medusa payment record created on authorization")
386
+ const refundRes = createMockRes()
387
+ await refundRoute(
388
+ {
389
+ scope: harness.scope,
390
+ body: {
391
+ payment_id: payment.id,
392
+ amount: 50000,
393
+ note: "Partial refund QA",
394
+ },
395
+ } as any,
396
+ refundRes as any
397
+ )
398
+ assert.equal(refundRes.statusCode, 200)
399
+
400
+ const overRefundRes = createMockRes()
401
+ await refundRoute(
402
+ {
403
+ scope: harness.scope,
404
+ body: {
405
+ payment_id: payment.id,
406
+ amount: 90000,
407
+ note: "Exceeds balance",
408
+ },
409
+ } as any,
410
+ overRefundRes as any
411
+ )
412
+ assert.equal(overRefundRes.statusCode, 500)
413
+ })
414
+
415
+ it("Use Case 2 (QR Code): creates Bold QR intent, returns base64 QR payload, handles approval & expiration", async () => {
416
+ const harness = createMedusaTestHarness(emulator)
417
+ const col = await harness.paymentModule.createPaymentCollections({
418
+ amount: 85000,
419
+ currency_code: "cop",
420
+ })
421
+
422
+ const qrRes = createMockRes()
423
+ await createQrRoute(
424
+ {
425
+ scope: harness.scope,
426
+ body: {
427
+ paymentCollectionId: col.id,
428
+ amount: 85000,
429
+ currency: "COP",
430
+ reference: "ORD-QR-2001",
431
+ description: "Airport Transfer QR",
432
+ qrFormat: "BOLD_BASE64",
433
+ email: "guest@example.com",
434
+ },
435
+ } as any,
436
+ qrRes as any
437
+ )
438
+ assert.equal(qrRes.statusCode, 200)
439
+ const body = qrRes.jsonBody as {
440
+ qr_payload: string
441
+ paymentSession: MockSession
442
+ }
443
+ assert.ok(body.qr_payload.length > 10, "returns non-empty QR payload")
444
+ assert.equal(
445
+ body.paymentSession.provider_id,
446
+ EMedusaFormatBoldPaymentProvider.ONLINE
447
+ )
448
+
449
+ const intentReq = emulator.requests.find(
450
+ (r) => r.path === "/v1/payment-intent"
451
+ )
452
+ assert.ok(intentReq, "Bold /v1/payment-intent was called")
453
+ assert.equal(intentReq.authorization, `x-api-key ${buttonApiKey}`)
454
+ assert.deepEqual(intentReq.body?.payment_method, {
455
+ name: "QR",
456
+ qr_format: "BOLD_BASE64",
457
+ })
458
+
459
+ // Simulate customer scanning & paying QR -> status transitions to AUTHORIZED
460
+ emulator.simulatePaymentOutcome("ORD-QR-2001", "APPROVED")
461
+ const statusOut = await harness.providers.onlineProvider.getPaymentStatus({
462
+ data: body.paymentSession.data,
463
+ })
464
+ assert.equal(statusOut.status, "authorized")
465
+
466
+ // Test expired QR path
467
+ const qrExpiredRes = createMockRes()
468
+ await createQrRoute(
469
+ {
470
+ scope: harness.scope,
471
+ body: {
472
+ paymentCollectionId: col.id,
473
+ amount: 40000,
474
+ currency: "COP",
475
+ reference: "ORD-QR-2002",
476
+ qrFormat: "TEXT",
477
+ },
478
+ } as any,
479
+ qrExpiredRes as any
480
+ )
481
+ const expiredBody = qrExpiredRes.jsonBody as {
482
+ qr_payload: string
483
+ paymentSession: MockSession
484
+ }
485
+ assert.ok(
486
+ expiredBody.qr_payload.startsWith("000201"),
487
+ "TEXT EMVCo QR payload returned"
488
+ )
489
+ emulator.simulatePaymentOutcome("ORD-QR-2002", "EXPIRED")
490
+ const expiredStatus =
491
+ await harness.providers.onlineProvider.getPaymentStatus({
492
+ data: expiredBody.paymentSession.data,
493
+ })
494
+ assert.equal(expiredStatus.status, "canceled")
495
+ })
496
+
497
+ it("Use Case 3 (Checkout Button): generates deterministic SHA-256 integrity hash, authorizes via voucher & refunds", async () => {
498
+ const harness = createMedusaTestHarness(emulator)
499
+ const col = await harness.paymentModule.createPaymentCollections({
500
+ amount: 250000,
501
+ currency_code: "cop",
502
+ })
503
+
504
+ const btnRes = createMockRes()
505
+ await createButtonRoute(
506
+ {
507
+ scope: harness.scope,
508
+ body: {
509
+ paymentCollectionId: col.id,
510
+ amount: 250000,
511
+ currency: "COP",
512
+ reference: "ORD-BTN-3001",
513
+ description: "Hotel Booking Button",
514
+ },
515
+ } as any,
516
+ btnRes as any
517
+ )
518
+ assert.equal(btnRes.statusCode, 200)
519
+ const { paymentSession } = btnRes.jsonBody as {
520
+ paymentSession: MockSession
521
+ }
522
+ const expectedHash = BoldIntegrityService.generateButtonHash(
523
+ "ORD-BTN-3001",
524
+ 250000,
525
+ "COP",
526
+ webhookSecret
527
+ )
528
+ assert.equal(paymentSession.data.hash, expectedHash)
529
+ assert.equal(paymentSession.data.integrity_signature, expectedHash)
530
+
531
+ // Simulate storefront Bold Button completion -> voucher lookup authorizes session
532
+ emulator.seedButtonOrder("ORD-BTN-3001", 250000, "COP")
533
+ emulator.simulatePaymentOutcome("ORD-BTN-3001", "APPROVED")
534
+
535
+ const authorized = await harness.paymentModule.authorizePaymentSession(
536
+ paymentSession.id
537
+ )
538
+ assert.equal(paymentSession.status, "authorized")
539
+ assert.ok(authorized.data.transaction_id)
540
+
541
+ const refunded = await harness.paymentModule.refundPayment({
542
+ payment_id: authorized.id,
543
+ amount: 250000,
544
+ note: "Full button refund",
545
+ })
546
+ assert.ok(refunded.id)
547
+ })
548
+
549
+ it("Use Case 4 (POS Terminal): lists dataphones, dispatches checkout, handles approved/declined tap & streams SSE", async () => {
550
+ const harness = createMedusaTestHarness(emulator)
551
+
552
+ // 4a. List bound physical terminals
553
+ const termRes = createMockRes()
554
+ await getTerminalsRoute({ scope: harness.scope } as any, termRes as any)
555
+ assert.equal(termRes.statusCode, 200)
556
+ const { terminals } = termRes.jsonBody as {
557
+ terminals: Array<{ terminal_serial: string; terminal_model: string }>
558
+ }
559
+ assert.equal(terminals.length, 2)
560
+ assert.equal(terminals[0].terminal_serial, "N86-QA-001")
561
+
562
+ // 4b. Dispatch POS checkout to first dataphone
563
+ const col = await harness.paymentModule.createPaymentCollections({
564
+ amount: 175000,
565
+ currency_code: "cop",
566
+ })
567
+ const pushRes = createMockRes()
568
+ await posPushRoute(
569
+ {
570
+ scope: harness.scope,
571
+ body: {
572
+ paymentCollectionId: col.id,
573
+ amount: 175000,
574
+ vatAmount: 27941,
575
+ currency: "COP",
576
+ reference: "ORD-POS-4001",
577
+ terminalModel: terminals[0].terminal_model,
578
+ terminalSerial: terminals[0].terminal_serial,
579
+ userEmail: "cashier@vicachatravels.com",
580
+ description: "Desk Ticket Purchase",
581
+ },
582
+ } as any,
583
+ pushRes as any
584
+ )
585
+ assert.equal(pushRes.statusCode, 200)
586
+ const { paymentSession } = pushRes.jsonBody as {
587
+ paymentSession: MockSession
588
+ }
589
+ assert.ok(paymentSession.data.terminal_checkout_id)
590
+
591
+ const posReq = emulator.requests.find(
592
+ (r) => r.path === "/payments/app-checkout"
593
+ )
594
+ assert.ok(posReq, "Bold /payments/app-checkout was called")
595
+ assert.equal(posReq.body?.payment_method, "POS")
596
+ assert.equal(posReq.body?.terminal_serial, "N86-QA-001")
597
+
598
+ // 4c. Check GET /admin/bold/payment-status while pending
599
+ const statusRes = createMockRes()
600
+ await getPaymentStatusRoute(
601
+ {
602
+ scope: harness.scope,
603
+ query: { paymentSessionId: paymentSession.id },
604
+ } as any,
605
+ statusRes as any
606
+ )
607
+ assert.equal(statusRes.statusCode, 200)
608
+ assert.equal((statusRes.jsonBody as { status: string }).status, "pending")
609
+
610
+ // 4d. Simulate customer card tap APPROVED -> verify SSE stream auto-captures & closes
611
+ emulator.simulatePaymentOutcome("ORD-POS-4001", "APPROVED")
612
+ const sseReq = new EventEmitter() as any
613
+ sseReq.scope = harness.scope
614
+ sseReq.query = { paymentSessionId: paymentSession.id }
615
+ const sseRes = createMockRes()
616
+ await streamPaymentRoute(sseReq, sseRes as any)
617
+ await sseRes.done
618
+ assert.equal(sseRes.headers["content-type"], "text/event-stream")
619
+ assert.ok(sseRes.chunks.some((c) => c.includes('"status":"captured"')))
620
+ assert.equal(paymentSession.status, "captured")
621
+
622
+ // 4e. Simulate declined card on virtual dataphone
623
+ const pushDeclineRes = createMockRes()
624
+ await posPushRoute(
625
+ {
626
+ scope: harness.scope,
627
+ body: {
628
+ paymentCollectionId: col.id,
629
+ amount: 50000,
630
+ currency: "COP",
631
+ reference: "ORD-POS-4002",
632
+ terminalModel: "SMART_PRO",
633
+ terminalSerial: "SMART-QA-002",
634
+ userEmail: "cashier@vicachatravels.com",
635
+ },
636
+ } as any,
637
+ pushDeclineRes as any
638
+ )
639
+ const declinedSession = (
640
+ pushDeclineRes.jsonBody as { paymentSession: MockSession }
641
+ ).paymentSession
642
+ emulator.simulatePaymentOutcome("ORD-POS-4002", "REJECTED")
643
+ const declineAuth =
644
+ await harness.providers.terminalProvider.authorizePayment({
645
+ data: declinedSession.data,
646
+ })
647
+ assert.equal(declineAuth.status, "canceled")
648
+
649
+ // 4f. Reject unknown/unbound terminal serial
650
+ const badTermRes = createMockRes()
651
+ await posPushRoute(
652
+ {
653
+ scope: harness.scope,
654
+ body: {
655
+ paymentCollectionId: col.id,
656
+ amount: 50000,
657
+ currency: "COP",
658
+ reference: "ORD-POS-4003",
659
+ terminalModel: "N86",
660
+ terminalSerial: "UNKNOWN-999",
661
+ userEmail: "cashier@vicachatravels.com",
662
+ },
663
+ } as any,
664
+ badTermRes as any
665
+ )
666
+ assert.equal(badTermRes.statusCode, 500)
667
+ })
668
+
669
+ it("Security & Fault Injection: rejects bad HMAC, tampered amount/currency, unsafe HTTP base URL & maps Bold 401/500", async () => {
670
+ const harness = createMedusaTestHarness(emulator)
671
+
672
+ // Create a pending link session for 100,000 COP
673
+ const linkRes = createMockRes()
674
+ await createLinkRoute(
675
+ {
676
+ scope: harness.scope,
677
+ body: {
678
+ amount: 100000,
679
+ currency: "COP",
680
+ reference: "ORD-SEC-5001",
681
+ description: "Security Test",
682
+ email: "sec@example.com",
683
+ callbackUrl: "https://vicachatravels.com/return",
684
+ },
685
+ } as any,
686
+ linkRes as any
687
+ )
688
+ const { paymentSession } = linkRes.jsonBody as {
689
+ paymentSession: MockSession
690
+ }
691
+
692
+ // 5a. Missing signature headers -> 401
693
+ const noSigRes = createMockRes()
694
+ await webhookRoute(
695
+ { scope: harness.scope, headers: {}, body: {}, rawBody: "{}" } as any,
696
+ noSigRes as any
697
+ )
698
+ assert.equal(noSigRes.statusCode, 401)
699
+
700
+ // 5b. Wrong signing secret -> 401
701
+ const forged = signBoldWebhook(
702
+ {
703
+ event: "sale.successful",
704
+ data: {
705
+ reference: "ORD-SEC-5001",
706
+ status: "APPROVED",
707
+ amount: 100000,
708
+ currency: "COP",
709
+ },
710
+ },
711
+ "wrong-secret-key"
712
+ )
713
+ const badSigRes = createMockRes()
714
+ await webhookRoute(
715
+ {
716
+ scope: harness.scope,
717
+ headers: forged.headers,
718
+ body: forged.payload,
719
+ rawBody: forged.rawBody,
720
+ } as any,
721
+ badSigRes as any
722
+ )
723
+ assert.equal(badSigRes.statusCode, 401)
724
+ assert.equal(paymentSession.status, "pending")
725
+
726
+ // 5c. Valid signature but tampered amount (1000 instead of 100000) -> NOT authorized
727
+ const tampered = emulator.simulatePaymentOutcome(
728
+ "ORD-SEC-5001",
729
+ "APPROVED",
730
+ {
731
+ amount: 1000,
732
+ }
733
+ )
734
+ const tamperRes = createMockRes()
735
+ await webhookRoute(
736
+ {
737
+ scope: harness.scope,
738
+ headers: tampered.headers,
739
+ body: tampered.payload,
740
+ rawBody: tampered.rawBody,
741
+ } as any,
742
+ tamperRes as any
743
+ )
744
+ assert.equal(tamperRes.statusCode, 200)
745
+ assert.equal(
746
+ paymentSession.status,
747
+ "pending",
748
+ "tampered amount must NOT authorize session"
749
+ )
750
+
751
+ // 5d. SSRF guard: reject non-HTTPS non-loopback custom base URL
752
+ assert.throws(() => {
753
+ new BoldHttpClient(
754
+ {
755
+ buttonApiKey: "k",
756
+ integrationsUrl: "http://169.254.169.254",
757
+ },
758
+ createSilentLogger()
759
+ )
760
+ }, /Unsafe Bold base URL/)
761
+
762
+ // 5e. Fault injection: Bold 401 maps to MedusaError UNAUTHORIZED
763
+ emulator.injectFault("/payments/binded-terminals", 401, "Expired API key")
764
+ const client = new BoldHttpClient(
765
+ emulator.clientOptions,
766
+ createSilentLogger()
767
+ )
768
+ await assert.rejects(
769
+ () => client.getTerminals(),
770
+ (err: any) => err.type === "unauthorized"
771
+ )
772
+ })
773
+ })