-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AdvancedSearchFilters.tsx
420 lines (383 loc) · 18 KB
/
AdvancedSearchFilters.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
import React, {useMemo} from 'react';
import {View} from 'react-native';
import type {ValueOf} from 'react-native-gesture-handler/lib/typescript/typeUtils';
import type {OnyxCollection} from 'react-native-onyx';
import {useOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import FormAlertWithSubmitButton from '@components/FormAlertWithSubmitButton';
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription';
import {usePersonalDetails} from '@components/OnyxProvider';
import ScrollView from '@components/ScrollView';
import type {SearchFilterKey} from '@components/Search/types';
import useLocalize from '@hooks/useLocalize';
import useSingleExecution from '@hooks/useSingleExecution';
import useThemeStyles from '@hooks/useThemeStyles';
import useWaitForNavigation from '@hooks/useWaitForNavigation';
import {convertToDisplayStringWithoutCurrency} from '@libs/CurrencyUtils';
import localeCompare from '@libs/LocaleCompare';
import Navigation from '@libs/Navigation/Navigation';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import {getAllTaxRates, getTagNamesFromTagsLists} from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as SearchQueryUtils from '@libs/SearchQueryUtils';
import * as SearchUIUtils from '@libs/SearchUIUtils';
import * as SearchActions from '@userActions/Search';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {SearchAdvancedFiltersForm} from '@src/types/form';
import type {CardList, PersonalDetailsList, Policy, PolicyTagLists, Report} from '@src/types/onyx';
const baseFilterConfig = {
date: {
getTitle: getFilterDisplayTitle,
description: 'common.date' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_DATE,
},
currency: {
getTitle: getFilterDisplayTitle,
description: 'common.currency' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_CURRENCY,
},
merchant: {
getTitle: getFilterDisplayTitle,
description: 'common.merchant' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_MERCHANT,
},
description: {
getTitle: getFilterDisplayTitle,
description: 'common.description' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_DESCRIPTION,
},
reportID: {
getTitle: getFilterDisplayTitle,
description: 'common.reportID' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_REPORT_ID,
},
amount: {
getTitle: getFilterDisplayTitle,
description: 'common.total' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_AMOUNT,
},
category: {
getTitle: getFilterDisplayTitle,
description: 'common.category' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_CATEGORY,
},
keyword: {
getTitle: getFilterDisplayTitle,
description: 'search.filters.hasKeywords' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_KEYWORD,
},
cardID: {
getTitle: getFilterCardDisplayTitle,
description: 'common.card' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_CARD,
},
taxRate: {
getTitle: getFilterTaxRateDisplayTitle,
description: 'workspace.taxes.taxRate' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_TAX_RATE,
},
expenseType: {
getTitle: getFilterExpenseDisplayTitle,
description: 'search.expenseType' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_EXPENSE_TYPE,
},
tag: {
getTitle: getFilterDisplayTitle,
description: 'common.tag' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_TAG,
},
from: {
getTitle: getFilterParticipantDisplayTitle,
description: 'common.from' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_FROM,
},
to: {
getTitle: getFilterParticipantDisplayTitle,
description: 'common.to' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_TO,
},
in: {
getTitle: getFilterInDisplayTitle,
description: 'common.in' as const,
route: ROUTES.SEARCH_ADVANCED_FILTERS_IN,
},
};
const typeFiltersKeys: Record<string, Array<ValueOf<typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>>> = {
[CONST.SEARCH.DATA_TYPES.EXPENSE]: ['date', 'currency', 'merchant', 'description', 'reportID', 'amount', 'category', 'keyword', 'taxRate', 'expenseType', 'tag', 'from', 'to', 'cardID'],
[CONST.SEARCH.DATA_TYPES.INVOICE]: ['date', 'currency', 'merchant', 'description', 'reportID', 'amount', 'category', 'keyword', 'taxRate', 'tag', 'from', 'to', 'cardID'],
[CONST.SEARCH.DATA_TYPES.TRIP]: ['date', 'currency', 'merchant', 'description', 'reportID', 'amount', 'category', 'keyword', 'taxRate', 'tag', 'from', 'to', 'cardID'],
[CONST.SEARCH.DATA_TYPES.CHAT]: ['date', 'keyword', 'from', 'in'],
};
function getFilterCardDisplayTitle(filters: Partial<SearchAdvancedFiltersForm>, cards: CardList) {
const filterValue = filters[CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID];
return filterValue
? Object.values(cards)
.filter((card) => filterValue.includes(card.cardID.toString()))
.map((card) => card.bank)
.join(', ')
: undefined;
}
function getFilterParticipantDisplayTitle(accountIDs: string[], personalDetails: PersonalDetailsList) {
const selectedPersonalDetails = accountIDs.map((id) => personalDetails[id]);
return selectedPersonalDetails
.map((personalDetail) => {
if (!personalDetail) {
return '';
}
return PersonalDetailsUtils.createDisplayName(personalDetail.login ?? '', personalDetail);
})
.filter(Boolean)
.join(', ');
}
const sortOptionsWithEmptyValue = (a: string, b: string) => {
// Always show `No category` and `No tag` as the first option
if (a === CONST.SEARCH.EMPTY_VALUE) {
return -1;
}
if (b === CONST.SEARCH.EMPTY_VALUE) {
return 1;
}
return localeCompare(a, b);
};
function getFilterDisplayTitle(filters: Partial<SearchAdvancedFiltersForm>, filterKey: SearchFilterKey, translate: LocaleContextProps['translate']) {
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE) {
// the value of date filter is a combination of dateBefore + dateAfter values
const {dateAfter, dateBefore} = filters;
let dateValue = '';
if (dateBefore) {
dateValue = translate('search.filters.date.before', {date: dateBefore});
}
if (dateBefore && dateAfter) {
dateValue += ', ';
}
if (dateAfter) {
dateValue += translate('search.filters.date.after', {date: dateAfter});
}
return dateValue;
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT) {
const {lessThan, greaterThan} = filters;
if (lessThan && greaterThan) {
return translate('search.filters.amount.between', {
lessThan: convertToDisplayStringWithoutCurrency(Number(lessThan)),
greaterThan: convertToDisplayStringWithoutCurrency(Number(greaterThan)),
});
}
if (lessThan) {
return translate('search.filters.amount.lessThan', {amount: convertToDisplayStringWithoutCurrency(Number(lessThan))});
}
if (greaterThan) {
return translate('search.filters.amount.greaterThan', {amount: convertToDisplayStringWithoutCurrency(Number(greaterThan))});
}
// Will never happen
return;
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CURRENCY && filters[filterKey]) {
const filterArray = filters[filterKey] ?? [];
return filterArray.sort(localeCompare).join(', ');
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY && filters[filterKey]) {
const filterArray = filters[filterKey] ?? [];
return filterArray
.sort(sortOptionsWithEmptyValue)
.map((value) => (value === CONST.SEARCH.EMPTY_VALUE ? translate('search.noCategory') : value))
.join(', ');
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG && filters[filterKey]) {
const filterArray = filters[filterKey] ?? [];
return filterArray
.sort(sortOptionsWithEmptyValue)
.map((value) => (value === CONST.SEARCH.EMPTY_VALUE ? translate('search.noTag') : value))
.join(', ');
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.DESCRIPTION) {
return filters[filterKey];
}
const filterValue = filters[filterKey];
return Array.isArray(filterValue) ? filterValue.join(', ') : filterValue;
}
function getFilterTaxRateDisplayTitle(filters: Partial<SearchAdvancedFiltersForm>, taxRates: Record<string, string[]>) {
const selectedTaxRateKeys = filters[CONST.SEARCH.SYNTAX_FILTER_KEYS.TAX_RATE];
if (!selectedTaxRateKeys) {
return undefined;
}
const result: string[] = [];
Object.entries(taxRates).forEach(([taxRateName, taxRateKeys]) => {
if (!taxRateKeys.some((taxRateKey) => selectedTaxRateKeys.includes(taxRateKey)) || result.includes(taxRateName)) {
return;
}
result.push(taxRateName);
});
return result.join(', ');
}
function getFilterExpenseDisplayTitle(filters: Partial<SearchAdvancedFiltersForm>, translate: LocaleContextProps['translate']) {
const filterValue = filters[CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPENSE_TYPE];
return filterValue
? Object.values(CONST.SEARCH.TRANSACTION_TYPE)
.filter((expenseType) => filterValue.includes(expenseType))
.map((expenseType) => translate(SearchUIUtils.getExpenseTypeTranslationKey(expenseType)))
.join(', ')
: undefined;
}
function getFilterInDisplayTitle(filters: Partial<SearchAdvancedFiltersForm>, _: LocaleContextProps['translate'], reports?: OnyxCollection<Report>) {
return filters.in
? filters.in
.map((id) => ReportUtils.getReportName(reports?.[`${ONYXKEYS.COLLECTION.REPORT}${id}`]))
.filter(Boolean)
.join(', ')
: undefined;
}
function AdvancedSearchFilters() {
const {translate} = useLocalize();
const styles = useThemeStyles();
const {singleExecution} = useSingleExecution();
const waitForNavigate = useWaitForNavigation();
const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const [savedSearches] = useOnyx(ONYXKEYS.SAVED_SEARCHES);
const [searchAdvancedFilters = {} as SearchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM);
const policyID = searchAdvancedFilters.policyID ?? '-1';
const [cardList = {}] = useOnyx(ONYXKEYS.CARD_LIST);
const taxRates = getAllTaxRates();
const personalDetails = usePersonalDetails();
const [policies = {}] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [allPolicyCategories = {}] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES);
const singlePolicyCategories = allPolicyCategories[`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`];
const [allPolicyTagLists = {}] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS);
const singlePolicyTagLists = allPolicyTagLists[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`];
const tagListsUnpacked = Object.values(allPolicyTagLists ?? {})
.filter((item): item is NonNullable<PolicyTagLists> => !!item)
.map(getTagNamesFromTagsLists)
.flat();
// When looking if a user has any categories to display, we want to ignore the policies that are of type PERSONAL
const nonPersonalPolicyCategoryIds = Object.values(policies)
.filter((policy): policy is NonNullable<Policy> => !!(policy && policy.type !== CONST.POLICY.TYPE.PERSONAL))
.map((policy) => `${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy.id}`);
const nonPersonalPolicyCategoryCount = Object.keys(allPolicyCategories).filter((policyCategoryId) => nonPersonalPolicyCategoryIds.includes(policyCategoryId)).length;
const shouldDisplayCategoryFilter = nonPersonalPolicyCategoryCount !== 0 || !!singlePolicyCategories;
const shouldDisplayTagFilter = tagListsUnpacked.length !== 0 || !!singlePolicyTagLists;
const shouldDisplayCardFilter = Object.keys(cardList).length !== 0;
const shouldDisplayTaxFilter = Object.keys(taxRates).length !== 0;
let currentType = searchAdvancedFilters?.type ?? CONST.SEARCH.DATA_TYPES.EXPENSE;
if (!Object.keys(typeFiltersKeys).includes(currentType)) {
currentType = CONST.SEARCH.DATA_TYPES.EXPENSE;
}
const queryString = useMemo(() => SearchQueryUtils.buildQueryStringFromFilterFormValues(searchAdvancedFilters), [searchAdvancedFilters]);
const queryJSON = useMemo(() => SearchQueryUtils.buildSearchQueryJSON(queryString || SearchQueryUtils.buildCannedSearchQuery()), [queryString]);
const applyFiltersAndNavigate = () => {
SearchActions.clearAllFilters();
Navigation.dismissModal();
Navigation.navigate(
ROUTES.SEARCH_CENTRAL_PANE.getRoute({
query: queryString,
}),
);
};
const onSaveSearch = () => {
const savedSearchKeys = Object.keys(savedSearches ?? {});
if (!queryJSON || (savedSearches && savedSearchKeys.includes(String(queryJSON.hash)))) {
// If the search is already saved, return early to prevent unnecessary API calls
Navigation.dismissModal();
return;
}
// We only want to show the tooltip once, the NVP will not be set if the user has not saved a search yet
if (!savedSearches) {
SearchActions.showSavedSearchRenameTooltip();
}
SearchActions.saveSearch({
queryJSON,
});
applyFiltersAndNavigate();
};
const filters = typeFiltersKeys[currentType]
.map((key) => {
const onPress = singleExecution(waitForNavigate(() => Navigation.navigate(baseFilterConfig[key].route)));
let filterTitle;
if (
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.CURRENCY ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DESCRIPTION ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_ID ||
key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD
) {
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, key, translate);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY) {
if (!shouldDisplayCategoryFilter) {
return;
}
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, key, translate);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG) {
if (!shouldDisplayTagFilter) {
return;
}
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, key, translate);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID) {
if (!shouldDisplayCardFilter) {
return;
}
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, cardList);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAX_RATE) {
if (!shouldDisplayTaxFilter) {
return;
}
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, taxRates);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPENSE_TYPE) {
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, translate);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM || key === CONST.SEARCH.SYNTAX_FILTER_KEYS.TO) {
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters[key] ?? [], personalDetails);
} else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.IN) {
filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, translate, reports);
}
return {
key,
title: filterTitle,
description: translate(baseFilterConfig[key].description),
onPress,
};
})
.sort((a, b) => (a?.description ?? '')?.localeCompare(b?.description ?? ''));
const displaySearchButton = queryJSON && !SearchQueryUtils.isCannedSearchQuery(queryJSON);
return (
<>
<ScrollView contentContainerStyle={[styles.flexGrow1, styles.justifyContentBetween]}>
<View>
{filters.map((filter) => {
if (filter === undefined) {
return undefined;
}
return (
<MenuItemWithTopDescription
key={filter.description}
title={filter.title}
titleStyle={styles.flex1}
description={filter.description}
shouldShowRightIcon
onPress={filter.onPress}
/>
);
})}
</View>
</ScrollView>
{!!displaySearchButton && (
<Button
text={translate('search.saveSearch')}
onPress={onSaveSearch}
style={[styles.mh4, styles.mt4]}
large
/>
)}
<FormAlertWithSubmitButton
buttonText={translate('search.viewResults')}
containerStyles={[styles.m4, styles.mb5]}
onSubmit={applyFiltersAndNavigate}
enabledWhenOffline
/>
</>
);
}
AdvancedSearchFilters.displayName = 'AdvancedSearchFilters';
export default AdvancedSearchFilters;