-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
SearchUtils.ts
826 lines (713 loc) · 33.1 KB
/
SearchUtils.ts
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
import type {OnyxCollection} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import type {ASTNode, QueryFilter, QueryFilters, SearchColumnType, SearchQueryJSON, SearchQueryString, SearchStatus, SortOrder} from '@components/Search/types';
import ChatListItem from '@components/SelectionList/ChatListItem';
import ReportListItem from '@components/SelectionList/Search/ReportListItem';
import TransactionListItem from '@components/SelectionList/Search/TransactionListItem';
import type {ListItem, ReportActionListItemType, ReportListItemType, TransactionListItemType} from '@components/SelectionList/types';
import * as Expensicons from '@src/components/Icon/Expensicons';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
import type {SearchAdvancedFiltersForm} from '@src/types/form';
import FILTER_KEYS from '@src/types/form/SearchAdvancedFiltersForm';
import type * as OnyxTypes from '@src/types/onyx';
import type SearchResults from '@src/types/onyx/SearchResults';
import type {ListItemDataType, ListItemType, SearchDataTypes, SearchPersonalDetails, SearchReport, SearchTransaction} from '@src/types/onyx/SearchResults';
import * as CurrencyUtils from './CurrencyUtils';
import DateUtils from './DateUtils';
import {translateLocal} from './Localize';
import Navigation from './Navigation/Navigation';
import navigationRef from './Navigation/navigationRef';
import type {AuthScreensParamList, RootStackParamList, State} from './Navigation/types';
import * as PersonalDetailsUtils from './PersonalDetailsUtils';
import * as ReportActionsUtils from './ReportActionsUtils';
import * as ReportUtils from './ReportUtils';
import * as searchParser from './SearchParser/searchParser';
import * as TransactionUtils from './TransactionUtils';
import * as UserUtils from './UserUtils';
type FilterKeys = keyof typeof CONST.SEARCH.SYNTAX_FILTER_KEYS;
const columnNamesToSortingProperty = {
[CONST.SEARCH.TABLE_COLUMNS.TO]: 'formattedTo' as const,
[CONST.SEARCH.TABLE_COLUMNS.FROM]: 'formattedFrom' as const,
[CONST.SEARCH.TABLE_COLUMNS.DATE]: 'date' as const,
[CONST.SEARCH.TABLE_COLUMNS.TAG]: 'tag' as const,
[CONST.SEARCH.TABLE_COLUMNS.MERCHANT]: 'formattedMerchant' as const,
[CONST.SEARCH.TABLE_COLUMNS.TOTAL_AMOUNT]: 'formattedTotal' as const,
[CONST.SEARCH.TABLE_COLUMNS.CATEGORY]: 'category' as const,
[CONST.SEARCH.TABLE_COLUMNS.TYPE]: 'transactionType' as const,
[CONST.SEARCH.TABLE_COLUMNS.ACTION]: 'action' as const,
[CONST.SEARCH.TABLE_COLUMNS.DESCRIPTION]: 'comment' as const,
[CONST.SEARCH.TABLE_COLUMNS.TAX_AMOUNT]: null,
[CONST.SEARCH.TABLE_COLUMNS.RECEIPT]: null,
};
// This map contains signs with spaces that match each operator
const operatorToSignMap = {
[CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO]: ':' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN]: '<' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO]: '<=' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN]: '>' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO]: '>=' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO]: '!=' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.AND]: ',' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.OR]: ' ' as const,
};
/**
* @private
*/
function getTransactionItemCommonFormattedProperties(
transactionItem: SearchTransaction,
from: SearchPersonalDetails,
to: SearchPersonalDetails,
): Pick<TransactionListItemType, 'formattedFrom' | 'formattedTo' | 'formattedTotal' | 'formattedMerchant' | 'date'> {
const isExpenseReport = transactionItem.reportType === CONST.REPORT.TYPE.EXPENSE;
const formattedFrom = from?.displayName ?? from?.login ?? '';
const formattedTo = to?.displayName ?? to?.login ?? '';
const formattedTotal = TransactionUtils.getAmount(transactionItem, isExpenseReport);
const date = transactionItem?.modifiedCreated ? transactionItem.modifiedCreated : transactionItem?.created;
const merchant = TransactionUtils.getMerchant(transactionItem);
const formattedMerchant = merchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT || merchant === CONST.TRANSACTION.DEFAULT_MERCHANT ? '' : merchant;
return {
formattedFrom,
formattedTo,
date,
formattedTotal,
formattedMerchant,
};
}
type ReportKey = `${typeof ONYXKEYS.COLLECTION.REPORT}${string}`;
type TransactionKey = `${typeof ONYXKEYS.COLLECTION.TRANSACTION}${string}`;
type ReportActionKey = `${typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS}${string}`;
function isReportEntry(key: string): key is ReportKey {
return key.startsWith(ONYXKEYS.COLLECTION.REPORT);
}
function isTransactionEntry(key: string): key is TransactionKey {
return key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION);
}
function isReportActionEntry(key: string): key is ReportActionKey {
return key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
}
function getShouldShowMerchant(data: OnyxTypes.SearchResults['data']): boolean {
return Object.keys(data).some((key) => {
if (isTransactionEntry(key)) {
const item = data[key];
const merchant = item.modifiedMerchant ? item.modifiedMerchant : item.merchant ?? '';
return merchant !== '' && merchant !== CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT && merchant !== CONST.TRANSACTION.DEFAULT_MERCHANT;
}
return false;
});
}
const currentYear = new Date().getFullYear();
function isReportListItemType(item: ListItem): item is ReportListItemType {
return 'transactions' in item;
}
function isTransactionListItemType(item: TransactionListItemType | ReportListItemType | ReportActionListItemType): item is TransactionListItemType {
const transactionListItem = item as TransactionListItemType;
return transactionListItem.transactionID !== undefined;
}
function isReportActionListItemType(item: TransactionListItemType | ReportListItemType | ReportActionListItemType): item is ReportActionListItemType {
const reportActionListItem = item as ReportActionListItemType;
return reportActionListItem.reportActionID !== undefined;
}
function shouldShowYear(data: TransactionListItemType[] | ReportListItemType[] | OnyxTypes.SearchResults['data']): boolean {
if (Array.isArray(data)) {
return data.some((item: TransactionListItemType | ReportListItemType) => {
if (isReportListItemType(item)) {
// If the item is a ReportListItemType, iterate over its transactions and check them
return item.transactions.some((transaction) => {
const transactionYear = new Date(TransactionUtils.getCreated(transaction)).getFullYear();
return transactionYear !== currentYear;
});
}
const createdYear = new Date(item?.modifiedCreated ? item.modifiedCreated : item?.created || '').getFullYear();
return createdYear !== currentYear;
});
}
for (const key in data) {
if (isTransactionEntry(key)) {
const item = data[key];
const date = TransactionUtils.getCreated(item);
if (DateUtils.doesDateBelongToAPastYear(date)) {
return true;
}
} else if (isReportActionEntry(key)) {
const item = data[key];
for (const action of Object.values(item)) {
const date = action.created;
if (DateUtils.doesDateBelongToAPastYear(date)) {
return true;
}
}
}
}
return false;
}
function getTransactionsSections(data: OnyxTypes.SearchResults['data'], metadata: OnyxTypes.SearchResults['search']): TransactionListItemType[] {
const shouldShowMerchant = getShouldShowMerchant(data);
const doesDataContainAPastYearTransaction = shouldShowYear(data);
return Object.keys(data)
.filter(isTransactionEntry)
.map((key) => {
const transactionItem = data[key];
const from = data.personalDetailsList?.[transactionItem.accountID];
const to = data.personalDetailsList?.[transactionItem.managerID];
const {formattedFrom, formattedTo, formattedTotal, formattedMerchant, date} = getTransactionItemCommonFormattedProperties(transactionItem, from, to);
return {
...transactionItem,
from,
to,
formattedFrom,
formattedTo,
formattedTotal,
formattedMerchant,
date,
shouldShowMerchant,
shouldShowCategory: metadata?.columnsToShow?.shouldShowCategoryColumn,
shouldShowTag: metadata?.columnsToShow?.shouldShowTagColumn,
shouldShowTax: metadata?.columnsToShow?.shouldShowTaxColumn,
keyForList: transactionItem.transactionID,
shouldShowYear: doesDataContainAPastYearTransaction,
};
});
}
function getReportActionsSections(data: OnyxTypes.SearchResults['data']): ReportActionListItemType[] {
const reportActionItems: ReportActionListItemType[] = [];
for (const key in data) {
if (isReportActionEntry(key)) {
const reportActions = data[key];
for (const reportAction of Object.values(reportActions)) {
const from = data.personalDetailsList?.[reportAction.accountID];
if (ReportActionsUtils.isDeletedAction(reportAction)) {
// eslint-disable-next-line no-continue
continue;
}
reportActionItems.push({
...reportAction,
from,
formattedFrom: from?.displayName ?? from?.login ?? '',
date: reportAction.created,
keyForList: reportAction.reportActionID,
});
}
}
}
return reportActionItems;
}
function getIOUReportName(data: OnyxTypes.SearchResults['data'], reportItem: SearchReport) {
const payerPersonalDetails = data.personalDetailsList?.[reportItem.managerID ?? 0];
const payerName = payerPersonalDetails?.displayName ?? payerPersonalDetails?.login ?? translateLocal('common.hidden');
const formattedAmount = CurrencyUtils.convertToDisplayString(reportItem.total ?? 0, reportItem.currency ?? CONST.CURRENCY.USD);
if (reportItem.action === CONST.SEARCH.ACTION_TYPES.VIEW) {
return translateLocal('iou.payerOwesAmount', {
payer: payerName,
amount: formattedAmount,
});
}
if (reportItem.action === CONST.SEARCH.ACTION_TYPES.PAID) {
return translateLocal('iou.payerPaidAmount', {
payer: payerName,
amount: formattedAmount,
});
}
return reportItem.reportName;
}
function getReportSections(data: OnyxTypes.SearchResults['data'], metadata: OnyxTypes.SearchResults['search']): ReportListItemType[] {
const shouldShowMerchant = getShouldShowMerchant(data);
const doesDataContainAPastYearTransaction = shouldShowYear(data);
const reportIDToTransactions: Record<string, ReportListItemType> = {};
for (const key in data) {
if (isReportEntry(key)) {
const reportItem = {...data[key]};
const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${reportItem.reportID}`;
const transactions = reportIDToTransactions[reportKey]?.transactions ?? [];
const isIOUReport = reportItem.type === CONST.REPORT.TYPE.IOU;
reportIDToTransactions[reportKey] = {
...reportItem,
keyForList: reportItem.reportID,
from: data.personalDetailsList?.[reportItem.accountID ?? -1],
to: data.personalDetailsList?.[reportItem.managerID ?? -1],
transactions,
reportName: isIOUReport ? getIOUReportName(data, reportItem) : reportItem.reportName,
};
} else if (isTransactionEntry(key)) {
const transactionItem = {...data[key]};
const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${transactionItem.reportID}`;
const from = data.personalDetailsList?.[transactionItem.accountID];
const to = data.personalDetailsList?.[transactionItem.managerID];
const {formattedFrom, formattedTo, formattedTotal, formattedMerchant, date} = getTransactionItemCommonFormattedProperties(transactionItem, from, to);
const transaction = {
...transactionItem,
from,
to,
formattedFrom,
formattedTo,
formattedTotal,
formattedMerchant,
date,
shouldShowMerchant,
shouldShowCategory: metadata?.columnsToShow?.shouldShowCategoryColumn,
shouldShowTag: metadata?.columnsToShow?.shouldShowTagColumn,
shouldShowTax: metadata?.columnsToShow?.shouldShowTaxColumn,
keyForList: transactionItem.transactionID,
shouldShowYear: doesDataContainAPastYearTransaction,
};
if (reportIDToTransactions[reportKey]?.transactions) {
reportIDToTransactions[reportKey].transactions.push(transaction);
} else if (reportIDToTransactions[reportKey]) {
reportIDToTransactions[reportKey].transactions = [transaction];
}
}
}
return Object.values(reportIDToTransactions);
}
function getListItem(type: SearchDataTypes, status: SearchStatus): ListItemType<typeof type, typeof status> {
if (type === CONST.SEARCH.DATA_TYPES.CHAT) {
return ChatListItem;
}
return status === CONST.SEARCH.STATUS.EXPENSE.ALL ? TransactionListItem : ReportListItem;
}
function getSections(type: SearchDataTypes, status: SearchStatus, data: OnyxTypes.SearchResults['data'], metadata: OnyxTypes.SearchResults['search']) {
if (type === CONST.SEARCH.DATA_TYPES.CHAT) {
return getReportActionsSections(data);
}
return status === CONST.SEARCH.STATUS.EXPENSE.ALL ? getTransactionsSections(data, metadata) : getReportSections(data, metadata);
}
function getSortedSections(type: SearchDataTypes, status: SearchStatus, data: ListItemDataType<typeof type, typeof status>, sortBy?: SearchColumnType, sortOrder?: SortOrder) {
if (type === CONST.SEARCH.DATA_TYPES.CHAT) {
return getSortedReportActionData(data as ReportActionListItemType[]);
}
return status === CONST.SEARCH.STATUS.EXPENSE.ALL ? getSortedTransactionData(data as TransactionListItemType[], sortBy, sortOrder) : getSortedReportData(data as ReportListItemType[]);
}
function getSortedTransactionData(data: TransactionListItemType[], sortBy?: SearchColumnType, sortOrder?: SortOrder) {
if (!sortBy || !sortOrder) {
return data;
}
const sortingProperty = columnNamesToSortingProperty[sortBy];
if (!sortingProperty) {
return data;
}
return data.sort((a, b) => {
const aValue = sortingProperty === 'comment' ? a.comment?.comment : a[sortingProperty];
const bValue = sortingProperty === 'comment' ? b.comment?.comment : b[sortingProperty];
if (aValue === undefined || bValue === undefined) {
return 0;
}
// We are guaranteed that both a and b will be string or number at the same time
if (typeof aValue === 'string' && typeof bValue === 'string') {
return sortOrder === CONST.SEARCH.SORT_ORDER.ASC ? aValue.toLowerCase().localeCompare(bValue) : bValue.toLowerCase().localeCompare(aValue);
}
const aNum = aValue as number;
const bNum = bValue as number;
return sortOrder === CONST.SEARCH.SORT_ORDER.ASC ? aNum - bNum : bNum - aNum;
});
}
function getReportNewestTransactionDate(report: ReportListItemType) {
return report.transactions?.reduce((max, curr) => (curr.modifiedCreated ?? curr.created > max.created ? curr : max), report.transactions[0])?.created;
}
function getSortedReportData(data: ReportListItemType[]) {
return data.sort((a, b) => {
const aNewestTransaction = getReportNewestTransactionDate(a);
const bNewestTransaction = getReportNewestTransactionDate(b);
if (!aNewestTransaction || !bNewestTransaction) {
return 0;
}
return bNewestTransaction.toLowerCase().localeCompare(aNewestTransaction);
});
}
function getSortedReportActionData(data: ReportActionListItemType[]) {
return data.sort((a, b) => {
const aValue = a?.created;
const bValue = b?.created;
if (aValue === undefined || bValue === undefined) {
return 0;
}
return bValue.toLowerCase().localeCompare(aValue);
});
}
function getCurrentSearchParams() {
const rootState = navigationRef.getRootState() as State<RootStackParamList>;
const lastSearchRoute = rootState.routes.filter((route) => route.name === SCREENS.SEARCH.CENTRAL_PANE).at(-1);
return lastSearchRoute ? (lastSearchRoute.params as AuthScreensParamList[typeof SCREENS.SEARCH.CENTRAL_PANE]) : undefined;
}
function isSearchResultsEmpty(searchResults: SearchResults) {
return !Object.keys(searchResults?.data).some((key) => key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION));
}
function getQueryHashFromString(query: SearchQueryString): number {
return UserUtils.hashText(query, 2 ** 32);
}
/**
* Update string query with all the default params that are set by parser
*/
function normalizeQuery(query: string) {
const normalizedQueryJSON = buildSearchQueryJSON(query);
return buildSearchQueryString(normalizedQueryJSON);
}
/**
* @private
* returns Date filter query string part, which needs special logic
*/
function buildDateFilterQuery(filterValues: Partial<SearchAdvancedFiltersForm>) {
const dateBefore = filterValues[FILTER_KEYS.DATE_BEFORE];
const dateAfter = filterValues[FILTER_KEYS.DATE_AFTER];
let dateFilter = '';
if (dateBefore) {
dateFilter += `${CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE}<${dateBefore}`;
}
if (dateBefore && dateAfter) {
dateFilter += ' ';
}
if (dateAfter) {
dateFilter += `${CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE}>${dateAfter}`;
}
return dateFilter;
}
/**
* @private
* returns Date filter query string part, which needs special logic
*/
function buildAmountFilterQuery(filterValues: Partial<SearchAdvancedFiltersForm>) {
const lessThan = filterValues[FILTER_KEYS.LESS_THAN];
const greaterThan = filterValues[FILTER_KEYS.GREATER_THAN];
let amountFilter = '';
if (greaterThan) {
amountFilter += `${CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT}>${greaterThan}`;
}
if (lessThan && greaterThan) {
amountFilter += ' ';
}
if (lessThan) {
amountFilter += `${CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT}<${lessThan}`;
}
return amountFilter;
}
function sanitizeString(str: string) {
const regexp = /[<>,:= ]/g;
if (regexp.test(str)) {
return `"${str}"`;
}
return str;
}
function getExpenseTypeTranslationKey(expenseType: ValueOf<typeof CONST.SEARCH.TRANSACTION_TYPE>): TranslationPaths {
// eslint-disable-next-line default-case
switch (expenseType) {
case CONST.SEARCH.TRANSACTION_TYPE.DISTANCE:
return 'common.distance';
case CONST.SEARCH.TRANSACTION_TYPE.CARD:
return 'common.card';
case CONST.SEARCH.TRANSACTION_TYPE.CASH:
return 'iou.cash';
}
}
function buildSearchQueryJSON(query: SearchQueryString) {
try {
const result = searchParser.parse(query) as SearchQueryJSON;
const flatFilters = getFilters(result);
// Add the full input and hash to the results
result.inputQuery = query;
result.hash = getQueryHashFromString(query);
result.flatFilters = flatFilters;
return result;
} catch (e) {
console.error(`Error when parsing SearchQuery: "${query}"`, e);
}
}
function buildSearchQueryString(queryJSON?: SearchQueryJSON) {
const queryParts: string[] = [];
const defaultQueryJSON = buildSearchQueryJSON('');
for (const [, key] of Object.entries(CONST.SEARCH.SYNTAX_ROOT_KEYS)) {
const existingFieldValue = queryJSON?.[key];
const queryFieldValue = existingFieldValue ?? defaultQueryJSON?.[key];
if (queryFieldValue) {
queryParts.push(`${key}:${queryFieldValue}`);
}
}
if (!queryJSON) {
return queryParts.join(' ');
}
const filters = queryJSON.flatFilters;
for (const [, filterKey] of Object.entries(CONST.SEARCH.SYNTAX_FILTER_KEYS)) {
const queryFilter = filters[filterKey];
if (queryFilter) {
const filterValueString = buildFilterString(filterKey, queryFilter);
queryParts.push(filterValueString);
}
}
return queryParts.join(' ');
}
/**
* Given object with chosen search filters builds correct query string from them
*/
function buildQueryStringFromFilterValues(filterValues: Partial<SearchAdvancedFiltersForm>) {
const filtersString = Object.entries(filterValues).map(([filterKey, filterValue]) => {
if ((filterKey === FILTER_KEYS.MERCHANT || filterKey === FILTER_KEYS.DESCRIPTION || filterKey === FILTER_KEYS.REPORT_ID) && filterValue) {
const keyInCorrectForm = (Object.keys(CONST.SEARCH.SYNTAX_FILTER_KEYS) as FilterKeys[]).find((key) => CONST.SEARCH.SYNTAX_FILTER_KEYS[key] === filterKey);
if (keyInCorrectForm) {
return `${CONST.SEARCH.SYNTAX_FILTER_KEYS[keyInCorrectForm]}:${sanitizeString(filterValue as string)}`;
}
}
if (filterKey === FILTER_KEYS.KEYWORD && filterValue) {
const value = (filterValue as string).split(' ').map(sanitizeString).join(' ');
return `${value}`;
}
if (filterKey === FILTER_KEYS.TYPE && filterValue) {
return `${CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE}:${sanitizeString(filterValue as string)}`;
}
if (filterKey === FILTER_KEYS.STATUS && filterValue) {
return `${CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS}:${sanitizeString(filterValue as string)}`;
}
if (
(filterKey === FILTER_KEYS.CATEGORY ||
filterKey === FILTER_KEYS.CARD_ID ||
filterKey === FILTER_KEYS.TAX_RATE ||
filterKey === FILTER_KEYS.EXPENSE_TYPE ||
filterKey === FILTER_KEYS.TAG ||
filterKey === FILTER_KEYS.CURRENCY ||
filterKey === FILTER_KEYS.FROM ||
filterKey === FILTER_KEYS.TO ||
filterKey === FILTER_KEYS.IN) &&
Array.isArray(filterValue) &&
filterValue.length > 0
) {
const filterValueArray = [...new Set<string>(filterValues[filterKey] ?? [])];
const keyInCorrectForm = (Object.keys(CONST.SEARCH.SYNTAX_FILTER_KEYS) as FilterKeys[]).find((key) => CONST.SEARCH.SYNTAX_FILTER_KEYS[key] === filterKey);
if (keyInCorrectForm) {
return `${CONST.SEARCH.SYNTAX_FILTER_KEYS[keyInCorrectForm]}:${filterValueArray.map(sanitizeString).join(',')}`;
}
}
return undefined;
});
const dateFilter = buildDateFilterQuery(filterValues);
filtersString.push(dateFilter);
const amountFilter = buildAmountFilterQuery(filterValues);
filtersString.push(amountFilter);
return filtersString.filter(Boolean).join(' ');
}
/**
*
* @private
* traverses the AST and returns filters as a QueryFilters object
*/
function getFilters(queryJSON: SearchQueryJSON) {
const filters = {} as QueryFilters;
const filterKeys = Object.values(CONST.SEARCH.SYNTAX_FILTER_KEYS);
function traverse(node: ASTNode) {
if (!node.operator) {
return;
}
if (typeof node?.left === 'object' && node.left) {
traverse(node.left);
}
if (typeof node?.right === 'object' && node.right && !Array.isArray(node.right)) {
traverse(node.right);
}
const nodeKey = node.left as ValueOf<typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>;
if (!filterKeys.includes(nodeKey)) {
return;
}
if (!filters[nodeKey]) {
filters[nodeKey] = [];
}
// the "?? []" is added only for typescript because otherwise TS throws an error, in newer TS versions this should be fixed
const filterArray = filters[nodeKey] ?? [];
if (!Array.isArray(node.right)) {
filterArray.push({
operator: node.operator,
value: node.right as string | number,
});
} else {
node.right.forEach((element) => {
filterArray.push({
operator: node.operator,
value: element as string | number,
});
});
}
}
if (queryJSON.filters) {
traverse(queryJSON.filters);
}
return filters;
}
/**
* returns the values of the filters in a format that can be used in the SearchAdvancedFiltersForm as initial form values
*/
function getFiltersFormValues(queryJSON: SearchQueryJSON) {
const filters = getFilters(queryJSON);
const filterKeys = Object.keys(filters);
const filtersForm = {} as Partial<SearchAdvancedFiltersForm>;
for (const filterKey of filterKeys) {
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_ID || filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT || filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.DESCRIPTION) {
filtersForm[filterKey] = filters[filterKey]?.[0]?.value.toString();
}
if (
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAX_RATE ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPENSE_TYPE ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAG ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CURRENCY ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TO ||
filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.IN
) {
filtersForm[filterKey] = filters[filterKey]?.map((filter) => filter.value.toString());
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD) {
filtersForm[filterKey] = filters[filterKey]
?.map((filter) => filter.value.toString())
.map((filter) => {
if (filter.includes(' ')) {
return `"${filter}"`;
}
return filter;
})
.join(' ');
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE) {
filtersForm[FILTER_KEYS.DATE_BEFORE] = filters[filterKey]?.find((filter) => filter.operator === 'lt')?.value.toString();
filtersForm[FILTER_KEYS.DATE_AFTER] = filters[filterKey]?.find((filter) => filter.operator === 'gt')?.value.toString();
}
if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT) {
filtersForm[FILTER_KEYS.LESS_THAN] = filters[filterKey]?.find((filter) => filter.operator === 'lt')?.value.toString();
filtersForm[FILTER_KEYS.GREATER_THAN] = filters[filterKey]?.find((filter) => filter.operator === 'gt')?.value.toString();
}
}
filtersForm[FILTER_KEYS.TYPE] = queryJSON.type;
filtersForm[FILTER_KEYS.STATUS] = queryJSON.status;
return filtersForm;
}
/**
* Given a SearchQueryJSON this function will try to find the value of policyID filter saved in query
* and return just the first policyID value from the filter.
*
* Note: `policyID` property can store multiple policy ids (just like many other search filters) as a comma separated value;
* however there are several places in the app (related to WorkspaceSwitcher) that will accept only a single policyID.
*/
function getPolicyIDFromSearchQuery(queryJSON: SearchQueryJSON) {
const policyIDFilter = queryJSON.policyID;
if (!policyIDFilter) {
return;
}
// policyID is a comma-separated value
const [policyID] = policyIDFilter.split(',');
return policyID;
}
function getDisplayValue(filterName: string, filter: string, personalDetails: OnyxTypes.PersonalDetailsList, cardList: OnyxTypes.CardList, reports: OnyxCollection<OnyxTypes.Report>) {
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM || filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.TO) {
return PersonalDetailsUtils.createDisplayName(personalDetails[filter]?.login ?? '', personalDetails[filter]);
}
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID) {
return cardList[filter].bank;
}
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.IN) {
return ReportUtils.getReportName(reports?.[`${ONYXKEYS.COLLECTION.REPORT}${filter}`]);
}
return filter;
}
function buildFilterString(filterName: string, queryFilters: QueryFilter[], delimiter = ',') {
let filterValueString = '';
queryFilters.forEach((queryFilter, index) => {
// If the previous queryFilter has the same operator (this rule applies only to eq and neq operators) then append the current value
if ((queryFilter.operator === 'eq' && queryFilters[index - 1]?.operator === 'eq') || (queryFilter.operator === 'neq' && queryFilters[index - 1]?.operator === 'neq')) {
filterValueString += `${delimiter}${sanitizeString(queryFilter.value.toString())}`;
} else {
filterValueString += ` ${filterName}${operatorToSignMap[queryFilter.operator]}${sanitizeString(queryFilter.value.toString())}`;
}
});
return filterValueString;
}
function getSearchHeaderTitle(
queryJSON: SearchQueryJSON,
PersonalDetails: OnyxTypes.PersonalDetailsList,
cardList: OnyxTypes.CardList,
reports: OnyxCollection<OnyxTypes.Report>,
TaxRates: Record<string, string[]>,
) {
const {type, status} = queryJSON;
const filters = queryJSON.flatFilters ?? {};
let title = `type:${type} status:${status}`;
Object.keys(filters).forEach((key) => {
const queryFilter = filters[key as ValueOf<typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>] ?? [];
let displayQueryFilters: QueryFilter[] = [];
if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAX_RATE) {
const taxRateIDs = queryFilter.map((filter) => filter.value.toString());
const taxRateNames = Object.entries(TaxRates)
.filter(([, taxRateKeys]) => taxRateKeys.some((taxID) => taxRateIDs.includes(taxID)))
.map(([taxRate]) => taxRate);
displayQueryFilters = taxRateNames.map((taxRate) => ({
operator: queryFilter[0].operator,
value: taxRate,
}));
} else {
displayQueryFilters = queryFilter.map((filter) => ({
operator: filter.operator,
value: getDisplayValue(key, filter.value.toString(), PersonalDetails, cardList, reports),
}));
}
title += buildFilterString(key, displayQueryFilters, ' ');
});
return title;
}
function buildCannedSearchQuery(type: SearchDataTypes = CONST.SEARCH.DATA_TYPES.EXPENSE, status: SearchStatus = CONST.SEARCH.STATUS.EXPENSE.ALL): SearchQueryString {
return normalizeQuery(`type:${type} status:${status}`);
}
function getOverflowMenu(itemName: string, hash: number, inputQuery: string, showDeleteModal: (hash: number) => void, isMobileMenu?: boolean, closeMenu?: () => void) {
return [
{
text: translateLocal('common.rename'),
onSelected: () => {
if (isMobileMenu && closeMenu) {
closeMenu();
}
Navigation.navigate(ROUTES.SEARCH_SAVED_SEARCH_RENAME.getRoute({name: itemName, jsonQuery: inputQuery}));
},
icon: Expensicons.Pencil,
shouldShowRightIcon: false,
shouldShowRightComponent: false,
shouldCallAfterModalHide: true,
},
{
text: translateLocal('common.delete'),
onSelected: () => showDeleteModal(hash),
icon: Expensicons.Trashcan,
shouldShowRightIcon: false,
shouldShowRightComponent: false,
shouldCallAfterModalHide: true,
shouldCloseAllModals: true,
},
];
}
/**
* Returns whether a given search query is a Canned query.
*
* Canned queries are simple predefined queries, that are defined only using type and status and no additional filters.
* For example: "type:trip status:all" is a canned query.
*/
function isCannedSearchQuery(queryJSON: SearchQueryJSON) {
return !queryJSON.filters;
}
export {
buildQueryStringFromFilterValues,
buildSearchQueryJSON,
buildSearchQueryString,
getCurrentSearchParams,
getFiltersFormValues,
getPolicyIDFromSearchQuery,
getListItem,
getSearchHeaderTitle,
getSections,
getShouldShowMerchant,
getSortedSections,
isReportListItemType,
isSearchResultsEmpty,
isTransactionListItemType,
isReportActionListItemType,
normalizeQuery,
shouldShowYear,
buildCannedSearchQuery,
isCannedSearchQuery,
getExpenseTypeTranslationKey,
getOverflowMenu,
};