@brissoto/pay-react-native 0.0.0-stage → 1.5.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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/assets/brand/paypal-wordmark.png +0 -0
  4. package/assets/fonts/Figtree-Bold.ttf +0 -0
  5. package/assets/fonts/Figtree-ExtraBold.ttf +0 -0
  6. package/assets/fonts/Figtree-Medium.ttf +0 -0
  7. package/assets/fonts/Figtree-Regular.ttf +0 -0
  8. package/assets/fonts/Figtree-SemiBold.ttf +0 -0
  9. package/assets/fonts/OFL.txt +93 -0
  10. package/assets/logos/airtel.png +0 -0
  11. package/assets/logos/app-store.png +0 -0
  12. package/assets/logos/apple-pay.png +0 -0
  13. package/assets/logos/at.png +0 -0
  14. package/assets/logos/bancontact.png +0 -0
  15. package/assets/logos/card.png +0 -0
  16. package/assets/logos/cb.png +0 -0
  17. package/assets/logos/celtiis.png +0 -0
  18. package/assets/logos/eps.png +0 -0
  19. package/assets/logos/feexpay.png +0 -0
  20. package/assets/logos/google-pay.png +0 -0
  21. package/assets/logos/google-play.png +0 -0
  22. package/assets/logos/iapkit.png +0 -0
  23. package/assets/logos/ideal.png +0 -0
  24. package/assets/logos/mastercard.png +0 -0
  25. package/assets/logos/mixx.png +0 -0
  26. package/assets/logos/moov.png +0 -0
  27. package/assets/logos/mtn.png +0 -0
  28. package/assets/logos/mybank.png +0 -0
  29. package/assets/logos/nexus.png +0 -0
  30. package/assets/logos/orange.png +0 -0
  31. package/assets/logos/pawapay.png +0 -0
  32. package/assets/logos/paypal.png +0 -0
  33. package/assets/logos/telecel.png +0 -0
  34. package/assets/logos/tnm.png +0 -0
  35. package/assets/logos/visa.png +0 -0
  36. package/assets/logos/vodacom.png +0 -0
  37. package/assets/logos/wave.png +0 -0
  38. package/dist/checkout-core/hooks/use-checkout-controller.d.ts +9 -0
  39. package/dist/checkout-core/hooks/use-checkout-controller.js +563 -0
  40. package/dist/checkout-core/hooks/use-checkout-payment.d.ts +9 -0
  41. package/dist/checkout-core/hooks/use-checkout-payment.js +136 -0
  42. package/dist/checkout-core/hooks/use-checkout-timers.d.ts +15 -0
  43. package/dist/checkout-core/hooks/use-checkout-timers.js +44 -0
  44. package/dist/checkout-core/hooks/use-phone-number.d.ts +7 -0
  45. package/dist/checkout-core/hooks/use-phone-number.js +82 -0
  46. package/dist/checkout-core/messages/en.d.ts +302 -0
  47. package/dist/checkout-core/messages/en.js +301 -0
  48. package/dist/checkout-core/messages/fr.d.ts +4 -0
  49. package/dist/checkout-core/messages/fr.js +302 -0
  50. package/dist/checkout-core/models/checkout.card.utils.d.ts +7 -0
  51. package/dist/checkout-core/models/checkout.card.utils.js +25 -0
  52. package/dist/checkout-core/models/checkout.constants.d.ts +101 -0
  53. package/dist/checkout-core/models/checkout.constants.js +339 -0
  54. package/dist/checkout-core/models/checkout.country.utils.d.ts +17 -0
  55. package/dist/checkout-core/models/checkout.country.utils.js +45 -0
  56. package/dist/checkout-core/models/checkout.enum.d.ts +233 -0
  57. package/dist/checkout-core/models/checkout.enum.js +259 -0
  58. package/dist/checkout-core/models/checkout.fetch.utils.d.ts +6 -0
  59. package/dist/checkout-core/models/checkout.fetch.utils.js +22 -0
  60. package/dist/checkout-core/models/checkout.interface.d.ts +698 -0
  61. package/dist/checkout-core/models/checkout.interface.js +1 -0
  62. package/dist/checkout-core/models/checkout.money.utils.d.ts +7 -0
  63. package/dist/checkout-core/models/checkout.money.utils.js +21 -0
  64. package/dist/checkout-core/models/checkout.phone.utils.d.ts +33 -0
  65. package/dist/checkout-core/models/checkout.phone.utils.js +159 -0
  66. package/dist/checkout-core/models/checkout.view.utils.d.ts +77 -0
  67. package/dist/checkout-core/models/checkout.view.utils.js +331 -0
  68. package/dist/checkout-core/models/domain.enum.d.ts +106 -0
  69. package/dist/checkout-core/models/domain.enum.js +113 -0
  70. package/dist/components/BrissotoPayProvider.d.ts +8 -0
  71. package/dist/components/BrissotoPayProvider.js +39 -0
  72. package/dist/components/PaymentSheetModal.d.ts +9 -0
  73. package/dist/components/PaymentSheetModal.js +106 -0
  74. package/dist/components/SheetBone.d.ts +3 -0
  75. package/dist/components/SheetBone.js +12 -0
  76. package/dist/components/SheetButton.d.ts +7 -0
  77. package/dist/components/SheetButton.js +47 -0
  78. package/dist/components/SheetCardFields.d.ts +10 -0
  79. package/dist/components/SheetCardFields.js +86 -0
  80. package/dist/components/SheetChosenMethod.d.ts +3 -0
  81. package/dist/components/SheetChosenMethod.js +60 -0
  82. package/dist/components/SheetCodeField.d.ts +8 -0
  83. package/dist/components/SheetCodeField.js +98 -0
  84. package/dist/components/SheetContent.d.ts +3 -0
  85. package/dist/components/SheetContent.js +133 -0
  86. package/dist/components/SheetDial.d.ts +7 -0
  87. package/dist/components/SheetDial.js +36 -0
  88. package/dist/components/SheetFailed.d.ts +3 -0
  89. package/dist/components/SheetFailed.js +44 -0
  90. package/dist/components/SheetForm.d.ts +8 -0
  91. package/dist/components/SheetForm.js +141 -0
  92. package/dist/components/SheetGrabber.d.ts +2 -0
  93. package/dist/components/SheetGrabber.js +17 -0
  94. package/dist/components/SheetHeader.d.ts +7 -0
  95. package/dist/components/SheetHeader.js +83 -0
  96. package/dist/components/SheetIcon.d.ts +3 -0
  97. package/dist/components/SheetIcon.js +78 -0
  98. package/dist/components/SheetLayout.d.ts +11 -0
  99. package/dist/components/SheetLayout.js +63 -0
  100. package/dist/components/SheetLogo.d.ts +3 -0
  101. package/dist/components/SheetLogo.js +20 -0
  102. package/dist/components/SheetMessage.d.ts +3 -0
  103. package/dist/components/SheetMessage.js +15 -0
  104. package/dist/components/SheetMethodCard.d.ts +3 -0
  105. package/dist/components/SheetMethodCard.js +71 -0
  106. package/dist/components/SheetNameField.d.ts +7 -0
  107. package/dist/components/SheetNameField.js +48 -0
  108. package/dist/components/SheetPaypalButton.d.ts +3 -0
  109. package/dist/components/SheetPaypalButton.js +23 -0
  110. package/dist/components/SheetPhoneField.d.ts +3 -0
  111. package/dist/components/SheetPhoneField.js +59 -0
  112. package/dist/components/SheetPillSelect.d.ts +7 -0
  113. package/dist/components/SheetPillSelect.js +134 -0
  114. package/dist/components/SheetRow.d.ts +3 -0
  115. package/dist/components/SheetRow.js +28 -0
  116. package/dist/components/SheetSimulator.d.ts +6 -0
  117. package/dist/components/SheetSimulator.js +40 -0
  118. package/dist/components/SheetSkeleton.d.ts +5 -0
  119. package/dist/components/SheetSkeleton.js +23 -0
  120. package/dist/components/SheetStep.d.ts +6 -0
  121. package/dist/components/SheetStep.js +21 -0
  122. package/dist/components/SheetStoreTab.d.ts +7 -0
  123. package/dist/components/SheetStoreTab.js +27 -0
  124. package/dist/components/SheetSuccess.d.ts +3 -0
  125. package/dist/components/SheetSuccess.js +51 -0
  126. package/dist/components/SheetSummary.d.ts +3 -0
  127. package/dist/components/SheetSummary.js +32 -0
  128. package/dist/components/SheetTerminal.d.ts +6 -0
  129. package/dist/components/SheetTerminal.js +31 -0
  130. package/dist/components/SheetText.d.ts +5 -0
  131. package/dist/components/SheetText.js +27 -0
  132. package/dist/components/SheetToast.d.ts +7 -0
  133. package/dist/components/SheetToast.js +71 -0
  134. package/dist/components/SheetWaiting.d.ts +7 -0
  135. package/dist/components/SheetWaiting.js +88 -0
  136. package/dist/hooks/use-native-platform.d.ts +10 -0
  137. package/dist/hooks/use-native-platform.js +71 -0
  138. package/dist/hooks/use-payment-sheet.d.ts +4 -0
  139. package/dist/hooks/use-payment-sheet.js +10 -0
  140. package/dist/hooks/use-shake.d.ts +3 -0
  141. package/dist/hooks/use-shake.js +18 -0
  142. package/dist/hooks/use-sheet-motion.d.ts +7 -0
  143. package/dist/hooks/use-sheet-motion.js +62 -0
  144. package/dist/hooks/use-sheet-resize.d.ts +6 -0
  145. package/dist/hooks/use-sheet-resize.js +15 -0
  146. package/dist/hooks/use-sheet-room.d.ts +4 -0
  147. package/dist/hooks/use-sheet-room.js +8 -0
  148. package/dist/hooks/use-sheet-theme.d.ts +4 -0
  149. package/dist/hooks/use-sheet-theme.js +12 -0
  150. package/dist/hooks/use-step-slide.d.ts +16 -0
  151. package/dist/hooks/use-step-slide.js +50 -0
  152. package/dist/hooks/use-store-recovery.d.ts +9 -0
  153. package/dist/hooks/use-store-recovery.js +50 -0
  154. package/dist/hooks/use-store-tab.d.ts +11 -0
  155. package/dist/hooks/use-store-tab.js +112 -0
  156. package/dist/index.d.ts +3 -0
  157. package/dist/index.js +2 -0
  158. package/dist/models/sheet.constants.d.ts +125 -0
  159. package/dist/models/sheet.constants.js +204 -0
  160. package/dist/models/sheet.enum.d.ts +46 -0
  161. package/dist/models/sheet.enum.js +53 -0
  162. package/dist/models/sheet.interface.d.ts +426 -0
  163. package/dist/models/sheet.interface.js +1 -0
  164. package/dist/models/sheet.utils.d.ts +68 -0
  165. package/dist/models/sheet.utils.js +214 -0
  166. package/dist/services/checkout.service.d.ts +15 -0
  167. package/dist/services/checkout.service.js +96 -0
  168. package/dist/services/provider-window.service.d.ts +13 -0
  169. package/dist/services/provider-window.service.js +53 -0
  170. package/dist/services/store.service.d.ts +36 -0
  171. package/dist/services/store.service.js +107 -0
  172. package/package.json +73 -4
@@ -0,0 +1,563 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { useLocale, useTranslations } from 'use-intl';
3
+ import { COPIED_MS, FLOW_TRAITS, OPEN_RETRY_MS, OPEN_TRIES, OTP_MAX_LENGTH, } from "../models/checkout.constants.js";
4
+ import { CardFieldsMessageEnum, CheckoutScreenEnum, CheckoutStepEnum, CheckoutTabEnum, CheckoutToastToneEnum, FlowAskEnum, MethodStateEnum, PayRefusalEnum, PayRouteEnum, ProviderWindowEndEnum, } from "../models/checkout.enum.js";
5
+ import { AttemptStatusEnum, CountryEnum, CurrencyEnum, } from "../models/domain.enum.js";
6
+ import { maskE164 } from "../models/checkout.phone.utils.js";
7
+ import { countriesOf, deriveCheckout, dialHelpOf, fullNameOf, initialUi, logoOf, missingBeforePay, payInputOf, pickedPatch, screenOf, waitLeftOf, } from "../models/checkout.view.utils.js";
8
+ import { useNow, useReturnCountdown, useToast } from "./use-checkout-timers.js";
9
+ import { usePhoneNumber } from "./use-phone-number.js";
10
+ /** Before the payment has loaded, or for a link that matches none. */
11
+ const NO_PAYMENT_UI = {
12
+ tab: CheckoutTabEnum.MOBILE_MONEY,
13
+ country: CountryEnum.CAMEROON,
14
+ method: null,
15
+ code: '',
16
+ cardComplete: false,
17
+ cardPaying: false,
18
+ step: CheckoutStepEnum.METHOD,
19
+ summaryOpen: false,
20
+ submitting: false,
21
+ dismissed: null,
22
+ redirecting: false,
23
+ methodMissing: 0,
24
+ payerCountry: null,
25
+ countrySent: false,
26
+ payerName: '',
27
+ nameMissing: 0,
28
+ otherBanksOpen: false,
29
+ };
30
+ /**
31
+ * The whole checkout for one payment, on any platform: the gateway's live
32
+ * view of it, what the payer does, the number, the clocks, and every action
33
+ * the screens can take. What only a platform can do (coming back, the
34
+ * clipboard, leaving for the app, the card fields page) comes in `platform`.
35
+ * The language is not here: it comes from the IntlProvider around it.
36
+ */
37
+ export function useCheckoutController(view, { clues, calls, platform }) {
38
+ const t = useTranslations('checkout');
39
+ const mutations = calls?.mutations ?? null;
40
+ const lang = useLocale();
41
+ const [patch, setPatch] = useState({});
42
+ const [helpOpen, setHelpOpen] = useState(false);
43
+ const [copied, setCopied] = useState(false);
44
+ const copiedTimer = useRef(undefined);
45
+ /** A Pay press is on its way: a second tap must not start another attempt. */
46
+ const paying = useRef(false);
47
+ const [cardHeight, setCardHeight] = useState(null);
48
+ const [cardBankPage, setCardBankPage] = useState(false);
49
+ const toast = useToast();
50
+ const ui = {
51
+ ...(view ? initialUi(view, clues) : NO_PAYMENT_UI),
52
+ ...patch,
53
+ };
54
+ const update = useCallback((next) => setPatch((previous) => ({ ...previous, ...next })), []);
55
+ const countries = view ? countriesOf(view.methods) : [];
56
+ const phone = usePhoneNumber({
57
+ country: ui.country,
58
+ countries,
59
+ // A full number of another country moves the page there; its method follows from the number.
60
+ onCountryChange: (country) => update({ country, method: null }),
61
+ });
62
+ const derived = view
63
+ ? deriveCheckout(view, ui, phone.status)
64
+ : {
65
+ screen: screenOf(view, ui),
66
+ countries,
67
+ wallets: [],
68
+ cards: [],
69
+ otherBanks: [],
70
+ otherBanksOpen: false,
71
+ nameError: false,
72
+ step: CheckoutStepEnum.METHOD,
73
+ selected: null,
74
+ canPay: false,
75
+ detected: null,
76
+ mismatch: null,
77
+ suggestion: null,
78
+ total: { amount: 0, currency: CurrencyEnum.XAF },
79
+ };
80
+ const { screen } = derived;
81
+ const attempt = view?.attempt ?? null;
82
+ // The payer's number from the app, once the field exists.
83
+ const prefill = view?.payer.phone;
84
+ const { fill } = phone;
85
+ useEffect(() => {
86
+ if (prefill)
87
+ fill(prefill);
88
+ }, [prefill, fill]);
89
+ const waiting = screen === CheckoutScreenEnum.WAITING;
90
+ const now = useNow(waiting);
91
+ const waitLeft = attempt ? waitLeftOf(attempt.startedAt, now) : 0;
92
+ const attemptReference = attempt?.reference;
93
+ // A store's sheet and PayPal's window take their own time.
94
+ const timed = !attempt || FLOW_TRAITS[attempt.flow].clock;
95
+ const noAnswer = t('toast.no_answer');
96
+ const showToast = toast.show;
97
+ useEffect(() => {
98
+ if (!waiting || !timed || waitLeft > 0)
99
+ return;
100
+ update({ dismissed: attemptReference });
101
+ showToast(noAnswer, CheckoutToastToneEnum.WARNING);
102
+ }, [waiting, timed, waitLeft, attemptReference, noAnswer, showToast, update]);
103
+ // A number that tells its method picks it when none is picked, once per
104
+ // number. The app's own number picks without a word. Off the form, or on the Card tab,
105
+ // the number is not looked at: it counts once the payer is back on Mobile Money.
106
+ const detectedMethod = derived.detected;
107
+ const numberE164 = phone.e164;
108
+ const onMobileForm = screen === CheckoutScreenEnum.FORM &&
109
+ ui.tab === CheckoutTabEnum.MOBILE_MONEY;
110
+ const nonePicked = !derived.selected;
111
+ const lastKey = useRef('');
112
+ useEffect(() => {
113
+ if (!onMobileForm)
114
+ return;
115
+ const key = detectedMethod ? `${detectedMethod.id}|${numberE164}` : '';
116
+ if (key === lastKey.current)
117
+ return;
118
+ lastKey.current = key;
119
+ if (!detectedMethod || !nonePicked)
120
+ return;
121
+ update(pickedPatch(detectedMethod.id));
122
+ if (numberE164 !== prefill) {
123
+ showToast(t('toast.switched', { method: detectedMethod.name }), CheckoutToastToneEnum.SUCCESS, logoOf(detectedMethod));
124
+ }
125
+ }, [
126
+ onMobileForm,
127
+ detectedMethod,
128
+ numberE164,
129
+ nonePicked,
130
+ prefill,
131
+ t,
132
+ showToast,
133
+ update,
134
+ ]);
135
+ const paymentId = view?.id;
136
+ const fail = calls?.fail;
137
+ // A payer opened the link, said once per page (the dashboard's preview has
138
+ // no mutations), with the phone's store to price a product payment. A lost
139
+ // open would leave a product payment on its skeleton: it is tried again a
140
+ // few times, and given up, the payment is marked failed so the page says so.
141
+ const opened = useRef(null);
142
+ useEffect(() => {
143
+ if (!paymentId || !mutations || opened.current === paymentId)
144
+ return;
145
+ opened.current = paymentId;
146
+ const tryOpen = (store, left) => mutations.open({ paymentId, ...store }).then(() => undefined, (error) => {
147
+ platform.report?.(error, 'open');
148
+ if (left <= 1) {
149
+ fail?.();
150
+ return undefined;
151
+ }
152
+ return new Promise((resolve) => setTimeout(resolve, OPEN_RETRY_MS)).then(() => tryOpen(store, left - 1));
153
+ });
154
+ void platform
155
+ .phoneStore()
156
+ .catch(() => null)
157
+ .then((store) => tryOpen(store, OPEN_TRIES));
158
+ }, [paymentId, mutations, platform, fail]);
159
+ // Away from the page or the app while waiting, the payment is not followed
160
+ // live. Coming back follows again at once and asks the provider now (ADR
161
+ // 0001): the live connection must not wait on a check that hangs.
162
+ const [away, setAway] = useState(false);
163
+ useEffect(() => {
164
+ if (!waiting || !paymentId || !mutations)
165
+ return undefined;
166
+ // Already away when the wait starts (off to the dialler): not followed until back.
167
+ if (platform.isAway())
168
+ setAway(true);
169
+ const stopLeave = platform.onLeave(() => setAway(true));
170
+ const stopReturn = platform.onReturn(() => {
171
+ setAway(false);
172
+ void mutations
173
+ .checkNow({ paymentId })
174
+ .catch((error) => platform.report?.(error, 'checkNow'));
175
+ });
176
+ return () => {
177
+ stopLeave();
178
+ stopReturn();
179
+ setAway(false);
180
+ };
181
+ }, [waiting, paymentId, mutations, platform]);
182
+ // Followed live only on the waiting screen (ADR 0006).
183
+ const followed = waiting && !away;
184
+ const follow = calls?.follow;
185
+ useEffect(() => {
186
+ follow?.(followed);
187
+ }, [follow, followed]);
188
+ const refresh = calls?.refresh;
189
+ const goBack = useCallback(() => update({ redirecting: true }), [update]);
190
+ const countdown = useReturnCountdown(screen === CheckoutScreenEnum.SUCCESS, goBack);
191
+ const returnUrl = view?.returnUrl;
192
+ useEffect(() => {
193
+ if (ui.redirecting && returnUrl)
194
+ platform.openUrl(returnUrl);
195
+ }, [ui.redirecting, returnUrl, platform]);
196
+ useEffect(() => () => clearTimeout(copiedTimer.current), []);
197
+ // PayPal's window, or the bank's, has nothing left to do once the payer approved, or the attempt settled.
198
+ const windowDone = !!attempt &&
199
+ FLOW_TRAITS[attempt.flow].providerWindow &&
200
+ (attempt.payerApproved || attempt.status !== AttemptStatusEnum.PENDING);
201
+ useEffect(() => {
202
+ if (windowDone)
203
+ platform.closeProviderWindow();
204
+ }, [windowDone, platform]);
205
+ /** The bank redirect whose window was lost with no word from our return page (ADR 0014). */
206
+ const [lostWindow, setLostWindow] = useState(null);
207
+ const bankWindowLost = waiting &&
208
+ !!attempt &&
209
+ attempt.reference === lostWindow &&
210
+ !attempt.payerApproved;
211
+ const failedToast = t('toast.failed');
212
+ const refusals = useCallback((reason) => t(`refusals.${reason}`), [t]);
213
+ // The card fields page says how it stands; the card itself never comes here.
214
+ useEffect(() => {
215
+ const onMessage = (message) => {
216
+ switch (message.type) {
217
+ case CardFieldsMessageEnum.HEIGHT:
218
+ setCardHeight(message.height);
219
+ break;
220
+ case CardFieldsMessageEnum.BANK_PAGE:
221
+ setCardBankPage(message.showing);
222
+ break;
223
+ case CardFieldsMessageEnum.STATE:
224
+ // Incomplete on Pay: the fields say what is missing, the form stays.
225
+ update({
226
+ cardComplete: message.complete,
227
+ ...(message.complete ? {} : { cardPaying: false }),
228
+ });
229
+ break;
230
+ // The card is with its provider: read the attempt, the waiting screen follows the checks.
231
+ case CardFieldsMessageEnum.DONE:
232
+ update({ cardPaying: false });
233
+ refresh?.();
234
+ break;
235
+ // Nothing to read: the attempt only closes, and the form stays.
236
+ case CardFieldsMessageEnum.CLOSED:
237
+ update({ cardPaying: false });
238
+ break;
239
+ case CardFieldsMessageEnum.REFUSED:
240
+ update({ cardPaying: false });
241
+ showToast(message.reason ? refusals(message.reason) : failedToast, CheckoutToastToneEnum.WARNING);
242
+ break;
243
+ }
244
+ };
245
+ return platform.onCardMessage(onMessage);
246
+ }, [update, showToast, refusals, failedToast, platform, refresh]);
247
+ /* ---------------------------------------------------------- helpers */
248
+ const reference = attempt?.reference ?? view?.id ?? '';
249
+ const comingSoon = (name) => toast.show(t('toast.soon', { method: name }), CheckoutToastToneEnum.INFO);
250
+ /**
251
+ * Starts an attempt with the number, and the payment code of an OTP
252
+ * method; a second tap while one is on its way does nothing.
253
+ */
254
+ const submit = (method, { phone: e164, otp }) => {
255
+ if (paying.current)
256
+ return;
257
+ paying.current = true;
258
+ update({ submitting: true });
259
+ const args = { paymentId: view.id, method, phone: e164 };
260
+ void (otp === undefined
261
+ ? mutations.pay(args)
262
+ : mutations.payWithCode({ ...args, otp }))
263
+ .then((result) => {
264
+ if (!result.ok)
265
+ toast.show(t(`refusals.${result.reason}`), CheckoutToastToneEnum.WARNING);
266
+ })
267
+ .catch((error) => {
268
+ platform.report?.(error, 'pay');
269
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
270
+ })
271
+ .finally(() => {
272
+ paying.current = false;
273
+ update({ submitting: false });
274
+ });
275
+ };
276
+ /**
277
+ * Pay in a window of PayPal's (ADR 0010, 0014): it opens at once (a
278
+ * browser blocks one opened later), our attempt and PayPal's order are
279
+ * opened (`start`), and the window goes to PayPal, or to the bank. How it
280
+ * ends tells the gateway: approved, it checks now; closed, it checks
281
+ * whether it was; back on our return page, that page told it. A bank's
282
+ * window lost without a word from that page is no proof of a cancel: the
283
+ * check runs on, and the payer may say they did not finish. A method
284
+ * PayPal cannot take sends the payer back to the methods.
285
+ */
286
+ const payInWindow = (method, open, start, about) => {
287
+ if (paying.current)
288
+ return;
289
+ let resolveStarted;
290
+ const started = new Promise((resolve) => {
291
+ resolveStarted = resolve;
292
+ });
293
+ const ended = open(started);
294
+ if (!ended) {
295
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
296
+ return;
297
+ }
298
+ paying.current = true;
299
+ update({ submitting: true });
300
+ void start()
301
+ .then((result) => {
302
+ resolveStarted(result);
303
+ if (!result.ok) {
304
+ toast.show(t(`refusals.${result.reason}`), CheckoutToastToneEnum.WARNING);
305
+ }
306
+ else if (result.unavailable) {
307
+ update({
308
+ dismissed: result.reference,
309
+ method: null,
310
+ step: CheckoutStepEnum.METHOD,
311
+ });
312
+ toast.show(t('toast.method_unavailable', { method: method.name }), CheckoutToastToneEnum.WARNING, logoOf(method));
313
+ }
314
+ else if (!result.approvalUrl) {
315
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
316
+ }
317
+ })
318
+ .catch((error) => {
319
+ resolveStarted(null);
320
+ platform.report?.(error, about);
321
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
322
+ })
323
+ .finally(() => {
324
+ paying.current = false;
325
+ update({ submitting: false });
326
+ });
327
+ void Promise.all([ended, started])
328
+ .then(([end, result]) => {
329
+ // No link: the attempt failed with its start, nothing to close.
330
+ if (!result?.ok || !result.approvalUrl)
331
+ return null;
332
+ const attemptRef = result.reference;
333
+ if (end === ProviderWindowEndEnum.RETURNED)
334
+ return null;
335
+ if (end === ProviderWindowEndEnum.LOST) {
336
+ setLostWindow(attemptRef);
337
+ return null;
338
+ }
339
+ const told = end === ProviderWindowEndEnum.APPROVED
340
+ ? mutations.paypalReturned
341
+ : mutations.paypalClosed;
342
+ return told({ reference: attemptRef });
343
+ })
344
+ .then(() => refresh?.())
345
+ .catch((error) => platform.report?.(error, 'paypalClosed'));
346
+ };
347
+ /* ---------------------------------------------------------- actions */
348
+ const actions = {
349
+ // One tap opens one attempt, however often it is tapped.
350
+ payWithStore: async (store, refundConsent) => {
351
+ const storeCalls = mutations?.store;
352
+ if (!storeCalls || paying.current)
353
+ return null;
354
+ paying.current = true;
355
+ update({ submitting: true });
356
+ try {
357
+ const result = await storeCalls.payWithStore({
358
+ paymentId: view.id,
359
+ store,
360
+ refundConsent,
361
+ });
362
+ if (result.ok)
363
+ return result;
364
+ toast.show(t(`refusals.${result.reason}`), CheckoutToastToneEnum.WARNING);
365
+ }
366
+ catch (error) {
367
+ platform.report?.(error, 'payWithStore');
368
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
369
+ }
370
+ finally {
371
+ paying.current = false;
372
+ update({ submitting: false });
373
+ }
374
+ return null;
375
+ },
376
+ toggleSummary: () => update({ summaryOpen: !ui.summaryOpen }),
377
+ setTab: (tab) => update({ tab }),
378
+ setCountry: (country) => update({ country, method: null, step: CheckoutStepEnum.METHOD }),
379
+ selectMethod: (method) => {
380
+ if (method.state === MethodStateEnum.SOON) {
381
+ comingSoon(method.name);
382
+ }
383
+ else if (method.state === MethodStateEnum.MAINTENANCE) {
384
+ toast.show(method.note ?? t('toast.unavailable', { method: method.name }), CheckoutToastToneEnum.WARNING, logoOf(method));
385
+ }
386
+ else {
387
+ // Picked on the methods: the details wait for Continue.
388
+ update({ ...pickedPatch(method.id), step: CheckoutStepEnum.METHOD });
389
+ }
390
+ },
391
+ comingSoon,
392
+ continueToDetails: () => update(derived.selected
393
+ ? { step: CheckoutStepEnum.DETAILS }
394
+ : { methodMissing: ui.methodMissing + 1 }),
395
+ // Not while Pay is on its way: the card fields page would go with it.
396
+ backToMethods: () => {
397
+ if (ui.submitting || ui.cardPaying)
398
+ return;
399
+ update({ step: CheckoutStepEnum.METHOD, code: '', cardComplete: false });
400
+ },
401
+ // Only offered while the number belongs to another method.
402
+ switchToDetected: () => {
403
+ const detected = derived.mismatch;
404
+ update({ method: detected.id });
405
+ toast.show(t('toast.switched', { method: detected.name }), CheckoutToastToneEnum.SUCCESS, logoOf(detected));
406
+ },
407
+ // Only offered on the details, which need a usable method.
408
+ pay: () => {
409
+ const selected = derived.selected;
410
+ const { route } = FLOW_TRAITS[selected.flow];
411
+ const missing = missingBeforePay(selected, payInputOf(ui, phone.status));
412
+ if (missing.includes(FlowAskEnum.NAME)) {
413
+ update({ nameMissing: ui.nameMissing + 1 });
414
+ return;
415
+ }
416
+ if (missing.includes(FlowAskEnum.PHONE)) {
417
+ phone.reject();
418
+ platform.onPhoneRejected();
419
+ return;
420
+ }
421
+ if (missing.includes(FlowAskEnum.CODE)) {
422
+ toast.show(t(`refusals.${PayRefusalEnum.CODE}`), CheckoutToastToneEnum.WARNING);
423
+ return;
424
+ }
425
+ // The preview offers no card: it shows Mobile Money only.
426
+ if (route === PayRouteEnum.CARD) {
427
+ // A second tap while the fields pay would start a second attempt.
428
+ if (ui.cardPaying)
429
+ return;
430
+ // The fields page pays with its provider, then says how it went.
431
+ update({ cardPaying: true });
432
+ try {
433
+ platform.submitCard();
434
+ }
435
+ catch (error) {
436
+ platform.report?.(error, 'card');
437
+ update({ cardPaying: false });
438
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
439
+ }
440
+ return;
441
+ }
442
+ if (!mutations) {
443
+ toast.show(t('toast.preview'), CheckoutToastToneEnum.INFO);
444
+ return;
445
+ }
446
+ const args = { paymentId: view.id, method: selected.id };
447
+ if (route === PayRouteEnum.BANK) {
448
+ const payerName = fullNameOf(ui.payerName);
449
+ payInWindow(selected, platform.openBankRedirect, () => mutations.startBankRedirect({ ...args, payerName }), 'bankRedirect');
450
+ return;
451
+ }
452
+ if (route === PayRouteEnum.PAYPAL) {
453
+ payInWindow(selected, platform.openPaypal, () => mutations.startPaypal(args), 'paypal');
454
+ return;
455
+ }
456
+ // A phone prompt, or a payment code with its number.
457
+ submit(selected.id, {
458
+ phone: phone.e164,
459
+ ...(route === PayRouteEnum.CODE ? { otp: ui.code } : {}),
460
+ });
461
+ },
462
+ // Only offered while an OTP method, which always has its code, is picked.
463
+ cannotDial: () => {
464
+ const method = derived.selected;
465
+ toast.show(t('toast.dial', { code: method.otpCode, method: method.name }), CheckoutToastToneEnum.INFO, logoOf(method));
466
+ },
467
+ // Only on the failure screen, which the preview never shows.
468
+ retry: () => {
469
+ // A payment code works once, a card is typed again: back to the form.
470
+ const traits = FLOW_TRAITS[attempt.flow];
471
+ if (!traits.prompt) {
472
+ update({
473
+ dismissed: attempt.reference,
474
+ tab: traits.tab,
475
+ method: attempt.method,
476
+ step: CheckoutStepEnum.DETAILS,
477
+ code: '',
478
+ cardComplete: false,
479
+ });
480
+ return;
481
+ }
482
+ submit(attempt.method, { phone: attempt.phone });
483
+ },
484
+ setPayerName: (payerName) => update({ payerName }),
485
+ showOtherBanks: () => update({ otherBanksOpen: true }),
486
+ // Only offered while the waiting bank redirect's window is lost.
487
+ notFinished: () => {
488
+ void mutations
489
+ .paypalClosed({ reference: attempt.reference })
490
+ .then(() => refresh?.())
491
+ .catch((error) => {
492
+ platform.report?.(error, 'paypalClosed');
493
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
494
+ });
495
+ },
496
+ setCode: (code) => update({ code: code.replace(/\D/g, '').slice(0, OTP_MAX_LENGTH) }),
497
+ useAnother: () => {
498
+ const { suggestion } = derived;
499
+ update({
500
+ dismissed: attempt.reference,
501
+ tab: CheckoutTabEnum.MOBILE_MONEY,
502
+ country: suggestion?.country ?? ui.country,
503
+ method: suggestion?.id ?? null,
504
+ step: CheckoutStepEnum.METHOD,
505
+ });
506
+ },
507
+ // Only offered on a waiting attempt's steps.
508
+ cannotDialCode: (code) => {
509
+ toast.show(t('toast.dial', { code, method: attempt.methodName }), CheckoutToastToneEnum.INFO, logoOf(attempt));
510
+ },
511
+ sendAgain: () => {
512
+ void mutations
513
+ .resend({ paymentId: view.id })
514
+ .then((result) => result.ok
515
+ ? toast.show(t('toast.sent_again', { phone: maskE164(attempt.phone) }), CheckoutToastToneEnum.SUCCESS)
516
+ : toast.show(t('toast.send_again_wait'), CheckoutToastToneEnum.INFO))
517
+ .catch((error) => {
518
+ platform.report?.(error, 'resend');
519
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
520
+ });
521
+ },
522
+ cancel: () => {
523
+ void mutations
524
+ .cancel({ paymentId: view.id })
525
+ .catch((error) => {
526
+ platform.report?.(error, 'cancel');
527
+ toast.show(t('toast.failed'), CheckoutToastToneEnum.WARNING);
528
+ });
529
+ },
530
+ returnNow: goBack,
531
+ openHelp: () => setHelpOpen(true),
532
+ closeHelp: () => setHelpOpen(false),
533
+ copyReference: () => {
534
+ platform.copyText(reference);
535
+ clearTimeout(copiedTimer.current);
536
+ setCopied(true);
537
+ copiedTimer.current = setTimeout(() => setCopied(false), COPIED_MS);
538
+ toast.show(t('toast.copied'), CheckoutToastToneEnum.SUCCESS);
539
+ },
540
+ simulate: (outcome) => {
541
+ void mutations
542
+ .simulate({ paymentId: view.id, outcome })
543
+ .catch((error) => platform.report?.(error, 'simulate'));
544
+ },
545
+ };
546
+ return {
547
+ view: view ?? null,
548
+ ui,
549
+ derived,
550
+ phone,
551
+ waitLeft,
552
+ dialHelp: dialHelpOf(attempt, lang),
553
+ returnLeft: countdown,
554
+ helpOpen,
555
+ toast: toast.toast,
556
+ copied,
557
+ preview: !mutations,
558
+ cardHeight,
559
+ cardBankPage,
560
+ bankWindowLost,
561
+ actions,
562
+ };
563
+ }
@@ -0,0 +1,9 @@
1
+ import type { CheckoutConnection, CheckoutPayment, CheckoutPlatform } from '../models/checkout.interface.js';
2
+ /**
3
+ * One payment for a checkout (ADR 0006): read once over plain calls, read
4
+ * again after each call that changes it, and followed live only between
5
+ * `follow(true)` and `follow(false)`, which the controller says while the
6
+ * payer is on the waiting screen. Once `paymentId` is cleared (a sheet
7
+ * closing) the last answer stays.
8
+ */
9
+ export declare function useCheckoutPayment(connection: CheckoutConnection, paymentId: string | null, report?: CheckoutPlatform['report']): CheckoutPayment;