@brissoto/pay-react-native 0.0.0-stage → 1.4.5

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 +180 -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 +297 -0
  47. package/dist/checkout-core/messages/en.js +296 -0
  48. package/dist/checkout-core/messages/fr.d.ts +4 -0
  49. package/dist/checkout-core/messages/fr.js +297 -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 +230 -0
  57. package/dist/checkout-core/models/checkout.enum.js +256 -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 +696 -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 +328 -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 +132 -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 +139 -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 +3 -0
  129. package/dist/components/SheetTerminal.js +21 -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 +423 -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 +211 -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,7 @@
1
+ import type { CurrencyEnum } from './domain.enum.js';
2
+ /** 15000 XAF → "15 000", 1250 EUR → "12.50": grouped with a narrow no-break space, so it never wraps. */
3
+ export declare function formatAmount(minor: number, currency: CurrencyEnum): string;
4
+ /** "15 000 FCFA". */
5
+ export declare function formatMoney(minor: number, currency: CurrencyEnum): string;
6
+ /** "02:05" style clock for the approval countdown. */
7
+ export declare function formatClock(totalSeconds: number): string;
@@ -0,0 +1,21 @@
1
+ import { CURRENCY_DECIMALS, CURRENCY_LABEL } from "./checkout.constants.js";
2
+ const THIN_SPACE = ' ';
3
+ /** 15000 XAF → "15 000", 1250 EUR → "12.50": grouped with a narrow no-break space, so it never wraps. */
4
+ export function formatAmount(minor, currency) {
5
+ const decimals = CURRENCY_DECIMALS[currency];
6
+ const [whole, fraction] = (minor / 10 ** decimals)
7
+ .toFixed(decimals)
8
+ .split('.');
9
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, THIN_SPACE);
10
+ return fraction ? `${grouped}.${fraction}` : grouped;
11
+ }
12
+ /** "15 000 FCFA". */
13
+ export function formatMoney(minor, currency) {
14
+ return `${formatAmount(minor, currency)} ${CURRENCY_LABEL[currency]}`;
15
+ }
16
+ /** "02:05" style clock for the approval countdown. */
17
+ export function formatClock(totalSeconds) {
18
+ const minutes = Math.floor(totalSeconds / 60);
19
+ const seconds = String(totalSeconds % 60).padStart(2, '0');
20
+ return `${minutes}:${seconds}`;
21
+ }
@@ -0,0 +1,33 @@
1
+ import { CountryEnum } from './domain.enum.js';
2
+ import type { OperatorDetection, PhoneInputs, PhoneStatus, TypedNumber } from './checkout.interface.js';
3
+ /** Which operator a number belongs to, from its first digits. */
4
+ export declare function detectOperator(country: CountryEnum, digits: string): OperatorDetection;
5
+ /**
6
+ * What the field should say about the number typed so far, by the country's
7
+ * own mobile rules. Errors that typing more can never fix (a wrong first
8
+ * digit) show at once; the rest wait until the field is left or Pay pressed.
9
+ */
10
+ export declare function getPhoneStatus({ country, digits, foreign, touched, focused, submitTried, }: PhoneInputs): PhoneStatus;
11
+ /** "691234567" → "6 91 23 45 67", grouped the way the country writes it. */
12
+ export declare function formatNational(digits: string, country: CountryEnum): string;
13
+ /** "+33612345678" → "+33 6 12 34 56 78": a full number, grouped its country's way. */
14
+ export declare function formatInternational(number: string): string;
15
+ /** A real-looking mobile number of the country, for the empty field. */
16
+ export declare function placeholderOf(country: CountryEnum): string;
17
+ /** The number as providers want it: `+237691234567`. Empty while incomplete. */
18
+ export declare function toE164(digits: string, country: CountryEnum): string;
19
+ /**
20
+ * Reads what the payer typed or pasted. A national number stays in the
21
+ * country; a full international one (`+225…`, `00225…`) moves to its country
22
+ * when the payment can be paid there, and is kept as typed until its country
23
+ * is known.
24
+ */
25
+ export declare function readTypedNumber(raw: string, country: CountryEnum, countries: Array<CountryEnum>): TypedNumber;
26
+ /** "6 91 23 45 67" → "6 91 •• •• 67": keeps the first 3 and last 2 digits. */
27
+ export declare function maskNumber(formatted: string): string;
28
+ /** Where the caret goes in `formatted` to sit after its `count`-th digit. */
29
+ export declare function caretAfterDigits(formatted: string, count: number): number;
30
+ /** A USSD code as a link that dials it: `#` must be escaped in a `tel:` URL. */
31
+ export declare function telHref(code: string): string;
32
+ /** `+237691234567` → `+237 6 91 •• •• 67`: the dial code, then the number masked. */
33
+ export declare function maskE164(phone: string): string;
@@ -0,0 +1,159 @@
1
+ import { AsYouType, getExampleNumber, isValidPhoneNumber, parsePhoneNumberFromString, validatePhoneNumberLength, } from 'libphonenumber-js/mobile';
2
+ import examples from 'libphonenumber-js/mobile/examples';
3
+ import { DIAL_CODES } from "./checkout.constants.js";
4
+ import { CountryEnum } from "./domain.enum.js";
5
+ import { MethodBrandEnum, PhoneErrorEnum } from "./checkout.enum.js";
6
+ /** Cameroon mobile numbers are 9 digits and always start with 6. */
7
+ const CAMEROON_LENGTH = 9;
8
+ const MTN_CAMEROON = /^6(7\d|5[0-4]|8[0-4])$/;
9
+ const ORANGE_CAMEROON = /^6(9\d|5[5-9]|8[5-9]|4\d)$/;
10
+ const CI_OPERATOR_BY_PREFIX = {
11
+ '07': MethodBrandEnum.ORANGE,
12
+ '05': MethodBrandEnum.MTN,
13
+ '01': MethodBrandEnum.MOOV,
14
+ };
15
+ /** `cm` → `CM`, the library's country code. */
16
+ function codeOf(country) {
17
+ return country.toUpperCase();
18
+ }
19
+ /** Which operator a number belongs to, from its first digits. */
20
+ export function detectOperator(country, digits) {
21
+ if (country === CountryEnum.CAMEROON) {
22
+ if (digits.length < 3)
23
+ return { operator: null, unrecognized: false };
24
+ const prefix = digits.slice(0, 3);
25
+ if (MTN_CAMEROON.test(prefix))
26
+ return { operator: MethodBrandEnum.MTN, unrecognized: false };
27
+ if (ORANGE_CAMEROON.test(prefix))
28
+ return { operator: MethodBrandEnum.ORANGE, unrecognized: false };
29
+ return { operator: null, unrecognized: true };
30
+ }
31
+ if (country === CountryEnum.COTE_D_IVOIRE && digits.length >= 2) {
32
+ return {
33
+ operator: CI_OPERATOR_BY_PREFIX[digits.slice(0, 2)] ?? null,
34
+ unrecognized: false,
35
+ };
36
+ }
37
+ return { operator: null, unrecognized: false };
38
+ }
39
+ /**
40
+ * What the field should say about the number typed so far, by the country's
41
+ * own mobile rules. Errors that typing more can never fix (a wrong first
42
+ * digit) show at once; the rest wait until the field is left or Pay pressed.
43
+ */
44
+ export function getPhoneStatus({ country, digits, foreign, touched, focused, submitTried, }) {
45
+ const isCameroon = country === CountryEnum.CAMEROON;
46
+ const { operator, unrecognized } = detectOperator(country, digits);
47
+ const valid = isValidPhoneNumber(digits, codeOf(country));
48
+ let error = null;
49
+ if (isCameroon && digits.length > 0 && !digits.startsWith('6')) {
50
+ error = PhoneErrorEnum.START;
51
+ }
52
+ else if (isCameroon && digits.length === CAMEROON_LENGTH && unrecognized) {
53
+ error = PhoneErrorEnum.OPERATOR;
54
+ }
55
+ else if ((touched && !focused) || submitTried) {
56
+ if (foreign) {
57
+ error = PhoneErrorEnum.COUNTRY;
58
+ }
59
+ else if (digits.length === 0) {
60
+ if (submitTried)
61
+ error = PhoneErrorEnum.EMPTY;
62
+ }
63
+ else if (validatePhoneNumberLength(digits, codeOf(country)) === 'TOO_SHORT') {
64
+ error = PhoneErrorEnum.SHORT;
65
+ }
66
+ else if (!valid) {
67
+ error = PhoneErrorEnum.INVALID;
68
+ }
69
+ }
70
+ return { error, valid: error === null && valid, operator };
71
+ }
72
+ /** "691234567" → "6 91 23 45 67", grouped the way the country writes it. */
73
+ export function formatNational(digits, country) {
74
+ return new AsYouType(codeOf(country)).input(digits);
75
+ }
76
+ /** "+33612345678" → "+33 6 12 34 56 78": a full number, grouped its country's way. */
77
+ export function formatInternational(number) {
78
+ return new AsYouType().input(number);
79
+ }
80
+ /** A real-looking mobile number of the country, for the empty field. */
81
+ export function placeholderOf(country) {
82
+ return getExampleNumber(codeOf(country), examples).formatNational();
83
+ }
84
+ /** The number as providers want it: `+237691234567`. Empty while incomplete. */
85
+ export function toE164(digits, country) {
86
+ return parsePhoneNumberFromString(digits, codeOf(country))?.number ?? '';
87
+ }
88
+ /** Drops the digits past the longest number the country has. */
89
+ function fit(digits, country) {
90
+ let kept = digits;
91
+ while (validatePhoneNumberLength(kept, codeOf(country)) === 'TOO_LONG') {
92
+ kept = kept.slice(0, -1);
93
+ }
94
+ return kept;
95
+ }
96
+ /**
97
+ * Reads what the payer typed or pasted. A national number stays in the
98
+ * country; a full international one (`+225…`, `00225…`) moves to its country
99
+ * when the payment can be paid there, and is kept as typed until its country
100
+ * is known.
101
+ */
102
+ export function readTypedNumber(raw, country, countries) {
103
+ const text = raw.trim();
104
+ if (text.startsWith('+') || text.startsWith('00')) {
105
+ const international = `+${text.replace(/^(\+|00)/, '').replace(/\D/g, '')}`;
106
+ const typer = new AsYouType();
107
+ typer.input(international);
108
+ const found = typer.getCountry()?.toLowerCase();
109
+ if (found && countries.includes(found)) {
110
+ return {
111
+ country: found,
112
+ // A known country comes with its digits.
113
+ digits: fit(typer.getNumber().nationalNumber, found),
114
+ pending: null,
115
+ };
116
+ }
117
+ return { country, digits: '', pending: international };
118
+ }
119
+ const typed = text.replace(/\D/g, '');
120
+ // "237691234567": the dial code typed without its plus.
121
+ const parsed = typed.startsWith(DIAL_CODES[country])
122
+ ? parsePhoneNumberFromString(typed, codeOf(country))
123
+ : undefined;
124
+ const digits = parsed?.isValid() ? parsed.nationalNumber : typed;
125
+ return { country, digits: fit(digits, country), pending: null };
126
+ }
127
+ /** "6 91 23 45 67" → "6 91 •• •• 67": keeps the first 3 and last 2 digits. */
128
+ export function maskNumber(formatted) {
129
+ const total = (formatted.match(/\d/g) ?? []).length;
130
+ let seen = 0;
131
+ return formatted.replace(/\d/g, (digit) => {
132
+ seen += 1;
133
+ return seen <= 3 || seen > total - 2 ? digit : '•';
134
+ });
135
+ }
136
+ /** Where the caret goes in `formatted` to sit after its `count`-th digit. */
137
+ export function caretAfterDigits(formatted, count) {
138
+ if (count === 0)
139
+ return 0;
140
+ let seen = 0;
141
+ for (let index = 0; index < formatted.length; index++) {
142
+ if (/\d/.test(formatted[index]))
143
+ seen += 1;
144
+ if (seen === count)
145
+ return index + 1;
146
+ }
147
+ return formatted.length;
148
+ }
149
+ /** A USSD code as a link that dials it: `#` must be escaped in a `tel:` URL. */
150
+ export function telHref(code) {
151
+ return `tel:${code.replace(/#/g, '%23')}`;
152
+ }
153
+ /** `+237691234567` → `+237 6 91 •• •• 67`: the dial code, then the number masked. */
154
+ export function maskE164(phone) {
155
+ const parsed = parsePhoneNumberFromString(phone);
156
+ if (!parsed)
157
+ return maskNumber(phone);
158
+ return `+${parsed.countryCallingCode} ${maskNumber(parsed.formatNational())}`;
159
+ }
@@ -0,0 +1,77 @@
1
+ import { CheckoutScreenEnum, FlowAskEnum, SimulatorOutcomeEnum } from './checkout.enum.js';
2
+ import { CountryEnum } from './domain.enum.js';
3
+ import type { LangEnum, ProviderLogoEnum } from './domain.enum.js';
4
+ import type { CheckoutApp, CheckoutAttempt, CheckoutDerived, CheckoutMethod, CheckoutPreviewApp, CheckoutUi, CheckoutView, CountryClues, DialHelp, PayInput, PhoneStatus, SupportContact } from './checkout.interface.js';
5
+ /** Countries with Mobile Money methods, in the order their first method comes. */
6
+ export declare function countriesOf(methods: Array<CheckoutMethod>): Array<CountryEnum>;
7
+ /**
8
+ * The Mobile Money country the page opens on: the payer country when this
9
+ * payment has Mobile Money there, else the first country it has; with none,
10
+ * the first the gateway serves, for a page that has nothing to offer.
11
+ */
12
+ export declare function pickCountry(view: CheckoutView, clues: CountryClues, countries: Array<CountryEnum>): CountryEnum;
13
+ /**
14
+ * How the page opens: on the details of the app's preferred method when it
15
+ * can be paid with, or of the only one that can; else on the methods, on its
16
+ * preferred tab. Without one, a payer country with no Mobile Money opens the
17
+ * Card tab, when there is a card to pay with.
18
+ */
19
+ export declare function initialUi(view: CheckoutView, clues: CountryClues): CheckoutUi;
20
+ /** Which screen shows: the payment's status first, then what the payer is doing. */
21
+ export declare function screenOf(view: CheckoutView | null | undefined, ui: CheckoutUi): CheckoutScreenEnum;
22
+ /** The brand of a Mobile Money method, which a number's first digits can reveal. */
23
+ export declare function brandOf(method: CheckoutMethod): string;
24
+ /** What the page keeps when a method is picked: the step stays, what the last one had starts over. */
25
+ export declare function pickedPatch(id: string): Partial<CheckoutUi>;
26
+ /**
27
+ * What the form still needs before Pay, by what the method's flow asks for
28
+ * (`FLOW_TRAITS.asks`): none, Pay can go. The one answer for whether Pay is
29
+ * on, what Pay points at when pressed early, and the name field's error.
30
+ */
31
+ export declare function missingBeforePay(method: Pick<CheckoutMethod, 'flow'>, input: PayInput): Array<FlowAskEnum>;
32
+ /** What the page holds of the payer's input, as `missingBeforePay` reads it. */
33
+ export declare const payInputOf: (ui: CheckoutUi, phone: PhoneStatus) => PayInput;
34
+ /** The tile of a method or an attempt: the generic card for cards, whatever networks they take. */
35
+ export declare function logoOf(of: Pick<CheckoutMethod, 'flow' | 'logos'>): ProviderLogoEnum;
36
+ /** Works out what the screens show from the payment, the page and the number typed. */
37
+ export declare function deriveCheckout(view: CheckoutView, ui: CheckoutUi, phone: PhoneStatus): CheckoutDerived;
38
+ /** Seconds left to approve an attempt started at `startedAt`. */
39
+ export declare function waitLeftOf(startedAt: number, now: number): number;
40
+ /** The payer can still ask for a new request of this attempt. */
41
+ export declare const canSendAgain: (attempt: Pick<CheckoutAttempt, "sendsLeft">) => boolean;
42
+ /**
43
+ * What the waiting screen offers a payer with no prompt. USSD is the last
44
+ * resort: it shows after the last new request, or at once when the network's
45
+ * prompt never shows by itself, in the payer's language; a channel that only
46
+ * differs in its other language or by letter case shows once. The method's own
47
+ * code to see pending payments takes over when there are no steps to show.
48
+ * Nothing for a flow with no prompt.
49
+ */
50
+ export declare function dialHelpOf(attempt: CheckoutAttempt | null, lang: LangEnum): DialHelp;
51
+ /**
52
+ * What the Simulator offers the tester: what the flow can do, and a success on
53
+ * every send only once the payer asked again.
54
+ */
55
+ export declare function simulatorOutcomesOf(attempt: CheckoutAttempt): Array<SimulatorOutcomeEnum>;
56
+ /**
57
+ * Seconds before the prompt can be sent again: 30 from the last time it went
58
+ * out, by the attempt or by `sentAt`, the second of the wait a sheet just asked at.
59
+ */
60
+ export declare function sendAgainLeftOf(attempt: CheckoutAttempt, waitLeft: number, sentAt?: number): number;
61
+ /** How payers reach the app's support, when it set any. */
62
+ export declare function supportContactsOf(app: CheckoutApp): Array<SupportContact>;
63
+ /** A pending test payment for the Branding tab's preview, branded as typed. */
64
+ export declare function previewView(app: CheckoutPreviewApp, methods: Array<CheckoutMethod>): CheckoutView;
65
+ /**
66
+ * A method's line under its name: the network that runs it ("Orange
67
+ * Cameroun"). A bank redirect names itself (ADR 0014): its line says its
68
+ * country, in the words `countryName` gives.
69
+ */
70
+ export declare function methodLineOf(method: Pick<CheckoutMethod, 'flow' | 'country' | 'network'>, countryName: (country: string) => string): string;
71
+ /**
72
+ * The account holder's full name as a bank redirect sends it (ADR 0014):
73
+ * trimmed, one space between words, a first and a last name at least, of
74
+ * letters, `'` and `-` only. Null when it is not one. The web, the sheet and
75
+ * the backend read it the same way.
76
+ */
77
+ export declare function fullNameOf(typed: string): string | null;
@@ -0,0 +1,328 @@
1
+ import { CARD_LOGO, FLOW_TRAITS, FULL_NAME_MAX_LENGTH, OTP_PATTERN, PREVIEW_AMOUNT, PREVIEW_ORDER_REF, SEND_AGAIN_SECONDS, WAIT_SECONDS, } from "./checkout.constants.js";
2
+ import { payerCountryOf } from "./checkout.country.utils.js";
3
+ import { CheckoutPaymentStatusEnum, CheckoutScreenEnum, CheckoutStepEnum, CheckoutTabEnum, FlowAskEnum, MethodKindEnum, MethodLineEnum, MethodStateEnum, SimulatorOutcomeEnum, SupportChannelEnum, } from "./checkout.enum.js";
4
+ import { AttemptStatusEnum, CountryEnum, CurrencyEnum, FailureReasonEnum, } from "./domain.enum.js";
5
+ /** Countries with Mobile Money methods, in the order their first method comes. */
6
+ export function countriesOf(methods) {
7
+ const countries = methods
8
+ .filter((method) => method.kind === MethodKindEnum.MOBILE_MONEY)
9
+ .map((method) => method.country);
10
+ return [...new Set(countries)];
11
+ }
12
+ /**
13
+ * The Mobile Money country the page opens on: the payer country when this
14
+ * payment has Mobile Money there, else the first country it has; with none,
15
+ * the first the gateway serves, for a page that has nothing to offer.
16
+ */
17
+ export function pickCountry(view, clues, countries) {
18
+ const { payerCountry } = payerCountryOf(view, clues);
19
+ const served = countries.find((country) => country === payerCountry);
20
+ return served ?? countries.at(0) ?? Object.values(CountryEnum)[0];
21
+ }
22
+ /**
23
+ * How the page opens: on the details of the app's preferred method when it
24
+ * can be paid with, or of the only one that can; else on the methods, on its
25
+ * preferred tab. Without one, a payer country with no Mobile Money opens the
26
+ * Card tab, when there is a card to pay with.
27
+ */
28
+ export function initialUi(view, clues) {
29
+ const countries = countriesOf(view.methods);
30
+ const available = view.methods.filter((method) => method.state === MethodStateEnum.AVAILABLE);
31
+ const opening = available.find((method) => method.id === view.preferredMethod) ??
32
+ (available.length === 1 ? available[0] : undefined);
33
+ const payer = payerCountryOf(view, clues);
34
+ const away = !!payer.payerCountry &&
35
+ !countries.some((country) => country === payer.payerCountry) &&
36
+ view.methods.some((method) => method.kind === MethodKindEnum.CARD);
37
+ const base = {
38
+ tab: view.preferredTab ??
39
+ (away && !view.preferredMethod
40
+ ? CheckoutTabEnum.CARD
41
+ : CheckoutTabEnum.MOBILE_MONEY),
42
+ country: pickCountry(view, clues, countries),
43
+ method: null,
44
+ code: '',
45
+ cardComplete: false,
46
+ cardPaying: false,
47
+ step: CheckoutStepEnum.METHOD,
48
+ summaryOpen: false,
49
+ submitting: false,
50
+ dismissed: null,
51
+ redirecting: false,
52
+ methodMissing: 0,
53
+ ...payer,
54
+ payerName: view.payer.name ?? '',
55
+ nameMissing: 0,
56
+ otherBanksOpen: false,
57
+ };
58
+ if (!opening)
59
+ return base;
60
+ return {
61
+ ...base,
62
+ tab: FLOW_TRAITS[opening.flow].tab,
63
+ // Mobile Money methods are grouped by country: the page opens on its own.
64
+ country: opening.kind === MethodKindEnum.MOBILE_MONEY
65
+ ? opening.country
66
+ : base.country,
67
+ method: opening.id,
68
+ step: CheckoutStepEnum.DETAILS,
69
+ };
70
+ }
71
+ const TERMINAL_SCREEN = {
72
+ [CheckoutPaymentStatusEnum.PAID]: CheckoutScreenEnum.SUCCESS,
73
+ [CheckoutPaymentStatusEnum.EXPIRED]: CheckoutScreenEnum.EXPIRED,
74
+ [CheckoutPaymentStatusEnum.CANCELLED]: CheckoutScreenEnum.CANCELLED,
75
+ [CheckoutPaymentStatusEnum.LOCKED]: CheckoutScreenEnum.LOCKED,
76
+ // Nothing left to pay, and no longer paid: the payer goes back to the app.
77
+ [CheckoutPaymentStatusEnum.REFUNDED]: CheckoutScreenEnum.CANCELLED,
78
+ };
79
+ /** Which screen shows: the payment's status first, then what the payer is doing. */
80
+ export function screenOf(view, ui) {
81
+ if (view === undefined)
82
+ return CheckoutScreenEnum.LOADING;
83
+ if (view === null)
84
+ return CheckoutScreenEnum.INVALID;
85
+ if (ui.redirecting)
86
+ return CheckoutScreenEnum.REDIRECT;
87
+ const terminal = TERMINAL_SCREEN[view.status];
88
+ if (terminal)
89
+ return terminal;
90
+ // A store product's price comes once the sheet said it opened.
91
+ if (!view.priced)
92
+ return CheckoutScreenEnum.LOADING;
93
+ const { attempt } = view;
94
+ // A card's fields page is still paying: the form stays until it says how it went.
95
+ const shown = attempt && attempt.reference !== ui.dismissed && !ui.cardPaying
96
+ ? attempt.status
97
+ : null;
98
+ if (shown === AttemptStatusEnum.PENDING)
99
+ return CheckoutScreenEnum.WAITING;
100
+ // The app offers nothing any more: no form to fill, no other method to try.
101
+ if (view.methods.length === 0)
102
+ return CheckoutScreenEnum.NO_METHOD;
103
+ // A store's sheet closed with nothing bought: back on the form, no failure.
104
+ if (shown === AttemptStatusEnum.FAILED &&
105
+ attempt.failureReason !== FailureReasonEnum.CANCELLED) {
106
+ return CheckoutScreenEnum.FAILED;
107
+ }
108
+ return ui.submitting ? CheckoutScreenEnum.SUBMITTING : CheckoutScreenEnum.FORM;
109
+ }
110
+ /** The brand of a Mobile Money method, which a number's first digits can reveal. */
111
+ export function brandOf(method) {
112
+ return method.logos[0];
113
+ }
114
+ /** What the page keeps when a method is picked: the step stays, what the last one had starts over. */
115
+ export function pickedPatch(id) {
116
+ return {
117
+ method: id,
118
+ code: '',
119
+ cardComplete: false,
120
+ methodMissing: 0,
121
+ };
122
+ }
123
+ /**
124
+ * What the form still needs before Pay, by what the method's flow asks for
125
+ * (`FLOW_TRAITS.asks`): none, Pay can go. The one answer for whether Pay is
126
+ * on, what Pay points at when pressed early, and the name field's error.
127
+ */
128
+ export function missingBeforePay(method, input) {
129
+ const given = {
130
+ [FlowAskEnum.PHONE]: input.phoneValid,
131
+ [FlowAskEnum.CODE]: OTP_PATTERN.test(input.code),
132
+ [FlowAskEnum.CARD]: input.cardComplete,
133
+ [FlowAskEnum.NAME]: fullNameOf(input.payerName) !== null,
134
+ };
135
+ return FLOW_TRAITS[method.flow].asks.filter((ask) => !given[ask]);
136
+ }
137
+ /** What the page holds of the payer's input, as `missingBeforePay` reads it. */
138
+ export const payInputOf = (ui, phone) => ({
139
+ phoneValid: phone.valid,
140
+ code: ui.code,
141
+ cardComplete: ui.cardComplete,
142
+ payerName: ui.payerName,
143
+ });
144
+ /** The tile of a method or an attempt: the generic card for cards, whatever networks they take. */
145
+ export function logoOf(of) {
146
+ return FLOW_TRAITS[of.flow].genericTile ? CARD_LOGO : of.logos[0];
147
+ }
148
+ /** Works out what the screens show from the payment, the page and the number typed. */
149
+ export function deriveCheckout(view, ui, phone) {
150
+ const wallets = view.methods.filter((method) => method.kind === MethodKindEnum.MOBILE_MONEY &&
151
+ method.country === ui.country);
152
+ // A bank redirect shows in its own country; a guessed one may be wrong.
153
+ const home = (method) => !FLOW_TRAITS[method.flow].countryScheme ||
154
+ method.country === ui.payerCountry;
155
+ const cards = view.methods.filter((method) => method.kind === MethodKindEnum.CARD && home(method));
156
+ const otherBanks = ui.countrySent
157
+ ? []
158
+ : view.methods.filter((method) => FLOW_TRAITS[method.flow].countryScheme && !home(method));
159
+ const onCard = ui.tab === CheckoutTabEnum.CARD;
160
+ const picked = (onCard ? [...cards, ...otherBanks] : wallets).find((method) => method.id === ui.method);
161
+ const selected = picked?.state === MethodStateEnum.AVAILABLE ? picked : null;
162
+ const missing = selected
163
+ ? missingBeforePay(selected, payInputOf(ui, phone))
164
+ : [];
165
+ const detected = phone.valid
166
+ ? (wallets.find((method) => method.state === MethodStateEnum.AVAILABLE &&
167
+ brandOf(method) === phone.operator) ?? null)
168
+ : null;
169
+ const failed = view.methods.find((method) => method.id === view.attempt?.method);
170
+ const suggestion = view.methods.find((method) => method.kind === MethodKindEnum.MOBILE_MONEY &&
171
+ method.state === MethodStateEnum.AVAILABLE &&
172
+ method.country === failed?.country &&
173
+ method.id !== failed.id) ?? null;
174
+ return {
175
+ screen: screenOf(view, ui),
176
+ countries: countriesOf(view.methods),
177
+ wallets,
178
+ cards,
179
+ otherBanks,
180
+ otherBanksOpen: ui.otherBanksOpen || otherBanks.some((method) => method.id === ui.method),
181
+ nameError: ui.nameMissing > 0 && missing.includes(FlowAskEnum.NAME),
182
+ step: selected && ui.step === CheckoutStepEnum.DETAILS
183
+ ? CheckoutStepEnum.DETAILS
184
+ : CheckoutStepEnum.METHOD,
185
+ selected,
186
+ canPay: !!selected && missing.length === 0 && !ui.submitting && !ui.cardPaying,
187
+ detected,
188
+ total: selected?.price ??
189
+ view.attempt?.price ?? { amount: view.amount, currency: view.currency },
190
+ // Only a Mobile Money method has a number to belong to another one.
191
+ mismatch: selected && !onCard && detected && detected.id !== selected.id
192
+ ? detected
193
+ : null,
194
+ suggestion,
195
+ };
196
+ }
197
+ /** Seconds left to approve an attempt started at `startedAt`. */
198
+ export function waitLeftOf(startedAt, now) {
199
+ const elapsed = Math.floor((now - startedAt) / 1000);
200
+ return Math.min(WAIT_SECONDS, Math.max(0, WAIT_SECONDS - elapsed));
201
+ }
202
+ /** The payer can still ask for a new request of this attempt. */
203
+ export const canSendAgain = (attempt) => attempt.sendsLeft > 0;
204
+ /**
205
+ * What the waiting screen offers a payer with no prompt. USSD is the last
206
+ * resort: it shows after the last new request, or at once when the network's
207
+ * prompt never shows by itself, in the payer's language; a channel that only
208
+ * differs in its other language or by letter case shows once. The method's own
209
+ * code to see pending payments takes over when there are no steps to show.
210
+ * Nothing for a flow with no prompt.
211
+ */
212
+ export function dialHelpOf(attempt, lang) {
213
+ if (!attempt || !FLOW_TRAITS[attempt.flow].prompt) {
214
+ return { channels: [], pendingCode: null };
215
+ }
216
+ const sendAgain = canSendAgain(attempt);
217
+ const channels = new Map();
218
+ for (const { title, quickLink, steps } of sendAgain ? [] : attempt.dial) {
219
+ const key = [quickLink, ...steps[lang]].join('|').toLowerCase();
220
+ channels.set(key, { title: title[lang], quickLink, steps: steps[lang] });
221
+ }
222
+ return {
223
+ channels: [...channels.values()],
224
+ pendingCode: !sendAgain && channels.size === 0 ? attempt.pendingCode : null,
225
+ };
226
+ }
227
+ /** The payer asked for a new request since Pay. */
228
+ const askedAgain = (attempt) => attempt.lastSentAt > attempt.startedAt;
229
+ /**
230
+ * What the Simulator offers the tester: what the flow can do, and a success on
231
+ * every send only once the payer asked again.
232
+ */
233
+ export function simulatorOutcomesOf(attempt) {
234
+ const { hiddenOutcomes } = FLOW_TRAITS[attempt.flow];
235
+ return Object.values(SimulatorOutcomeEnum).filter((outcome) => !hiddenOutcomes.includes(outcome) &&
236
+ (outcome !== SimulatorOutcomeEnum.APPROVED_ALL || askedAgain(attempt)));
237
+ }
238
+ /**
239
+ * Seconds before the prompt can be sent again: 30 from the last time it went
240
+ * out, by the attempt or by `sentAt`, the second of the wait a sheet just asked at.
241
+ */
242
+ export function sendAgainLeftOf(attempt, waitLeft, sentAt = 0) {
243
+ const lastSent = Math.floor((attempt.lastSentAt - attempt.startedAt) / 1000);
244
+ const waited = WAIT_SECONDS - waitLeft - Math.max(sentAt, lastSent);
245
+ return Math.max(0, SEND_AGAIN_SECONDS - waited);
246
+ }
247
+ /** How payers reach the app's support, when it set any. */
248
+ export function supportContactsOf(app) {
249
+ const contacts = [];
250
+ if (app.supportWhatsapp) {
251
+ contacts.push({
252
+ channel: SupportChannelEnum.WHATSAPP,
253
+ value: app.supportWhatsapp,
254
+ href: `https://wa.me/${app.supportWhatsapp.slice(1)}`,
255
+ });
256
+ }
257
+ if (app.supportEmail) {
258
+ contacts.push({
259
+ channel: SupportChannelEnum.EMAIL,
260
+ value: app.supportEmail,
261
+ href: `mailto:${app.supportEmail}`,
262
+ });
263
+ }
264
+ return contacts;
265
+ }
266
+ /** A pending test payment for the Branding tab's preview, branded as typed. */
267
+ export function previewView(app, methods) {
268
+ return {
269
+ id: 'preview',
270
+ status: CheckoutPaymentStatusEnum.PENDING,
271
+ test: false,
272
+ amount: PREVIEW_AMOUNT,
273
+ currency: CurrencyEnum.XAF,
274
+ orderRef: PREVIEW_ORDER_REF,
275
+ items: [],
276
+ returnUrl: '',
277
+ expiresAt: 0,
278
+ paidAt: null,
279
+ payer: { name: null, phone: null, email: null },
280
+ country: null,
281
+ language: null,
282
+ theme: null,
283
+ preferredMethod: null,
284
+ preferredTab: null,
285
+ priced: true,
286
+ stores: [],
287
+ attemptsLeft: 0,
288
+ maxAttempts: 0,
289
+ // The preview offers no card: nothing loads from the site.
290
+ siteUrl: '',
291
+ app: {
292
+ ...app,
293
+ termsUrl: null,
294
+ privacyUrl: null,
295
+ supportEmail: null,
296
+ supportWhatsapp: null,
297
+ },
298
+ methods,
299
+ attempt: null,
300
+ };
301
+ }
302
+ /**
303
+ * A method's line under its name: the network that runs it ("Orange
304
+ * Cameroun"). A bank redirect names itself (ADR 0014): its line says its
305
+ * country, in the words `countryName` gives.
306
+ */
307
+ export function methodLineOf(method, countryName) {
308
+ return FLOW_TRAITS[method.flow].line === MethodLineEnum.COUNTRY
309
+ ? countryName(method.country)
310
+ : method.network;
311
+ }
312
+ /** One word of a name: letters, with `'` or `-` inside it (`D'Arc`, `Anne-Marie`). */
313
+ const NAME_WORD = /^[\p{L}\p{M}]+(?:['’-][\p{L}\p{M}]+)*$/u;
314
+ /**
315
+ * The account holder's full name as a bank redirect sends it (ADR 0014):
316
+ * trimmed, one space between words, a first and a last name at least, of
317
+ * letters, `'` and `-` only. Null when it is not one. The web, the sheet and
318
+ * the backend read it the same way.
319
+ */
320
+ export function fullNameOf(typed) {
321
+ const words = typed.trim().split(/\s+/);
322
+ const name = words.join(' ');
323
+ return words.length >= 2 &&
324
+ name.length <= FULL_NAME_MAX_LENGTH &&
325
+ words.every((word) => NAME_WORD.test(word))
326
+ ? name
327
+ : null;
328
+ }