-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
SearchUtils.ts
604 lines (507 loc) · 23.8 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
import type {ValueOf} from 'type-fest';
import type {ASTNode, QueryFilter, QueryFilters, SearchColumnType, SearchQueryJSON, SearchQueryString, SearchStatus, SortOrder} from '@components/Search/types';
import ReportListItem from '@components/SelectionList/Search/ReportListItem';
import TransactionListItem from '@components/SelectionList/Search/TransactionListItem';
import type {ListItem, ReportListItemType, TransactionListItemType} from '@components/SelectionList/types';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
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 navigationRef from './Navigation/navigationRef';
import type {AuthScreensParamList, BottomTabNavigatorParamList, RootStackParamList, State} from './Navigation/types';
import * as searchParser from './SearchParser/searchParser';
import * as TransactionUtils from './TransactionUtils';
import * as UserUtils from './UserUtils';
type KeysOfFilterKeysObject = 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,
};
}
function getShouldShowMerchant(data: OnyxTypes.SearchResults['data']): boolean {
return Object.values(data).some((item) => {
const merchant = item.modifiedMerchant ? item.modifiedMerchant : item.merchant ?? '';
return merchant !== '' && merchant !== CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT && merchant !== CONST.TRANSACTION.DEFAULT_MERCHANT;
});
}
const currentYear = new Date().getFullYear();
function isReportListItemType(item: ListItem): item is ReportListItemType {
return 'transactions' in item;
}
function isTransactionListItemType(item: TransactionListItemType | ReportListItemType): item is TransactionListItemType {
const transactionListItem = item as TransactionListItemType;
return transactionListItem.transactionID !== 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, transactionItem] of Object.entries(data)) {
if (key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION)) {
const item = transactionItem as SearchTransaction;
const date = TransactionUtils.getCreated(item);
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.entries(data)
.filter(([key]) => key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION))
.map(([, transactionItem]) => {
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 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 (key.startsWith(ONYXKEYS.COLLECTION.REPORT)) {
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],
to: data.personalDetailsList?.[reportItem.managerID],
transactions,
reportName: isIOUReport ? getIOUReportName(data, reportItem) : reportItem.reportName,
};
} else if (key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION)) {
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(status: SearchStatus): ListItemType<typeof status> {
return status === CONST.SEARCH.STATUS.EXPENSE.ALL ? TransactionListItem : ReportListItem;
}
function getSections(status: SearchStatus, data: OnyxTypes.SearchResults['data'], metadata: OnyxTypes.SearchResults['search']) {
return status === CONST.SEARCH.STATUS.EXPENSE.ALL ? getTransactionsSections(data, metadata) : getReportSections(data, metadata);
}
function getSortedSections(status: SearchStatus, data: ListItemDataType<typeof status>, sortBy?: SearchColumnType, sortOrder?: SortOrder) {
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 getSortedReportData(data: ReportListItemType[]) {
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 lastSearchCentralPaneRoute = rootState.routes.filter((route) => route.name === SCREENS.SEARCH.CENTRAL_PANE).at(-1);
const lastSearchBottomTabRoute = rootState.routes[0].state?.routes.filter((route) => route.name === SCREENS.SEARCH.BOTTOM_TAB).at(-1);
if (lastSearchCentralPaneRoute) {
return lastSearchCentralPaneRoute.params as AuthScreensParamList[typeof SCREENS.SEARCH.CENTRAL_PANE];
}
if (lastSearchBottomTabRoute) {
return lastSearchBottomTabRoute.params as BottomTabNavigatorParamList[typeof SCREENS.SEARCH.BOTTOM_TAB];
}
}
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);
}
function buildSearchQueryJSON(query: SearchQueryString) {
try {
const result = searchParser.parse(query) as SearchQueryJSON;
// Add the full input and hash to the results
result.inputQuery = query;
result.hash = getQueryHashFromString(query);
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 = getFilters(queryJSON);
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(' ');
}
/**
* 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) {
if (str.includes(' ') || str.includes(',')) {
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 getChatFiltersTranslationKey(has: ValueOf<typeof CONST.SEARCH.CHAT_TYPES>): TranslationPaths {
// eslint-disable-next-line default-case
switch (has) {
case CONST.SEARCH.CHAT_TYPES.LINK:
return 'search.filters.link';
case CONST.SEARCH.CHAT_TYPES.ATTACHMENT:
return 'common.attachment';
}
}
/**
* Given object with chosen search filters builds correct query string from them
*/
function buildQueryStringFromFilters(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 KeysOfFilterKeysObject[]).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 keyInCorrectForm = (Object.keys(CONST.SEARCH.SYNTAX_FILTER_KEYS) as KeysOfFilterKeysObject[]).find((key) => CONST.SEARCH.SYNTAX_FILTER_KEYS[key] === filterKey);
if (keyInCorrectForm) {
return `${CONST.SEARCH.SYNTAX_FILTER_KEYS[keyInCorrectForm]}:${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 ||
filterKey === FILTER_KEYS.HAS) &&
Array.isArray(filterValue) &&
filterValue.length > 0
) {
const filterValueArray = filterValues[filterKey] ?? [];
const keyInCorrectForm = (Object.keys(CONST.SEARCH.SYNTAX_FILTER_KEYS) as KeysOfFilterKeysObject[]).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(' ');
}
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) {
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] ?? [];
filterArray.push({
operator: node.operator,
value: node.right as string | number,
});
}
if (queryJSON.filters) {
traverse(queryJSON.filters);
}
return filters;
}
/**
* 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 buildFilterString(filterName: string, queryFilters: QueryFilter[]) {
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 += ` ${sanitizeString(queryFilter.value.toString())}`;
} else {
filterValueString += ` ${filterName}${operatorToSignMap[queryFilter.operator]}${queryFilter.value}`;
}
});
return filterValueString;
}
function getSearchHeaderTitle(queryJSON: SearchQueryJSON) {
const {type, status} = queryJSON;
const filters = getFilters(queryJSON) ?? {};
let title = `type:${type} status:${status}`;
Object.keys(filters).forEach((key) => {
const queryFilter = filters[key as ValueOf<typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>] ?? [];
title += buildFilterString(key, queryFilter);
});
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}`);
}
export {
buildQueryStringFromFilters,
buildSearchQueryJSON,
buildSearchQueryString,
getCurrentSearchParams,
getFilters,
getPolicyIDFromSearchQuery,
getListItem,
getSearchHeaderTitle,
getSections,
getShouldShowMerchant,
getSortedSections,
isReportListItemType,
isSearchResultsEmpty,
isTransactionListItemType,
normalizeQuery,
shouldShowYear,
buildCannedSearchQuery,
getExpenseTypeTranslationKey,
getChatFiltersTranslationKey,
};