-
Notifications
You must be signed in to change notification settings - Fork 3k
/
PaymentMethodList.tsx
424 lines (377 loc) · 18.4 KB
/
PaymentMethodList.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import lodashSortBy from 'lodash/sortBy';
import type {ReactElement, Ref} from 'react';
import React, {useCallback, useMemo} from 'react';
import type {GestureResponderEvent, StyleProp, ViewStyle} from 'react-native';
import {FlatList, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import {useOnyx, withOnyx} from 'react-native-onyx';
import type {SvgProps} from 'react-native-svg/lib/typescript/ReactNativeSVG';
import type {ValueOf} from 'type-fest';
import type {RenderSuggestionMenuItemProps} from '@components/AutoCompleteSuggestions/types';
import Button from '@components/Button';
import FormAlertWrapper from '@components/FormAlertWrapper';
import getBankIcon from '@components/Icon/BankIcons';
import type {BankName} from '@components/Icon/BankIconsUtils';
import * as Expensicons from '@components/Icon/Expensicons';
import MenuItem from '@components/MenuItem';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import Text from '@components/Text';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import * as CardUtils from '@libs/CardUtils';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import * as PaymentUtils from '@libs/PaymentUtils';
import variables from '@styles/variables';
import * as PaymentMethods from '@userActions/PaymentMethods';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {AccountData, BankAccountList, CardList} from '@src/types/onyx';
import type {BankIcon} from '@src/types/onyx/Bank';
import type {Errors} from '@src/types/onyx/OnyxCommon';
import type PaymentMethod from '@src/types/onyx/PaymentMethod';
import type {FilterMethodPaymentType} from '@src/types/onyx/WalletTransfer';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {FormattedSelectedPaymentMethodIcon} from './WalletPage/types';
type PaymentMethodListOnyxProps = {
/** List of bank accounts */
bankAccountList: OnyxEntry<BankAccountList>;
/** List of assigned cards */
cardList: OnyxEntry<CardList>;
/** List of user's cards */
// fundList: OnyxEntry<FundList>;
/** Are we loading payment methods? */
isLoadingPaymentMethods: OnyxEntry<boolean>;
};
type PaymentMethodListProps = PaymentMethodListOnyxProps & {
/** Type of active/highlighted payment method */
actionPaymentMethodType?: string;
/** ID of active/highlighted payment method */
activePaymentMethodID?: string | number;
/** ID of selected payment method */
selectedMethodID?: string | number;
/** Content for the FlatList header component */
listHeaderComponent?: ReactElement;
/** Callback for whenever FlatList component size changes */
onListContentSizeChange?: () => void;
/** Should menu items be selectable with a checkbox */
shouldShowSelectedState?: boolean;
/** React ref being forwarded to the PaymentMethodList Button */
buttonRef?: Ref<View>;
/** To enable/disable scrolling */
shouldEnableScroll?: boolean;
/** List container style */
style?: StyleProp<ViewStyle>;
/** List item style */
listItemStyle?: StyleProp<ViewStyle>;
/** Type to filter the payment Method list */
filterType?: FilterMethodPaymentType;
/** Whether the add bank account button should be shown on the list */
shouldShowAddBankAccount?: boolean;
/** Whether the add Payment button be shown on the list */
shouldShowAddPaymentMethodButton?: boolean;
/** Whether the assigned cards should be shown on the list */
shouldShowAssignedCards?: boolean;
/** Whether the empty list message should be shown when the list is empty */
shouldShowEmptyListMessage?: boolean;
/** Whether the right icon should be shown in PaymentMethodItem */
shouldShowRightIcon?: boolean;
/** What to do when a menu item is pressed */
onPress: (
event?: GestureResponderEvent | KeyboardEvent,
accountType?: string,
accountData?: AccountData,
icon?: FormattedSelectedPaymentMethodIcon,
isDefault?: boolean,
methodID?: number,
) => void;
};
type PaymentMethodItem = PaymentMethod & {
key?: string;
title?: string;
description: string;
onPress?: (e: GestureResponderEvent | KeyboardEvent | undefined) => void;
isGroupedCardDomain?: boolean;
canDismissError?: boolean;
disabled?: boolean;
shouldShowRightIcon?: boolean;
interactive?: boolean;
brickRoadIndicator?: ValueOf<typeof CONST.BRICK_ROAD_INDICATOR_STATUS>;
errors?: Errors;
iconRight?: React.FC<SvgProps>;
isMethodActive?: boolean;
} & BankIcon;
function dismissError(item: PaymentMethod) {
const isBankAccount = item.accountType === CONST.PAYMENT_METHODS.PERSONAL_BANK_ACCOUNT;
const paymentList = isBankAccount ? ONYXKEYS.BANK_ACCOUNT_LIST : ONYXKEYS.FUND_LIST;
const paymentID = isBankAccount ? item.accountData?.bankAccountID ?? '' : item.accountData?.fundID ?? '';
if (!paymentID) {
Log.info('Unable to clear payment method error: ', undefined, item);
return;
}
if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
PaymentMethods.clearDeletePaymentMethodError(paymentList, paymentID);
if (!isBankAccount) {
PaymentMethods.clearDeletePaymentMethodError(ONYXKEYS.FUND_LIST, paymentID);
}
} else {
PaymentMethods.clearAddPaymentMethodError(paymentList, paymentID);
if (!isBankAccount) {
PaymentMethods.clearAddPaymentMethodError(ONYXKEYS.FUND_LIST, paymentID);
}
}
}
function shouldShowDefaultBadge(filteredPaymentMethods: PaymentMethod[], isDefault = false): boolean {
if (!isDefault) {
return false;
}
const defaultablePaymentMethodCount = filteredPaymentMethods.filter(
(method) => method.accountType === CONST.PAYMENT_METHODS.PERSONAL_BANK_ACCOUNT || method.accountType === CONST.PAYMENT_METHODS.DEBIT_CARD,
).length;
return defaultablePaymentMethodCount > 1;
}
function isPaymentMethodActive(actionPaymentMethodType: string, activePaymentMethodID: string | number, paymentMethod: PaymentMethod) {
return paymentMethod.accountType === actionPaymentMethodType && paymentMethod.methodID === activePaymentMethodID;
}
function keyExtractor(item: PaymentMethod) {
return item.key ?? '';
}
function PaymentMethodList({
actionPaymentMethodType = '',
activePaymentMethodID = '',
bankAccountList = {},
buttonRef = () => {},
cardList = {},
// Temporarily disabled because P2P debit cards are disabled.
// fundList = {},
filterType = '',
listHeaderComponent,
isLoadingPaymentMethods = true,
onPress,
shouldShowSelectedState = false,
shouldShowAddPaymentMethodButton = true,
shouldShowAddBankAccount = true,
shouldShowEmptyListMessage = true,
shouldShowAssignedCards = false,
selectedMethodID = '',
onListContentSizeChange = () => {},
shouldEnableScroll = true,
style = {},
listItemStyle = {},
shouldShowRightIcon = true,
}: PaymentMethodListProps) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const filteredPaymentMethods = useMemo(() => {
if (shouldShowAssignedCards) {
const assignedCards = Object.values(cardList ?? {})
// Filter by active cards associated with a domain
.filter((card) => !!card.domainName && CONST.EXPENSIFY_CARD.ACTIVE_STATES.includes(card.state ?? 0));
const assignedCardsSorted = lodashSortBy(assignedCards, (card) => !CardUtils.isExpensifyCard(card.cardID));
const assignedCardsGrouped: PaymentMethodItem[] = [];
assignedCardsSorted.forEach((card) => {
const icon = getBankIcon({bankName: card.bank as BankName, isCard: true, styles});
if (!CardUtils.isExpensifyCard(card.cardID)) {
assignedCardsGrouped.push({
key: card.cardID.toString(),
title: card.bank,
description: card.domainName,
shouldShowRightIcon: false,
interactive: false,
canDismissError: false,
errors: card.errors,
brickRoadIndicator:
card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.DOMAIN || card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.INDIVIDUAL
? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR
: undefined,
...icon,
});
return;
}
const isAdminIssuedVirtualCard = !!card?.nameValuePairs?.issuedBy && !!card?.nameValuePairs?.isVirtual;
// The card should be grouped to a specific domain and such domain already exists in a assignedCardsGrouped
if (assignedCardsGrouped.some((item) => item.isGroupedCardDomain && item.description === card.domainName) && !isAdminIssuedVirtualCard) {
const domainGroupIndex = assignedCardsGrouped.findIndex((item) => item.isGroupedCardDomain && item.description === card.domainName);
assignedCardsGrouped[domainGroupIndex].errors = {...assignedCardsGrouped[domainGroupIndex].errors, ...card.errors};
if (card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.DOMAIN || card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.INDIVIDUAL) {
assignedCardsGrouped[domainGroupIndex].brickRoadIndicator = CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
}
return;
}
// The card shouldn't be grouped or it's domain group doesn't exist yet
assignedCardsGrouped.push({
key: card.cardID.toString(),
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
title: card?.nameValuePairs?.cardTitle || card.bank,
description: card.domainName,
onPress: () => Navigation.navigate(ROUTES.SETTINGS_WALLET_DOMAINCARD.getRoute(String(card.cardID))),
isGroupedCardDomain: !isAdminIssuedVirtualCard,
shouldShowRightIcon: true,
interactive: true,
canDismissError: true,
errors: card.errors,
brickRoadIndicator:
card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.DOMAIN || card.fraud === CONST.EXPENSIFY_CARD.FRAUD_TYPES.INDIVIDUAL
? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR
: undefined,
...icon,
});
});
return assignedCardsGrouped;
}
// Hide any billing cards that are not P2P debit cards for now because you cannot make them your default method, or delete them
// All payment cards are temporarily disabled for use as a payment method
// const paymentCardList = fundList ?? {};
// const filteredCardList = Object.values(paymentCardList).filter((card) => !!card.accountData?.additionalData?.isP2PDebitCard);
const filteredCardList = {};
let combinedPaymentMethods = PaymentUtils.formatPaymentMethods(bankAccountList ?? {}, filteredCardList, styles);
if (filterType !== '') {
combinedPaymentMethods = combinedPaymentMethods.filter((paymentMethod) => paymentMethod.accountType === filterType);
}
if (!isOffline) {
combinedPaymentMethods = combinedPaymentMethods.filter(
(paymentMethod) => paymentMethod.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || !isEmptyObject(paymentMethod.errors),
);
}
combinedPaymentMethods = combinedPaymentMethods.map((paymentMethod) => {
const isMethodActive = isPaymentMethodActive(actionPaymentMethodType, activePaymentMethodID, paymentMethod);
return {
...paymentMethod,
onPress: (e: GestureResponderEvent) =>
onPress(
e,
paymentMethod.accountType,
paymentMethod.accountData,
{
icon: paymentMethod.icon,
iconHeight: paymentMethod?.iconHeight,
iconWidth: paymentMethod?.iconWidth,
iconStyles: paymentMethod?.iconStyles,
iconSize: paymentMethod?.iconSize,
},
paymentMethod.isDefault,
paymentMethod.methodID,
),
wrapperStyle: isMethodActive ? [StyleUtils.getButtonBackgroundColorStyle(CONST.BUTTON_STATES.PRESSED)] : null,
disabled: paymentMethod.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
isMethodActive,
iconRight: Expensicons.ThreeDots,
shouldShowRightIcon,
};
});
return combinedPaymentMethods;
}, [shouldShowAssignedCards, bankAccountList, styles, filterType, isOffline, cardList, actionPaymentMethodType, activePaymentMethodID, StyleUtils, shouldShowRightIcon, onPress]);
/**
* Render placeholder when there are no payments methods
*/
const renderListEmptyComponent = () => <Text style={styles.popoverMenuItem}>{translate('paymentMethodList.addFirstPaymentMethod')}</Text>;
const renderListFooterComponent = useCallback(
() => (
<MenuItem
onPress={onPress}
title={translate('walletPage.addBankAccount')}
icon={Expensicons.Plus}
wrapperStyle={[styles.paymentMethod, listItemStyle]}
hoverAndPressStyle={styles.hoveredComponentBG}
ref={buttonRef}
disabled={!isUserValidated}
/>
),
[onPress, translate, styles.paymentMethod, styles.hoveredComponentBG, listItemStyle, buttonRef, isUserValidated],
);
/**
* Create a menuItem for each passed paymentMethod
*/
const renderItem = useCallback(
({item}: RenderSuggestionMenuItemProps<PaymentMethodItem>) => (
<OfflineWithFeedback
onClose={() => dismissError(item)}
pendingAction={item.pendingAction}
errors={item.errors}
errorRowStyles={styles.ph6}
canDismissError={item.canDismissError}
>
<MenuItem
onPress={item.onPress}
title={item.title}
description={item.description}
icon={item.icon}
disabled={item.disabled}
displayInDefaultIconColor
iconHeight={item.iconHeight ?? item.iconSize}
iconWidth={item.iconWidth ?? item.iconSize}
iconStyles={item.iconStyles}
badgeText={shouldShowDefaultBadge(filteredPaymentMethods, item.isDefault) ? translate('paymentMethodList.defaultPaymentMethod') : undefined}
wrapperStyle={[styles.paymentMethod, listItemStyle]}
iconRight={item.iconRight}
badgeStyle={styles.badgeBordered}
hoverAndPressStyle={styles.hoveredComponentBG}
shouldShowRightIcon={item.shouldShowRightIcon}
shouldShowSelectedState={shouldShowSelectedState}
isSelected={selectedMethodID.toString() === item.methodID?.toString()}
interactive={item.interactive}
brickRoadIndicator={item.brickRoadIndicator}
success={item.isMethodActive}
/>
</OfflineWithFeedback>
),
[styles.ph6, styles.paymentMethod, styles.badgeBordered, styles.hoveredComponentBG, filteredPaymentMethods, translate, listItemStyle, shouldShowSelectedState, selectedMethodID],
);
return (
<>
<View style={[style, {minHeight: (filteredPaymentMethods.length + (shouldShowAddBankAccount ? 1 : 0)) * variables.optionRowHeight}]}>
<FlatList
data={filteredPaymentMethods}
renderItem={renderItem}
keyExtractor={keyExtractor}
ListEmptyComponent={shouldShowEmptyListMessage ? renderListEmptyComponent : null}
ListHeaderComponent={listHeaderComponent}
onContentSizeChange={onListContentSizeChange}
scrollEnabled={shouldEnableScroll}
/>
{shouldShowAddBankAccount && renderListFooterComponent()}
</View>
{shouldShowAddPaymentMethodButton && (
<FormAlertWrapper>
{(isFormOffline) => (
<Button
text={translate('paymentMethodList.addPaymentMethod')}
icon={Expensicons.CreditCard}
onPress={onPress}
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
isDisabled={isLoadingPaymentMethods || isFormOffline}
style={[styles.mh4, styles.buttonCTA]}
key="addPaymentMethodButton"
success
shouldShowRightIcon
large
ref={buttonRef}
/>
)}
</FormAlertWrapper>
)}
</>
);
}
PaymentMethodList.displayName = 'PaymentMethodList';
export default withOnyx<PaymentMethodListProps, PaymentMethodListOnyxProps>({
bankAccountList: {
key: ONYXKEYS.BANK_ACCOUNT_LIST,
},
cardList: {
key: ONYXKEYS.CARD_LIST,
},
// Temporarily disabled - used for P2P debit cards
// fundList: {
// key: ONYXKEYS.FUND_LIST,
// },
isLoadingPaymentMethods: {
key: ONYXKEYS.IS_LOADING_PAYMENT_METHODS,
},
})(PaymentMethodList);