-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathWorkspaceTaxesPage.tsx
362 lines (334 loc) · 16.9 KB
/
WorkspaceTaxesPage.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
import {useFocusEffect} from '@react-navigation/native';
import React, {useCallback, useMemo, useState} from 'react';
import {ActivityIndicator, View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import ButtonWithDropdownMenu from '@components/ButtonWithDropdownMenu';
import type {DropdownOption, WorkspaceTaxRatesBulkActionType} from '@components/ButtonWithDropdownMenu/types';
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 ScreenWrapper from '@components/ScreenWrapper';
import ListItemRightCaretWithLabel from '@components/SelectionList/ListItemRightCaretWithLabel';
import TableListItem from '@components/SelectionList/TableListItem';
import type {ListItem} from '@components/SelectionList/types';
import SelectionListWithModal from '@components/SelectionListWithModal';
import CustomListHeader from '@components/SelectionListWithModal/CustomListHeader';
import Text from '@components/Text';
import TextLink from '@components/TextLink';
import useCleanupSelectedOptions from '@hooks/useCleanupSelectedOptions';
import useEnvironment from '@hooks/useEnvironment';
import useLocalize from '@hooks/useLocalize';
import useMobileSelectionMode from '@hooks/useMobileSelectionMode';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import {isConnectionInProgress} from '@libs/actions/connections';
import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode';
import {clearTaxRateError, deletePolicyTaxes, setPolicyTaxesEnabled} from '@libs/actions/TaxRate';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import * as ErrorUtils from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import * as PolicyUtils from '@libs/PolicyUtils';
import type {FullScreenNavigatorParamList} from '@navigation/types';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
import type {WithPolicyAndFullscreenLoadingProps} from '@pages/workspace/withPolicyAndFullscreenLoading';
import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading';
import {openPolicyTaxesPage} from '@userActions/Policy/Policy';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type SCREENS from '@src/SCREENS';
import type {TaxRate} from '@src/types/onyx';
type WorkspaceTaxesPageProps = WithPolicyAndFullscreenLoadingProps & PlatformStackScreenProps<FullScreenNavigatorParamList, typeof SCREENS.WORKSPACE.TAXES>;
function WorkspaceTaxesPage({
policy,
route: {
params: {policyID},
},
}: WorkspaceTaxesPageProps) {
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth
const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout();
const styles = useThemeStyles();
const theme = useTheme();
const {translate} = useLocalize();
const {environmentURL} = useEnvironment();
const [selectedTaxesIDs, setSelectedTaxesIDs] = useState<string[]>([]);
const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
const {selectionMode} = useMobileSelectionMode();
const defaultExternalID = policy?.taxRates?.defaultExternalID;
const foreignTaxDefault = policy?.taxRates?.foreignTaxDefault;
const hasAccountingConnections = PolicyUtils.hasAccountingConnections(policy);
const [connectionSyncProgress] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CONNECTION_SYNC_PROGRESS}${policy?.id}`);
const isSyncInProgress = isConnectionInProgress(connectionSyncProgress, policy);
const hasSyncError = PolicyUtils.shouldShowSyncError(policy, isSyncInProgress);
const isConnectedToAccounting = Object.keys(policy?.connections ?? {}).length > 0;
const currentConnectionName = PolicyUtils.getCurrentConnectionName(policy);
const canSelectMultiple = shouldUseNarrowLayout ? selectionMode?.isEnabled : true;
const enabledRatesCount = selectedTaxesIDs.filter((taxID) => !policy?.taxRates?.taxes[taxID]?.isDisabled).length;
const disabledRatesCount = selectedTaxesIDs.length - enabledRatesCount;
const fetchTaxes = useCallback(() => {
openPolicyTaxesPage(policyID);
}, [policyID]);
const {isOffline} = useNetwork({onReconnect: fetchTaxes});
useFocusEffect(
useCallback(() => {
fetchTaxes();
}, [fetchTaxes]),
);
const cleanupSelectedOption = useCallback(() => setSelectedTaxesIDs([]), []);
useCleanupSelectedOptions(cleanupSelectedOption);
const textForDefault = useCallback(
(taxID: string, taxRate: TaxRate): string => {
let suffix;
if (taxID === defaultExternalID && taxID === foreignTaxDefault) {
suffix = translate('common.default');
} else if (taxID === defaultExternalID) {
suffix = translate('workspace.taxes.workspaceDefault');
} else if (taxID === foreignTaxDefault) {
suffix = translate('workspace.taxes.foreignDefault');
}
if (suffix) {
return `${taxRate.value} ${CONST.DOT_SEPARATOR} ${suffix}`;
}
return `${taxRate.value}`;
},
[defaultExternalID, foreignTaxDefault, translate],
);
const taxesList = useMemo<ListItem[]>(() => {
if (!policy) {
return [];
}
return Object.entries(policy.taxRates?.taxes ?? {})
.map(([key, value]) => ({
text: value.name,
alternateText: textForDefault(key, value),
keyForList: key,
isSelected: !!selectedTaxesIDs.includes(key) && canSelectMultiple,
isDisabledCheckbox: !PolicyUtils.canEditTaxRate(policy, key),
isDisabled: value.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
pendingAction: value.pendingAction ?? (Object.keys(value.pendingFields ?? {}).length > 0 ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE : null),
errors: value.errors ?? ErrorUtils.getLatestErrorFieldForAnyField(value),
rightElement: <ListItemRightCaretWithLabel labelText={!value.isDisabled ? translate('workspace.common.enabled') : translate('workspace.common.disabled')} />,
}))
.sort((a, b) => (a.text ?? a.keyForList ?? '').localeCompare(b.text ?? b.keyForList ?? ''));
}, [policy, textForDefault, selectedTaxesIDs, canSelectMultiple, translate]);
const isLoading = !isOffline && taxesList === undefined;
const toggleTax = (tax: ListItem) => {
const key = tax.keyForList;
if (typeof key !== 'string' || key === defaultExternalID || key === foreignTaxDefault) {
return;
}
setSelectedTaxesIDs((prev) => {
if (prev?.includes(key)) {
return prev.filter((item) => item !== key);
}
return [...prev, key];
});
};
const toggleAllTaxes = () => {
const taxesToSelect = taxesList.filter(
(tax) => tax.keyForList !== defaultExternalID && tax.keyForList !== foreignTaxDefault && tax.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
);
setSelectedTaxesIDs((prev) => {
if (prev.length === taxesToSelect.length) {
return [];
}
return taxesToSelect.map((item) => (item.keyForList ? item.keyForList : ''));
});
};
const getCustomListHeader = () => {
return (
<CustomListHeader
canSelectMultiple={canSelectMultiple}
leftHeaderText={translate('common.name')}
rightHeaderText={translate('statusPage.status')}
/>
);
};
const deleteTaxes = useCallback(() => {
if (!policyID) {
return;
}
deletePolicyTaxes(policyID, selectedTaxesIDs);
setSelectedTaxesIDs([]);
setIsDeleteModalVisible(false);
}, [policyID, selectedTaxesIDs]);
const toggleTaxes = useCallback(
(isEnabled: boolean) => {
if (!policyID) {
return;
}
setPolicyTaxesEnabled(policyID, selectedTaxesIDs, isEnabled);
setSelectedTaxesIDs([]);
},
[policyID, selectedTaxesIDs],
);
const navigateToEditTaxRate = (taxRate: ListItem) => {
if (!taxRate.keyForList) {
return;
}
if (isSmallScreenWidth && selectionMode?.isEnabled) {
toggleTax(taxRate);
return;
}
Navigation.navigate(ROUTES.WORKSPACE_TAX_EDIT.getRoute(policyID, taxRate.keyForList));
};
const dropdownMenuOptions = useMemo(() => {
const isMultiple = selectedTaxesIDs.length > 1;
const options: Array<DropdownOption<WorkspaceTaxRatesBulkActionType>> = [];
if (!hasAccountingConnections) {
options.push({
icon: Expensicons.Trashcan,
text: isMultiple ? translate('workspace.taxes.actions.deleteMultiple') : translate('workspace.taxes.actions.delete'),
value: CONST.POLICY.BULK_ACTION_TYPES.DELETE,
onSelected: () => setIsDeleteModalVisible(true),
});
}
// `Disable rates` when at least one enabled rate is selected.
if (selectedTaxesIDs.some((taxID) => !policy?.taxRates?.taxes[taxID]?.isDisabled)) {
options.push({
icon: Expensicons.Close,
text: translate('workspace.taxes.actions.disableTaxRates', {count: enabledRatesCount}),
value: CONST.POLICY.BULK_ACTION_TYPES.DISABLE,
onSelected: () => toggleTaxes(false),
});
}
// `Enable rates` when at least one disabled rate is selected.
if (selectedTaxesIDs.some((taxID) => policy?.taxRates?.taxes[taxID]?.isDisabled)) {
options.push({
icon: Expensicons.Checkmark,
text: translate('workspace.taxes.actions.enableTaxRates', {count: disabledRatesCount}),
value: CONST.POLICY.BULK_ACTION_TYPES.ENABLE,
onSelected: () => toggleTaxes(true),
});
}
return options;
}, [hasAccountingConnections, policy?.taxRates?.taxes, selectedTaxesIDs, toggleTaxes, translate, enabledRatesCount, disabledRatesCount]);
const shouldShowBulkActionsButton = shouldUseNarrowLayout ? selectionMode?.isEnabled : selectedTaxesIDs.length > 0;
const headerButtons = !shouldShowBulkActionsButton ? (
<View style={[styles.w100, styles.flexRow, styles.gap2, shouldUseNarrowLayout && styles.mb3]}>
{!hasAccountingConnections && (
<Button
success
onPress={() => Navigation.navigate(ROUTES.WORKSPACE_TAX_CREATE.getRoute(policyID))}
icon={Expensicons.Plus}
text={translate('workspace.taxes.addRate')}
style={[shouldUseNarrowLayout && styles.flex1]}
/>
)}
<Button
onPress={() => Navigation.navigate(ROUTES.WORKSPACE_TAXES_SETTINGS.getRoute(policyID))}
icon={Expensicons.Gear}
text={translate('common.settings')}
style={[shouldUseNarrowLayout && styles.flex1]}
/>
</View>
) : (
<ButtonWithDropdownMenu<WorkspaceTaxRatesBulkActionType>
onPress={() => {}}
options={dropdownMenuOptions}
buttonSize={CONST.DROPDOWN_BUTTON_SIZE.MEDIUM}
customText={translate('workspace.common.selected', {count: selectedTaxesIDs.length})}
shouldAlwaysShowDropdownMenu
pressOnEnter
isSplitButton={false}
style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]}
isDisabled={!selectedTaxesIDs.length}
/>
);
const getHeaderText = () => (
<View style={[styles.ph5, styles.pb5, styles.pt3, shouldUseNarrowLayout ? styles.workspaceSectionMobile : styles.workspaceSection]}>
{!hasSyncError && isConnectedToAccounting ? (
<Text>
<Text style={[styles.textNormal, styles.colorMuted]}>{`${translate('workspace.taxes.importedFromAccountingSoftware')} `}</Text>
<TextLink
style={[styles.textNormal, styles.link]}
href={`${environmentURL}/${ROUTES.POLICY_ACCOUNTING.getRoute(policyID)}`}
>
{`${currentConnectionName} ${translate('workspace.accounting.settings')}`}
</TextLink>
<Text style={[styles.textNormal, styles.colorMuted]}>.</Text>
</Text>
) : (
<Text style={[styles.textNormal, styles.colorMuted]}>{translate('workspace.taxes.subtitle')}</Text>
)}
</View>
);
const selectionModeHeader = selectionMode?.isEnabled && shouldUseNarrowLayout;
return (
<AccessOrNotFoundWrapper
accessVariants={[CONST.POLICY.ACCESS_VARIANTS.ADMIN, CONST.POLICY.ACCESS_VARIANTS.PAID]}
policyID={policyID}
featureName={CONST.POLICY.MORE_FEATURES.ARE_TAXES_ENABLED}
>
<ScreenWrapper
includeSafeAreaPaddingBottom={false}
style={[styles.defaultModalContainer]}
testID={WorkspaceTaxesPage.displayName}
shouldShowOfflineIndicatorInWideScreen
>
<HeaderWithBackButton
icon={!selectionModeHeader ? Illustrations.Coins : undefined}
shouldUseHeadlineHeader={!selectionModeHeader}
title={translate(selectionModeHeader ? 'common.selectMultiple' : 'workspace.common.taxes')}
shouldShowBackButton={shouldUseNarrowLayout}
onBackButtonPress={() => {
if (selectionMode?.isEnabled) {
setSelectedTaxesIDs([]);
turnOffMobileSelectionMode();
return;
}
Navigation.goBack();
}}
>
{!shouldUseNarrowLayout && headerButtons}
</HeaderWithBackButton>
{shouldUseNarrowLayout && <View style={[styles.pl5, styles.pr5]}>{headerButtons}</View>}
{!shouldUseNarrowLayout && getHeaderText()}
{isLoading && (
<ActivityIndicator
size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={[styles.flex1]}
color={theme.spinner}
/>
)}
<SelectionListWithModal
canSelectMultiple={canSelectMultiple}
turnOnSelectionModeOnLongPress
onTurnOnSelectionMode={(item) => item && toggleTax(item)}
sections={[{data: taxesList, isDisabled: false}]}
onCheckboxPress={toggleTax}
onSelectRow={navigateToEditTaxRate}
onSelectAll={toggleAllTaxes}
ListItem={TableListItem}
customListHeader={getCustomListHeader()}
listHeaderContent={shouldUseNarrowLayout ? getHeaderText() : null}
shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
listHeaderWrapperStyle={[styles.ph9, styles.pv3, styles.pb5]}
onDismissError={(item) => (item.keyForList ? clearTaxRateError(policyID, item.keyForList, item.pendingAction) : undefined)}
showScrollIndicator={false}
/>
<ConfirmModal
title={translate('workspace.taxes.actions.delete')}
isVisible={isDeleteModalVisible}
onConfirm={deleteTaxes}
onCancel={() => setIsDeleteModalVisible(false)}
prompt={
selectedTaxesIDs.length > 1
? translate('workspace.taxes.deleteMultipleTaxConfirmation', {taxAmount: selectedTaxesIDs.length})
: translate('workspace.taxes.deleteTaxConfirmation')
}
confirmText={translate('common.delete')}
cancelText={translate('common.cancel')}
danger
/>
</ScreenWrapper>
</AccessOrNotFoundWrapper>
);
}
WorkspaceTaxesPage.displayName = 'WorkspaceTaxesPage';
export default withPolicyAndFullscreenLoading(WorkspaceTaxesPage);