-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathAddPlaidBankAccount.js
273 lines (243 loc) · 10.2 KB
/
AddPlaidBankAccount.js
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
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useRef} from 'react';
import {ActivityIndicator, View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import KeyboardShortcut from '@libs/KeyboardShortcut';
import Log from '@libs/Log';
import {plaidDataPropTypes} from '@pages/ReimbursementAccount/plaidDataPropTypes';
import useTheme from '@styles/themes/useTheme';
import useThemeStyles from '@styles/useThemeStyles';
import * as App from '@userActions/App';
import * as BankAccounts from '@userActions/BankAccounts';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import FullPageOfflineBlockingView from './BlockingViews/FullPageOfflineBlockingView';
import Icon from './Icon';
import getBankIcon from './Icon/BankIcons';
import Picker from './Picker';
import PlaidLink from './PlaidLink';
import Text from './Text';
const propTypes = {
/** If the user has been throttled from Plaid */
isPlaidDisabled: PropTypes.bool,
/** Contains plaid data */
plaidData: plaidDataPropTypes.isRequired,
/** Selected account ID from the Picker associated with the end of the Plaid flow */
selectedPlaidAccountID: PropTypes.string,
/** Plaid SDK token to use to initialize the widget */
plaidLinkToken: PropTypes.string,
/** Fired when the user exits the Plaid flow */
onExitPlaid: PropTypes.func,
/** Fired when the user selects an account */
onSelect: PropTypes.func,
/** Additional text to display */
text: PropTypes.string,
/** The OAuth URI + stateID needed to re-initialize the PlaidLink after the user logs into their bank */
receivedRedirectURI: PropTypes.string,
/** During the OAuth flow we need to use the plaidLink token that we initially connected with */
plaidLinkOAuthToken: PropTypes.string,
/** If we're updating an existing bank account, what's its bank account ID? */
bankAccountID: PropTypes.number,
/** Are we adding a withdrawal account? */
allowDebit: PropTypes.bool,
};
const defaultProps = {
selectedPlaidAccountID: '',
plaidLinkToken: '',
onExitPlaid: () => {},
onSelect: () => {},
text: '',
receivedRedirectURI: null,
plaidLinkOAuthToken: '',
allowDebit: false,
bankAccountID: 0,
isPlaidDisabled: false,
};
function AddPlaidBankAccount({
plaidData,
selectedPlaidAccountID,
plaidLinkToken,
onExitPlaid,
onSelect,
text,
receivedRedirectURI,
plaidLinkOAuthToken,
bankAccountID,
allowDebit,
isPlaidDisabled,
}) {
const theme = useTheme();
const styles = useThemeStyles();
const subscribedKeyboardShortcuts = useRef([]);
const previousNetworkState = useRef();
const {translate} = useLocalize();
const {isOffline} = useNetwork();
/**
* @returns {String}
*/
const getPlaidLinkToken = () => {
if (plaidLinkToken) {
return plaidLinkToken;
}
if (receivedRedirectURI && plaidLinkOAuthToken) {
return plaidLinkOAuthToken;
}
};
/**
* @returns {Boolean}
* I'm using useCallback so the useEffect which uses this function doesn't run on every render.
*/
const isAuthenticatedWithPlaid = useCallback(
() => (receivedRedirectURI && plaidLinkOAuthToken) || !_.isEmpty(lodashGet(plaidData, 'bankAccounts')) || !_.isEmpty(lodashGet(plaidData, 'errors')),
[plaidData, plaidLinkOAuthToken, receivedRedirectURI],
);
/**
* Blocks the keyboard shortcuts that can navigate
*/
const subscribeToNavigationShortcuts = () => {
// find and block the shortcuts
const shortcutsToBlock = _.filter(CONST.KEYBOARD_SHORTCUTS, (x) => x.type === CONST.KEYBOARD_SHORTCUTS_TYPES.NAVIGATION_SHORTCUT);
subscribedKeyboardShortcuts.current = _.map(shortcutsToBlock, (shortcut) =>
KeyboardShortcut.subscribe(
shortcut.shortcutKey,
() => {}, // do nothing
shortcut.descriptionKey,
shortcut.modifiers,
false,
() => lodashGet(plaidData, 'bankAccounts', []).length > 0, // start bubbling when there are bank accounts
),
);
};
/**
* Unblocks the keyboard shortcuts that can navigate
*/
const unsubscribeToNavigationShortcuts = () => {
_.each(subscribedKeyboardShortcuts.current, (unsubscribe) => unsubscribe());
subscribedKeyboardShortcuts.current = [];
};
useEffect(() => {
subscribeToNavigationShortcuts();
// If we're coming from Plaid OAuth flow then we need to reuse the existing plaidLinkToken
if (isAuthenticatedWithPlaid()) {
return unsubscribeToNavigationShortcuts;
}
BankAccounts.openPlaidBankLogin(allowDebit, bankAccountID);
return unsubscribeToNavigationShortcuts;
// disabling this rule, as we want this to run only on the first render
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
// If we are coming back from offline and we haven't authenticated with Plaid yet, we need to re-run our call to kick off Plaid
// previousNetworkState.current also makes sure that this doesn't run on the first render.
if (previousNetworkState.current && !isOffline && !isAuthenticatedWithPlaid()) {
BankAccounts.openPlaidBankLogin(allowDebit, bankAccountID);
}
previousNetworkState.current = isOffline;
}, [allowDebit, bankAccountID, isAuthenticatedWithPlaid, isOffline]);
const plaidBankAccounts = lodashGet(plaidData, 'bankAccounts') || [];
const token = getPlaidLinkToken();
const options = _.map(plaidBankAccounts, (account) => ({
value: account.plaidAccountID,
label: `${account.addressName} ${account.mask}`,
}));
const {icon, iconSize, iconStyles} = getBankIcon();
const plaidErrors = lodashGet(plaidData, 'errors');
const plaidDataErrorMessage = !_.isEmpty(plaidErrors) ? _.chain(plaidErrors).values().first().value() : '';
const bankName = lodashGet(plaidData, 'bankName');
if (isPlaidDisabled) {
return (
<View>
<Text style={[styles.formError]}>{translate('bankAccount.error.tooManyAttempts')}</Text>
</View>
);
}
// Plaid Link view
if (!plaidBankAccounts.length) {
return (
<FullPageOfflineBlockingView>
{lodashGet(plaidData, 'isLoading') && (
<View style={[styles.flex1, styles.alignItemsCenter, styles.justifyContentCenter]}>
<ActivityIndicator
color={theme.spinner}
size="large"
/>
</View>
)}
{Boolean(plaidDataErrorMessage) && <Text style={[styles.formError, styles.mh5]}>{plaidDataErrorMessage}</Text>}
{Boolean(token) && !bankName && (
<PlaidLink
token={token}
onSuccess={({publicToken, metadata}) => {
Log.info('[PlaidLink] Success!');
BankAccounts.openPlaidBankAccountSelector(publicToken, metadata.institution.name, allowDebit, bankAccountID);
}}
onError={(error) => {
Log.hmmm('[PlaidLink] Error: ', error.message);
}}
onEvent={(event, metadata) => {
BankAccounts.setPlaidEvent(event);
// Handle Plaid login errors (will potentially reset plaid token and item depending on the error)
if (event === 'ERROR') {
Log.hmmm('[PlaidLink] Error: ', metadata);
if (bankAccountID && metadata.error_code) {
BankAccounts.handlePlaidError(bankAccountID, metadata.error_code, metadata.error_message, metadata.request_id);
}
}
// Limit the number of times a user can submit Plaid credentials
if (event === 'SUBMIT_CREDENTIALS') {
App.handleRestrictedEvent(event);
}
}}
// User prematurely exited the Plaid flow
// eslint-disable-next-line react/jsx-props-no-multi-spaces
onExit={onExitPlaid}
receivedRedirectURI={receivedRedirectURI}
/>
)}
</FullPageOfflineBlockingView>
);
}
// Plaid bank accounts view
return (
<FullPageOfflineBlockingView>
{!_.isEmpty(text) && <Text style={[styles.mb5]}>{text}</Text>}
<View style={[styles.flexRow, styles.alignItemsCenter, styles.mb5]}>
<Icon
src={icon}
height={iconSize}
width={iconSize}
additionalStyles={iconStyles}
/>
<Text style={[styles.ml3, styles.textStrong]}>{bankName}</Text>
</View>
<View>
<Picker
label={translate('addPersonalBankAccountPage.chooseAccountLabel')}
onInputChange={onSelect}
items={options}
placeholder={{
value: '',
label: translate('bankAccount.chooseAnAccount'),
}}
value={selectedPlaidAccountID}
/>
</View>
</FullPageOfflineBlockingView>
);
}
AddPlaidBankAccount.propTypes = propTypes;
AddPlaidBankAccount.defaultProps = defaultProps;
AddPlaidBankAccount.displayName = 'AddPlaidBankAccount';
export default withOnyx({
plaidLinkToken: {
key: ONYXKEYS.PLAID_LINK_TOKEN,
initWithStoredValues: false,
},
isPlaidDisabled: {
key: ONYXKEYS.IS_PLAID_DISABLED,
},
})(AddPlaidBankAccount);