Repository navigation
Expand file tree
/
Copy pathSearchQueryUtils.ts
More file actions
3599 lines (3118 loc) · 156 KB
/
Copy pathSearchQueryUtils.ts
File metadata and controls
3599 lines (3118 loc) · 156 KB
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {LocaleContextProps, LocalizedTranslate} from '@components/LocaleContextProvider';
import type {TextInputFilterContentProps} from '@components/Search/FilterComponents/AdvancedFilters/TextInputFilterContent';
import type {ListFilterContentProps} from '@components/Search/FilterComponents/ListFilterContent';
import type {
ASTNode,
Filter,
QueryFilter,
QueryFilters,
RawQueryFilter,
ReportFieldDateKey,
ReportFieldNegatedKey,
ReportFieldTextKey,
SearchAmountFilterKeys,
SearchDateFilterKeys,
SearchDateKey,
SearchDatePreset,
SearchFilterKey,
SearchFooterCount,
SearchFooterTotal,
SearchQueryJSON,
SearchQueryString,
SearchWithdrawalType,
SelectedTransactions,
SyntaxFilterKey,
UserFriendlyKey,
UserFriendlyValue,
} from '@components/Search/types';
import type {FeedKeysWithAssignedCards} from '@hooks/useFeedKeysWithAssignedCards';
import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import type {OnyxCollectionKey, OnyxCollectionValuesMapping} from '@src/ONYXKEYS';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';
import type {SearchAdvancedFiltersForm} from '@src/types/form';
import FILTER_KEYS, {ALLOWED_TYPE_FILTERS, AMOUNT_FILTER_KEYS, DATE_FILTER_KEYS, NEGATABLE_FILTERS} from '@src/types/form/SearchAdvancedFiltersForm';
import type {
ExpenseTypeValue,
ExpenseTypeValues,
HasFilterValue,
HasFilterValues,
IsFilterValue,
IsFilterValues,
MerchantMatchType,
ReceiptTypeValue,
TransactionStatusValue,
SearchAdvancedFiltersKey,
SearchNegatableFilterKeys,
} from '@src/types/form/SearchAdvancedFiltersForm';
import type * as OnyxTypes from '@src/types/onyx';
import type {SearchDataTypes, SearchResultDataType} from '@src/types/onyx/SearchResults';
import type {Locale as DateFnsLocale} from 'date-fns';
import type {NullishDeep, OnyxCollection, OnyxUpdate} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import {
addDays,
endOfMonth,
endOfQuarter,
endOfWeek,
endOfYear,
format,
parse,
startOfMonth,
startOfQuarter,
startOfWeek,
startOfYear,
subDays,
subMonths,
subQuarters,
subWeeks,
subYears,
} from 'date-fns';
import cloneDeep from 'lodash/cloneDeep';
import Onyx from 'react-native-onyx';
import type {SearchFullscreenNavigatorParamList} from './Navigation/types';
import {getStandardExportTemplateDisplayName} from './AccountingUtils';
import {getBankAccountSearchLabel, isBankAccountPartiallySetup} from './BankAccountUtils';
import {getCardFeedsForDisplay} from './CardFeedUtils';
import {getCardDescription} from './CardUtils';
import getCollator from './CollatorUtils';
import {convertToBackendAmount, convertToFrontendAmountAsInteger} from './CurrencyUtils';
import DateUtils from './DateUtils';
import Log from './Log';
import {validateAmount} from './MoneyRequestUtils';
import {getPreservedNavigatorState} from './Navigation/AppNavigator/createSplitNavigator/usePreserveNavigatorState';
import navigationRef from './Navigation/navigationRef';
import {isRecord} from './ObjectUtils';
import {temporaryGetDisplayNameOrDefault} from './PersonalDetailsUtils';
import {getCleanedTagName, getValidConnectedIntegration} from './PolicyUtils';
import {getReportName} from './ReportNameUtils';
import {parseAmountFilterValue, supportsAmountFilterCurrency} from './SearchAmountFilterUtils';
import {parse as parseSearchQuery} from './SearchParser/searchParser';
import StringUtils from './StringUtils';
import {hashText} from './UserUtils';
import {isValidDate} from './ValidationUtils';
type FilterKeys = keyof typeof CONST.SEARCH.SYNTAX_FILTER_KEYS;
type SearchRootParams = SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT];
type NavigationRouteLike = {
/** Unique React Navigation route identifier. */
key?: string;
/** Screen name as registered in the navigator. */
name?: string;
/** Screen-specific params passed to the route. */
params?: Record<string, unknown>;
/** Nested navigator state, if this route is itself a navigator. */
state?: unknown;
};
/**
* The outcome for one tab navigator that has Search state. `params` is `undefined` when its Search navigator is
* mounted but has no usable root route params. Wrapping it lets that "resolved, but empty" outcome be told apart
* from a tab navigator with no Search state at all, which returns no resolution so the walk keeps going.
*/
type TabNavigatorSearchResolution = {params: SearchRootParams | undefined};
// This map contains chars that match each operator
const operatorToCharMap = {
[CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO]: ':' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS]: '*:' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.NOT_CONTAINS]: '*:' 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.AND]: ',' as const,
[CONST.SEARCH.SYNTAX_OPERATORS.OR]: ' ' as const,
};
const EXPLICIT_EQUAL_TO_OPERATOR = '=' as const;
const DEFAULT_MERCHANT_OPERATOR = CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS;
function getMerchantOperator(operator: MerchantMatchType | undefined): MerchantMatchType {
return operator ?? DEFAULT_MERCHANT_OPERATOR;
}
/**
* Builds the Merchant part of the query. The form has one Merchant field, so a changed condition updates every Merchant clause from flatFilters.
*/
function buildMerchantFilterQuery(
value: string,
prefix: string,
isNegated: boolean,
isMerchantNegated: boolean,
merchantOperator: MerchantMatchType | undefined,
flatFilters: QueryFilters | undefined,
): string {
const merchantFilters = flatFilters?.filter((filter) => filter.key === FILTER_KEYS.MERCHANT) ?? [];
const positiveMerchantFilters = merchantFilters.filter((filter) => !filter.filters.some((item) => item.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO));
const negativeMerchantFilters = merchantFilters.filter((filter) => filter.filters.some((item) => item.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO));
const wasMerchantNegated = negativeMerchantFilters.length > 0;
const hasMerchantNegationChanged = wasMerchantNegated !== isMerchantNegated;
const lastVisibleMerchantFilter = (wasMerchantNegated ? negativeMerchantFilters : positiveMerchantFilters).at(-1);
const selectedMerchantOperator = getMerchantOperator(merchantOperator);
const originalMerchantFilters = isNegated ? negativeMerchantFilters : positiveMerchantFilters;
const lastMerchantFilter = hasMerchantNegationChanged ? lastVisibleMerchantFilter : originalMerchantFilters.at(-1);
const isMerchantValueUnchanged = value === lastMerchantFilter?.filters.map((item) => item.value.toString()).join(',');
if (lastMerchantFilter && isMerchantValueUnchanged) {
const currentMerchantOperator = positiveMerchantFilters.at(-1)?.filters.some((item) => item.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)
? CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO
: DEFAULT_MERCHANT_OPERATOR;
const hasMerchantOperatorChanged = !isMerchantNegated && selectedMerchantOperator !== currentMerchantOperator;
const hasMerchantConditionChanged = hasMerchantNegationChanged || hasMerchantOperatorChanged;
const filtersToUpdate = hasMerchantConditionChanged ? merchantFilters : originalMerchantFilters;
const updatedOperator = isNegated ? CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO : selectedMerchantOperator;
// The single field cannot represent every clause or distinguish lists from names containing commas.
const merchantClauses = filtersToUpdate.map((filter) => {
const clauseFilters = hasMerchantConditionChanged ? filter.filters.map((item) => ({...item, operator: updatedOperator})) : filter.filters;
return buildFilterValuesString(FILTER_KEYS.MERCHANT, clauseFilters).trim();
});
// Different operators can become identical clauses after the change.
return [...new Set(merchantClauses)].join(' ');
}
let operator: ValueOf<typeof operatorToCharMap> | typeof EXPLICIT_EQUAL_TO_OPERATOR = operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO];
if (!isNegated) {
operator = selectedMerchantOperator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO ? EXPLICIT_EQUAL_TO_OPERATOR : operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS];
}
return `${prefix}${CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT}${operator}${sanitizeSearchValue(value)}`;
}
// Pre-computed validation Sets for buildFilterFormValuesFromQuery (avoids recreating per filter iteration)
const VALID_EXPENSE_TYPES = new Set(Object.values(CONST.SEARCH.TRANSACTION_TYPE));
const VALID_RECEIPT_TYPES = new Set<string>(Object.values(CONST.SEARCH.RECEIPT_TYPE));
const VALID_VIOLATION_NAMES = new Set<string>(Object.values(CONST.VIOLATIONS));
// Search, Insights and the CSV export skip the cash expense notice that only Classic records, so violation filter skips it too.
// customRules and ruleViolation belong to the new rules engine, so they're left out until it ships with clearer names.
const EXCLUDED_VIOLATION_FILTER_VALUES = new Set<string>([CONST.VIOLATIONS.CASH_EXPENSE_WITH_NO_RECEIPT, CONST.VIOLATIONS.CUSTOM_RULES, CONST.VIOLATIONS.RULE_VIOLATION]);
const VIOLATION_FILTER_VALUES: OnyxTypes.ViolationName[] = Object.values(CONST.VIOLATIONS).filter((name) => !EXCLUDED_VIOLATION_FILTER_VALUES.has(name));
function isViolationName(name: string): name is OnyxTypes.ViolationName {
return VALID_VIOLATION_NAMES.has(name);
}
/**
* Returns the display label for a violation name.
* Falls back to the raw identifier when no short-name translation exists.
*/
function getViolationDisplayName(violationName: string, translate: LocalizedTranslate): string {
return isViolationName(violationName) ? translate(`violations.shortName.${violationName}`) : violationName;
}
const VALID_TRANSACTION_STATUSES = new Set<string>(Object.values(CONST.SEARCH.TRANSACTION_STATUS));
const VALID_HAS_TYPES = new Set(Object.values(CONST.SEARCH.HAS_VALUES));
const VALID_IS_TYPES = new Set(Object.values(CONST.SEARCH.IS_VALUES));
const VALID_WITHDRAWAL_TYPES = new Set(Object.values(CONST.SEARCH.WITHDRAWAL_TYPE));
const VALID_WITHDRAWAL_STATUSES = new Set<string>(Object.values(CONST.SEARCH.SETTLEMENT_STATUS));
const VALID_PAID_STATUSES = new Set<string>(Object.values(CONST.SEARCH.PAID_STATUS));
const VALID_FOOTER_COUNTS = new Set<string>(Object.values(CONST.SEARCH.FOOTER_COUNT));
const VALID_FOOTER_TOTALS = new Set<string>(Object.values(CONST.SEARCH.FOOTER_TOTAL));
const FOOTER_FILTER_KEYS = new Set<SearchFilterKey>([
CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_COUNT,
CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_TOTAL,
CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_CURRENCY,
]);
// Submitting, approving or forwarding a report changes which expenses these filters match without changing a transaction.
const WORKFLOW_FILTER_KEYS = new Set<SearchFilterKey>([
CONST.SEARCH.SYNTAX_FILTER_KEYS.APPROVER,
CONST.SEARCH.SYNTAX_FILTER_KEYS.ANY_APPROVAL,
CONST.SEARCH.SYNTAX_FILTER_KEYS.SUBMITTED,
CONST.SEARCH.SYNTAX_FILTER_KEYS.APPROVED,
]);
const VIOLATION_HAS_VALUES = [CONST.SEARCH.HAS_VALUES.SUBMITTED_VIOLATION, CONST.SEARCH.HAS_VALUES.APPROVED_VIOLATION] as const;
function isFooterCount(value: string): value is SearchFooterCount {
return VALID_FOOTER_COUNTS.has(value);
}
function isFooterTotal(value: string): value is SearchFooterTotal {
return VALID_FOOTER_TOTALS.has(value);
}
const VALID_GROUP_BYS = new Set<string>(Object.values(CONST.SEARCH.GROUP_BY));
/** Group-bys only Insights queries use. The Search command doesn't return data for them yet (see https://github.com/Expensify/App/issues/105303) */
const INSIGHTS_ONLY_GROUP_BYS = new Set<string>([CONST.SEARCH.GROUP_BY.VIOLATION, CONST.SEARCH.GROUP_BY.PAID_BY, CONST.SEARCH.GROUP_BY.WORKFLOW_STAGE]);
function isGroupBySupportedBySearch(groupBy: string | undefined): boolean {
return !groupBy || !INSIGHTS_ONLY_GROUP_BYS.has(groupBy);
}
// Create reverse lookup maps for O(1) performance
const createKeyToUserFriendlyMap = () => {
const map = new Map<string, string>();
// Map SYNTAX_FILTER_KEYS values to their user-friendly names
for (const [keyName, keyValue] of Object.entries(CONST.SEARCH.SYNTAX_FILTER_KEYS)) {
if (!(keyName in CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS)) {
continue;
}
map.set(keyValue, CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS[keyName as keyof typeof CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS]);
}
// Map SYNTAX_ROOT_KEYS values to their user-friendly names
for (const [keyName, keyValue] of Object.entries(CONST.SEARCH.SYNTAX_ROOT_KEYS)) {
if (!(keyName in CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS)) {
continue;
}
map.set(keyValue, CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS[keyName as keyof typeof CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS]);
}
return map;
};
// Create the maps once at module initialization for performance
const keyToUserFriendlyMap = createKeyToUserFriendlyMap();
/**
* Lookup a key in the keyToUserFriendlyMap and return the user-friendly key.
*
* @example
* getUserFriendlyKey("taxRate") // returns "tax-rate"
*/
function getUserFriendlyKey(
keyName: SearchFilterKey | typeof CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY | typeof CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER | typeof CONST.SEARCH.SYNTAX_ROOT_KEYS.LIMIT,
): UserFriendlyKey {
const isReportField = keyName.startsWith(CONST.SEARCH.REPORT_FIELD.GLOBAL_PREFIX);
if (isReportField) {
return keyName.replace(CONST.SEARCH.REPORT_FIELD.GLOBAL_PREFIX, CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS.REPORT_FIELD) as UserFriendlyKey;
}
return (keyToUserFriendlyMap.get(keyName) ?? keyName) as UserFriendlyKey;
}
/**
* Converts a filter value from backend value to user friendly display text.
*
* @example
* getUserFriendlyValues("perDiem") // returns "per-diem"
*/
function getUserFriendlyValue(value: string | undefined): UserFriendlyValue {
return CONST.SEARCH.SEARCH_USER_FRIENDLY_VALUES_MAP[value as keyof typeof CONST.SEARCH.SEARCH_USER_FRIENDLY_VALUES_MAP] ?? value;
}
/**
* @private
* Escapes the characters the parser would otherwise act on, then wraps the value in quotes "" if it contains a space,
* (no-breaking space) or a comma. Callers pass one value at a time and join them with commas themselves, so a
* comma inside the value is part of it and has to survive being read back.
*/
function sanitizeSearchValue(str: string) {
const escaped = str.replaceAll(/[\\"“”]/g, '\\$&');
if (escaped.includes(' ') || escaped.includes(`\xA0`) || escaped.includes(',')) {
return `"${escaped}"`;
}
return escaped;
}
function getKeywordQueryForSearchInput(keywords: string[]) {
const keywordQuery = keywords.map(sanitizeSearchValue).join(' ');
// An unmatched opening quote is a literal keyword character, not a phrase delimiter.
// Show it as entered only when there is no later quote that could close it on resubmission.
if (keywords.at(0)?.startsWith('"') && keywordQuery.startsWith('\\"') && !keywordQuery.slice(2).includes('"')) {
return keywordQuery.slice(1);
}
return keywordQuery;
}
function sanitizeSearchValuePreservingEscapes(str: string) {
let escaped = '';
for (let index = 0; index < str.length; index++) {
const char = str.at(index) ?? '';
if (char !== '\\') {
escaped += /["“”]/.test(char) ? `\\${char}` : char;
continue;
}
let nextIndex = index;
while (str.at(nextIndex) === '\\') {
nextIndex++;
}
const backslashCount = nextIndex - index;
const nextChar = str.at(nextIndex);
if (nextChar === ',') {
escaped += `${'\\'.repeat(backslashCount)}${nextChar}`;
index = nextIndex;
continue;
}
if (nextChar && /["“”]/.test(nextChar)) {
escaped += `${'\\'.repeat(backslashCount + (backslashCount % 2 === 0 ? 1 : 0))}${nextChar}`;
index = nextIndex;
continue;
}
escaped += '\\'.repeat(backslashCount + (backslashCount % 2));
index = nextIndex - 1;
}
if (escaped.includes(' ') || escaped.includes(`\xA0`) || escaped.includes(',')) {
return `"${escaped}"`;
}
return escaped;
}
const syntaxKeyPattern = `-?(?:${Object.values(CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS).join('|')}|report-?field(?:-[^\\s:><=]+)+)`;
const syntaxOperatorPattern = '\\*?:|[<>]=?|=';
const syntaxValuePattern = '"(?:\\\\.|[^"\\\\])*"|[^\\s]+';
const syntaxSpanRegex = new RegExp(`(^|\\s)(${syntaxKeyPattern})\\s*(${syntaxOperatorPattern})\\s*(${syntaxValuePattern})`, 'gi');
const syntaxWithoutValueRegex = new RegExp(`^${syntaxKeyPattern}\\s*(?:${syntaxOperatorPattern})$`, 'i');
function quoteSyntaxSpans(segment: string) {
return segment.replace(syntaxSpanRegex, (match: string, prefix: string) => {
const syntaxValue = match.slice(prefix.length).trim();
const sanitizedSyntaxValue = sanitizeSearchValuePreservingEscapes(syntaxValue);
return `${prefix}${sanitizedSyntaxValue.startsWith('"') ? sanitizedSyntaxValue : `"${sanitizedSyntaxValue}"`}`;
});
}
function isEscaped(str: string, index: number) {
let backslashCount = 0;
for (let i = index - 1; i >= 0 && str.at(i) === '\\'; i--) {
backslashCount++;
}
return backslashCount % 2 === 1;
}
function isQuoteChar(char: string | undefined) {
return char === '"' || char === '“' || char === '”';
}
function isCompleteQuotedValue(str: string) {
return isQuoteChar(str.at(0)) && str.length > 1 && isQuoteChar(str.at(-1)) && !isEscaped(str, str.length - 1);
}
function hasUnescapedQuote(str: string) {
for (let index = 0; index < str.length; index++) {
if (isQuoteChar(str.at(index)) && !isEscaped(str, index)) {
return true;
}
}
return false;
}
function hasClosingQuote(str: string, openingQuoteIndex: number) {
for (let index = openingQuoteIndex + 1; index < str.length; index++) {
if (isQuoteChar(str.at(index)) && !isEscaped(str, index)) {
return true;
}
}
return false;
}
function tokenizeKeywordSegments(keywords: string) {
const segments: string[] = [];
let index = 0;
while (index < keywords.length) {
while (index < keywords.length && /\s/.test(keywords.at(index) ?? '')) {
index++;
}
if (index >= keywords.length) {
break;
}
const start = index;
const startsWithQuote = isQuoteChar(keywords.at(index)) && hasClosingQuote(keywords, index);
let insideQuote = startsWithQuote;
if (startsWithQuote) {
index++;
}
while (index < keywords.length) {
const char = keywords.at(index);
if (!insideQuote && /\s/.test(char ?? '')) {
break;
}
if (char === '\\') {
// Match the search parser's escapedChar rule: a backslash does not escape whitespace.
index += /[,"“”\\]/.test(keywords.at(index + 1) ?? '') ? 2 : 1;
continue;
}
if (isQuoteChar(char)) {
if (insideQuote) {
index++;
if (startsWithQuote) {
break;
}
insideQuote = false;
continue;
}
if (hasClosingQuote(keywords, index) && !syntaxWithoutValueRegex.test(keywords.slice(start, index))) {
insideQuote = true;
}
}
index++;
}
segments.push(keywords.slice(start, index));
}
return segments;
}
const groupByWithoutValueRegex = new RegExp(`^${CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS.GROUP_BY}\\s*(?:${syntaxOperatorPattern})$`, 'i');
function getGroupByValueForValidation(segment: string) {
const valueWithoutTrailingCommas = segment.replaceAll(/,+$/g, '');
return isCompleteQuotedValue(valueWithoutTrailingCommas) ? valueWithoutTrailingCommas.slice(1, -1) : valueWithoutTrailingCommas;
}
function getUnclosedQuotedGroupByValue(segment: string | undefined) {
if (!segment || !isQuoteChar(segment.at(0)) || hasClosingQuote(segment, 0)) {
return;
}
const value = segment.slice(1);
return VALID_GROUP_BYS.has(value.toLowerCase()) ? value : undefined;
}
function shouldCombineKeywordSegments(segment: string, nextSegment: string | undefined) {
if (!nextSegment || !syntaxWithoutValueRegex.test(segment)) {
return false;
}
const nextSegmentValue = getGroupByValueForValidation(nextSegment);
return syntaxWithoutValueRegex.test(nextSegment) || (groupByWithoutValueRegex.test(segment) && !VALID_GROUP_BYS.has(nextSegmentValue.toLowerCase()));
}
function sanitizeIncompleteQuotedValue(str: string) {
const sanitized = sanitizeSearchValue(str);
return sanitized.startsWith('"') ? sanitized : `"${sanitized}"`;
}
/**
* Escapes each keyword that would otherwise be re-interpreted as query syntax by wrapping it in quotes.
* A keyword that looks like a filter (e.g. `type:expense`) becomes `"type:expense"` so it is matched as a
* keyword instead of being parsed as the `type` filter. Plain keywords (e.g. `foo`) are left untouched.
*/
function escapeKeyword(keywords: string) {
const segments = tokenizeKeywordSegments(keywords);
let skipNextSegment = false;
return segments
.map((segment, index) => {
if (skipNextSegment) {
skipNextSegment = false;
return '';
}
const nextSegment = segments.at(index + 1);
const unclosedGroupByValue = groupByWithoutValueRegex.test(segment) ? getUnclosedQuotedGroupByValue(nextSegment) : undefined;
if (unclosedGroupByValue) {
skipNextSegment = true;
return `${segment}${unclosedGroupByValue}`;
}
skipNextSegment = shouldCombineKeywordSegments(segment, nextSegment);
const q = skipNextSegment ? `${segment} ${nextSegment}` : segment;
if (isQuoteChar(q.at(0))) {
return isCompleteQuotedValue(q) ? q : sanitizeIncompleteQuotedValue(q);
}
// A quoted span embedded in an ordinary token is one keyword; syntax inside it is literal text.
if (/\s/.test(segment) && hasUnescapedQuote(segment)) {
return sanitizeSearchValuePreservingEscapes(q);
}
const quotedSyntax = quoteSyntaxSpans(q).trim();
if (quotedSyntax !== q) {
return quotedSyntax;
}
return hasUnescapedQuote(q) || q.includes('\\') ? sanitizeSearchValuePreservingEscapes(q) : q;
})
.filter(Boolean)
.join(' ');
}
function getRangeQueryValue(from?: string, to?: string) {
if (from && to) {
return `${from},${to}`;
}
if (from) {
return from;
}
if (to) {
return `,${to}`;
}
return '';
}
function getInclusiveRangeBoundary(date?: string, dayOffset = 0) {
const validDate = date ?? '';
if (!isValidDate(validDate)) {
return undefined;
}
return format(addDays(parse(validDate, 'yyyy-MM-dd', new Date()), dayOffset), 'yyyy-MM-dd');
}
function getRangeBoundariesFromFormValue(rangeValue?: string, fallbackAfter?: string, fallbackBefore?: string) {
const parsedRange = parseRangeQueryValue(rangeValue);
if (rangeValue && (parsedRange.from || parsedRange.to)) {
return parsedRange;
}
const from = getInclusiveRangeBoundary(fallbackAfter, 1);
const to = getInclusiveRangeBoundary(fallbackBefore, -1);
if (from && to && from > to) {
return {
from: undefined,
to: undefined,
};
}
return {
from,
to,
};
}
function getDateRangeDisplayValueFromFormValue(
dateFnsLocale: DateFnsLocale | undefined,
rangeValue?: string,
fallbackAfter?: string,
fallbackBefore?: string,
shouldOmitCurrentYear = false,
) {
if (!rangeValue) {
return '';
}
const rangeBoundaries = getRangeBoundariesFromFormValue(rangeValue, fallbackAfter, fallbackBefore);
if (rangeBoundaries.from && rangeBoundaries.to) {
const shouldShowFullYear = !shouldOmitCurrentYear || DateUtils.doesDateBelongToAPastYear(rangeBoundaries.from) || DateUtils.doesDateBelongToAPastYear(rangeBoundaries.to);
return DateUtils.getFormattedDateRangeForSearch(rangeBoundaries.from, rangeBoundaries.to, dateFnsLocale, shouldShowFullYear, shouldOmitCurrentYear);
}
const singleBoundary = rangeBoundaries.from ?? rangeBoundaries.to;
return singleBoundary ? DateUtils.formatToReadableString(singleBoundary, dateFnsLocale) : '';
}
function parseRangeQueryValue(rangeValue?: string) {
if (!rangeValue) {
return {
from: undefined,
to: undefined,
};
}
const [rawFrom = '', rawTo = ''] = rangeValue.split(',', 2);
const from = isValidDate(rawFrom) ? rawFrom : undefined;
const to = isValidDate(rawTo) ? rawTo : undefined;
return {
from,
to,
};
}
/**
* @private
* Returns date filter value for QueryString.
*/
function buildDateFilterQuery(filterValues: Partial<SearchAdvancedFiltersForm>, filterKey: SearchDateFilterKeys) {
const negatedDate = filterValues[`${filterKey}${CONST.SEARCH.NOT_MODIFIER}`];
const dateOn = filterValues[`${filterKey}${CONST.SEARCH.DATE_MODIFIERS.ON}`];
const dateAfter = filterValues[`${filterKey}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`];
const dateBefore = filterValues[`${filterKey}${CONST.SEARCH.DATE_MODIFIERS.BEFORE}`];
const dateRange = filterValues[`${filterKey}${CONST.SEARCH.DATE_MODIFIERS.RANGE}`];
const rangeBoundaries = parseRangeQueryValue(dateRange);
const hasRange = !!(rangeBoundaries.from ?? rangeBoundaries.to);
const dateFilters = [];
if (dateOn) {
dateFilters.push(`${filterKey}:${dateOn}`);
}
if (hasRange) {
if (rangeBoundaries.from) {
dateFilters.push(`${filterKey}${operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO]}${rangeBoundaries.from}`);
}
if (rangeBoundaries.to) {
dateFilters.push(`${filterKey}${operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO]}${rangeBoundaries.to}`);
}
}
if (dateAfter) {
dateFilters.push(`${filterKey}>${dateAfter}`);
}
if (dateBefore) {
dateFilters.push(`${filterKey}<${dateBefore}`);
}
if (negatedDate) {
dateFilters.push(`-${filterKey}:${negatedDate}`);
}
return dateFilters.join(' ');
}
/**
* @private
* Returns amount filter value for QueryString.
*/
function buildAmountFilterQuery(filterKey: SearchAmountFilterKeys, filterValues: Partial<SearchAdvancedFiltersForm>) {
const negatedAmount = filterValues[`${filterKey}${CONST.SEARCH.NOT_MODIFIER}`];
const equalTo = filterValues[`${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO}`];
const lessThan = filterValues[`${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}`];
const greaterThan = filterValues[`${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`];
const greaterThanOrEqualTo = filterValues[`${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN_OR_EQUAL_TO}`];
const lessThanOrEqualTo = filterValues[`${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN_OR_EQUAL_TO}`];
const amountStrings = [];
if (equalTo) {
amountStrings.push(`${filterKey}:${sanitizeSearchValue(equalTo)}`);
}
if (greaterThan) {
amountStrings.push(`${filterKey}>${sanitizeSearchValue(greaterThan)}`);
}
if (lessThan) {
amountStrings.push(`${filterKey}<${sanitizeSearchValue(lessThan)}`);
}
if (greaterThanOrEqualTo) {
amountStrings.push(`${filterKey}>=${sanitizeSearchValue(greaterThanOrEqualTo)}`);
}
if (lessThanOrEqualTo) {
amountStrings.push(`${filterKey}<=${sanitizeSearchValue(lessThanOrEqualTo)}`);
}
if (negatedAmount) {
amountStrings.push(`-${filterKey}:${sanitizeSearchValue(negatedAmount)}`);
}
return amountStrings.join(' ');
}
/**
* @private
* Returns string of correctly formatted filter values from QueryFilters object.
*/
function buildFilterValuesString(filterName: string, queryFilters: QueryFilter[]) {
const delimiter = filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD ? ' ' : ',';
const allowedOps = new Set<string>([CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO]);
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT) {
allowedOps.add(CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS);
}
let filterValueString = '';
for (const [index, queryFilter] of queryFilters.entries()) {
const previousValueHasSameOp = allowedOps.has(queryFilter.operator) && queryFilters?.at(index - 1)?.operator === queryFilter.operator;
const nextValueHasSameOp = allowedOps.has(queryFilter.operator) && queryFilters?.at(index + 1)?.operator === queryFilter.operator;
// If the previous queryFilter has the same operator and that operator supports comma-delimited values, append the current value
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD) {
filterValueString += `${delimiter}${escapeKeyword(sanitizeSearchValue(queryFilter.value.toString()))}`;
} else if (index !== 0 && (previousValueHasSameOp || nextValueHasSameOp)) {
filterValueString += `${delimiter}${sanitizeSearchValue(queryFilter.value.toString())}`;
} else if (queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO) {
filterValueString += ` ${CONST.SEARCH.NOT_PREFIX}${filterName}:${sanitizeSearchValue(queryFilter.value.toString())}`;
} else if (queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_CONTAINS) {
filterValueString += ` ${CONST.SEARCH.NOT_PREFIX}${filterName}${operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.NOT_CONTAINS]}${sanitizeSearchValue(queryFilter.value.toString())}`;
} else if (queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.RANGE) {
const rangeBoundaries = parseRangeQueryValue(queryFilter.value.toString());
if (rangeBoundaries.from) {
filterValueString += ` ${filterName}${operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO]}${sanitizeSearchValue(rangeBoundaries.from)}`;
}
if (rangeBoundaries.to) {
filterValueString += ` ${filterName}${operatorToCharMap[CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO]}${sanitizeSearchValue(rangeBoundaries.to)}`;
}
} else {
const operatorChar =
filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT && queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO
? EXPLICIT_EQUAL_TO_OPERATOR
: operatorToCharMap[queryFilter.operator];
if (!operatorChar) {
continue;
}
filterValueString += ` ${filterName}${operatorChar}${sanitizeSearchValue(queryFilter.value.toString())}`;
}
}
return filterValueString;
}
/**
* @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);
}
// Only process if its a leaf
if (typeof node.left !== 'string') {
return;
}
const nodeKey = node.left;
if (!filterKeys.includes(nodeKey) && !nodeKey.startsWith(CONST.SEARCH.REPORT_FIELD.GLOBAL_PREFIX)) {
return;
}
const filterArray: QueryFilter[] = [];
if (!Array.isArray(node.right)) {
if (typeof node.right !== 'string' && typeof node.right !== 'number') {
return;
}
filterArray.push({
operator: node.operator,
value: node.right,
});
} else {
for (const element of node.right) {
filterArray.push({
operator: node.operator,
value: element,
});
}
}
filters.push({key: nodeKey, filters: filterArray});
}
if (queryJSON.filters) {
traverse(queryJSON.filters);
}
return filters;
}
function getFilterFromQuery(queryJSON: SearchQueryJSON | undefined, filterKey: SearchAdvancedFiltersKey): Filter {
const filters = queryJSON?.flatFilters?.find((filter) => filter.key === filterKey)?.filters;
const isNegated = filters?.at(0)?.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO;
const value = filters?.map((filter) => filter.value.toString());
return {value, isNegated};
}
/**
* The Spend footer's display selections, read off the query the footer is showing. A value the footer cannot render is
* dropped rather than displayed, so a hand-typed one behaves like no selection at all. The currency is upper-cased so
* `footerCurrency:eur` and `footerCurrency:EUR` are one selection rather than two.
*/
function getFooterSelectionFromQuery(queryJSON: SearchQueryJSON | undefined) {
const count = getFilterFromQuery(queryJSON, CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_COUNT).value?.at(0);
const total = getFilterFromQuery(queryJSON, CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_TOTAL).value?.at(0);
const currency = getFilterFromQuery(queryJSON, CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_CURRENCY).value?.at(0);
return {
footerCount: count && isFooterCount(count) ? count : undefined,
footerTotal: total && isFooterTotal(total) ? total : undefined,
footerCurrency: currency ? currency.toUpperCase() : undefined,
};
}
/** The query without its group-by, and without the group sort that came with it, for searches that can't be grouped. */
function getQueryWithoutGroupBy(queryJSON: SearchQueryJSON | Readonly<SearchQueryJSON>) {
const isGroupSort = queryJSON.sortBy.startsWith(CONST.SEARCH.GROUP_COLUMN_PREFIX);
return buildSearchQueryString({
...queryJSON,
groupBy: undefined,
sortBy: isGroupSort ? CONST.SEARCH.TABLE_COLUMNS.DATE : queryJSON.sortBy,
sortOrder: isGroupSort ? CONST.SEARCH.SORT_ORDER.DESC : queryJSON.sortOrder,
});
}
/**
* The query the Spend footer's selections produce, built from the query the footer is showing. Only `footerTotal`
* changes what the backend returns. The other two ride along so the selection is restored with the search.
*/
/** The count a footer with no selection shows: reports on the Reports search, expenses everywhere else. */
function getDefaultFooterCount(type: SearchDataTypes | undefined): SearchFooterCount {
return type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT ? CONST.SEARCH.FOOTER_COUNT.REPORTS : CONST.SEARCH.FOOTER_COUNT.EXPENSES;
}
function getQueryWithFooterSelection(
queryJSON: SearchQueryJSON | Readonly<SearchQueryJSON>,
selection: {footerCount?: SearchFooterCount; footerTotal?: SearchFooterTotal; footerCurrency?: string},
) {
const flatFilters = queryJSON.flatFilters.filter((filter) => !FOOTER_FILTER_KEYS.has(filter.key));
const nextSelection = {...getFooterSelectionFromQuery(queryJSON), ...selection};
for (const [key, value] of [
[CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_COUNT, nextSelection.footerCount],
[CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_TOTAL, nextSelection.footerTotal],
[CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_CURRENCY, nextSelection.footerCurrency],
] as const) {
// The plain total and the type's own count are what a query with no selection already shows, so they are left
// out rather than spelled out: going back to them returns the query to what it was before the footer was
// touched, in the URL and in a saved search alike.
const isDefaultSelection =
(key === CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_TOTAL && value === CONST.SEARCH.FOOTER_TOTAL.TOTAL) ||
(key === CONST.SEARCH.SYNTAX_FILTER_KEYS.FOOTER_COUNT && value === getDefaultFooterCount(queryJSON.type));
if (!value || isDefaultSelection) {
continue;
}
flatFilters.push({key, filters: [{operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value}]});
}
return buildSearchQueryString({...queryJSON, flatFilters});
}
/**
* Whether the query includes a positive `has:submitted-violation` or `has:approved-violation` filter.
* Used so the Violations column and CSV export only appear when those filters are active. Normal
* search snapshots can still include FORWARDED actions with violation data.
*/
function queryHasViolationFilter(queryJSON: SearchQueryJSON | undefined): boolean {
return queryHasHasFilter(queryJSON, VIOLATION_HAS_VALUES);
}
/**
* Whether the query includes a `has:` filter for any of the given values. Negated filters only count when `shouldIncludeNegated` is set.
*/
function queryHasHasFilter(queryJSON: SearchQueryJSON | undefined, hasValues: ReadonlyArray<ValueOf<typeof CONST.SEARCH.HAS_VALUES>>, shouldIncludeNegated = false): boolean {
const hasFilterGroups = queryJSON?.flatFilters.filter((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.HAS) ?? [];
if (hasFilterGroups.length === 0) {
return false;
}
return hasFilterGroups.some((group) =>
group.filters.some((filter) => {
if (!shouldIncludeNegated && filter.operator !== CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO) {
return false;
}
const value = filter.value.toString();
return hasValues.some((hasValue) => hasValue === value);
}),
);
}
/**
* Whether the query's results depend on report state that only report actions reveal, so adding a workflow action
* must refetch it: grouping by approver, an `approver:`, `anyApproval:`, `submitted:` or `approved:` filter, or a
* `submitted-violation` or `approved-violation` filter. Negated filters count too, because submitting or approving a
* report moves its expenses out of a `-has:submitted-violation` or `-has:approved-violation` search.
*/
function shouldRefetchSearchOnReportActionChange(queryJSON: SearchQueryJSON): boolean {
return (
queryJSON.groupBy === CONST.SEARCH.GROUP_BY.APPROVER ||
queryJSON.flatFilters.some((filter) => WORKFLOW_FILTER_KEYS.has(filter.key)) ||
queryHasHasFilter(queryJSON, VIOLATION_HAS_VALUES, true)
);
}
/**
* Same meaning as queryHasViolationFilter, for the advanced-filters form `has` array rather than parsed query JSON.
*/
function hasValuesIncludeViolationFilter(hasValues: readonly string[] | undefined): boolean {
return VIOLATION_HAS_VALUES.some((violationHasValue) => !!hasValues?.includes(violationHasValue));
}
/**
* Resolves a typed workspace name to its ID. Names are not unique, so an ambiguous one is left alone rather than
* guessing which workspace was meant.
*/
function resolvePolicyIDFromName(value: string, policies: OnyxCollection<OnyxTypes.Policy>) {
if (policies?.[`${ONYXKEYS.COLLECTION.POLICY}${value}`]) {
return value;
}
const lowerCaseValue = value.toLowerCase();
const matches = Object.values(policies ?? {}).filter((policy) => policy?.name?.toLowerCase() === lowerCaseValue);
return matches.length === 1 ? (matches.at(0)?.id ?? value) : value;
}
/**
* @private
* Returns an updated filter value for some query filters.
* - for `AMOUNT` it formats value to "backend" amount
* - for personal filters it tries to substitute any user emails with accountIDs
* - for `POLICY_ID` it tries to substitute an unambiguous workspace name with its ID
*/
function getUpdatedFilterValue(filterName: SyntaxFilterKey, filterValue: string | string[], shouldSkipAmountConversion = false, policies?: OnyxCollection<OnyxTypes.Policy>) {
if (AMOUNT_FILTER_KEYS.includes(filterName as SearchAmountFilterKeys)) {
if (shouldSkipAmountConversion) {
return filterValue;
}
if (typeof filterValue === 'string') {
const backendAmount = convertToBackendAmount(Number(filterValue));
return Number.isNaN(backendAmount) ? filterValue : backendAmount.toString();
}
return filterValue.map((amount) => {
const backendAmount = convertToBackendAmount(Number(amount));
return Number.isNaN(backendAmount) ? amount : backendAmount.toString();
});
}
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID) {
if (typeof filterValue === 'string') {
return resolvePolicyIDFromName(filterValue, policies);
}
return filterValue.map((value) => resolvePolicyIDFromName(value, policies));
}
if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_ID || filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.WITHDRAWAL_ID) {
const cleanIDs = (value: string) =>
value
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0)
.join(',');
if (typeof filterValue === 'string') {
return cleanIDs(filterValue);
}
return filterValue.map(cleanIDs);
}
return filterValue;
}