@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,334 @@
1
+ export const Modules = {
2
+ PAYMENT: "payment",
3
+ ORDER: "order",
4
+ CART: "cart",
5
+ PRODUCT: "product",
6
+ EVENT_BUS: "event_bus",
7
+ }
8
+
9
+ // Type-only symbol stubs for TS files importing Medusa interfaces without `import type`
10
+ export const IPaymentModuleService = undefined
11
+ export const MedusaRequest = undefined
12
+ export const MedusaResponse = undefined
13
+ export const AuthenticatedMedusaRequest = undefined
14
+ export const Logger = undefined
15
+ export const ConfigModule = undefined
16
+ export const MedusaContainer = undefined
17
+ export const InitiatePaymentInput = undefined
18
+ export const InitiatePaymentOutput = undefined
19
+ export const AuthorizePaymentInput = undefined
20
+ export const AuthorizePaymentOutput = undefined
21
+ export const CapturePaymentInput = undefined
22
+ export const CapturePaymentOutput = undefined
23
+ export const CancelPaymentInput = undefined
24
+ export const CancelPaymentOutput = undefined
25
+ export const RefundPaymentInput = undefined
26
+ export const RefundPaymentOutput = undefined
27
+ export const DeletePaymentInput = undefined
28
+ export const DeletePaymentOutput = undefined
29
+ export const UpdatePaymentInput = undefined
30
+ export const UpdatePaymentOutput = undefined
31
+ export const GetPaymentStatusInput = undefined
32
+ export const GetPaymentStatusOutput = undefined
33
+ export const ProviderWebhookPayload = undefined
34
+ export const WebhookActionResult = undefined
35
+
36
+ export const ContainerRegistrationKeys = {
37
+ LOGGER: "logger",
38
+ CONFIG_MODULE: "configModule",
39
+ REMOTE_QUERY: "remoteQuery",
40
+ }
41
+
42
+ export const PaymentSessionStatus = {
43
+ AUTHORIZED: "authorized",
44
+ CAPTURED: "captured",
45
+ PENDING: "pending",
46
+ REQUIRES_MORE: "requires_more",
47
+ ERROR: "error",
48
+ CANCELED: "canceled",
49
+ }
50
+
51
+ export const PaymentActions = {
52
+ AUTHORIZED: "authorized",
53
+ SUCCESSFUL: "captured",
54
+ FAILED: "failed",
55
+ CANCELED: "canceled",
56
+ NOT_SUPPORTED: "not_supported",
57
+ }
58
+
59
+ export class AbstractPaymentProvider {
60
+ constructor(container, options) {
61
+ this.__container = container
62
+ this.__options = options
63
+ }
64
+ }
65
+
66
+ export class MedusaError extends Error {
67
+ static Types = {
68
+ DB_ERROR: "database_error",
69
+ DUPLICATE_ERROR: "duplicate_error",
70
+ INVALID_ARGUMENT: "invalid_argument",
71
+ INVALID_DATA: "invalid_data",
72
+ UNAUTHORIZED: "unauthorized",
73
+ NOT_FOUND: "not_found",
74
+ NOT_ALLOWED: "not_allowed",
75
+ UNEXPECTED_STATE: "unexpected_state",
76
+ CONFLICT: "conflict",
77
+ }
78
+
79
+ constructor(type, message, code) {
80
+ super(message)
81
+ this.type = type
82
+ this.code = code
83
+ this.name = "MedusaError"
84
+ }
85
+ }
86
+
87
+ export class StepResponse {
88
+ constructor(output, compensateInput) {
89
+ this.output = output
90
+ this.compensateInput = compensateInput
91
+ }
92
+ }
93
+
94
+ export class WorkflowResponse {
95
+ constructor(output) {
96
+ this.output = output
97
+ }
98
+ }
99
+
100
+ export function createStep(name, invokeFn, compensateFn) {
101
+ const stepFn = (input) => ({
102
+ __stepName: name,
103
+ input,
104
+ invokeFn,
105
+ compensateFn,
106
+ })
107
+ stepFn.__stepName = name
108
+ stepFn.invoke = invokeFn
109
+ stepFn.compensate = compensateFn
110
+ return stepFn
111
+ }
112
+
113
+ export function createWorkflow(name, composerFn) {
114
+ const wf = (container) => ({
115
+ async run({ input } = {}) {
116
+ const composed = composerFn(input)
117
+ const stepDescriptor =
118
+ composed instanceof WorkflowResponse ? composed.output : composed
119
+ if (stepDescriptor && typeof stepDescriptor.invokeFn === "function") {
120
+ const stepRes = await stepDescriptor.invokeFn(stepDescriptor.input, {
121
+ container,
122
+ })
123
+ const result =
124
+ stepRes instanceof StepResponse ? stepRes.output : stepRes
125
+ return {
126
+ result,
127
+ compensate: async () => {
128
+ if (typeof stepDescriptor.compensateFn === "function") {
129
+ await stepDescriptor.compensateFn(stepRes?.compensateInput, {
130
+ container,
131
+ })
132
+ }
133
+ },
134
+ }
135
+ }
136
+ return { result: stepDescriptor }
137
+ },
138
+ })
139
+ wf.getName = () => name
140
+ return wf
141
+ }
142
+
143
+ export const createPaymentSessionsWorkflow = (container) => ({
144
+ async run({ input }) {
145
+ const paymentModule = container.resolve(Modules.PAYMENT)
146
+ const collection = await paymentModule.retrievePaymentCollection(
147
+ input.payment_collection_id
148
+ )
149
+ const session = await paymentModule.createPaymentSession(
150
+ input.payment_collection_id,
151
+ {
152
+ provider_id: input.provider_id,
153
+ amount: collection?.amount ?? input.amount ?? 0,
154
+ currency_code: collection?.currency_code ?? "cop",
155
+ data: input.data,
156
+ }
157
+ )
158
+ return { result: session }
159
+ },
160
+ })
161
+
162
+ export const capturePaymentWorkflow = (container) => ({
163
+ async run({ input }) {
164
+ const paymentModule = container.resolve(Modules.PAYMENT)
165
+ const payment = await paymentModule.capturePayment({
166
+ payment_id: input.payment_id,
167
+ })
168
+ return { result: payment }
169
+ },
170
+ })
171
+
172
+ export const refundPaymentWorkflow = (container) => ({
173
+ async run({ input }) {
174
+ const paymentModule = container.resolve(Modules.PAYMENT)
175
+ const refund = await paymentModule.refundPayment({
176
+ payment_id: input.payment_id,
177
+ amount: input.amount,
178
+ note: input.note,
179
+ })
180
+ return { result: refund }
181
+ },
182
+ })
183
+
184
+ // Real lightweight validating Zod micro-shim so negative validation tests truly enforce schemas
185
+ function makeValidator(baseCheck) {
186
+ const checks = []
187
+ let isOptional = false
188
+ let hasDefault = false
189
+ let defaultVal
190
+ let transformFn = null
191
+
192
+ const schema = {
193
+ min(n, msg) {
194
+ checks.push((v) =>
195
+ typeof v === "string"
196
+ ? v.length >= n
197
+ ? null
198
+ : msg || `Must be at least ${n} chars`
199
+ : v >= n
200
+ ? null
201
+ : msg || `Must be >= ${n}`
202
+ )
203
+ return schema
204
+ },
205
+ max(n, msg) {
206
+ checks.push((v) =>
207
+ typeof v === "string"
208
+ ? v.length <= n
209
+ ? null
210
+ : msg || `Must be at most ${n} chars`
211
+ : v <= n
212
+ ? null
213
+ : msg || `Must be <= ${n}`
214
+ )
215
+ return schema
216
+ },
217
+ positive(msg) {
218
+ checks.push((v) => (v > 0 ? null : msg || "Must be positive"))
219
+ return schema
220
+ },
221
+ finite(msg) {
222
+ checks.push((v) => (Number.isFinite(v) ? null : msg || "Must be finite"))
223
+ return schema
224
+ },
225
+ email(msg) {
226
+ checks.push((v) =>
227
+ typeof v === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)
228
+ ? null
229
+ : msg || "Invalid email"
230
+ )
231
+ return schema
232
+ },
233
+ url(msg) {
234
+ checks.push((v) => {
235
+ try {
236
+ new URL(String(v))
237
+ return null
238
+ } catch {
239
+ return msg || "Invalid URL"
240
+ }
241
+ })
242
+ return schema
243
+ },
244
+ refine(fn, opts) {
245
+ const msg = typeof opts === "string" ? opts : opts?.message || "Invalid"
246
+ checks.push((v) => (fn(v) ? null : msg))
247
+ return schema
248
+ },
249
+ transform(fn) {
250
+ transformFn = fn
251
+ return schema
252
+ },
253
+ optional() {
254
+ isOptional = true
255
+ return schema
256
+ },
257
+ default(val) {
258
+ hasDefault = true
259
+ defaultVal = val
260
+ return schema
261
+ },
262
+ _parseValue(raw) {
263
+ if (raw === undefined) {
264
+ if (hasDefault) return { ok: true, value: defaultVal }
265
+ if (isOptional) return { ok: true, value: undefined }
266
+ return { ok: false, error: "Required" }
267
+ }
268
+ const base = baseCheck(raw)
269
+ if (!base.ok) return base
270
+ let val = base.value
271
+ for (const check of checks) {
272
+ const err = check(val)
273
+ if (err) return { ok: false, error: err }
274
+ }
275
+ if (transformFn) val = transformFn(val)
276
+ return { ok: true, value: val }
277
+ },
278
+ }
279
+ return schema
280
+ }
281
+
282
+ export const z = {
283
+ string: () =>
284
+ makeValidator((v) =>
285
+ typeof v === "string"
286
+ ? { ok: true, value: v }
287
+ : { ok: false, error: "Expected string" }
288
+ ),
289
+ number: () =>
290
+ makeValidator((v) =>
291
+ typeof v === "number" && !Number.isNaN(v)
292
+ ? { ok: true, value: v }
293
+ : { ok: false, error: "Expected number" }
294
+ ),
295
+ enum: (values) =>
296
+ makeValidator((v) =>
297
+ values.includes(v)
298
+ ? { ok: true, value: v }
299
+ : { ok: false, error: `Expected one of ${values.join(", ")}` }
300
+ ),
301
+ coerce: {
302
+ number: () =>
303
+ makeValidator((v) => {
304
+ const n = Number(v)
305
+ return Number.isNaN(n)
306
+ ? { ok: false, error: "Expected number" }
307
+ : { ok: true, value: n }
308
+ }),
309
+ },
310
+ object: (shape) => ({
311
+ safeParse(input) {
312
+ const src = input && typeof input === "object" ? input : {}
313
+ const data = {}
314
+ const fieldErrors = {}
315
+ let hasErrors = false
316
+ for (const [key, validator] of Object.entries(shape)) {
317
+ const res = validator._parseValue(src[key])
318
+ if (!res.ok) {
319
+ hasErrors = true
320
+ fieldErrors[key] = [res.error]
321
+ } else if (res.value !== undefined) {
322
+ data[key] = res.value
323
+ }
324
+ }
325
+ if (hasErrors) {
326
+ return {
327
+ success: false,
328
+ error: { flatten: () => ({ fieldErrors }) },
329
+ }
330
+ }
331
+ return { success: true, data }
332
+ },
333
+ }),
334
+ }
@@ -0,0 +1,101 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs"
2
+ import * as nodeModule from "node:module"
3
+ import { dirname, join, resolve as resolvePath } from "node:path"
4
+ import { fileURLToPath, pathToFileURL } from "node:url"
5
+
6
+ const { registerHooks, stripTypeScriptTypes } = nodeModule
7
+ const currentDir = dirname(fileURLToPath(import.meta.url))
8
+ const srcDir = resolvePath(currentDir, "..")
9
+ const shimUrl = pathToFileURL(
10
+ resolvePath(currentDir, "medusa-payment-shim.mjs")
11
+ ).href
12
+
13
+ function resolveTsCandidate(baseCandidate) {
14
+ const candidates = [
15
+ baseCandidate,
16
+ `${baseCandidate}.ts`,
17
+ `${baseCandidate}.tsx`,
18
+ `${baseCandidate}.json`,
19
+ join(baseCandidate, "index.ts"),
20
+ join(baseCandidate, "index.tsx"),
21
+ ]
22
+ for (const candidate of candidates) {
23
+ if (existsSync(candidate) && statSync(candidate).isFile()) {
24
+ return candidate
25
+ }
26
+ }
27
+ return null
28
+ }
29
+
30
+ registerHooks({
31
+ resolve(specifier, context, nextResolve) {
32
+ if (specifier.startsWith("@medusajs/") || specifier === "zod") {
33
+ return { url: shimUrl, shortCircuit: true }
34
+ }
35
+
36
+ if (specifier.startsWith("@payment-bold/")) {
37
+ const subPath = specifier.slice("@payment-bold/".length)
38
+ const matched = resolveTsCandidate(join(srcDir, subPath))
39
+ if (matched) {
40
+ return nextResolve(pathToFileURL(matched).href, context)
41
+ }
42
+ }
43
+
44
+ if (
45
+ (specifier.startsWith("./") || specifier.startsWith("../")) &&
46
+ context.parentURL
47
+ ) {
48
+ const parentDir = dirname(fileURLToPath(context.parentURL))
49
+ const matched = resolveTsCandidate(resolvePath(parentDir, specifier))
50
+ if (matched) {
51
+ return nextResolve(pathToFileURL(matched).href, context)
52
+ }
53
+ }
54
+
55
+ return nextResolve(specifier, context)
56
+ },
57
+
58
+ load(url, context, nextLoad) {
59
+ if (url.endsWith(".json") && !url.includes("/node_modules/")) {
60
+ const source = readFileSync(fileURLToPath(url), "utf8")
61
+ return {
62
+ format: "module",
63
+ source: `export default ${source}`,
64
+ shortCircuit: true,
65
+ }
66
+ }
67
+ if (
68
+ (url.endsWith(".ts") || url.endsWith(".tsx")) &&
69
+ !url.includes("/node_modules/") &&
70
+ typeof stripTypeScriptTypes === "function"
71
+ ) {
72
+ let source = readFileSync(fileURLToPath(url), "utf8")
73
+ const exportedTypeNames = []
74
+ for (const m of source.matchAll(
75
+ /^\s*export\s+(?:interface|type)\s+([A-Za-z0-9_]+)/gm
76
+ )) {
77
+ exportedTypeNames.push(m[1])
78
+ }
79
+ source = source.replace(
80
+ /export\s+enum\s+([A-Za-z0-9_]+)\s*\{([^}]*)\}/g,
81
+ (_m, name, body) => {
82
+ const objBody = body.replace(/([A-Za-z0-9_]+)\s*=\s*/g, "$1: ")
83
+ return `export const ${name} = {${objBody}} as const`
84
+ }
85
+ )
86
+ let stripped = stripTypeScriptTypes(source, { mode: "strip" })
87
+ if (exportedTypeNames.length > 0) {
88
+ const stubs = [...new Set(exportedTypeNames)]
89
+ .map((n) => `export const ${n} = undefined;`)
90
+ .join("\n")
91
+ stripped = `${stripped}\n${stubs}\n`
92
+ }
93
+ return {
94
+ format: "module",
95
+ source: stripped,
96
+ shortCircuit: true,
97
+ }
98
+ }
99
+ return nextLoad(url, context)
100
+ },
101
+ })
@@ -0,0 +1,70 @@
1
+ # Medusa v2 Bold Payment Admin Module (`src/admin`)
2
+
3
+ Injects the interactive **Bold Payment Actions** widget (`BoldPaymentActionsWidget`) into the Medusa v2 Admin Panel under the **Order Details** screen (`order.details.after`).
4
+
5
+ ```text
6
+ admin/
7
+ ├── widgets/
8
+ │ ├── bold-payment-actions.tsx # Order details widget (mounts at order.details.after)
9
+ │ └── components/
10
+ │ ├── bold-pos-terminal-section.tsx # Dataphone model/serial selector & Push action
11
+ │ └── bold-payment-link-section.tsx # On-demand Payment Link generator & copy action
12
+ ├── hooks/
13
+ │ ├── use-bold-widget-state.tsx # Aggregates balance state, terminal list, and action hooks
14
+ │ ├── bold-order-balance.ts # getBoldOrderBalanceInfo() for full & partial payment balances
15
+ │ ├── use-bold-pos-push.ts # Mutation hook for POST /admin/bold/pos-push
16
+ │ └── use-bold-payment-link.ts # Mutation hook for POST /admin/bold/payment-link
17
+ ├── i18n/ # English (en) & Spanish (es) translations
18
+ └── lib/
19
+ └── sdk.ts # Medusa Admin SDK client instance
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Features
25
+
26
+ 1. **Partial Payment & Remaining Balance Support (`bold-order-balance.ts`)**:
27
+ - Remains active for both unpaid and **partially paid** orders (`partially_paid`, `partially_captured`, `partially_authorized`, or `summary.pending_difference > 0`).
28
+ - Displays a **Partial Payment Balance** banner showing how much has already been paid (`paidAmount`) and the exact remaining balance (`payableAmount`) that will be charged.
29
+ - Automatically disables actions only when the order is `canceled` or `isFullyPaid` (`payableAmount === 0`).
30
+
31
+ 2. **Smart POS Terminal Push (`bold-terminal`)**:
32
+ - Queries active bound terminals via `GET /admin/bold/terminals` with automatic fallback to manual model + serial number entry.
33
+ - Dispatches checkout requests for `payableAmount` directly to physical Bold Smart Dataphones via `POST /admin/bold/pos-push`.
34
+
35
+ 3. **Payment Link & QR Generator (`bold-link`)**:
36
+ - Generates secure Bold online payment links on demand for `payableAmount` via `POST /admin/bold/payment-link`.
37
+ - Includes one-click copy-to-clipboard functionality for sharing via WhatsApp, Email, or SMS.
38
+
39
+ ---
40
+
41
+ ## How It Works
42
+
43
+ 1. **Widget Mounting**:
44
+ - The widget binds to `order.details.after` using `defineWidgetConfig`.
45
+ - It retrieves the active `payment_collection_id` associated with the target order.
46
+
47
+ 2. **API Communication**:
48
+ - Operations hit custom admin routes under `/admin/bold/*` (e.g., `/admin/bold/pos-push`, `/admin/bold/payment-link`).
49
+ - The API routes delegate execution directly to Medusa's native `Modules.PAYMENT` service rather than issuing detached external HTTP calls.
50
+
51
+ 3. **State Management**:
52
+ - Payment states update asynchronously via native Medusa webhook receivers (`/hooks/payment/bold-online`, `/hooks/payment/bold-terminal`).
53
+
54
+ ---
55
+
56
+ ## Usage Guide
57
+
58
+ ### Pushing a Payment to a Physical POS Dataphone
59
+
60
+ 1. Open any pending order in the **Medusa Admin Panel**.
61
+ 2. Scroll to the **Bold Payment Actions** widget at the bottom of the order details page.
62
+ 3. Select the terminal model (e.g., `Smart POS` or `Bold Neo`).
63
+ 4. Enter the physical Dataphone's **Serial Number (S/N)**.
64
+ 5. Click **Push to Dataphone**. The terminal will prompt the customer for card tap/chip/PIN insertion immediately.
65
+
66
+ ### Generating a Payment Link
67
+
68
+ 1. Click **Generate Link** inside the **Payment Link & QR** section of the widget.
69
+ 2. Once generated, click the **Copy Icon** to copy the URL to your clipboard.
70
+ 3. Send the link to the customer via WhatsApp, Email, or SMS.
@@ -0,0 +1,166 @@
1
+ import { useMemo } from "react"
2
+ import { Container, Heading, Badge, Table, Button, Alert } from "@medusajs/ui"
3
+ import { useTranslation } from "react-i18next"
4
+
5
+ import { useBoldTerminals } from "../../hooks"
6
+ import { isUnauthorizedError } from "../../lib/error-utils"
7
+
8
+ const BoldTerminalStatusWidget = () => {
9
+ const { t } = useTranslation()
10
+ const {
11
+ data: terminals = [],
12
+ isLoading,
13
+ isRefetching,
14
+ refetch,
15
+ error,
16
+ } = useBoldTerminals()
17
+
18
+ // Memoized error flags and visibility conditions
19
+ const { isUnauthorized, showEmptyOrNotFoundError } = useMemo(() => {
20
+ const err = error as any
21
+ const isAuth = isUnauthorizedError(error)
22
+ const is404 =
23
+ Boolean(err) &&
24
+ (err?.status === 404 ||
25
+ err?.statusCode === 404 ||
26
+ err?.response?.status === 404 ||
27
+ err?.message?.toLowerCase().includes("not found") ||
28
+ err?.message?.toLowerCase().includes("404"))
29
+
30
+ return {
31
+ isUnauthorized: isAuth,
32
+ showEmptyOrNotFoundError: isAuth || is404 || terminals.length === 0,
33
+ }
34
+ }, [error, terminals.length])
35
+
36
+ return (
37
+ <Container className="p-4 rounded-lg border bg-card space-y-3 mb-4">
38
+ <div className="flex items-center justify-between border-b pb-3">
39
+ <Heading level="h2" className="text-base font-semibold">
40
+ {t("bold.admin.terminal_status.title", {
41
+ defaultValue: "Bold POS Terminal Status",
42
+ })}
43
+ </Heading>
44
+ <Button
45
+ size="small"
46
+ variant="secondary"
47
+ isLoading={isLoading || isRefetching}
48
+ onClick={() => refetch()}
49
+ >
50
+ {t("bold.admin.terminal_status.refresh", {
51
+ defaultValue: "Refresh Fleet",
52
+ })}
53
+ </Button>
54
+ </div>
55
+
56
+ {showEmptyOrNotFoundError ? (
57
+ <Alert
58
+ variant={isUnauthorized ? "error" : "warning"}
59
+ className="p-3 text-xs"
60
+ >
61
+ <div className="flex items-start justify-between w-full gap-x-3">
62
+ <div className="space-y-1 min-w-0 flex-1">
63
+ <span className="font-semibold text-ui-fg-base block leading-tight">
64
+ {isUnauthorized
65
+ ? t("bold.admin.settings.unauthorized_terminals_title", {
66
+ defaultValue:
67
+ "POS Terminal Integration Authorization Required (403)",
68
+ })
69
+ : t("bold.admin.terminal_status.no_terminals_title", {
70
+ defaultValue: "No POS Terminals Configured (404)",
71
+ })}
72
+ </span>
73
+ <p className="text-ui-fg-subtle text-xs leading-normal">
74
+ {isUnauthorized
75
+ ? t("bold.admin.settings.unauthorized_terminals_desc", {
76
+ defaultValue:
77
+ "Datáfono POS transactions must be explicitly authorized for API Integrations in your Bold merchant portal.",
78
+ })
79
+ : t("bold.admin.terminal_status.no_terminals_desc", {
80
+ defaultValue:
81
+ "No POS terminals are currently registered or bound to your Bold account. To bind datáfonos, please review the setup instructions.",
82
+ })}
83
+ </p>
84
+ </div>
85
+ <a
86
+ href="https://developers.bold.co/api-integrations/integration#4-habilitar-terminales-para-api-integrations"
87
+ target="_blank"
88
+ rel="noopener noreferrer"
89
+ className="text-[11px] font-medium text-ui-fg-interactive hover:underline shrink-0 whitespace-nowrap pt-0.5"
90
+ >
91
+ {t("bold.admin.terminal_status.setup_terminals_link", {
92
+ defaultValue: "Setup Terminals →",
93
+ })}
94
+ </a>
95
+ </div>
96
+ </Alert>
97
+ ) : (
98
+ <Table>
99
+ <Table.Header>
100
+ <Table.Row>
101
+ <Table.HeaderCell>
102
+ {t("bold.admin.terminal_status.serial", {
103
+ defaultValue: "Serial Number",
104
+ })}
105
+ </Table.HeaderCell>
106
+ <Table.HeaderCell>
107
+ {t("bold.admin.terminal_status.model", {
108
+ defaultValue: "Hardware Model",
109
+ })}
110
+ </Table.HeaderCell>
111
+ <Table.HeaderCell>
112
+ {t("bold.admin.terminal_status.status", {
113
+ defaultValue: "Status",
114
+ })}
115
+ </Table.HeaderCell>
116
+ <Table.HeaderCell>
117
+ {t("bold.admin.terminal_status.battery", {
118
+ defaultValue: "Battery",
119
+ })}
120
+ </Table.HeaderCell>
121
+ <Table.HeaderCell>
122
+ {t("bold.admin.terminal_status.connectivity", {
123
+ defaultValue: "Connectivity",
124
+ })}
125
+ </Table.HeaderCell>
126
+ </Table.Row>
127
+ </Table.Header>
128
+ <Table.Body>
129
+ {terminals.map((item: any) => (
130
+ <Table.Row key={item.terminal_serial || item.id}>
131
+ <Table.Cell className="font-mono text-xs font-semibold">
132
+ {item.terminal_serial || item.id}
133
+ </Table.Cell>
134
+ <Table.Cell>
135
+ {item.terminal_model || item.model || "Smart POS"}
136
+ </Table.Cell>
137
+ <Table.Cell>
138
+ <Badge
139
+ color={
140
+ item.status === "ONLINE"
141
+ ? "green"
142
+ : item.status === "BUSY"
143
+ ? "orange"
144
+ : "grey"
145
+ }
146
+ >
147
+ {item.status ||
148
+ t("bold.admin.terminal_status.unknown", {
149
+ defaultValue: "OFFLINE",
150
+ })}
151
+ </Badge>
152
+ </Table.Cell>
153
+ <Table.Cell>{item.battery || "N/A"}</Table.Cell>
154
+ <Table.Cell className="text-xs text-ui-fg-subtle">
155
+ {item.signal || "N/A"}
156
+ </Table.Cell>
157
+ </Table.Row>
158
+ ))}
159
+ </Table.Body>
160
+ </Table>
161
+ )}
162
+ </Container>
163
+ )
164
+ }
165
+
166
+ export default BoldTerminalStatusWidget