@fire-spark/payments-mxp-paybridge 0.0.0-stage → 0.20.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.
@@ -0,0 +1,417 @@
1
+ import { PaymentAdapter, PaymentContext, PaymentErrorCode, PaymentMetadata, PaymentPolicy, PaymentResult } from "@fire-spark/payments";
2
+ import { TenderDetails } from "@fire-spark/types";
3
+ //#region src/constants.d.ts
4
+ declare const MXP_PAYBRIDGE_PROVIDER = "mxp_paybridge";
5
+ /** Spark methods Paybridge charges (one adapter per method). */
6
+ declare const MXP_PAYBRIDGE_METHODS: readonly ["WALLET", "BANK_TRANSFER", "PIN_PAD", "FINANCING"];
7
+ type MxpPaybridgeMethod = (typeof MXP_PAYBRIDGE_METHODS)[number];
8
+ /**
9
+ * Paybridge providers Fire Spark charges: slug → Spark method and label
10
+ * shown to the customer. All use the hosted payment link except
11
+ * `sitefcashea` (`MXP_PAYBRIDGE_CASHEA`), which runs the Cashea V2 flow.
12
+ *
13
+ * Mirrors MXP_PAYBRIDGE_PROCESSORS of @repo/validations (slugs, method and
14
+ * label only; that package is private). Keep both in the same order.
15
+ */
16
+ declare const MXP_PAYBRIDGE_PROCESSORS: {
17
+ readonly mach: {
18
+ readonly method: "WALLET";
19
+ readonly label: "MachPay";
20
+ };
21
+ readonly deuna: {
22
+ readonly method: "WALLET";
23
+ readonly label: "DeUna Pichincha";
24
+ };
25
+ readonly rutpay: {
26
+ readonly method: "BANK_TRANSFER";
27
+ readonly label: "RutPay";
28
+ };
29
+ readonly sitefp2c: {
30
+ readonly method: "BANK_TRANSFER";
31
+ readonly label: "Pago Móvil";
32
+ };
33
+ readonly sitefdebito: {
34
+ readonly method: "PIN_PAD";
35
+ readonly label: "Pinpad SiTef";
36
+ };
37
+ readonly sitefcashea: {
38
+ readonly method: "FINANCING";
39
+ readonly label: "Cashea";
40
+ };
41
+ };
42
+ type MxpPaybridgeProcessor = keyof typeof MXP_PAYBRIDGE_PROCESSORS;
43
+ /** Processor that runs the Cashea V2 flow instead of the hosted link. */
44
+ declare const MXP_PAYBRIDGE_CASHEA = "sitefcashea";
45
+ /** Cashea `confirm` is read every 3 seconds (Paybridge guide). */
46
+ declare const MXP_PAYBRIDGE_CASHEA_POLL_MS = 3000;
47
+ /**
48
+ * Longest Cashea wait: the pre-order lives 5 minutes and the guide stops
49
+ * polling at 4 (or at `expires_at`, whichever comes first).
50
+ */
51
+ declare const MXP_PAYBRIDGE_CASHEA_MAX_MS = 240000;
52
+ declare const MXP_PAYBRIDGE_PROCESSOR_KEYS: MxpPaybridgeProcessor[];
53
+ /** How the channel shows the enabled processors (`processor_display`). */
54
+ declare const MXP_PAYBRIDGE_DISPLAYS: readonly ["grouped", "separate"];
55
+ type MxpPaybridgeDisplay = (typeof MXP_PAYBRIDGE_DISPLAYS)[number];
56
+ /** Label of a grouped button when the payment has no name. */
57
+ declare const MXP_PAYBRIDGE_METHOD_LABELS: Record<MxpPaybridgeMethod, string>;
58
+ /** Seconds the hosted link stays payable when the payment sets none. */
59
+ declare const MXP_PAYBRIDGE_DEFAULT_TIMEOUT_S = 600;
60
+ /** Extra time over the link's life to read the final status. */
61
+ declare const MXP_PAYBRIDGE_TIMEOUT_MARGIN_MS = 60000;
62
+ /**
63
+ * One automatic attempt (a retry is a new Paybridge transaction); the
64
+ * attempt lives as long as the hosted link (`payment_timeout` seconds)
65
+ * plus a margin, and a pending transaction is read every 5 seconds.
66
+ */
67
+ declare const mxpPaybridgePolicyFor: (paymentTimeoutSeconds?: number) => Partial<PaymentPolicy>;
68
+ declare const MXP_PAYBRIDGE_POLICY: Partial<PaymentPolicy>;
69
+ /** Device storage key of the signed transaction of one attempt. */
70
+ declare const mxpPaybridgeStorageKey: (attemptReference: string) => string;
71
+ //#endregion
72
+ //#region src/types.d.ts
73
+ /** Answer of the Spark Paybridge `status` operation (no secret). */
74
+ type MxpPaybridgeOutcome = {
75
+ status: "PAID" | "FAILED" | "PENDING";
76
+ /** Raw Paybridge status (`approved`, `rejected`, `expired`…). */
77
+ paybridge_status: string | null;
78
+ transaction_id: string;
79
+ processor: string;
80
+ message: string | null;
81
+ authorization_code: string | null;
82
+ reference: string | null;
83
+ brand: string | null;
84
+ last4: string | null;
85
+ card_type: string | null;
86
+ amount: number | null;
87
+ };
88
+ /** `create_payment` answer: the hosted link of this attempt. */
89
+ type MxpPaybridgePaymentLink = {
90
+ transaction_id: string;
91
+ processor: string;
92
+ /**
93
+ * Paybridge's hosted UI (QR, numeric code, form or device prompt).
94
+ * Cashea (`sitefcashea`) is paid in the Cashea app and needs none.
95
+ */
96
+ payment_link: string | null;
97
+ /** Binds the transaction to the attempt; sent back to `status`. */
98
+ signature: string;
99
+ /** Seconds the link stays payable (`payment_timeout`). */
100
+ timeout_seconds: number;
101
+ };
102
+ /** `cancel_payment` answer: an approved transaction is never cancelled. */
103
+ type MxpPaybridgeCancelAnswer = {
104
+ cancelled: boolean;
105
+ outcome: MxpPaybridgeOutcome;
106
+ message?: string | null;
107
+ };
108
+ /** Signed transaction of one attempt (kept in the device storage). */
109
+ type MxpPaybridgeTransaction = {
110
+ transaction_id: string;
111
+ processor: string;
112
+ signature: string;
113
+ };
114
+ type MxpPaybridgeOpenInput = {
115
+ /** Paybridge hosted page: redirect, iframe, popup or QR of this URL. */
116
+ url: string;
117
+ /** Processor slug (e.g. `mach`), to pick how to show the link. */
118
+ processor: string;
119
+ attemptReference: string;
120
+ /** Seconds the link stays payable; close it after that. */
121
+ timeoutSeconds: number;
122
+ /** Aborted on timeout or cancel: close the page, resolve `cancelled`. */
123
+ signal: AbortSignal;
124
+ };
125
+ /**
126
+ * How the hosted page ended. An iframe, popup, QR or new tab resolves
127
+ * `returned` when the customer says they paid or the page finishes;
128
+ * `cancelled` when the customer closes it; a full page navigation
129
+ * resolves `redirected` and the checkout resumes with the transaction
130
+ * saved for the attempt.
131
+ */
132
+ type MxpPaybridgeOpenOutcome = {
133
+ type: "returned";
134
+ } | {
135
+ type: "cancelled";
136
+ } | {
137
+ type: "redirected";
138
+ };
139
+ /**
140
+ * Implemented once per template. Paybridge's result is never read from
141
+ * the browser: Fire Spark asks Paybridge for the transaction status.
142
+ */
143
+ type MxpPaybridgeBridge = {
144
+ open(input: MxpPaybridgeOpenInput): Promise<MxpPaybridgeOpenOutcome>;
145
+ };
146
+ /** `cashea_validate` answer: the Cashea pre-order (lives 5 minutes). */
147
+ type MxpPaybridgeCasheaOrder = {
148
+ uuid: string | null;
149
+ /** Order number the customer scans in the Cashea app. */
150
+ id_number: number | string | null;
151
+ expires_at: string | null;
152
+ invoice_amount: number | null;
153
+ down_payment?: number | null;
154
+ financed_amount?: number | null;
155
+ day_rate?: number | null;
156
+ message?: string | null;
157
+ error_code?: string | null;
158
+ };
159
+ /** `cashea_confirm` answer: state of the down payment. */
160
+ type MxpPaybridgeCasheaConfirm = {
161
+ uuid?: string | null;
162
+ id_number?: number | string | null;
163
+ down_payment_status: "PAID" | "PENDING" | string | null;
164
+ payment_source: "APP" | "STORE" | "NONE" | string | null;
165
+ requires_store_collection: boolean;
166
+ down_payment_to_collect: number | null;
167
+ down_payment: number | null;
168
+ financed_amount: number | null;
169
+ invoice_amount: number | null;
170
+ day_rate: number | null;
171
+ message: string | null;
172
+ error_code: string | null;
173
+ };
174
+ /** `cashea_close` answer: the payment outcome plus Cashea's fields. */
175
+ type MxpPaybridgeCasheaClose = MxpPaybridgeOutcome & {
176
+ cashea?: Partial<MxpPaybridgeCasheaConfirm> | null;
177
+ };
178
+ /** Time source of the Cashea poll (tests inject a fake one). */
179
+ type MxpPaybridgeClock = {
180
+ now: () => number;
181
+ /** Resolves after `ms` or as soon as `signal` aborts. */
182
+ wait: (ms: number, signal: AbortSignal) => Promise<void>;
183
+ };
184
+ //#endregion
185
+ //#region src/adapter.d.ts
186
+ type MxpPaybridgeOptions = {
187
+ /** Spark method this adapter charges (one adapter per method). */
188
+ method: MxpPaybridgeMethod;
189
+ /** Shows the hosted payment link (redirect, iframe, popup or QR). */
190
+ bridge: MxpPaybridgeBridge;
191
+ /**
192
+ * Fixed processor slug for every charge of this adapter. Wins over the
193
+ * channel's pick (`config.processor`).
194
+ */
195
+ processor?: string;
196
+ /**
197
+ * Default `payment_timeout` (seconds) for the adapter policy; the
198
+ * dashboard `runtime` still wins. Default 600.
199
+ */
200
+ paymentTimeout?: number;
201
+ /** Title of the processor select of a grouped button. */
202
+ selectTitle?: string;
203
+ /** Clock of the Cashea poll (tests); real time by default. */
204
+ clock?: MxpPaybridgeClock;
205
+ };
206
+ /**
207
+ * MXP Paybridge (KFC payment aggregator), one adapter per Spark method
208
+ * (WALLET, BANK_TRANSFER, PIN_PAD, FINANCING).
209
+ *
210
+ * The processor of the charge is `options.processor`, else the channel's
211
+ * pick (`config.processor`, see `withMxpPaybridgeProcessor`), else the only
212
+ * enabled one, else the customer picks it with `ui.select`. Spark creates
213
+ * the Paybridge transaction (`create_payment`), the template shows the
214
+ * hosted link (`bridge`) and Spark reads its status from Paybridge
215
+ * (`status`): the browser is never trusted. A link the customer leaves is
216
+ * cancelled (`cancel_payment`); an approved one stays paid. A paid charge
217
+ * is refunded by Spark with the order cancel or refund (whole amount).
218
+ *
219
+ * Cashea (`sitefcashea`, FINANCING) has no link: the customer's cédula
220
+ * (else `ui.input`) creates the pre-order, the customer pays the down
221
+ * payment in the Cashea app and Spark closes it (see `./cashea`).
222
+ */
223
+ declare const mxpPaybridgePayments: (options: MxpPaybridgeOptions) => PaymentAdapter;
224
+ /** One adapter per Paybridge method, sharing the bridge and options. */
225
+ declare const mxpPaybridgeAdapters: (options: Omit<MxpPaybridgeOptions, "method" | "processor">) => PaymentAdapter[];
226
+ //#endregion
227
+ //#region src/errors.d.ts
228
+ /**
229
+ * Paybridge transaction statuses (lowercase) that end a charge unpaid.
230
+ * Declines and expirations depend on the method: see
231
+ * `mxpPaybridgeErrorsFor`. Unknown statuses fall back to the method's
232
+ * decline.
233
+ */
234
+ declare const mxpPaybridgeErrors: Readonly<Record<string, import("@fire-spark/payments").PaymentErrorEntry>> & {
235
+ cancelled: {
236
+ code: "CANCELLED_BY_USER";
237
+ source: string;
238
+ };
239
+ canceled: {
240
+ code: "CANCELLED_BY_USER";
241
+ source: string;
242
+ };
243
+ failed: {
244
+ code: "WALLET_REJECTED";
245
+ source: string;
246
+ };
247
+ rejected: {
248
+ code: "WALLET_REJECTED";
249
+ source: string;
250
+ };
251
+ expired: {
252
+ code: "WALLET_EXPIRED";
253
+ source: string;
254
+ };
255
+ refundpayment: {
256
+ code: "INVALID_REQUEST";
257
+ message: string;
258
+ source: string;
259
+ };
260
+ refunded: {
261
+ code: "INVALID_REQUEST";
262
+ message: string;
263
+ source: string;
264
+ };
265
+ };
266
+ /** Decline of a failed / rejected / unknown status, by method. */
267
+ declare const mxpPaybridgeDeclinedCode: (method: MxpPaybridgeMethod) => PaymentErrorCode;
268
+ /** Expired hosted link, by method. */
269
+ declare const mxpPaybridgeExpiredCode: (method: MxpPaybridgeMethod) => PaymentErrorCode;
270
+ /** Paybridge statuses with the decline and expiration of `method`. */
271
+ declare const mxpPaybridgeErrorsFor: (method: MxpPaybridgeMethod) => Readonly<Record<string, import("@fire-spark/payments").PaymentErrorEntry>> & {
272
+ cancelled: {
273
+ code: "CANCELLED_BY_USER";
274
+ source: string;
275
+ };
276
+ canceled: {
277
+ code: "CANCELLED_BY_USER";
278
+ source: string;
279
+ };
280
+ refundpayment: {
281
+ code: "INVALID_REQUEST";
282
+ message: string;
283
+ source: string;
284
+ };
285
+ refunded: {
286
+ code: "INVALID_REQUEST";
287
+ message: string;
288
+ source: string;
289
+ };
290
+ failed: {
291
+ code: "AMBIGUOUS" | "BATCH_CLOSE_REQUIRED" | "CANCELLED_BY_USER" | "CARD_DECLINED" | "EXPIRED_CARD" | "FINANCING_EXPIRED" | "FINANCING_REJECTED" | "FRAUD_SUSPECTED" | "INSUFFICIENT_BALANCE" | "INSUFFICIENT_FUNDS" | "INVALID_CARD" | "INVALID_CREDENTIALS" | "INVALID_PIN" | "INVALID_REQUEST" | "LIMIT_EXCEEDED" | "MANUAL_REVERSAL_REQUIRED" | "NETWORK_ERROR" | "PROVIDER_UNAVAILABLE" | "REVERSAL_NOT_ALLOWED" | "TERMINAL_BUSY" | "TERMINAL_NEEDS_INIT" | "TERMINAL_NOT_CONFIGURED" | "TERMINAL_UNAVAILABLE" | "TIMEOUT" | "TRANSFER_ALREADY_USED" | "TRANSFER_AMOUNT_MISMATCH" | "TRANSFER_NOT_FOUND" | "UNKNOWN" | "USER_TIMEOUT" | "WALLET_EXPIRED" | "WALLET_REJECTED";
292
+ source: string;
293
+ };
294
+ rejected: {
295
+ code: "AMBIGUOUS" | "BATCH_CLOSE_REQUIRED" | "CANCELLED_BY_USER" | "CARD_DECLINED" | "EXPIRED_CARD" | "FINANCING_EXPIRED" | "FINANCING_REJECTED" | "FRAUD_SUSPECTED" | "INSUFFICIENT_BALANCE" | "INSUFFICIENT_FUNDS" | "INVALID_CARD" | "INVALID_CREDENTIALS" | "INVALID_PIN" | "INVALID_REQUEST" | "LIMIT_EXCEEDED" | "MANUAL_REVERSAL_REQUIRED" | "NETWORK_ERROR" | "PROVIDER_UNAVAILABLE" | "REVERSAL_NOT_ALLOWED" | "TERMINAL_BUSY" | "TERMINAL_NEEDS_INIT" | "TERMINAL_NOT_CONFIGURED" | "TERMINAL_UNAVAILABLE" | "TIMEOUT" | "TRANSFER_ALREADY_USED" | "TRANSFER_AMOUNT_MISMATCH" | "TRANSFER_NOT_FOUND" | "UNKNOWN" | "USER_TIMEOUT" | "WALLET_EXPIRED" | "WALLET_REJECTED";
296
+ source: string;
297
+ };
298
+ expired: {
299
+ code: "AMBIGUOUS" | "BATCH_CLOSE_REQUIRED" | "CANCELLED_BY_USER" | "CARD_DECLINED" | "EXPIRED_CARD" | "FINANCING_EXPIRED" | "FINANCING_REJECTED" | "FRAUD_SUSPECTED" | "INSUFFICIENT_BALANCE" | "INSUFFICIENT_FUNDS" | "INVALID_CARD" | "INVALID_CREDENTIALS" | "INVALID_PIN" | "INVALID_REQUEST" | "LIMIT_EXCEEDED" | "MANUAL_REVERSAL_REQUIRED" | "NETWORK_ERROR" | "PROVIDER_UNAVAILABLE" | "REVERSAL_NOT_ALLOWED" | "TERMINAL_BUSY" | "TERMINAL_NEEDS_INIT" | "TERMINAL_NOT_CONFIGURED" | "TERMINAL_UNAVAILABLE" | "TIMEOUT" | "TRANSFER_ALREADY_USED" | "TRANSFER_AMOUNT_MISMATCH" | "TRANSFER_NOT_FOUND" | "UNKNOWN" | "USER_TIMEOUT" | "WALLET_EXPIRED" | "WALLET_REJECTED";
300
+ source: string;
301
+ };
302
+ };
303
+ //#endregion
304
+ //#region src/processors.d.ts
305
+ /** Catalog entry of a processor slug; `null` if Spark doesn't know it. */
306
+ declare const mxpPaybridgeProcessorOf: (key: unknown) => {
307
+ readonly method: "WALLET";
308
+ readonly label: "MachPay";
309
+ } | {
310
+ readonly method: "WALLET";
311
+ readonly label: "DeUna Pichincha";
312
+ } | {
313
+ readonly method: "BANK_TRANSFER";
314
+ readonly label: "RutPay";
315
+ } | {
316
+ readonly method: "BANK_TRANSFER";
317
+ readonly label: "Pago Móvil";
318
+ } | {
319
+ readonly method: "PIN_PAD";
320
+ readonly label: "Pinpad SiTef";
321
+ } | {
322
+ readonly method: "FINANCING";
323
+ readonly label: "Cashea";
324
+ } | null;
325
+ /** Processors of one method, in catalog order. */
326
+ declare const mxpPaybridgeProcessorsFor: (method: string) => ("deuna" | "mach" | "rutpay" | "sitefcashea" | "sitefdebito" | "sitefp2c")[];
327
+ /**
328
+ * Processors the payment enables (`config.processors`) that charge its
329
+ * method, in catalog order. Unknown slugs and other methods are skipped.
330
+ */
331
+ declare const mxpPaybridgeEnabledProcessors: (method: string, config: Record<string, unknown> | null | undefined) => MxpPaybridgeProcessor[];
332
+ /** `processor_display` of the config; `grouped` by default. */
333
+ declare const mxpPaybridgeDisplayOf: (config: Record<string, unknown> | null | undefined) => MxpPaybridgeDisplay;
334
+ /** Label of a processor slug (the catalog's, else the slug). */
335
+ declare const mxpPaybridgeProcessorLabel: (processor: string, labels?: MxpPaybridgeLabels) => string;
336
+ /**
337
+ * Text overrides for `mxpPaybridgeOptionsOf`, keyed by processor slug
338
+ * (`mach`) or by method (`WALLET`, used for an unnamed grouped button).
339
+ */
340
+ type MxpPaybridgeLabels = Partial<Record<string, string>>;
341
+ /** One payment button of a channel. */
342
+ type MxpPaybridgeOption = {
343
+ /** Stable key: the payment id, or `${payment.id}:${processor}`. */
344
+ key: string;
345
+ label: string;
346
+ /** Processors this button can charge with. */
347
+ processors: MxpPaybridgeProcessor[];
348
+ /**
349
+ * The button's processor (`separate`): pass it to
350
+ * `withMxpPaybridgeProcessor` so the adapter skips the select. `null`
351
+ * for a grouped button: the adapter asks (or uses the only one).
352
+ */
353
+ processor: MxpPaybridgeProcessor | null;
354
+ };
355
+ type MxpPaybridgePaymentLike = {
356
+ id: string;
357
+ method: string;
358
+ config: Record<string, unknown> | null | undefined;
359
+ name?: string | null;
360
+ };
361
+ /**
362
+ * Buttons a channel renders for one Paybridge payment, by its
363
+ * `processor_display`:
364
+ *
365
+ * - `grouped` (default): ONE button with the payment name (else a label
366
+ * per method); the adapter asks for the processor with `ui.select` when
367
+ * more than one is enabled.
368
+ * - `separate`: one button per enabled processor, labelled with the
369
+ * processor; charge it with `withMxpPaybridgeProcessor`.
370
+ *
371
+ * A payment with no enabled processor of its method has no button.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * for (const option of mxpPaybridgeOptionsOf(payment)) {
376
+ * renderButton(option.key, option.label, () => {
377
+ * const config = withMxpPaybridgeProcessor(
378
+ * payment.config,
379
+ * option.processor
380
+ * );
381
+ * return checkout.pay({ ...payment, config });
382
+ * });
383
+ * }
384
+ * ```
385
+ */
386
+ declare const mxpPaybridgeOptionsOf: (payment: MxpPaybridgePaymentLike, labels?: MxpPaybridgeLabels) => MxpPaybridgeOption[];
387
+ /**
388
+ * The payment config with the channel's processor pick
389
+ * (`config.processor`), so the adapter charges it without asking.
390
+ * `null` / `undefined` removes a previous pick.
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * const config = withMxpPaybridgeProcessor(payment.config, "mach");
395
+ * // { ...payment.config, processor: "mach" }
396
+ * ```
397
+ */
398
+ declare const withMxpPaybridgeProcessor: <T extends Record<string, unknown>>(config: T | null | undefined, processor: string | null | undefined) => T & {
399
+ processor?: string;
400
+ };
401
+ //#endregion
402
+ //#region src/result.d.ts
403
+ /**
404
+ * Ids of a Paybridge outcome; nothing sensitive. `provider.transaction_id`
405
+ * and `provider.processor` are what the server ledger reverses with.
406
+ */
407
+ declare const mxpPaybridgeMetadataOf: (ctx: PaymentContext, outcome: MxpPaybridgeOutcome, signature: string | null) => PaymentMetadata;
408
+ /** Tender details allowed for each method (none when data is missing). */
409
+ declare const mxpPaybridgeDetailsOf: (method: MxpPaybridgeMethod, outcome: MxpPaybridgeOutcome) => TenderDetails | null;
410
+ /** PAID / FAILED / PENDING result of a Paybridge outcome. */
411
+ declare const mxpPaybridgeResultOf: (ctx: PaymentContext, method: MxpPaybridgeMethod, outcome: MxpPaybridgeOutcome, signature: string | null) => PaymentResult;
412
+ //#endregion
413
+ //#region src/cashea.d.ts
414
+ /** Real clock: `wait` resolves early when the signal aborts. */
415
+ declare const defaultMxpPaybridgeClock: () => MxpPaybridgeClock;
416
+ //#endregion
417
+ export { MXP_PAYBRIDGE_CASHEA, MXP_PAYBRIDGE_CASHEA_MAX_MS, MXP_PAYBRIDGE_CASHEA_POLL_MS, MXP_PAYBRIDGE_DEFAULT_TIMEOUT_S, MXP_PAYBRIDGE_DISPLAYS, MXP_PAYBRIDGE_METHODS, MXP_PAYBRIDGE_METHOD_LABELS, MXP_PAYBRIDGE_POLICY, MXP_PAYBRIDGE_PROCESSORS, MXP_PAYBRIDGE_PROCESSOR_KEYS, MXP_PAYBRIDGE_PROVIDER, MXP_PAYBRIDGE_TIMEOUT_MARGIN_MS, type MxpPaybridgeBridge, type MxpPaybridgeCancelAnswer, type MxpPaybridgeCasheaClose, type MxpPaybridgeCasheaConfirm, type MxpPaybridgeCasheaOrder, type MxpPaybridgeClock, MxpPaybridgeDisplay, MxpPaybridgeLabels, MxpPaybridgeMethod, type MxpPaybridgeOpenInput, type MxpPaybridgeOpenOutcome, MxpPaybridgeOption, MxpPaybridgeOptions, type MxpPaybridgeOutcome, MxpPaybridgePaymentLike, type MxpPaybridgePaymentLink, MxpPaybridgeProcessor, type MxpPaybridgeTransaction, defaultMxpPaybridgeClock, mxpPaybridgeAdapters, mxpPaybridgeDeclinedCode, mxpPaybridgeDetailsOf, mxpPaybridgeDisplayOf, mxpPaybridgeEnabledProcessors, mxpPaybridgeErrors, mxpPaybridgeErrorsFor, mxpPaybridgeExpiredCode, mxpPaybridgeMetadataOf, mxpPaybridgeOptionsOf, mxpPaybridgePayments, mxpPaybridgePolicyFor, mxpPaybridgeProcessorLabel, mxpPaybridgeProcessorOf, mxpPaybridgeProcessorsFor, mxpPaybridgeResultOf, mxpPaybridgeStorageKey, withMxpPaybridgeProcessor };
package/dist/index.js ADDED
@@ -0,0 +1,888 @@
1
+ import { PaymentError, createPaymentError, definePaymentErrors, toPaymentError } from "@fire-spark/payments";
2
+ //#region src/constants.ts
3
+ const MXP_PAYBRIDGE_PROVIDER = "mxp_paybridge";
4
+ /** Spark methods Paybridge charges (one adapter per method). */
5
+ const MXP_PAYBRIDGE_METHODS = [
6
+ "WALLET",
7
+ "BANK_TRANSFER",
8
+ "PIN_PAD",
9
+ "FINANCING"
10
+ ];
11
+ /**
12
+ * Paybridge providers Fire Spark charges: slug → Spark method and label
13
+ * shown to the customer. All use the hosted payment link except
14
+ * `sitefcashea` (`MXP_PAYBRIDGE_CASHEA`), which runs the Cashea V2 flow.
15
+ *
16
+ * Mirrors MXP_PAYBRIDGE_PROCESSORS of @repo/validations (slugs, method and
17
+ * label only; that package is private). Keep both in the same order.
18
+ */
19
+ const MXP_PAYBRIDGE_PROCESSORS = {
20
+ mach: {
21
+ method: "WALLET",
22
+ label: "MachPay"
23
+ },
24
+ deuna: {
25
+ method: "WALLET",
26
+ label: "DeUna Pichincha"
27
+ },
28
+ rutpay: {
29
+ method: "BANK_TRANSFER",
30
+ label: "RutPay"
31
+ },
32
+ sitefp2c: {
33
+ method: "BANK_TRANSFER",
34
+ label: "Pago Móvil"
35
+ },
36
+ sitefdebito: {
37
+ method: "PIN_PAD",
38
+ label: "Pinpad SiTef"
39
+ },
40
+ sitefcashea: {
41
+ method: "FINANCING",
42
+ label: "Cashea"
43
+ }
44
+ };
45
+ /** Processor that runs the Cashea V2 flow instead of the hosted link. */
46
+ const MXP_PAYBRIDGE_CASHEA = "sitefcashea";
47
+ /** Cashea `confirm` is read every 3 seconds (Paybridge guide). */
48
+ const MXP_PAYBRIDGE_CASHEA_POLL_MS = 3e3;
49
+ /**
50
+ * Longest Cashea wait: the pre-order lives 5 minutes and the guide stops
51
+ * polling at 4 (or at `expires_at`, whichever comes first).
52
+ */
53
+ const MXP_PAYBRIDGE_CASHEA_MAX_MS = 24e4;
54
+ const MXP_PAYBRIDGE_PROCESSOR_KEYS = Object.keys(MXP_PAYBRIDGE_PROCESSORS);
55
+ /** How the channel shows the enabled processors (`processor_display`). */
56
+ const MXP_PAYBRIDGE_DISPLAYS = ["grouped", "separate"];
57
+ /** Label of a grouped button when the payment has no name. */
58
+ const MXP_PAYBRIDGE_METHOD_LABELS = {
59
+ WALLET: "Billetera digital",
60
+ BANK_TRANSFER: "Transferencia",
61
+ PIN_PAD: "Pinpad",
62
+ FINANCING: "Crédito"
63
+ };
64
+ /** Seconds the hosted link stays payable when the payment sets none. */
65
+ const MXP_PAYBRIDGE_DEFAULT_TIMEOUT_S = 600;
66
+ /** Extra time over the link's life to read the final status. */
67
+ const MXP_PAYBRIDGE_TIMEOUT_MARGIN_MS = 6e4;
68
+ /**
69
+ * One automatic attempt (a retry is a new Paybridge transaction); the
70
+ * attempt lives as long as the hosted link (`payment_timeout` seconds)
71
+ * plus a margin, and a pending transaction is read every 5 seconds.
72
+ */
73
+ const mxpPaybridgePolicyFor = (paymentTimeoutSeconds = 600) => {
74
+ const ttl = (Number.isFinite(paymentTimeoutSeconds) && paymentTimeoutSeconds > 0 ? paymentTimeoutSeconds : 600) * 1e3;
75
+ return {
76
+ timeout_ms: ttl + MXP_PAYBRIDGE_TIMEOUT_MARGIN_MS,
77
+ max_attempts: 1,
78
+ poll_interval_ms: 5e3,
79
+ qr_ttl_ms: ttl
80
+ };
81
+ };
82
+ const MXP_PAYBRIDGE_POLICY = mxpPaybridgePolicyFor();
83
+ /** Device storage key of the signed transaction of one attempt. */
84
+ const mxpPaybridgeStorageKey = (attemptReference) => {
85
+ return `mxp_paybridge:transaction:${attemptReference}`;
86
+ };
87
+ //#endregion
88
+ //#region src/errors.ts
89
+ const source = "docs/payments/mxp_paybridge/checkout.md#11-errores";
90
+ /**
91
+ * Paybridge transaction statuses (lowercase) that end a charge unpaid.
92
+ * Declines and expirations depend on the method: see
93
+ * `mxpPaybridgeErrorsFor`. Unknown statuses fall back to the method's
94
+ * decline.
95
+ */
96
+ const mxpPaybridgeErrors = definePaymentErrors({
97
+ cancelled: {
98
+ code: "CANCELLED_BY_USER",
99
+ source
100
+ },
101
+ canceled: {
102
+ code: "CANCELLED_BY_USER",
103
+ source
104
+ },
105
+ failed: {
106
+ code: "WALLET_REJECTED",
107
+ source
108
+ },
109
+ rejected: {
110
+ code: "WALLET_REJECTED",
111
+ source
112
+ },
113
+ expired: {
114
+ code: "WALLET_EXPIRED",
115
+ source
116
+ },
117
+ refundpayment: {
118
+ code: "INVALID_REQUEST",
119
+ message: "Payment was refunded by the provider",
120
+ source
121
+ },
122
+ refunded: {
123
+ code: "INVALID_REQUEST",
124
+ message: "Payment was refunded by the provider",
125
+ source
126
+ }
127
+ });
128
+ /** Decline of a failed / rejected / unknown status, by method. */
129
+ const mxpPaybridgeDeclinedCode = (method) => {
130
+ if (method === "PIN_PAD") return "CARD_DECLINED";
131
+ if (method === "FINANCING") return "FINANCING_REJECTED";
132
+ return "WALLET_REJECTED";
133
+ };
134
+ /** Expired hosted link, by method. */
135
+ const mxpPaybridgeExpiredCode = (method) => {
136
+ if (method === "PIN_PAD") return "USER_TIMEOUT";
137
+ if (method === "FINANCING") return "FINANCING_EXPIRED";
138
+ return "WALLET_EXPIRED";
139
+ };
140
+ /** Paybridge statuses with the decline and expiration of `method`. */
141
+ const mxpPaybridgeErrorsFor = (method) => {
142
+ const declined = {
143
+ code: mxpPaybridgeDeclinedCode(method),
144
+ source
145
+ };
146
+ const expired = {
147
+ code: mxpPaybridgeExpiredCode(method),
148
+ source
149
+ };
150
+ return definePaymentErrors({
151
+ ...mxpPaybridgeErrors,
152
+ failed: declined,
153
+ rejected: declined,
154
+ expired
155
+ });
156
+ };
157
+ //#endregion
158
+ //#region src/processors.ts
159
+ const isMethod = (value) => {
160
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(MXP_PAYBRIDGE_METHOD_LABELS, value);
161
+ };
162
+ /** Catalog entry of a processor slug; `null` if Spark doesn't know it. */
163
+ const mxpPaybridgeProcessorOf = (key) => {
164
+ if (typeof key !== "string") return null;
165
+ if (!Object.prototype.hasOwnProperty.call(MXP_PAYBRIDGE_PROCESSORS, key)) return null;
166
+ return MXP_PAYBRIDGE_PROCESSORS[key];
167
+ };
168
+ /** Processors of one method, in catalog order. */
169
+ const mxpPaybridgeProcessorsFor = (method) => {
170
+ return MXP_PAYBRIDGE_PROCESSOR_KEYS.filter((key) => {
171
+ return MXP_PAYBRIDGE_PROCESSORS[key].method === method;
172
+ });
173
+ };
174
+ /**
175
+ * Processors the payment enables (`config.processors`) that charge its
176
+ * method, in catalog order. Unknown slugs and other methods are skipped.
177
+ */
178
+ const mxpPaybridgeEnabledProcessors = (method, config) => {
179
+ const values = Array.isArray(config?.processors) ? config.processors : [];
180
+ return mxpPaybridgeProcessorsFor(method).filter((key) => {
181
+ return values.includes(key);
182
+ });
183
+ };
184
+ /** `processor_display` of the config; `grouped` by default. */
185
+ const mxpPaybridgeDisplayOf = (config) => {
186
+ return config?.processor_display === "separate" ? "separate" : "grouped";
187
+ };
188
+ /** Label of a processor slug (the catalog's, else the slug). */
189
+ const mxpPaybridgeProcessorLabel = (processor, labels) => {
190
+ return labels?.[processor] ?? mxpPaybridgeProcessorOf(processor)?.label ?? processor;
191
+ };
192
+ /**
193
+ * Buttons a channel renders for one Paybridge payment, by its
194
+ * `processor_display`:
195
+ *
196
+ * - `grouped` (default): ONE button with the payment name (else a label
197
+ * per method); the adapter asks for the processor with `ui.select` when
198
+ * more than one is enabled.
199
+ * - `separate`: one button per enabled processor, labelled with the
200
+ * processor; charge it with `withMxpPaybridgeProcessor`.
201
+ *
202
+ * A payment with no enabled processor of its method has no button.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * for (const option of mxpPaybridgeOptionsOf(payment)) {
207
+ * renderButton(option.key, option.label, () => {
208
+ * const config = withMxpPaybridgeProcessor(
209
+ * payment.config,
210
+ * option.processor
211
+ * );
212
+ * return checkout.pay({ ...payment, config });
213
+ * });
214
+ * }
215
+ * ```
216
+ */
217
+ const mxpPaybridgeOptionsOf = (payment, labels) => {
218
+ const processors = mxpPaybridgeEnabledProcessors(payment.method, payment.config);
219
+ if (!processors.length) return [];
220
+ if (mxpPaybridgeDisplayOf(payment.config) === "separate") return processors.map((processor) => {
221
+ return {
222
+ key: `${payment.id}:${processor}`,
223
+ label: mxpPaybridgeProcessorLabel(processor, labels),
224
+ processors: [processor],
225
+ processor
226
+ };
227
+ });
228
+ const methodLabel = isMethod(payment.method) ? MXP_PAYBRIDGE_METHOD_LABELS[payment.method] : payment.method;
229
+ const label = payment.name?.trim() || labels?.[payment.method] || methodLabel;
230
+ return [{
231
+ key: payment.id,
232
+ label,
233
+ processors,
234
+ processor: null
235
+ }];
236
+ };
237
+ /**
238
+ * The payment config with the channel's processor pick
239
+ * (`config.processor`), so the adapter charges it without asking.
240
+ * `null` / `undefined` removes a previous pick.
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * const config = withMxpPaybridgeProcessor(payment.config, "mach");
245
+ * // { ...payment.config, processor: "mach" }
246
+ * ```
247
+ */
248
+ const withMxpPaybridgeProcessor = (config, processor) => {
249
+ const { processor: _previous, ...rest } = config ?? {};
250
+ if (!processor) return rest;
251
+ return {
252
+ ...rest,
253
+ processor
254
+ };
255
+ };
256
+ //#endregion
257
+ //#region src/result.ts
258
+ const last4Of = (digits) => {
259
+ const clean = (digits ?? "").replace(/\D/g, "");
260
+ return clean.length >= 4 ? clean.slice(-4) : null;
261
+ };
262
+ const clip = (value, max) => value.trim().slice(0, max);
263
+ /**
264
+ * Ids of a Paybridge outcome; nothing sensitive. `provider.transaction_id`
265
+ * and `provider.processor` are what the server ledger reverses with.
266
+ */
267
+ const mxpPaybridgeMetadataOf = (ctx, outcome, signature) => {
268
+ const payment = {
269
+ provider_transaction_id: outcome.transaction_id,
270
+ authorization_code: outcome.authorization_code,
271
+ reference: outcome.reference ?? outcome.transaction_id,
272
+ brand: outcome.brand,
273
+ last4: last4Of(outcome.last4)
274
+ };
275
+ const provider = {
276
+ transaction_id: outcome.transaction_id,
277
+ processor: outcome.processor,
278
+ paybridge_status: outcome.paybridge_status,
279
+ signature
280
+ };
281
+ return {
282
+ attempt_reference: ctx.attemptReference,
283
+ payment,
284
+ provider
285
+ };
286
+ };
287
+ /** Tender details allowed for each method (none when data is missing). */
288
+ const mxpPaybridgeDetailsOf = (method, outcome) => {
289
+ const reference = clip(outcome.reference ?? outcome.transaction_id, 128);
290
+ if (method === "PIN_PAD") return null;
291
+ if (!reference) return null;
292
+ const label = clip(mxpPaybridgeProcessorLabel(outcome.processor), 64);
293
+ if (method === "WALLET") return {
294
+ method: "WALLET",
295
+ wallet: label,
296
+ reference
297
+ };
298
+ if (method === "BANK_TRANSFER") return {
299
+ method: "BANK_TRANSFER",
300
+ reference,
301
+ bank: label
302
+ };
303
+ return null;
304
+ };
305
+ /** Signed input of every operation on an existing transaction. */
306
+ const transactionInputOf = (tx) => {
307
+ return {
308
+ transaction_id: tx.transaction_id,
309
+ processor: tx.processor,
310
+ signature: tx.signature
311
+ };
312
+ };
313
+ const failedResult = (ctx, error, metadata) => {
314
+ const base = metadata ?? { attempt_reference: ctx.attemptReference };
315
+ const review = error.code === "AMBIGUOUS" ? { needs_review: true } : {};
316
+ const m = {
317
+ ...base,
318
+ ...review,
319
+ error
320
+ };
321
+ return {
322
+ status: "FAILED",
323
+ amount: ctx.amount.value,
324
+ metadata: m,
325
+ error
326
+ };
327
+ };
328
+ /** PENDING result that `query` / `cancel` can resume. */
329
+ const pendingResult = (ctx, tx) => {
330
+ const provider = {
331
+ transaction_id: tx.transaction_id,
332
+ processor: tx.processor,
333
+ paybridge_status: null,
334
+ signature: tx.signature
335
+ };
336
+ const metadata = {
337
+ attempt_reference: ctx.attemptReference,
338
+ provider
339
+ };
340
+ return {
341
+ status: "PENDING",
342
+ amount: ctx.amount.value,
343
+ metadata
344
+ };
345
+ };
346
+ /** PAID / FAILED / PENDING result of a Paybridge outcome. */
347
+ const mxpPaybridgeResultOf = (ctx, method, outcome, signature) => {
348
+ const metadata = mxpPaybridgeMetadataOf(ctx, outcome, signature);
349
+ const amount = ctx.amount.value;
350
+ if (outcome.status === "PAID") return {
351
+ status: "PAID",
352
+ amount,
353
+ metadata,
354
+ details: mxpPaybridgeDetailsOf(method, outcome)
355
+ };
356
+ if (outcome.status === "PENDING") return {
357
+ status: "PENDING",
358
+ amount,
359
+ metadata
360
+ };
361
+ const raw = {
362
+ code: outcome.paybridge_status?.toLowerCase() ?? null,
363
+ message: outcome.message,
364
+ attempt: ctx.attempt
365
+ };
366
+ const error = toPaymentError(mxpPaybridgeErrorsFor(method), {
367
+ ...raw,
368
+ fallback: mxpPaybridgeDeclinedCode(method)
369
+ });
370
+ return failedResult(ctx, error, metadata);
371
+ };
372
+ /** Spark operation failures: a missing answer may still have charged. */
373
+ const serverErrorOf = (ctx, cause) => {
374
+ const e = cause;
375
+ const extra = {
376
+ provider_message: e?.message ?? "Paybridge request failed",
377
+ attempt: ctx.attempt
378
+ };
379
+ if (e?.code === "AMBIGUOUS" || e?.status === 504) return createPaymentError("AMBIGUOUS", extra);
380
+ if (e?.code === "INVALID_CREDENTIALS") return createPaymentError("INVALID_CREDENTIALS", extra);
381
+ if (e?.status === 409) return createPaymentError("AMBIGUOUS", extra);
382
+ if (e?.status === 400) return createPaymentError("INVALID_REQUEST", extra);
383
+ return createPaymentError("PROVIDER_UNAVAILABLE", extra);
384
+ };
385
+ //#endregion
386
+ //#region src/cashea.ts
387
+ const EMPTY_INFO = {
388
+ uuid: null,
389
+ id_number: null,
390
+ financed_amount: null,
391
+ down_payment: null,
392
+ day_rate: null
393
+ };
394
+ const STORE_MESSAGE = "La inicial debe cobrarse en caja";
395
+ const EXPIRED_MESSAGE = "La orden de Cashea expiró";
396
+ /** Real clock: `wait` resolves early when the signal aborts. */
397
+ const defaultMxpPaybridgeClock = () => {
398
+ return {
399
+ now: () => Date.now(),
400
+ wait: (ms, signal) => {
401
+ return new Promise((resolve) => {
402
+ if (signal.aborted) return resolve();
403
+ const timer = setTimeout(done, ms);
404
+ function done() {
405
+ clearTimeout(timer);
406
+ signal.removeEventListener("abort", done);
407
+ resolve();
408
+ }
409
+ signal.addEventListener("abort", done, { once: true });
410
+ });
411
+ }
412
+ };
413
+ };
414
+ const digitsOf = (value) => {
415
+ return typeof value === "string" ? value.replace(/\D/g, "") : "";
416
+ };
417
+ const upper = (value) => {
418
+ return typeof value === "string" ? value.trim().toUpperCase() : "";
419
+ };
420
+ const pick = (next, previous) => {
421
+ return next ?? previous;
422
+ };
423
+ const mergeInfo = (info, answer) => {
424
+ if (!answer) return info;
425
+ return {
426
+ uuid: pick(answer.uuid, info.uuid),
427
+ id_number: pick(answer.id_number, info.id_number),
428
+ financed_amount: pick(answer.financed_amount, info.financed_amount),
429
+ down_payment: pick(answer.down_payment, info.down_payment),
430
+ day_rate: pick(answer.day_rate, info.day_rate)
431
+ };
432
+ };
433
+ /** Cashea fields a previous result carries (`query` of a pending one). */
434
+ const infoOf = (result) => {
435
+ const provider = result.metadata.provider ?? {};
436
+ const num = (value) => typeof value === "number" ? value : null;
437
+ const id = provider.id_number;
438
+ return {
439
+ uuid: typeof provider.uuid === "string" ? provider.uuid : null,
440
+ id_number: typeof id === "number" || typeof id === "string" ? id : null,
441
+ financed_amount: num(provider.financed_amount),
442
+ down_payment: num(provider.down_payment),
443
+ day_rate: num(provider.day_rate)
444
+ };
445
+ };
446
+ /** The result with the Cashea fields in its metadata. */
447
+ const withCashea = (result, info) => {
448
+ const provider = {
449
+ ...result.metadata.provider,
450
+ ...info
451
+ };
452
+ const payment = result.metadata.payment ? {
453
+ ...result.metadata.payment,
454
+ financed_amount: info.financed_amount
455
+ } : void 0;
456
+ const p1 = payment ? { payment } : {};
457
+ return {
458
+ ...result,
459
+ metadata: {
460
+ ...result.metadata,
461
+ ...p1,
462
+ provider
463
+ }
464
+ };
465
+ };
466
+ /** Cashier-ready text of a Spark API error (`{ error, details }` body). */
467
+ const messageOf = (raw) => {
468
+ if (typeof raw !== "string" || !raw.trim()) return null;
469
+ try {
470
+ const body = JSON.parse(raw);
471
+ const text = body?.error ?? body?.message;
472
+ if (typeof text === "string" && text.trim()) return text.trim();
473
+ } catch {}
474
+ return raw.trim();
475
+ };
476
+ const failureOf = (cause) => {
477
+ const e = cause ?? {};
478
+ const detailsCode = e.details?.code;
479
+ const ownCode = typeof e.code === "string" ? e.code : null;
480
+ const code = typeof detailsCode === "string" ? detailsCode : ownCode;
481
+ return {
482
+ status: typeof e.status === "number" ? e.status : null,
483
+ code,
484
+ message: messageOf(e.message)
485
+ };
486
+ };
487
+ /** Cashea refused the step (409 / 422 with its code): not a lost answer. */
488
+ const isRefusal = (failure) => {
489
+ if (failure.status === 422) return true;
490
+ return failure.status === 409 && failure.code !== "AMBIGUOUS";
491
+ };
492
+ const refusalError = (ctx, failure) => {
493
+ return createPaymentError(failure.code === "ORDER_EXPIRED" ? "FINANCING_EXPIRED" : "FINANCING_REJECTED", {
494
+ provider_code: failure.code,
495
+ provider_message: failure.message,
496
+ attempt: ctx.attempt
497
+ });
498
+ };
499
+ /**
500
+ * `PAID` → close (nothing to charge); the down payment collected at a till
501
+ * (`STORE`) is not supported; anything else keeps polling.
502
+ */
503
+ const stepOf = (confirm) => {
504
+ if (confirm.requires_store_collection === true) return "store";
505
+ if (upper(confirm.down_payment_status) === "PAID") return "close";
506
+ if (upper(confirm.payment_source) === "STORE") return "store";
507
+ return "wait";
508
+ };
509
+ /**
510
+ * Cashea V2 (`sitefcashea`) on an existing Paybridge transaction: the
511
+ * customer's cédula creates the pre-order (`cashea_validate`), the
512
+ * customer scans its number in the Cashea app and pays the down payment,
513
+ * Spark polls `cashea_confirm` every 3 s and approves it with
514
+ * `cashea_close`. A pre-order not paid in the app is released with
515
+ * `cancel_payment`.
516
+ */
517
+ const mxpPaybridgeCashea = (method, clock) => {
518
+ const call = (ctx, operation, tx, extra = {}) => {
519
+ return ctx.server.call(operation, {
520
+ ...transactionInputOf(tx),
521
+ ...extra
522
+ });
523
+ };
524
+ const metadataOf = (ctx, tx, info) => {
525
+ return withCashea(pendingResult(ctx, tx), info).metadata;
526
+ };
527
+ /**
528
+ * Releases the pre-order (`cancel_payment`) and fails with `error`. An
529
+ * already approved transaction stays paid; one Paybridge didn't cancel
530
+ * (or a lost cancel answer) is left for review.
531
+ */
532
+ const release = async (ctx, tx, error, info) => {
533
+ try {
534
+ const answer = await call(ctx, "cancel_payment", tx);
535
+ const outcome = answer.outcome;
536
+ const result = mxpPaybridgeResultOf(ctx, method, outcome, tx.signature);
537
+ if (!answer.cancelled && result.status === "PAID") return withCashea(result, info);
538
+ const base = withCashea(result, info).metadata;
539
+ const review = !answer.cancelled && result.status === "PENDING" ? { needs_review: true } : {};
540
+ const { error: _previous, ...metadata } = base;
541
+ return failedResult(ctx, error, {
542
+ ...metadata,
543
+ ...review
544
+ });
545
+ } catch {
546
+ return failedResult(ctx, error, {
547
+ ...metadataOf(ctx, tx, info),
548
+ needs_review: true
549
+ });
550
+ }
551
+ };
552
+ /** A failed Cashea step: refusals release the pre-order. */
553
+ const failedStep = (ctx, tx, cause, info) => {
554
+ if (cause instanceof PaymentError) return release(ctx, tx, cause.error, info);
555
+ const failure = failureOf(cause);
556
+ if (isRefusal(failure)) return release(ctx, tx, refusalError(ctx, failure), info);
557
+ return failedResult(ctx, serverErrorOf(ctx, cause), metadataOf(ctx, tx, info));
558
+ };
559
+ /** Cédula of the Cashea account: the customer's, else asked. */
560
+ const cedulaOf = async (ctx) => {
561
+ const known = digitsOf(ctx.customer?.document);
562
+ if (known.length >= 5) return { dni: known };
563
+ const cancelled = () => {
564
+ return { error: createPaymentError("CANCELLED_BY_USER", { attempt: ctx.attempt }) };
565
+ };
566
+ try {
567
+ const typed = await ctx.ui.input({
568
+ label: "Cédula del titular de Cashea",
569
+ type: "number",
570
+ maxLength: 12
571
+ });
572
+ const dni = digitsOf(typed);
573
+ return dni ? { dni } : cancelled();
574
+ } catch (cause) {
575
+ if (cause instanceof PaymentError) return { error: cause.error };
576
+ return cancelled();
577
+ }
578
+ };
579
+ /** `cashea_close`: approves the transaction (payment outcome). */
580
+ const close = async (ctx, tx, info) => {
581
+ ctx.ui.message({
582
+ text: "Confirmando pago…",
583
+ kind: "waiting"
584
+ });
585
+ let answer;
586
+ try {
587
+ answer = await call(ctx, "cashea_close", tx);
588
+ } catch (cause) {
589
+ const failure = failureOf(cause);
590
+ if (isRefusal(failure)) return release(ctx, tx, refusalError(ctx, failure), info);
591
+ return failedResult(ctx, createPaymentError("AMBIGUOUS", {
592
+ provider_message: failure.message ?? "Cashea close did not answer",
593
+ attempt: ctx.attempt
594
+ }), metadataOf(ctx, tx, info));
595
+ }
596
+ const merged = mergeInfo(info, answer.cashea);
597
+ const result = mxpPaybridgeResultOf(ctx, method, answer, tx.signature);
598
+ return withCashea(result, merged);
599
+ };
600
+ /** Next step of a confirm answer: close, release (store) or keep going. */
601
+ const settle = (ctx, tx, confirm, info) => {
602
+ const step = stepOf(confirm);
603
+ if (step === "close") return close(ctx, tx, info);
604
+ if (step === "store") {
605
+ const error = createPaymentError("FINANCING_REJECTED", {
606
+ provider_code: "STORE",
607
+ provider_message: STORE_MESSAGE,
608
+ attempt: ctx.attempt
609
+ });
610
+ return release(ctx, tx, error, info);
611
+ }
612
+ return null;
613
+ };
614
+ const start = async (ctx, tx) => {
615
+ const cedula = await cedulaOf(ctx);
616
+ if ("error" in cedula) return release(ctx, tx, cedula.error, EMPTY_INFO);
617
+ let order;
618
+ try {
619
+ order = await call(ctx, "cashea_validate", tx, { dni: cedula.dni });
620
+ } catch (cause) {
621
+ return failedStep(ctx, tx, cause, EMPTY_INFO);
622
+ }
623
+ let info = mergeInfo(EMPTY_INFO, order);
624
+ const number = info.id_number == null ? "" : String(info.id_number);
625
+ const text = number ? `Escanea la orden N° ${number} con la app Cashea y paga la inicial` : "Abre la app Cashea y paga la inicial de tu orden";
626
+ ctx.ui.message({
627
+ text,
628
+ kind: "waiting"
629
+ });
630
+ const started = clock.now();
631
+ const expires = Date.parse(order.expires_at ?? "");
632
+ const limit = started + MXP_PAYBRIDGE_CASHEA_MAX_MS;
633
+ const deadline = Number.isFinite(expires) ? Math.min(limit, expires) : limit;
634
+ const cancelled = () => {
635
+ const error = createPaymentError("CANCELLED_BY_USER", { attempt: ctx.attempt });
636
+ return release(ctx, tx, error, info);
637
+ };
638
+ for (;;) {
639
+ const left = Math.max(0, deadline - clock.now());
640
+ await clock.wait(Math.min(MXP_PAYBRIDGE_CASHEA_POLL_MS, left), ctx.signal);
641
+ if (ctx.signal.aborted) return cancelled();
642
+ try {
643
+ const confirm = await call(ctx, "cashea_confirm", tx);
644
+ info = mergeInfo(info, confirm);
645
+ const next = settle(ctx, tx, confirm, info);
646
+ if (next) return await next;
647
+ } catch (cause) {
648
+ const failure = failureOf(cause);
649
+ if (cause instanceof PaymentError || isRefusal(failure)) return failedStep(ctx, tx, cause, info);
650
+ }
651
+ if (ctx.signal.aborted) return cancelled();
652
+ if (clock.now() >= deadline) {
653
+ const error = createPaymentError("FINANCING_EXPIRED", {
654
+ provider_message: EXPIRED_MESSAGE,
655
+ attempt: ctx.attempt
656
+ });
657
+ return release(ctx, tx, error, info);
658
+ }
659
+ }
660
+ };
661
+ /**
662
+ * Pending Cashea result: a closed transaction answers its status; an
663
+ * open one reads `cashea_confirm` and closes once the down payment is
664
+ * paid in the app.
665
+ */
666
+ const query = async (ctx, tx, result) => {
667
+ let info = infoOf(result);
668
+ const current = mxpPaybridgeResultOf(ctx, method, await call(ctx, "status", tx), tx.signature);
669
+ if (current.status !== "PENDING") return withCashea(current, info);
670
+ let confirm;
671
+ try {
672
+ confirm = await call(ctx, "cashea_confirm", tx);
673
+ } catch (cause) {
674
+ const failure = failureOf(cause);
675
+ if (isRefusal(failure)) return failedStep(ctx, tx, cause, info);
676
+ return result;
677
+ }
678
+ info = mergeInfo(info, confirm);
679
+ const next = settle(ctx, tx, confirm, info);
680
+ return next ? await next : withCashea(pendingResult(ctx, tx), info);
681
+ };
682
+ return {
683
+ start,
684
+ query
685
+ };
686
+ };
687
+ //#endregion
688
+ //#region src/adapter.ts
689
+ const text = (value) => {
690
+ return typeof value === "string" && value.trim() ? value.trim() : null;
691
+ };
692
+ const record = (value) => {
693
+ if (!value || typeof value !== "object") return {};
694
+ return value;
695
+ };
696
+ const fail = (ctx, message) => {
697
+ return new PaymentError(createPaymentError("INVALID_REQUEST", {
698
+ provider_message: message,
699
+ attempt: ctx.attempt
700
+ }));
701
+ };
702
+ const transactionOf = (value) => {
703
+ const source = record(value);
704
+ const transactionId = text(source.transaction_id);
705
+ const processor = text(source.processor);
706
+ const signature = text(source.signature);
707
+ if (!transactionId || !processor || !signature) return null;
708
+ return {
709
+ transaction_id: transactionId,
710
+ processor,
711
+ signature
712
+ };
713
+ };
714
+ const parse = (raw) => {
715
+ if (!raw) return null;
716
+ try {
717
+ return JSON.parse(raw);
718
+ } catch {
719
+ return null;
720
+ }
721
+ };
722
+ /** Signed transaction of the attempt: result metadata, else the storage. */
723
+ const savedTransaction = async (ctx, result) => {
724
+ const fromResult = transactionOf(result?.metadata.provider);
725
+ if (fromResult) return fromResult;
726
+ const saved = await ctx.storage.get(mxpPaybridgeStorageKey(ctx.attemptReference));
727
+ return transactionOf(parse(saved));
728
+ };
729
+ /**
730
+ * MXP Paybridge (KFC payment aggregator), one adapter per Spark method
731
+ * (WALLET, BANK_TRANSFER, PIN_PAD, FINANCING).
732
+ *
733
+ * The processor of the charge is `options.processor`, else the channel's
734
+ * pick (`config.processor`, see `withMxpPaybridgeProcessor`), else the only
735
+ * enabled one, else the customer picks it with `ui.select`. Spark creates
736
+ * the Paybridge transaction (`create_payment`), the template shows the
737
+ * hosted link (`bridge`) and Spark reads its status from Paybridge
738
+ * (`status`): the browser is never trusted. A link the customer leaves is
739
+ * cancelled (`cancel_payment`); an approved one stays paid. A paid charge
740
+ * is refunded by Spark with the order cancel or refund (whole amount).
741
+ *
742
+ * Cashea (`sitefcashea`, FINANCING) has no link: the customer's cédula
743
+ * (else `ui.input`) creates the pre-order, the customer pays the down
744
+ * payment in the Cashea app and Spark closes it (see `./cashea`).
745
+ */
746
+ const mxpPaybridgePayments = (options) => {
747
+ const { bridge, method } = options;
748
+ const errors = mxpPaybridgeErrorsFor(method);
749
+ const cashea = mxpPaybridgeCashea(method, options.clock ?? defaultMxpPaybridgeClock());
750
+ /** The processor of this charge; `null` lets the server pick the only one. */
751
+ const pickProcessor = async (ctx) => {
752
+ const enabled = mxpPaybridgeEnabledProcessors(method, ctx.config);
753
+ const wanted = text(options.processor) ?? text(ctx.config.processor);
754
+ if (wanted) {
755
+ if (mxpPaybridgeProcessorOf(wanted)?.method !== method) throw fail(ctx, `Paybridge processor ${wanted} is not ${method}`);
756
+ if (enabled.length && !enabled.some((key) => key === wanted)) throw fail(ctx, `Paybridge processor ${wanted} is not enabled`);
757
+ return wanted;
758
+ }
759
+ if (enabled.length <= 1) return enabled[0] ?? null;
760
+ const choices = enabled.map((key) => {
761
+ return {
762
+ label: mxpPaybridgeProcessorLabel(key),
763
+ value: key
764
+ };
765
+ });
766
+ const title = options.selectTitle ?? "¿Con qué quieres pagar?";
767
+ const picked = await ctx.ui.select({
768
+ title,
769
+ options: choices
770
+ }).catch((cause) => {
771
+ if (cause instanceof PaymentError) throw cause;
772
+ return null;
773
+ });
774
+ if (!picked || !enabled.some((key) => key === picked)) throw new PaymentError(createPaymentError("CANCELLED_BY_USER", { attempt: ctx.attempt }));
775
+ return picked;
776
+ };
777
+ const readStatus = async (ctx, tx) => {
778
+ const outcome = await ctx.server.call("status", transactionInputOf(tx));
779
+ return mxpPaybridgeResultOf(ctx, method, outcome, tx.signature);
780
+ };
781
+ /** Customer left the link: paid meanwhile, else cancel the transaction. */
782
+ const leave = async (ctx, tx) => {
783
+ const answer = await ctx.server.call("cancel_payment", transactionInputOf(tx));
784
+ const outcome = answer.outcome;
785
+ const result = mxpPaybridgeResultOf(ctx, method, outcome, tx.signature);
786
+ if (answer.cancelled) return failedResult(ctx, createPaymentError("CANCELLED_BY_USER", {
787
+ provider_message: answer.message ?? null,
788
+ attempt: ctx.attempt
789
+ }), result.metadata);
790
+ if (result.status === "PENDING") return pendingResult(ctx, tx);
791
+ return result;
792
+ };
793
+ const start = async (ctx) => {
794
+ try {
795
+ const processor = await pickProcessor(ctx);
796
+ const input = processor ? { processor } : {};
797
+ const link = await ctx.server.call("create_payment", input);
798
+ const tx = transactionOf(link);
799
+ const key = mxpPaybridgeStorageKey(ctx.attemptReference);
800
+ if (tx?.processor === "sitefcashea") {
801
+ await ctx.storage.set(key, JSON.stringify(tx));
802
+ return await cashea.start(ctx, tx);
803
+ }
804
+ if (!tx || !text(link.payment_link)) return failedResult(ctx, createPaymentError("AMBIGUOUS", {
805
+ provider_message: "Paybridge returned no payment link",
806
+ attempt: ctx.attempt
807
+ }));
808
+ await ctx.storage.set(key, JSON.stringify(tx));
809
+ const seconds = Number(link.timeout_seconds);
810
+ const outcome = await bridge.open({
811
+ url: text(link.payment_link) ?? "",
812
+ processor: tx.processor,
813
+ attemptReference: ctx.attemptReference,
814
+ timeoutSeconds: seconds > 0 ? seconds : 600,
815
+ signal: ctx.signal
816
+ });
817
+ if (outcome.type === "redirected") return pendingResult(ctx, tx);
818
+ ctx.ui.message({
819
+ text: "Confirmando pago…",
820
+ kind: "waiting"
821
+ });
822
+ if (outcome.type === "cancelled") return await leave(ctx, tx);
823
+ return await readStatus(ctx, tx);
824
+ } catch (cause) {
825
+ if (cause instanceof PaymentError) return failedResult(ctx, cause.error);
826
+ return failedResult(ctx, serverErrorOf(ctx, cause));
827
+ }
828
+ };
829
+ /** Pending transaction (redirect or not paid yet): read its status. */
830
+ const query = async (ctx, result) => {
831
+ if (result.status !== "PENDING") return result;
832
+ const tx = await savedTransaction(ctx, result);
833
+ if (!tx) return result;
834
+ try {
835
+ if (tx.processor === "sitefcashea") return await cashea.query(ctx, tx, result);
836
+ return await readStatus(ctx, tx);
837
+ } catch (cause) {
838
+ return failedResult(ctx, serverErrorOf(ctx, cause));
839
+ }
840
+ };
841
+ /**
842
+ * Timeout or cancel of a pending attempt: cancels the transaction at
843
+ * Paybridge. A paid or declined one is answered as such; anything not
844
+ * final stays for review.
845
+ */
846
+ const cancel = async (ctx, result) => {
847
+ const tx = await savedTransaction(ctx, result);
848
+ if (!tx) return {
849
+ ...result,
850
+ status: "CANCELLED"
851
+ };
852
+ try {
853
+ const next = await leave(ctx, tx);
854
+ if (next.error?.code === "CANCELLED_BY_USER") return {
855
+ ...result,
856
+ status: "CANCELLED"
857
+ };
858
+ return next;
859
+ } catch {
860
+ return result;
861
+ }
862
+ };
863
+ /** Spark refunds a paid transaction; an unpaid one is cancelled here. */
864
+ const reversalFor = (result) => {
865
+ return result.status === "PAID" ? "server" : "cancel";
866
+ };
867
+ return {
868
+ provider: MXP_PAYBRIDGE_PROVIDER,
869
+ method,
870
+ errors,
871
+ policy: mxpPaybridgePolicyFor(options.paymentTimeout),
872
+ start,
873
+ query,
874
+ cancel,
875
+ reversalFor
876
+ };
877
+ };
878
+ /** One adapter per Paybridge method, sharing the bridge and options. */
879
+ const mxpPaybridgeAdapters = (options) => {
880
+ return MXP_PAYBRIDGE_METHODS.map((method) => {
881
+ return mxpPaybridgePayments({
882
+ ...options,
883
+ method
884
+ });
885
+ });
886
+ };
887
+ //#endregion
888
+ export { MXP_PAYBRIDGE_CASHEA, MXP_PAYBRIDGE_CASHEA_MAX_MS, MXP_PAYBRIDGE_CASHEA_POLL_MS, MXP_PAYBRIDGE_DEFAULT_TIMEOUT_S, MXP_PAYBRIDGE_DISPLAYS, MXP_PAYBRIDGE_METHODS, MXP_PAYBRIDGE_METHOD_LABELS, MXP_PAYBRIDGE_POLICY, MXP_PAYBRIDGE_PROCESSORS, MXP_PAYBRIDGE_PROCESSOR_KEYS, MXP_PAYBRIDGE_PROVIDER, MXP_PAYBRIDGE_TIMEOUT_MARGIN_MS, defaultMxpPaybridgeClock, mxpPaybridgeAdapters, mxpPaybridgeDeclinedCode, mxpPaybridgeDetailsOf, mxpPaybridgeDisplayOf, mxpPaybridgeEnabledProcessors, mxpPaybridgeErrors, mxpPaybridgeErrorsFor, mxpPaybridgeExpiredCode, mxpPaybridgeMetadataOf, mxpPaybridgeOptionsOf, mxpPaybridgePayments, mxpPaybridgePolicyFor, mxpPaybridgeProcessorLabel, mxpPaybridgeProcessorOf, mxpPaybridgeProcessorsFor, mxpPaybridgeResultOf, mxpPaybridgeStorageKey, withMxpPaybridgeProcessor };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@fire-spark/payments-mxp-paybridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.20.0",
4
+ "description": "Fire Spark MXP Paybridge adapter (KFC payment aggregator): MachPay, DeUna Pichincha, RutPay, Pago Móvil and Pinpad SiTef through the hosted payment link, and Cashea V2, verified by the Fire Spark API; processors grouped in one button or shown one by one",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@fire-spark/payments": "^0.20.0",
21
+ "@fire-spark/types": "^0.20.0"
22
+ },
23
+ "devDependencies": {
24
+ "tsdown": "^0.22.14",
25
+ "typescript": "^7.0.2",
26
+ "vitest": "^2.1.8"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "tsdown": {
32
+ "entry": [
33
+ "src/index.ts"
34
+ ],
35
+ "format": [
36
+ "esm"
37
+ ],
38
+ "platform": "neutral",
39
+ "dts": {
40
+ "tsconfig": "tsconfig.build.json"
41
+ },
42
+ "clean": true,
43
+ "deps": {
44
+ "neverBundle": [
45
+ "@fire-spark/payments",
46
+ "@fire-spark/types"
47
+ ]
48
+ }
49
+ },
50
+ "scripts": {
51
+ "build": "tsdown",
52
+ "dev": "tsdown --watch",
53
+ "check-types": "tsc --noEmit",
54
+ "test:utils": "vitest run",
55
+ "lint": "oxlint ./src --max-warnings=0",
56
+ "format": "oxfmt ./src",
57
+ "check-format": "oxfmt --check ./src"
58
+ }
6
59
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.