-
Notifications
You must be signed in to change notification settings - Fork 3k
/
PolicyAccountingPage.tsx
490 lines (471 loc) · 24.8 KB
/
PolicyAccountingPage.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import {differenceInMinutes, isValid, parseISO} from 'date-fns';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import {ActivityIndicator, View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import CollapsibleSection from '@components/CollapsibleSection';
import ConfirmModal from '@components/ConfirmModal';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import * as Expensicons from '@components/Icon/Expensicons';
import * as Illustrations from '@components/Icon/Illustrations';
import MenuItem from '@components/MenuItem';
import MenuItemList from '@components/MenuItemList';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Section from '@components/Section';
import ThreeDotsMenu from '@components/ThreeDotsMenu';
import type ThreeDotsMenuProps from '@components/ThreeDotsMenu/types';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePermissions from '@hooks/usePermissions';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import {getSynchronizationErrorMessage, isAuthenticationError, isConnectionUnverified, removePolicyConnection, syncConnection} from '@libs/actions/connections';
import {
areSettingsInErrorFields,
findCurrentXeroOrganization,
getConnectedIntegration,
getCurrentSageIntacctEntityName,
getCurrentXeroOrganizationName,
getIntegrationLastSuccessfulDate,
getXeroTenants,
settingsPendingAction,
} from '@libs/PolicyUtils';
import Navigation from '@navigation/Navigation';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
import withPolicyConnections from '@pages/workspace/withPolicyConnections';
import type {AnchorPosition} from '@styles/index';
import * as Modal from '@userActions/Modal';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import {AccountingContextProvider, useAccountingContext} from './AccountingContext';
import type {MenuItemData, PolicyAccountingPageProps} from './types';
import {getAccountingIntegrationData} from './utils';
function PolicyAccountingPage({policy}: PolicyAccountingPageProps) {
const [connectionSyncProgress] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CONNECTION_SYNC_PROGRESS}${policy.id}`);
const theme = useTheme();
const styles = useThemeStyles();
const {translate, datetimeToRelative: getDatetimeToRelative} = useLocalize();
const {isOffline} = useNetwork();
const {windowWidth} = useWindowDimensions();
const {shouldUseNarrowLayout} = useResponsiveLayout();
const [threeDotsMenuPosition, setThreeDotsMenuPosition] = useState<AnchorPosition>({horizontal: 0, vertical: 0});
const [isDisconnectModalOpen, setIsDisconnectModalOpen] = useState(false);
const [datetimeToRelative, setDateTimeToRelative] = useState('');
const threeDotsMenuContainerRef = useRef<View>(null);
const {canUseWorkspaceFeeds} = usePermissions();
const {startIntegrationFlow, popoverAnchorRefs} = useAccountingContext();
const lastSyncProgressDate = parseISO(connectionSyncProgress?.timestamp ?? '');
const isSyncInProgress =
!!connectionSyncProgress?.stageInProgress &&
(connectionSyncProgress.stageInProgress !== CONST.POLICY.CONNECTIONS.SYNC_STAGE_NAME.JOB_DONE || !policy.connections?.[connectionSyncProgress.connectionName]) &&
isValid(lastSyncProgressDate) &&
differenceInMinutes(new Date(), lastSyncProgressDate) < CONST.POLICY.CONNECTIONS.SYNC_STAGE_TIMEOUT_MINUTES;
const accountingIntegrations = Object.values(CONST.POLICY.CONNECTIONS.NAME);
const connectedIntegration = getConnectedIntegration(policy, accountingIntegrations) ?? connectionSyncProgress?.connectionName;
const synchronizationError = connectedIntegration && getSynchronizationErrorMessage(policy, connectedIntegration, isSyncInProgress);
// Enter credentials item shouldn't be shown for SageIntacct and NetSuite integrations
const shouldShowEnterCredentials =
connectedIntegration &&
!!synchronizationError &&
isAuthenticationError(policy, connectedIntegration) &&
connectedIntegration !== CONST.POLICY.CONNECTIONS.NAME.SAGE_INTACCT &&
connectedIntegration !== CONST.POLICY.CONNECTIONS.NAME.NETSUITE;
const policyID = policy?.id ?? '-1';
// Get the last successful date of the integration. Then, if `connectionSyncProgress` is the same integration displayed and the state is 'jobDone', get the more recent update time of the two.
const successfulDate = getIntegrationLastSuccessfulDate(
connectedIntegration ? policy?.connections?.[connectedIntegration] : undefined,
connectedIntegration === connectionSyncProgress?.connectionName ? connectionSyncProgress : undefined,
);
const tenants = useMemo(() => getXeroTenants(policy), [policy]);
const currentXeroOrganization = findCurrentXeroOrganization(tenants, policy?.connections?.xero?.config?.tenantID);
const overflowMenu: ThreeDotsMenuProps['menuItems'] = useMemo(
() => [
...(shouldShowEnterCredentials
? [
{
icon: Expensicons.Key,
text: translate('workspace.accounting.enterCredentials'),
onSelected: () => Modal.close(() => startIntegrationFlow({name: connectedIntegration})),
disabled: isOffline,
iconRight: Expensicons.NewWindow,
shouldShowRightIcon: true,
},
]
: [
{
icon: Expensicons.Sync,
text: translate('workspace.accounting.syncNow'),
onSelected: () => syncConnection(policyID, connectedIntegration),
disabled: isOffline,
},
]),
{
icon: Expensicons.Trashcan,
text: translate('workspace.accounting.disconnect'),
onSelected: () => Modal.close(() => setIsDisconnectModalOpen(true)),
},
],
[shouldShowEnterCredentials, translate, isOffline, policyID, connectedIntegration, startIntegrationFlow],
);
useEffect(() => {
if (successfulDate) {
setDateTimeToRelative(getDatetimeToRelative(successfulDate));
return;
}
setDateTimeToRelative('');
}, [getDatetimeToRelative, successfulDate]);
const integrationSpecificMenuItems = useMemo(() => {
const sageIntacctEntityList = policy?.connections?.intacct?.data?.entities ?? [];
const netSuiteSubsidiaryList = policy?.connections?.netsuite?.options?.data?.subsidiaryList ?? [];
switch (connectedIntegration) {
case CONST.POLICY.CONNECTIONS.NAME.XERO:
return {
description: translate('workspace.xero.organization'),
iconRight: Expensicons.ArrowRight,
title: getCurrentXeroOrganizationName(policy),
wrapperStyle: [styles.sectionMenuItemTopDescription],
titleStyle: styles.fontWeightNormal,
shouldShowRightIcon: tenants.length > 1,
shouldShowDescriptionOnTop: true,
onPress: () => {
if (!(tenants.length > 1)) {
return;
}
Navigation.navigate(ROUTES.POLICY_ACCOUNTING_XERO_ORGANIZATION.getRoute(policyID, currentXeroOrganization?.id ?? '-1'));
},
pendingAction: settingsPendingAction([CONST.XERO_CONFIG.TENANT_ID], policy?.connections?.xero?.config?.pendingFields),
brickRoadIndicator: areSettingsInErrorFields([CONST.XERO_CONFIG.TENANT_ID], policy?.connections?.xero?.config?.errorFields)
? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR
: undefined,
};
case CONST.POLICY.CONNECTIONS.NAME.NETSUITE:
return {
description: translate('workspace.netsuite.subsidiary'),
iconRight: Expensicons.ArrowRight,
title: policy?.connections?.netsuite?.options?.config?.subsidiary ?? '',
wrapperStyle: [styles.sectionMenuItemTopDescription],
titleStyle: styles.fontWeightNormal,
shouldShowRightIcon: netSuiteSubsidiaryList?.length > 1,
shouldShowDescriptionOnTop: true,
pendingAction: policy?.connections?.netsuite?.options?.config?.pendingFields?.subsidiary,
brickRoadIndicator: policy?.connections?.netsuite?.options?.config?.errorFields?.subsidiary ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined,
onPress: () => {
if (!(netSuiteSubsidiaryList?.length > 1)) {
return;
}
Navigation.navigate(ROUTES.POLICY_ACCOUNTING_NETSUITE_SUBSIDIARY_SELECTOR.getRoute(policyID));
},
};
case CONST.POLICY.CONNECTIONS.NAME.SAGE_INTACCT:
return !sageIntacctEntityList.length
? {}
: {
description: translate('workspace.intacct.entity'),
iconRight: Expensicons.ArrowRight,
title: getCurrentSageIntacctEntityName(policy, translate('workspace.common.topLevel')),
wrapperStyle: [styles.sectionMenuItemTopDescription],
titleStyle: styles.fontWeightNormal,
shouldShowRightIcon: true,
shouldShowDescriptionOnTop: true,
pendingAction: policy?.connections?.intacct?.config?.pendingFields?.entity,
brickRoadIndicator: policy?.connections?.intacct?.config?.errorFields?.entity ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined,
onPress: () => {
if (!sageIntacctEntityList.length) {
return;
}
Navigation.navigate(ROUTES.POLICY_ACCOUNTING_SAGE_INTACCT_ENTITY.getRoute(policyID));
},
};
default:
return undefined;
}
}, [connectedIntegration, currentXeroOrganization?.id, policy, policyID, styles.fontWeightNormal, styles.sectionMenuItemTopDescription, tenants.length, translate]);
const connectionsMenuItems: MenuItemData[] = useMemo(() => {
if (isEmptyObject(policy?.connections) && !isSyncInProgress) {
return accountingIntegrations.map((integration) => {
const integrationData = getAccountingIntegrationData(integration, policyID, translate);
const iconProps = integrationData?.icon ? {icon: integrationData.icon, iconType: CONST.ICON_TYPE_AVATAR} : {};
return {
...iconProps,
interactive: false,
wrapperStyle: [styles.sectionMenuItemTopDescription],
shouldShowRightComponent: true,
title: integrationData?.title,
rightComponent: (
<Button
onPress={() => startIntegrationFlow({name: integration})}
text={translate('workspace.accounting.setup')}
style={styles.justifyContentCenter}
small
isDisabled={isOffline}
ref={(ref) => {
if (!popoverAnchorRefs?.current) {
return;
}
// eslint-disable-next-line react-compiler/react-compiler
popoverAnchorRefs.current[integration].current = ref;
}}
/>
),
};
});
}
if (!connectedIntegration) {
return [];
}
const shouldShowSynchronizationError = !!synchronizationError;
const shouldHideConfigurationOptions = isConnectionUnverified(policy, connectedIntegration);
const integrationData = getAccountingIntegrationData(connectedIntegration, policyID, translate, policy);
const iconProps = integrationData?.icon ? {icon: integrationData.icon, iconType: CONST.ICON_TYPE_AVATAR} : {};
const configurationOptions = [
{
icon: Expensicons.Pencil,
iconRight: Expensicons.ArrowRight,
shouldShowRightIcon: true,
title: translate('workspace.accounting.import'),
wrapperStyle: [styles.sectionMenuItemTopDescription],
onPress: integrationData?.onImportPagePress,
brickRoadIndicator: areSettingsInErrorFields(integrationData?.subscribedImportSettings, integrationData?.errorFields) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined,
pendingAction: settingsPendingAction(integrationData?.subscribedImportSettings, integrationData?.pendingFields),
},
{
icon: Expensicons.Send,
iconRight: Expensicons.ArrowRight,
shouldShowRightIcon: true,
title: translate('workspace.accounting.export'),
wrapperStyle: [styles.sectionMenuItemTopDescription],
onPress: integrationData?.onExportPagePress,
brickRoadIndicator: areSettingsInErrorFields(integrationData?.subscribedExportSettings, integrationData?.errorFields) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined,
pendingAction: settingsPendingAction(integrationData?.subscribedExportSettings, integrationData?.pendingFields),
},
{
icon: Expensicons.ExpensifyCard,
iconRight: Expensicons.ArrowRight,
shouldShowRightIcon: true,
title: translate('workspace.accounting.cardReconciliation'),
wrapperStyle: [styles.sectionMenuItemTopDescription],
onPress: integrationData?.onCardReconciliationPagePress,
},
{
icon: Expensicons.Gear,
iconRight: Expensicons.ArrowRight,
shouldShowRightIcon: true,
title: translate('workspace.accounting.advanced'),
wrapperStyle: [styles.sectionMenuItemTopDescription],
onPress: integrationData?.onAdvancedPagePress,
brickRoadIndicator: areSettingsInErrorFields(integrationData?.subscribedAdvancedSettings, integrationData?.errorFields) ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined,
pendingAction: settingsPendingAction(integrationData?.subscribedAdvancedSettings, integrationData?.pendingFields),
},
];
if (!canUseWorkspaceFeeds || !policy?.areExpensifyCardsEnabled) {
configurationOptions.splice(2, 1);
}
return [
{
...iconProps,
interactive: false,
wrapperStyle: [styles.sectionMenuItemTopDescription, shouldShowSynchronizationError && styles.pb0],
shouldShowRightComponent: true,
title: integrationData?.title,
errorText: synchronizationError,
errorTextStyle: [styles.mt5],
shouldShowRedDotIndicator: true,
description: isSyncInProgress
? translate('workspace.accounting.connections.syncStageName', connectionSyncProgress.stageInProgress)
: translate('workspace.accounting.lastSync', datetimeToRelative),
rightComponent: isSyncInProgress ? (
<ActivityIndicator
style={[styles.popoverMenuIcon]}
color={theme.spinner}
/>
) : (
<View ref={threeDotsMenuContainerRef}>
<ThreeDotsMenu
onIconPress={() => {
threeDotsMenuContainerRef.current?.measureInWindow((x, y, width, height) => {
setThreeDotsMenuPosition({
horizontal: x + width,
vertical: y + height,
});
});
}}
menuItems={overflowMenu}
anchorPosition={threeDotsMenuPosition}
anchorAlignment={{horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.RIGHT, vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP}}
/>
</View>
),
},
...(isEmptyObject(integrationSpecificMenuItems) || shouldShowSynchronizationError || isEmptyObject(policy?.connections) ? [] : [integrationSpecificMenuItems]),
...(isEmptyObject(policy?.connections) || shouldHideConfigurationOptions ? [] : configurationOptions),
];
}, [
policy,
isSyncInProgress,
connectedIntegration,
synchronizationError,
policyID,
translate,
styles.sectionMenuItemTopDescription,
styles.pb0,
styles.mt5,
styles.popoverMenuIcon,
canUseWorkspaceFeeds,
styles.justifyContentCenter,
connectionSyncProgress?.stageInProgress,
datetimeToRelative,
theme.spinner,
overflowMenu,
threeDotsMenuPosition,
integrationSpecificMenuItems,
accountingIntegrations,
isOffline,
startIntegrationFlow,
popoverAnchorRefs,
]);
const otherIntegrationsItems = useMemo(() => {
if (isEmptyObject(policy?.connections) && !isSyncInProgress) {
return;
}
const otherIntegrations = accountingIntegrations.filter(
(integration) => (isSyncInProgress && integration !== connectionSyncProgress?.connectionName) || integration !== connectedIntegration,
);
return otherIntegrations.map((integration) => {
const integrationData = getAccountingIntegrationData(integration, policyID, translate);
const iconProps = integrationData?.icon ? {icon: integrationData.icon, iconType: CONST.ICON_TYPE_AVATAR} : {};
return {
...iconProps,
title: integrationData?.title,
rightComponent: (
<Button
onPress={() =>
startIntegrationFlow({
name: integration,
integrationToDisconnect: connectedIntegration,
shouldDisconnectIntegrationBeforeConnecting: true,
})
}
text={translate('workspace.accounting.setup')}
style={styles.justifyContentCenter}
small
isDisabled={isOffline}
ref={(r) => {
if (!popoverAnchorRefs?.current) {
return;
}
popoverAnchorRefs.current[integration].current = r;
}}
/>
),
interactive: false,
shouldShowRightComponent: true,
wrapperStyle: styles.sectionMenuItemTopDescription,
};
});
}, [
policy?.connections,
isSyncInProgress,
accountingIntegrations,
connectionSyncProgress?.connectionName,
connectedIntegration,
policyID,
translate,
styles.justifyContentCenter,
styles.sectionMenuItemTopDescription,
isOffline,
startIntegrationFlow,
popoverAnchorRefs,
]);
return (
<AccessOrNotFoundWrapper
accessVariants={[CONST.POLICY.ACCESS_VARIANTS.ADMIN, CONST.POLICY.ACCESS_VARIANTS.PAID]}
policyID={policyID}
featureName={CONST.POLICY.MORE_FEATURES.ARE_CONNECTIONS_ENABLED}
>
<ScreenWrapper
testID={PolicyAccountingPage.displayName}
includeSafeAreaPaddingBottom={false}
shouldShowOfflineIndicatorInWideScreen
>
<HeaderWithBackButton
title={translate('workspace.common.accounting')}
shouldShowBackButton={shouldUseNarrowLayout}
icon={Illustrations.Accounting}
threeDotsAnchorPosition={styles.threeDotsPopoverOffsetNoCloseButton(windowWidth)}
/>
<ScrollView contentContainerStyle={styles.pt3}>
<View style={[styles.flex1, shouldUseNarrowLayout ? styles.workspaceSectionMobile : styles.workspaceSection]}>
<Section
title={translate('workspace.accounting.title')}
subtitle={translate('workspace.accounting.subtitle')}
isCentralPane
subtitleMuted
titleStyles={styles.accountSettingsSectionTitle}
childrenStyles={styles.pt5}
>
{connectionsMenuItems.map((menuItem) => (
<OfflineWithFeedback
pendingAction={menuItem.pendingAction}
key={menuItem.title}
>
<MenuItem
brickRoadIndicator={menuItem.brickRoadIndicator}
key={menuItem.title}
// eslint-disable-next-line react/jsx-props-no-spreading
{...menuItem}
/>
</OfflineWithFeedback>
))}
{otherIntegrationsItems && (
<CollapsibleSection
title={translate('workspace.accounting.other')}
wrapperStyle={[styles.pr3, styles.mt5, styles.pv3]}
titleStyle={[styles.textNormal, styles.colorMuted]}
textStyle={[styles.flex1, styles.userSelectNone, styles.textNormal, styles.colorMuted]}
>
<MenuItemList
menuItems={otherIntegrationsItems}
shouldUseSingleExecution
/>
</CollapsibleSection>
)}
</Section>
</View>
</ScrollView>
<ConfirmModal
title={translate('workspace.accounting.disconnectTitle', connectedIntegration)}
isVisible={isDisconnectModalOpen}
onConfirm={() => {
if (connectedIntegration) {
removePolicyConnection(policyID, connectedIntegration);
}
setIsDisconnectModalOpen(false);
}}
onCancel={() => setIsDisconnectModalOpen(false)}
prompt={translate('workspace.accounting.disconnectPrompt', connectedIntegration)}
confirmText={translate('workspace.accounting.disconnect')}
cancelText={translate('common.cancel')}
danger
/>
</ScreenWrapper>
</AccessOrNotFoundWrapper>
);
}
function PolicyAccountingPageWrapper(props: PolicyAccountingPageProps) {
return (
<AccountingContextProvider policy={props.policy}>
<PolicyAccountingPage
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
/>
</AccountingContextProvider>
);
}
PolicyAccountingPage.displayName = 'PolicyAccountingPage';
export default withPolicyConnections(PolicyAccountingPageWrapper);