diff --git a/src/components/CurrencySelectionList/index.tsx b/src/components/CurrencySelectionList/index.tsx index 96ebc9264c16..c7f72d66707c 100644 --- a/src/components/CurrencySelectionList/index.tsx +++ b/src/components/CurrencySelectionList/index.tsx @@ -15,6 +15,8 @@ import React, {useState} from 'react'; import type {CurrencyListItem, CurrencySelectionListProps} from './types'; +const ANY_CURRENCY_OPTION_KEY = 'any-currency'; + function CurrencySelectionList({ searchInputLabel, initiallySelectedCurrencyCode, @@ -23,12 +25,15 @@ function CurrencySelectionList({ selectedCurrencies = getEmptyArray(), recentlyUsedCurrencies, excludedCurrencies = [], + shouldAllowEmptySelection = false, ...restProps }: CurrencySelectionListProps) { const {currencyList} = useCurrencyListState(); const {getCurrencySymbol} = useCurrencyListActions(); const [searchValue, setSearchValue] = useState(''); - const selectedCurrencyCodes = [initiallySelectedCurrencyCode, ...selectedCurrencies].filter(Boolean); + const selectedCurrencyCodes = [initiallySelectedCurrencyCode, ...selectedCurrencies].filter( + (currencyCode) => currencyCode !== undefined && (currencyCode !== '' || shouldAllowEmptySelection), + ); const initiallyPinnedCurrencyCodes = useInitialSelection(selectedCurrencyCodes, {resetOnFocus: true}); const {translate} = useLocalize(); const initiallyPinnedCurrencyCodeSet = new Set(initiallyPinnedCurrencyCodes); @@ -67,6 +72,17 @@ function CurrencySelectionList({ .filter((currencyOption) => searchRegex.test(currencyOption.text ?? '') || searchRegex.test(currencyOption.currencyName)) .sort((currency1, currency2) => getMatchScore(currency2.text ?? '', searchValue) - getMatchScore(currency1.text ?? '', searchValue)); + const anyCurrencyLabel = translate('common.anyCurrency'); + if (shouldAllowEmptySelection && searchRegex.test(anyCurrencyLabel)) { + filteredCurrencies.unshift({ + currencyName: anyCurrencyLabel, + text: anyCurrencyLabel, + currencyCode: '', + keyForList: ANY_CURRENCY_OPTION_KEY, + isSelected: initiallySelectedCurrencyCode === '', + }); + } + const isEmpty = searchValue.trim() && !filteredCurrencies.length; const shouldDisplayRecentlyOptions = !isEmptyObject(recentlyUsedCurrencyOptions) && !searchValue; const initiallyPinnedOptions = filteredCurrencies.filter((option) => initiallyPinnedCurrencyCodeSet.has(option.currencyCode)); @@ -95,6 +111,7 @@ function CurrencySelectionList({ } } else if (!isEmpty) { sections.push({ + title: shouldAllowEmptySelection ? translate('common.all') : undefined, data: shouldDisplayInitiallyPinnedOptionsOnTop ? unpinnedOptions : filteredCurrencies, sectionIndex: 3, }); @@ -116,7 +133,7 @@ function CurrencySelectionList({ shouldShowTextInput={!!searchInputLabel} shouldSingleExecuteRowSelect shouldUpdateFocusedIndex - initiallyFocusedItemKey={initiallySelectedCurrencyCode} + initiallyFocusedItemKey={shouldAllowEmptySelection && initiallySelectedCurrencyCode === '' ? ANY_CURRENCY_OPTION_KEY : initiallySelectedCurrencyCode} shouldShowLoadingPlaceholder={!didScreenTransitionEnd} /> ); diff --git a/src/components/CurrencySelectionList/types.ts b/src/components/CurrencySelectionList/types.ts index 78dd52ce8868..1246b833e729 100644 --- a/src/components/CurrencySelectionList/types.ts +++ b/src/components/CurrencySelectionList/types.ts @@ -21,6 +21,9 @@ type CurrencySelectionListProps = Partial(null); useImperativeHandle(ref, () => ({ getValue: () => { const key = `${baseFilterKey}${modifier}`; - return {[key]: getBackendAmount(amount)}; + return {[key]: formatAmountFilterValue(amount, currency)}; }, })); @@ -79,16 +75,15 @@ function AmountInput({ref, baseFilterKey, modifier, value, label, autoFocus}: Am }, [didScreenTransitionEnd, autoFocus]); return ( - ); } @@ -103,9 +98,14 @@ type AmountBetweenInputProps = { function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue, autoFocus}: AmountBetweenInputProps) { const {translate} = useLocalize(); + const {shouldUseNarrowLayout} = useResponsiveLayout(); const styles = useThemeStyles(); - const [greaterThanAmount, setGreaterThanAmount] = useState(greaterThanValue); - const [lessThanAmount, setLessThanAmount] = useState(lessThanValue); + const initialGreaterThan = getAmountFilterInputValue(greaterThanValue); + const initialLessThan = getAmountFilterInputValue(lessThanValue); + const [greaterThanAmount, setGreaterThanAmount] = useState(initialGreaterThan.amount); + const [lessThanAmount, setLessThanAmount] = useState(initialLessThan.amount); + const {currency: greaterThanCurrency, setCurrency: setGreaterThanCurrency} = useAmountFilterCurrency(baseFilterKey, greaterThanValue); + const {currency: lessThanCurrency, setCurrency: setLessThanCurrency} = useAmountFilterCurrency(baseFilterKey, lessThanValue); const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus(); const inputRef = useRef(null); @@ -113,7 +113,10 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue getValue: () => { const greaterThanKey = `${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`; const lessThanKey = `${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}`; - return {[greaterThanKey]: getBackendAmount(greaterThanAmount), [lessThanKey]: getBackendAmount(lessThanAmount)}; + return { + [greaterThanKey]: formatAmountFilterValue(greaterThanAmount, greaterThanCurrency), + [lessThanKey]: formatAmountFilterValue(lessThanAmount, lessThanCurrency), + }; }, })); @@ -128,27 +131,25 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue const lessThanLabel = translate('search.filters.amount.lessThan'); return ( - - + - ); @@ -241,8 +242,8 @@ function AmountFilterContent({baseFilterKey, value, autoFocus, buttonSize, style ) : ( @@ -250,7 +251,7 @@ function AmountFilterContent({baseFilterKey, value, autoFocus, buttonSize, style ref={inputRef} baseFilterKey={baseFilterKey} modifier={config.keyForList} - value={getFrontendAmount(value?.[config.keyForList])} + value={value?.[config.keyForList] ?? ''} label={label} autoFocus={autoFocus} /> diff --git a/src/components/Search/FilterComponents/AmountFilterInput.tsx b/src/components/Search/FilterComponents/AmountFilterInput.tsx new file mode 100644 index 000000000000..3f7251a1d3cb --- /dev/null +++ b/src/components/Search/FilterComponents/AmountFilterInput.tsx @@ -0,0 +1,102 @@ +// Reuses money-request amount entry and currency selection without requiring a filter currency. +import AmountWithoutCurrencyInput from '@components/AmountWithoutCurrencyInput'; +import NumberWithSymbolForm from '@components/NumberWithSymbolForm'; +import type {SearchAmountFilterKeys} from '@components/Search/types'; +import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types'; + +import useLocalize from '@hooks/useLocalize'; + +import {getLocalizedCurrencySymbol} from '@libs/CurrencyUtils'; +import getAmountFilterInputKeyboard from '@libs/getAmountFilterInputKeyboard'; +import {supportsAmountFilterCurrency} from '@libs/SearchAmountFilterUtils'; + +import IOURequestStepCurrencyModal from '@pages/iou/request/step/IOURequestStepCurrencyModal'; + +import CONST from '@src/CONST'; + +import type {ForwardedRef} from 'react'; +import type {StyleProp, ViewStyle} from 'react-native'; + +import React, {useState} from 'react'; +import {View} from 'react-native'; + +type AmountFilterInputProps = { + ref?: ForwardedRef; + baseFilterKey: SearchAmountFilterKeys; + + /** Amount in major units, regardless of the saved operand's units. */ + amount: string; + + /** Empty or omitted means Any currency instead of a currency comparison. */ + currency?: string; + label: string; + name?: string; + autoFocus?: boolean; + containerStyles?: StyleProp; + onAmountChange: (amount: string) => void; + onCurrencyChange: (currency: string) => void; +}; + +function AmountFilterInput({ref, baseFilterKey, amount, currency, label, name, autoFocus, containerStyles, onAmountChange, onCurrencyChange}: AmountFilterInputProps) { + const {translate, preferredLocale} = useLocalize(); + const [isCurrencyPickerVisible, setIsCurrencyPickerVisible] = useState(false); + const [initialAmount] = useState(amount); + + if (!supportsAmountFilterCurrency(baseFilterKey)) { + return ( + + ); + } + + const hideCurrencyPicker = () => setIsCurrencyPickerVisible(false); + const {keyboardType, shouldShowFlipButton} = getAmountFilterInputKeyboard(); + + return ( + + setIsCurrencyPickerVisible(true)} + shouldShowBigNumberPad={false} + shouldUseBorderlessButtons + autoFocus={autoFocus} + /> + + + ); +} + +export default AmountFilterInput; diff --git a/src/components/Search/FilterDropdowns/AmountPopup.tsx b/src/components/Search/FilterDropdowns/AmountPopup.tsx index 3527f1f904eb..8e7abb2f67ab 100644 --- a/src/components/Search/FilterDropdowns/AmountPopup.tsx +++ b/src/components/Search/FilterDropdowns/AmountPopup.tsx @@ -1,11 +1,13 @@ -import AmountWithoutCurrencyInput from '@components/AmountWithoutCurrencyInput'; import MenuItem from '@components/MenuItem'; +import AmountFilterInput from '@components/Search/FilterComponents/AmountFilterInput'; import type {SearchAmountFilterKeys, SearchAmountValues} from '@components/Search/types'; +import useAmountFilterCurrency from '@hooks/useAmountFilterCurrency'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; -import {convertToBackendAmount, convertToFrontendAmountAsString} from '@libs/CurrencyUtils'; +import {convertToFrontendAmountAsString} from '@libs/CurrencyUtils'; +import {formatAmountFilterValue, getAmountFilterDisplayValue, getAmountFilterInputValue} from '@libs/SearchAmountFilterUtils'; import CONST from '@src/CONST'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; @@ -28,32 +30,34 @@ type AmountInputProps = { title: string; value: string; name: string; + baseFilterKey: SearchAmountFilterKeys; onSave: (value: string) => void; onBackButtonPress: () => void; }; -function AmountInput({title, value, name, onSave, onBackButtonPress}: AmountInputProps) { +function AmountInput({title, value, name, baseFilterKey, onSave, onBackButtonPress}: AmountInputProps) { const styles = useThemeStyles(); - const [amount, setAmount] = useState(value); + const initialValue = getAmountFilterInputValue(value); + const [amount, setAmount] = useState(initialValue.amount); + const {currency, setCurrency} = useAmountFilterCurrency(baseFilterKey, value); return ( onSave(amount)} + onApply={() => onSave(formatAmountFilterValue(amount, currency))} applySentryLabel={CONST.SENTRY_LABEL.SEARCH.FILTER_POPUP_APPLY_AMOUNT} onBackButtonPress={onBackButtonPress} shouldSubmitOnEnter > - @@ -74,7 +78,7 @@ function AmountPopup({baseFilterKey, label, value, closeOverlay, updateFilterFor const modifierConfig = [CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO, CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN, CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN]; const formatAmount = (amount: string | undefined) => { - return amount ? convertToFrontendAmountAsString(Number(amount), CONST.DEFAULT_CURRENCY_DECIMALS) : ''; + return getAmountFilterDisplayValue(amount, (backendAmount) => convertToFrontendAmountAsString(backendAmount, CONST.DEFAULT_CURRENCY_DECIMALS)); }; if (selectedModifier) { @@ -82,15 +86,13 @@ function AmountPopup({baseFilterKey, label, value, closeOverlay, updateFilterFor setSelectedModifier(null); }; - const save = (rawAmount: string) => { - if (rawAmount.trim() === '') { + const save = (newAmount: string) => { + if (newAmount === '') { setAmountValues((prevAmountValues) => ({...prevAmountValues, [selectedModifier]: undefined})); goBack(); return; } - const newAmount = convertToBackendAmount(Number(rawAmount)).toString(); - // When setting an Equal To value, clear Greater Than and Less Than to avoid conflicting filters. if (selectedModifier === CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO) { setAmountValues({[CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN]: '', [CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN]: '', [selectedModifier]: newAmount}); @@ -106,8 +108,9 @@ function AmountPopup({baseFilterKey, label, value, closeOverlay, updateFilterFor return ( diff --git a/src/hooks/useAmountFilterCurrency.ts b/src/hooks/useAmountFilterCurrency.ts new file mode 100644 index 000000000000..a3f9073b4662 --- /dev/null +++ b/src/hooks/useAmountFilterCurrency.ts @@ -0,0 +1,23 @@ +// Resolves currency defaults for new Search amount operands without rewriting saved filters. +import type {SearchAmountFilterKeys} from '@components/Search/types'; + +import {parseAmountFilterValue, supportsAmountFilterCurrency} from '@libs/SearchAmountFilterUtils'; + +import CONST from '@src/CONST'; + +import {useState} from 'react'; + +import useDefaultExpensePolicy from './useDefaultExpensePolicy'; + +function useAmountFilterCurrency(baseFilterKey: SearchAmountFilterKeys, value?: string) { + const defaultPolicy = useDefaultExpensePolicy(); + + // An empty string keeps Any currency selected. Undefined follows the saved operand or policy default. + const [selectedCurrency, setCurrency] = useState(); + const savedCurrency = value ? (parseAmountFilterValue(value).currency ?? '') : undefined; + const currency = supportsAmountFilterCurrency(baseFilterKey) ? (selectedCurrency ?? savedCurrency ?? (defaultPolicy?.outputCurrency || CONST.CURRENCY.USD)) : undefined; + + return {currency, setCurrency}; +} + +export default useAmountFilterCurrency; diff --git a/src/languages/de.ts b/src/languages/de.ts index f55d7a646175..4fc42d5e3fb8 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Wird noch festgelegt', selectCurrency: 'Wähle eine Währung', + any: 'Beliebig', + anyCurrency: 'Beliebige Währung', selectSymbolOrCurrency: 'Wähle ein Symbol oder eine Währung aus', card: 'Karte', mcc: 'MCC', diff --git a/src/languages/el.ts b/src/languages/el.ts index ada359f6b502..02fc9d27fb08 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -335,6 +335,8 @@ const translations: TranslationDeepObject = { pm: 'μ.μ.', tbd: 'Θα καθοριστεί', selectCurrency: 'Επιλέξτε νόμισμα', + any: 'Οποιοδήποτε', + anyCurrency: 'Οποιοδήποτε νόμισμα', selectSymbolOrCurrency: 'Επιλέξτε ένα σύμβολο ή νόμισμα', card: 'Κάρτα', mcc: 'MCC', diff --git a/src/languages/en.ts b/src/languages/en.ts index 97571886a4f3..2e84cac8fa74 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -412,6 +412,8 @@ const translations = { // @context Acronym meaning “To Be Determined.” Should be translated or localized according to the target language's convention. tbd: 'TBD', selectCurrency: 'Select a currency', + any: 'Any', + anyCurrency: 'Any currency', selectSymbolOrCurrency: 'Select a symbol or currency', card: 'Card', mcc: 'MCC', diff --git a/src/languages/es.ts b/src/languages/es.ts index c4ddd1713794..796a2d9bdfca 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -324,6 +324,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Por determinar', selectCurrency: 'Selecciona una moneda', + any: 'Cualquiera', + anyCurrency: 'Cualquier moneda', selectSymbolOrCurrency: 'Selecciona un símbolo o moneda', card: 'Tarjeta', mcc: 'MCC', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index d0e548bbb89a..ade546710e10 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'À déterminer', selectCurrency: 'Sélectionner une devise', + any: 'Toutes', + anyCurrency: 'N’importe quelle devise', selectSymbolOrCurrency: 'Sélectionner un symbole ou une devise', card: 'Carte', mcc: 'MCC', diff --git a/src/languages/it.ts b/src/languages/it.ts index 227f86d497ca..75b2174a6e94 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Da definire', selectCurrency: 'Seleziona una valuta', + any: 'Qualsiasi', + anyCurrency: 'Qualsiasi valuta', selectSymbolOrCurrency: 'Seleziona un simbolo o una valuta', card: 'Carta', mcc: 'MCC', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index fae9ee533839..14dbc781e0c1 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: '午後', tbd: '未定', selectCurrency: '通貨を選択', + any: 'すべて', + anyCurrency: 'すべての通貨', selectSymbolOrCurrency: '記号または通貨を選択', card: 'カード', mcc: 'MCC', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 2ffdac98971c..da0f6ce69c57 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Nader te bepalen', selectCurrency: 'Selecteer een valuta', + any: 'Alle', + anyCurrency: 'Elke valuta', selectSymbolOrCurrency: 'Selecteer een symbool of valuta', card: 'Kaart', mcc: 'MCC', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 429ce2804595..7d079a589dd5 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -336,6 +336,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Do ustalenia', selectCurrency: 'Wybierz walutę', + any: 'Dowolna', + anyCurrency: 'Dowolna waluta', selectSymbolOrCurrency: 'Wybierz symbol lub walutę', card: 'Karta', mcc: 'MCC', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 7cf435ba8acc..829b5bbc0926 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'A definir', selectCurrency: 'Selecione uma moeda', + any: 'Qualquer', + anyCurrency: 'Qualquer moeda', selectSymbolOrCurrency: 'Selecione um símbolo ou moeda', card: 'Cartão', mcc: 'MCC', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 186a44c3bbb2..8adf80e79037 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -330,6 +330,8 @@ const translations: TranslationDeepObject = { pm: '下午', tbd: '待定', selectCurrency: '选择货币', + any: '任意', + anyCurrency: '任意货币', selectSymbolOrCurrency: '选择符号或货币', card: '卡片', mcc: 'MCC', diff --git a/src/libs/SearchAmountFilterUtils.ts b/src/libs/SearchAmountFilterUtils.ts new file mode 100644 index 000000000000..8e08f4d84121 --- /dev/null +++ b/src/libs/SearchAmountFilterUtils.ts @@ -0,0 +1,50 @@ +// Bare operands store integer hundredths, such as "1250" for 12.50. +// Operands with a comparison currency store decimal major units, such as "12.50 USD". +import CONST from '@src/CONST'; + +import {convertToBackendAmount, convertToFrontendAmountAsString} from './CurrencyUtils'; + +type AmountFilterValue = { + amount: string; + currency?: string; +}; + +/** Whether this amount filter supports FX comparisons. */ +function supportsAmountFilterCurrency(filterKey: string): boolean { + return filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT || filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT; +} + +/** Reads "12.50 USD" as amount "12.50" and currency "USD". Bare values such as "1250" keep their stored units. */ +function parseAmountFilterValue(value = ''): AmountFilterValue { + const match = value.match(/^(-?\d+(?:\.\d{1,2})?) ([A-Z]{3})$/); + return match ? {amount: match.at(1) ?? '', currency: match.at(2)} : {amount: value}; +} + +/** Editors use major units, so "1250" becomes "12.50" while "12.50 USD" keeps its amount and currency. */ +function getAmountFilterInputValue(value?: string): AmountFilterValue { + const parsed = parseAmountFilterValue(value); + return parsed.currency ? parsed : {amount: parsed.amount ? convertToFrontendAmountAsString(Number(parsed.amount), CONST.DEFAULT_CURRENCY_DECIMALS) : ''}; +} + +/** Saves editor amount "12.50" as "1250" without a currency, or "12.50 USD" with USD selected. */ +function formatAmountFilterValue(amount: string, currency?: string): string { + if (!amount.trim() || !Number.isFinite(Number(amount))) { + return ''; + } + + const backendAmount = convertToBackendAmount(Number(amount)); + return currency ? `${convertToFrontendAmountAsString(backendAmount, CONST.DEFAULT_CURRENCY_DECIMALS)} ${currency}` : backendAmount.toString(); +} + +/** The localized formatter expects hundredths, so both "1250" and "12.50 USD" pass 1250 before adding any currency suffix. */ +function getAmountFilterDisplayValue(value: string | undefined, formatAmount: (amount: number) => string): string { + if (!value) { + return ''; + } + + const parsed = parseAmountFilterValue(value); + const formattedAmount = formatAmount(parsed.currency ? convertToBackendAmount(Number(parsed.amount)) : Number(parsed.amount)); + return parsed.currency ? `${formattedAmount} ${parsed.currency}` : formattedAmount; +} + +export {supportsAmountFilterCurrency, parseAmountFilterValue, getAmountFilterInputValue, formatAmountFilterValue, getAmountFilterDisplayValue}; diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 5fe3bfb7e5e0..bb2665d7ecfd 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -92,6 +92,7 @@ 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'; @@ -645,19 +646,19 @@ function buildAmountFilterQuery(filterKey: SearchAmountFilterKeys, filterValues: const amountStrings = []; if (equalTo) { - amountStrings.push(`${filterKey}:${equalTo}`); + amountStrings.push(`${filterKey}:${sanitizeSearchValue(equalTo)}`); } if (greaterThan) { - amountStrings.push(`${filterKey}>${greaterThan}`); + amountStrings.push(`${filterKey}>${sanitizeSearchValue(greaterThan)}`); } if (lessThan) { - amountStrings.push(`${filterKey}<${lessThan}`); + amountStrings.push(`${filterKey}<${sanitizeSearchValue(lessThan)}`); } if (negatedAmount) { - amountStrings.push(`-${filterKey}:${negatedAmount}`); + amountStrings.push(`-${filterKey}:${sanitizeSearchValue(negatedAmount)}`); } return amountStrings.join(' '); @@ -2080,23 +2081,29 @@ function buildFilterFormValuesFromQuery( const lessThanKey = `${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}` as `${SearchAmountFilterKeys}${typeof CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}`; const greaterThanKey = `${filterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}` as `${SearchAmountFilterKeys}${typeof CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`; - // backend amount is an integer and is 2 digits longer than frontend amount + const isValidAmount = (value: string) => { + const parsed = parseAmountFilterValue(value); + if (parsed.currency && !supportsAmountFilterCurrency(filterKey)) { + return false; + } + + // Bare amounts use integer hundredths, so they need two extra digits and no decimals. + // Amounts with a currency use decimals, such as "12.00 USD". + return validateAmount(parsed.amount, parsed.currency ? CONST.DEFAULT_CURRENCY_DECIMALS : 0, CONST.IOU.AMOUNT_MAX_LENGTH + (parsed.currency ? 0 : 2), true); + }; + filtersForm[equalToKey] = - filterList - .find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && validateAmount(filter.value.toString(), 0, CONST.IOU.AMOUNT_MAX_LENGTH + 2, true)) - ?.value.toString() ?? filtersForm[equalToKey]; + filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && isValidAmount(filter.value.toString()))?.value.toString() ?? + filtersForm[equalToKey]; filtersForm[lessThanKey] = - filterList - .find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN && validateAmount(filter.value.toString(), 0, CONST.IOU.AMOUNT_MAX_LENGTH + 2, true)) - ?.value.toString() ?? filtersForm[lessThanKey]; + filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN && isValidAmount(filter.value.toString()))?.value.toString() ?? + filtersForm[lessThanKey]; filtersForm[greaterThanKey] = - filterList - .find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN && validateAmount(filter.value.toString(), 0, CONST.IOU.AMOUNT_MAX_LENGTH + 2, true)) - ?.value.toString() ?? filtersForm[greaterThanKey]; + filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN && isValidAmount(filter.value.toString()))?.value.toString() ?? + filtersForm[greaterThanKey]; filtersForm[negatedKey] = - filterList - .find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO && validateAmount(filter.value.toString(), 0, CONST.IOU.AMOUNT_MAX_LENGTH + 2, true)) - ?.value.toString() ?? filtersForm[negatedKey]; + filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO && isValidAmount(filter.value.toString()))?.value.toString() ?? + filtersForm[negatedKey]; } if ( diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 9b57b8166a70..52ab7c3f2828 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -207,6 +207,7 @@ import { isSettled, shouldReportShowSubscript, } from './ReportUtils'; +import {getAmountFilterDisplayValue} from './SearchAmountFilterUtils'; import { buildSearchQueryJSON, buildSearchQueryString, @@ -6232,7 +6233,7 @@ function getAmountDisplayValue( const greaterThan = form[`${syntaxKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]; const equalTo = form[`${syntaxKey}${CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO}`]; - const formatAmount = (val: string) => convertToDisplayStringWithoutCurrency(Number(val)); + const formatAmount = (val: string) => getAmountFilterDisplayValue(val, convertToDisplayStringWithoutCurrency); if (equalTo) { return translate('search.filters.amount.equalTo', formatAmount(equalTo)); diff --git a/src/libs/getAmountFilterInputKeyboard/index.native.ts b/src/libs/getAmountFilterInputKeyboard/index.native.ts new file mode 100644 index 000000000000..11d13c933a96 --- /dev/null +++ b/src/libs/getAmountFilterInputKeyboard/index.native.ts @@ -0,0 +1,7 @@ +import getAmountInputKeyboard from '@libs/getAmountInputKeyboard'; + +function getAmountFilterInputKeyboard() { + return {...getAmountInputKeyboard(true), shouldShowFlipButton: false}; +} + +export default getAmountFilterInputKeyboard; diff --git a/src/libs/getAmountFilterInputKeyboard/index.ts b/src/libs/getAmountFilterInputKeyboard/index.ts new file mode 100644 index 000000000000..5a0ab0e2b786 --- /dev/null +++ b/src/libs/getAmountFilterInputKeyboard/index.ts @@ -0,0 +1,6 @@ +// Web decimal keypads need a separate sign button because they may omit the minus key. +function getAmountFilterInputKeyboard() { + return {keyboardType: undefined, shouldShowFlipButton: true}; +} + +export default getAmountFilterInputKeyboard; diff --git a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx index 2289ecff5b4d..2e0c02f299e3 100644 --- a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx +++ b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx @@ -9,8 +9,6 @@ import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; -import Navigation from '@libs/Navigation/Navigation'; - import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -27,11 +25,23 @@ type CurrencyPickerProps = { excludeCurrencies?: string[]; + /** Whether the picker includes an option to clear the selected currency. */ + shouldAllowEmptySelection?: boolean; + /** The button that opens the picker. When passed, focus returns to it after the picker closes. */ launcherRef?: FocusTrapForModalProps['launcherRef']; }; -function IOURequestStepCurrencyModal({isPickerVisible, hidePickerModal, headerText, value, excludeCurrencies, launcherRef, onInputChange = () => {}}: CurrencyPickerProps) { +function IOURequestStepCurrencyModal({ + isPickerVisible, + hidePickerModal, + headerText, + value, + excludeCurrencies, + shouldAllowEmptySelection = false, + launcherRef, + onInputChange = () => {}, +}: CurrencyPickerProps) { const {translate} = useLocalize(); const [recentlyUsedCurrencies] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES); const styles = useThemeStyles(); @@ -50,7 +60,7 @@ function IOURequestStepCurrencyModal({isPickerVisible, hidePickerModal, headerTe shouldEnableNewFocusManagement shouldReturnFocus={!!launcherRef} launcherRef={launcherRef} - onBackdropPress={Navigation.dismissModal} + onBackdropPress={hidePickerModal} shouldUseModalPaddingStyle={false} shouldHandleNavigationBack enableEdgeToEdgeBottomSafeAreaPadding @@ -72,6 +82,7 @@ function IOURequestStepCurrencyModal({isPickerVisible, hidePickerModal, headerTe onSelect={updateInput} searchInputLabel={translate('common.search')} excludedCurrencies={excludeCurrencies} + shouldAllowEmptySelection={shouldAllowEmptySelection} addBottomSafeAreaPadding /> diff --git a/tests/ui/CurrencySelectionListTest.tsx b/tests/ui/CurrencySelectionListTest.tsx index afa2c02940b6..b2e68d1df2eb 100644 --- a/tests/ui/CurrencySelectionListTest.tsx +++ b/tests/ui/CurrencySelectionListTest.tsx @@ -44,12 +44,13 @@ jest.mock('@hooks/useLocalize', () => })), ); -type MockSection = {sectionIndex: number; data: Array<{currencyCode: string; isSelected?: boolean}>}; +type MockSection = {sectionIndex: number; title?: string; data: Array<{currencyCode: string; isSelected?: boolean}>}; type MockSelectionListProps = { sections: MockSection[]; + initiallyFocusedItemKey?: string; shouldUpdateFocusedIndex?: boolean; - textInputOptions?: {onChangeText?: (value: string) => void}; + textInputOptions?: {onChangeText?: (value: string) => void; headerMessage?: string}; }; function renderCurrencyList(props: Partial> = {}) { @@ -72,6 +73,69 @@ describe('CurrencySelectionList', () => { mockedSelectionList.mockClear(); }); + it.each([ + {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: ['EUR']}, + {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: []}, + ])('puts Any currency first under All with selection "$initiallySelectedCurrencyCode" and recents $recentlyUsedCurrencies', (props) => { + // Given an optional currency picker with a saved selection and optional recent currencies. + renderCurrencyList({...props, shouldAllowEmptySelection: true}); + + // When the picker builds its selected, recent, and All sections. + const sections = getSelectionListProps()?.sections; + const allSection = sections?.at(-1); + + // Then Any currency leads All, stays out of earlier sections, and reflects the empty selection. + expect(allSection?.title).toBe('common.all'); + expect(allSection?.data.at(0)).toMatchObject({currencyCode: '', text: 'common.anyCurrency', isSelected: props.initiallySelectedCurrencyCode === ''}); + expect(getSelectionListProps()?.initiallyFocusedItemKey).toBe(props.initiallySelectedCurrencyCode || 'any-currency'); + expect(sections?.slice(0, -1).flatMap((section) => section.data.map((item) => item.currencyCode))).not.toContain(''); + if (props.initiallySelectedCurrencyCode) { + expect(pinnedCurrencyCodes()).toEqual(['USD']); + } + }); + + it.each([{recentlyUsedCurrencies: ['EUR']}, {recentlyUsedCurrencies: []}])('pins selected Any currency above recents $recentlyUsedCurrencies', ({recentlyUsedCurrencies}) => { + // Given an optional picker reopened with Any currency selected and optional recents. + renderCurrencyList({initiallySelectedCurrencyCode: '', recentlyUsedCurrencies, shouldAllowEmptySelection: true}); + + // When the selected option is pinned before the other sections. + const sections = getSelectionListProps()?.sections; + + // Then initial focus stays above Recents and Any currency does not appear twice. + expect(pinnedCurrencyCodes()).toEqual(['']); + expect(sections?.at(0)?.title).toBeUndefined(); + expect(sections?.at(0)?.data.at(0)).toMatchObject({currencyCode: '', isSelected: true}); + expect(sections?.slice(1).flatMap((section) => section.data.map((item) => item.currencyCode))).not.toContain(''); + expect(getSelectionListProps()?.initiallyFocusedItemKey).toBe('any-currency'); + }); + + it('searches Any currency as a list option', () => { + // Given a picker that permits comparisons without a currency. + renderCurrencyList({shouldAllowEmptySelection: true}); + + // When the search matches the Any currency label rather than a currency code. + act(() => getSelectionListProps()?.textInputOptions?.onChangeText?.('any')); + + // Then the option remains under All and does not show a no-results message. + expect(getSelectionListProps()?.sections.at(0)?.title).toBe('common.all'); + expect(getSelectionListProps()?.sections.at(0)?.data).toMatchObject([{currencyCode: ''}]); + expect(getSelectionListProps()?.textInputOptions?.headerMessage).toBeUndefined(); + + // When the search only matches USD, then Any currency is filtered out like other options. + act(() => getSelectionListProps()?.textInputOptions?.onChangeText?.('USD')); + expect(getSelectionListProps()?.sections.at(0)?.data).toMatchObject([{currencyCode: 'USD'}]); + }); + + it('omits Any currency when a currency is required', () => { + // Given a picker that requires an actual currency code. + // When the default list is built without enabling empty selections. + renderCurrencyList(); + + // Then no empty currency option or optional All header is offered. + expect(getSelectionListProps()?.sections.flatMap((section) => section.data.map((item) => item.currencyCode))).not.toContain(''); + expect(getSelectionListProps()?.sections.at(0)?.title).toBeUndefined(); + }); + it('pins the initially selected currency to its own top section on open', () => { renderCurrencyList({initiallySelectedCurrencyCode: 'USD'}); diff --git a/tests/ui/IOURequestStepCurrencyModalTest.tsx b/tests/ui/IOURequestStepCurrencyModalTest.tsx new file mode 100644 index 000000000000..1ef6b6417a11 --- /dev/null +++ b/tests/ui/IOURequestStepCurrencyModalTest.tsx @@ -0,0 +1,109 @@ +import {act, render} from '@testing-library/react-native'; + +import CurrencySelectionList from '@components/CurrencySelectionList'; +import Modal from '@components/Modal'; + +import Navigation from '@libs/Navigation/Navigation'; + +import IOURequestStepCurrencyModal from '@pages/iou/request/step/IOURequestStepCurrencyModal'; + +import React from 'react'; + +jest.mock('@components/HeaderWithBackButton', () => jest.fn(() => null)); +jest.mock('@components/Modal', () => jest.fn(({children}: {children: React.ReactNode}) => children)); +jest.mock('@components/ScreenWrapper', () => jest.fn(({children}: {children: React.ReactNode}) => children)); +jest.mock('@components/CurrencySelectionList', () => jest.fn(() => null)); +jest.mock('@hooks/useLocalize', () => () => ({translate: (key: string) => key, preferredLocale: 'en'})); +jest.mock('@libs/Navigation/Navigation', () => ({dismissModal: jest.fn()})); + +describe('IOURequestStepCurrencyModal', () => { + it.each([true, false])('preserves optional currencies with launcher focus restoration %s', (hasLauncher) => { + // Given an optional currency picker with or without an explicit launcher. + const launcherRef = hasLauncher ? React.createRef() : undefined; + render( + , + ); + + // When the picker configures its modal and currency list. + const modalProps = jest.mocked(Modal).mock.lastCall?.[0]; + const listProps = jest.mocked(CurrencySelectionList).mock.lastCall?.[0]; + + // Then focus restoration follows the launcher while Any currency remains available. + expect(modalProps?.launcherRef).toBe(launcherRef); + expect(modalProps?.shouldReturnFocus).toBe(hasLauncher); + expect(listProps?.shouldAllowEmptySelection).toBe(true); + }); + + it.each([true, false])('closes only the picker on backdrop press with optional currency %s', (shouldAllowEmptySelection) => { + // Given a local currency picker over a filter or money request. + const hidePickerModal = jest.fn(); + const onInputChange = jest.fn(); + render( + , + ); + + // When the backdrop is pressed instead of selecting another currency. + act(() => jest.mocked(Modal).mock.lastCall?.[0].onBackdropPress?.()); + + // Then only the local picker closes, without changing the selection or underlying route. + expect(hidePickerModal).toHaveBeenCalledTimes(1); + expect(onInputChange).not.toHaveBeenCalled(); + expect(Navigation.dismissModal).not.toHaveBeenCalled(); + }); + + it('selects Any currency as an empty currency and closes the picker', () => { + // Given an amount filter that permits currency-agnostic comparisons. + const onInputChange = jest.fn(); + const hidePickerModal = jest.fn(); + render( + , + ); + + // When Any currency is selected instead of a currency code. + const listProps = jest.mocked(CurrencySelectionList).mock.calls.at(-1)?.[0]; + expect(listProps?.shouldAllowEmptySelection).toBe(true); + act(() => listProps?.onSelect({currencyCode: '', currencyName: 'Any currency', keyForList: 'any-currency'})); + + // Then the caller receives the empty selection used by legacy operands. + expect(onInputChange).toHaveBeenCalledWith(''); + expect(hidePickerModal).toHaveBeenCalledTimes(1); + }); + + it('does not offer Any currency when a currency is required', () => { + // Given a money-request picker whose selection must remain a currency code. + // When the picker opens without allowing an empty selection. + render( + , + ); + + // Then money requests cannot select the search-only Any currency option. + expect(jest.mocked(CurrencySelectionList).mock.calls.at(-1)?.[0].shouldAllowEmptySelection).toBe(false); + }); +}); diff --git a/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx new file mode 100644 index 000000000000..23f6857f8e11 --- /dev/null +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -0,0 +1,366 @@ +import {act, fireEvent, render, renderHook, screen} from '@testing-library/react-native'; + +import NumberWithSymbolForm from '@components/NumberWithSymbolForm'; +import AmountFilterContent from '@components/Search/FilterComponents/AdvancedFilters/AmountFilterContent'; +import AmountFilterInput from '@components/Search/FilterComponents/AmountFilterInput'; +import AmountPopup from '@components/Search/FilterDropdowns/AmountPopup'; +import BasePopup from '@components/Search/FilterDropdowns/BasePopup'; + +import useAmountFilterCurrency from '@hooks/useAmountFilterCurrency'; +import useDefaultExpensePolicy from '@hooks/useDefaultExpensePolicy'; + +import IOURequestStepCurrencyModal from '@pages/iou/request/step/IOURequestStepCurrencyModal'; + +import CONST from '@src/CONST'; +import type {Policy} from '@src/types/onyx'; + +import React from 'react'; + +import createMock from '../../utils/createMock'; + +jest.mock('@components/NumberWithSymbolForm', () => jest.fn(() => null)); +jest.mock('@pages/iou/request/step/IOURequestStepCurrencyModal', () => jest.fn(() => null)); +jest.mock('@components/Search/FilterDropdowns/BasePopup', () => jest.fn(({children}: {children: React.ReactNode}) => children)); +jest.mock('@components/AmountWithoutCurrencyInput', () => jest.fn(() => null)); +jest.mock('@hooks/useScreenWrapperTransitionStatus', () => () => ({didScreenTransitionEnd: true})); +jest.mock('@hooks/useShouldFooterBeInsideList', () => () => false); +jest.mock('@hooks/useDefaultExpensePolicy', () => jest.fn(() => undefined)); +jest.mock('@hooks/useLocalize', () => () => ({translate: (key: string) => key, preferredLocale: 'en'})); + +beforeEach(() => { + jest.clearAllMocks(); + jest.mocked(useDefaultExpensePolicy).mockReturnValue(undefined); +}); + +describe('AmountFilterContent currency selection', () => { + it.each(['Greater than ', 'Less than '])('trims the %s label in the currency button name', (label) => { + // Given a range label whose translation leaves space for an optional amount. + render( + , + ); + + // When the currency button's accessible name combines the label with its selected currency. + const props = jest.mocked(NumberWithSymbolForm).mock.lastCall?.[0]; + + // Then no trailing translation space remains before the spoken separator. + expect(props?.currencyButtonAccessibilityLabel).toBe(`${label.trim()}, common.selectCurrency, USD`); + }); + + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('sends the selected currency for %s', (baseFilterKey) => { + // Given a legacy bare amount in a workspace whose default currency is GBP. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + render( + , + ); + + // When the money-request currency button opens its picker and a currency is selected. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0]).toMatchObject({value: '12.00', currency: '', shouldShowCurrencyButton: true, allowNegativeInput: true}); + act(() => jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].onCurrencyButtonPress?.()); + expect(jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].isPickerVisible).toBe(true); + act(() => { + jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].onInputChange?.('USD'); + jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].hidePickerModal(); + }); + fireEvent.press(screen.getByRole('button')); + + // Then the existing form field carries major units and the currency, not hundredths with a suffix. + expect(onChange).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: '12.00 USD', [`${baseFilterKey}GreaterThan`]: undefined, [`${baseFilterKey}LessThan`]: undefined}); + }); + + it.each([ + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, policyCurrency: 'GBP', expectedCurrency: 'GBP'}, + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT, policyCurrency: 'EUR', expectedCurrency: 'EUR'}, + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, policyCurrency: undefined, expectedCurrency: 'USD'}, + ])('defaults a new $baseFilterKey operand to $expectedCurrency', ({baseFilterKey, policyCurrency, expectedCurrency}) => { + // Given a new operand and an optional default expense policy. + if (policyCurrency) { + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: policyCurrency})); + } + const onChange = jest.fn(); + render( + , + ); + + // When an amount is entered and confirmed without manually choosing a currency. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].currency).toBe(expectedCurrency); + act(() => jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].onInputChange?.('12.00')); + fireEvent.press(screen.getByRole('button')); + + // Then the displayed default is also included in the submitted operand. + expect(onChange).toHaveBeenCalledWith({ + [`${baseFilterKey}EqualTo`]: `12.00 ${expectedCurrency}`, + [`${baseFilterKey}GreaterThan`]: undefined, + [`${baseFilterKey}LessThan`]: undefined, + }); + }); + + it('keeps saved currency-less amounts currency-less when a default policy exists', () => { + // Given a legacy operand and a GBP workspace default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + render( + , + ); + + // When the existing filter is reopened and confirmed without changes. + fireEvent.press(screen.getByRole('button')); + + // Then the default does not retroactively enable FX for the saved filter. + expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); + }); + + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('shows Any after selecting Any currency for %s', (baseFilterKey) => { + // Given a saved currency-qualified amount and a GBP workspace default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + render( + , + ); + + // When Any currency is selected and the filter is confirmed. + expect(jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].shouldAllowEmptySelection).toBe(true); + act(() => jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].onInputChange?.('')); + fireEvent.press(screen.getByRole('button')); + + // Then the button uses Any, its accessibility label keeps Any currency, and the amount returns to bare hundredths. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0]).toMatchObject({ + value: '0.10', + currency: '', + currencyButtonLabel: 'common.any', + }); + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].currencyButtonAccessibilityLabel).toContain('common.anyCurrency'); + expect(onChange).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: '10', [`${baseFilterKey}GreaterThan`]: undefined, [`${baseFilterKey}LessThan`]: undefined}); + }); + + it('keeps the saved operand when the currency picker is dismissed', () => { + // Given an existing USD amount and a different workspace default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + render( + , + ); + + // When the shared picker opens and closes without a selection. + act(() => jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].onCurrencyButtonPress?.()); + act(() => jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].hidePickerModal()); + fireEvent.press(screen.getByRole('button')); + + // Then neither the amount nor its comparison currency changes. + expect(jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].isPickerVisible).toBe(false); + expect(onChange).toHaveBeenCalledWith({amountEqualTo: '12.00 USD', amountGreaterThan: undefined, amountLessThan: undefined}); + }); + + it('defaults both new range bounds to the policy currency', () => { + // Given an empty filter and a GBP default expense policy. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + render( + , + ); + jest.mocked(NumberWithSymbolForm).mockClear(); + + // When a new Between filter is entered without selecting either currency. + fireEvent.press(screen.getByTestId('base-list-item-Between'), {nativeEvent: {}}); + const bounds = jest.mocked(NumberWithSymbolForm).mock.calls.slice(-2); + expect(bounds.map(([props]) => props.currency)).toEqual(['GBP', 'GBP']); + act(() => { + bounds.at(0)?.[0].onInputChange?.('10'); + bounds.at(1)?.[0].onInputChange?.('20'); + }); + fireEvent.press(screen.getByRole('button')); + + // Then both submitted bounds include the workspace currency. + expect(onChange).toHaveBeenCalledWith({purchaseAmountEqualTo: undefined, purchaseAmountGreaterThan: '10.00 GBP', purchaseAmountLessThan: '20.00 GBP'}); + }); + + it('preserves the currency on each side of a between filter', () => { + // Given two saved currencies that differ from the policy default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'EUR'})); + const onChange = jest.fn(); + render( + , + ); + + // When the range is reopened and confirmed without changes. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.map(([props]) => props.currency)).toEqual(['USD', 'GBP']); + fireEvent.press(screen.getByRole('button')); + + // Then neither bound inherits the other's currency or changes its numeric scale. + expect(onChange).toHaveBeenCalledWith({purchaseAmountEqualTo: undefined, purchaseAmountGreaterThan: '10.00 USD', purchaseAmountLessThan: '20.00 GBP'}); + }); + + it('selects Any currency for one range bound without changing the other', () => { + // Given a saved range whose bounds have different currencies. + const onChange = jest.fn(); + render( + , + ); + + // When only the lower bound switches to Any currency. + const [lowerBoundPicker] = jest.mocked(IOURequestStepCurrencyModal).mock.calls; + act(() => lowerBoundPicker?.[0].onInputChange?.('')); + fireEvent.press(screen.getByRole('button')); + + // Then the lower bound uses legacy hundredths and the upper bound retains GBP. + expect(onChange).toHaveBeenCalledWith({amountEqualTo: undefined, amountGreaterThan: '10', amountLessThan: '20.00 GBP'}); + }); + + it('does not offer currency selection for report totals', () => { + // Given a GBP policy and an amount-like filter that does not support FX comparisons. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const onChange = jest.fn(); + + // When its existing editor is rendered. + render( + , + ); + + // Then its UI does not gain a currency picker. + expect(IOURequestStepCurrencyModal).not.toHaveBeenCalled(); + expect(NumberWithSymbolForm).not.toHaveBeenCalled(); + fireEvent.press(screen.getByRole('button')); + expect(onChange).toHaveBeenCalledWith({totalEqualTo: '1200', totalGreaterThan: undefined, totalLessThan: undefined}); + }); +}); + +describe('AmountPopup currency selection', () => { + it('submits the default policy currency for a new quick filter', () => { + // Given a new purchase-amount filter and a GBP default expense policy. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + const updateFilterForm = jest.fn(); + render( + , + ); + const [equalTo] = screen.getAllByRole('button'); + if (!equalTo) { + throw new Error('Expected amount comparison options'); + } + + // When an amount is entered and both popup steps are applied without choosing a currency. + fireEvent.press(equalTo, {nativeEvent: {}}); + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].currency).toBe('GBP'); + act(() => jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].onInputChange?.('11.99')); + act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); + act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); + + // Then the default currency is serialized, not just displayed by the picker. + expect(updateFilterForm).toHaveBeenCalledWith({purchaseAmountEqualTo: '11.99 GBP', purchaseAmountGreaterThan: '', purchaseAmountLessThan: ''}); + }); + + it.each([ + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, currency: 'USD', expected: '12.00 USD'}, + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT, currency: 'USD', expected: '12.00 USD'}, + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, currency: '', expected: '1200'}, + {baseFilterKey: CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT, currency: '', expected: '1200'}, + ])('uses the money-request picker for the $baseFilterKey popup with currency "$currency"', ({baseFilterKey, currency, expected}) => { + // Given a quick filter popup holding a bare amount. + const updateFilterForm = jest.fn(); + render( + , + ); + const [equalTo] = screen.getAllByRole('button'); + if (!equalTo) { + throw new Error('Expected amount comparison options'); + } + + // When the shared picker selects a currency or Any currency and both popup steps are applied. + fireEvent.press(equalTo, {nativeEvent: {}}); + act(() => jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].onCurrencyButtonPress?.()); + expect(jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].isPickerVisible).toBe(true); + act(() => jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].onInputChange?.(currency)); + act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); + act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); + + // Then quick filters use the compact currency label and preserve the format used by advanced filters. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0].currencyButtonLabel).toBe(currency || 'common.any'); + expect(updateFilterForm).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: expected, [`${baseFilterKey}GreaterThan`]: '', [`${baseFilterKey}LessThan`]: ''}); + }); +}); + +describe('Amount filter currency defaults', () => { + it('follows policy defaults without overwriting saved or explicit currencies', () => { + // Given a new filter while its default policy has not loaded yet. + let savedValue: string | undefined; + const {result, rerender} = renderHook(() => useAmountFilterCurrency(CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, savedValue)); + expect(result.current.currency).toBe('USD'); + + // When policy data arrives, then the untouched default follows it. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); + rerender(undefined); + expect(result.current.currency).toBe('GBP'); + + // When the default is saved, then it stays part of that operand even if the workspace changes later. + savedValue = '12.00 GBP'; + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'EUR'})); + rerender(undefined); + expect(result.current.currency).toBe('GBP'); + + // When Any currency is chosen, then later policy updates do not re-enable FX. + act(() => result.current.setCurrency('')); + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'USD'})); + rerender(undefined); + expect(result.current.currency).toBe(''); + + // When another currency is explicitly chosen, then it also takes precedence over policy updates. + act(() => result.current.setCurrency('JPY')); + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'EUR'})); + rerender(undefined); + expect(result.current.currency).toBe('JPY'); + }); +}); diff --git a/tests/unit/Search/SearchAmountFilterUtilsTest.ts b/tests/unit/Search/SearchAmountFilterUtilsTest.ts new file mode 100644 index 000000000000..b0b404eb019e --- /dev/null +++ b/tests/unit/Search/SearchAmountFilterUtilsTest.ts @@ -0,0 +1,73 @@ +import {formatAmountFilterValue, getAmountFilterDisplayValue, getAmountFilterInputValue, parseAmountFilterValue, supportsAmountFilterCurrency} from '@libs/SearchAmountFilterUtils'; + +import CONST from '@src/CONST'; + +describe('SearchAmountFilterUtils', () => { + it.each([ + {amount: '12', currency: undefined, expected: '1200'}, + {amount: '12', currency: 'USD', expected: '12.00 USD'}, + {amount: '11.99', currency: 'GBP', expected: '11.99 GBP'}, + {amount: '-0.5', currency: 'EUR', expected: '-0.50 EUR'}, + {amount: '0', currency: 'JPY', expected: '0.00 JPY'}, + {amount: '12.50', currency: '', expected: '1250'}, + {amount: '0.10', currency: '', expected: '10'}, + {amount: '', currency: 'USD', expected: ''}, + ])('serializes $amount with currency $currency as $expected', ({amount, currency, expected}) => { + // Given an amount entered in major units and an optional comparison currency. + // When the editor prepares the operand for its filter form. + const value = formatAmountFilterValue(amount, currency); + + // Then qualified operands use decimal major units, while bare operands remain hundredths. + expect(value).toBe(expected); + }); + + it.each([ + {value: '1250', amount: '12.50', currency: undefined}, + {value: '10', amount: '0.10', currency: undefined}, + {value: '11.99 GBP', amount: '11.99', currency: 'GBP'}, + {value: '-0.50 EUR', amount: '-0.50', currency: 'EUR'}, + {value: '0.00 JPY', amount: '0.00', currency: 'JPY'}, + ])('reopens $value without changing its units', ({value, amount, currency}) => { + // Given a saved legacy or currency-qualified operand. + // When the editor reopens it. + const input = getAmountFilterInputValue(value); + + // Then both the visible amount and currency survive another save. + expect(input).toEqual({amount, ...(currency ? {currency} : {})}); + expect(formatAmountFilterValue(input.amount, input.currency)).toBe(value); + }); + + it('formats the number in the local locale without dropping its currency', () => { + // Given a qualified operand and a formatter that expects hundredths. + const formatAmount = jest.fn((amount: number) => (amount / 100).toFixed(2).replace('.', ',')); + + // When its filter label is formatted. + const label = getAmountFilterDisplayValue('11.99 GBP', formatAmount); + + // Then the amount is localized once and the comparison currency stays visible. + expect(formatAmount).toHaveBeenCalledWith(1199); + expect(label).toBe('11,99 GBP'); + }); + + it('only offers FX currencies for amount and purchase amount', () => { + // Given every amount-like search field. + const keys = CONST.SEARCH.SYNTAX_FILTER_KEYS; + + // When checking whether to show its currency picker. + const supported = [keys.AMOUNT, keys.PURCHASE_AMOUNT, keys.TOTAL, keys.AMOUNT_DEBITED, keys.AMOUNT_REIMBURSED].filter(supportsAmountFilterCurrency); + + // Then report totals and reimbursement fields keep their existing behavior. + expect(supported).toEqual([keys.AMOUNT, keys.PURCHASE_AMOUNT]); + }); + + it('does not reinterpret malformed qualified amounts as numeric input', () => { + // Given a value whose currency or amount does not follow the backend contract. + const value = '12.001 USD'; + + // When parsing it for validation. + const parsed = parseAmountFilterValue(value); + + // Then the full invalid value remains available to the existing amount validator. + expect(parsed).toEqual({amount: value}); + }); +}); diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 19d33503740a..473b9283667e 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -77,6 +77,84 @@ import {formatPhoneNumber, localeCompare, translateLocal} from '../../utils/Test const mockGetRootState = jest.fn(); +describe('currency-qualified amount filters', () => { + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('round-trips Any currency for %s using the legacy request format', (filterKey) => { + // Given an Any currency operand already expressed in legacy hundredths. + const form: Partial = {type: CONST.SEARCH.DATA_TYPES.EXPENSE, [`${filterKey}EqualTo`]: '10'}; + + // When the filter becomes a backend query and is reopened. + const query = buildFilterQueryWithSortDefaults(form, {}, {}) ?? ''; + const queryJSON = buildSearchQueryJSON(getQueryWithUpdatedValues(query, true) ?? ''); + if (!queryJSON) { + throw new Error('Expected the legacy amount query to parse'); + } + const reopenedForm = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); + + // Then the request has a bare operand and reopening does not add a currency or rescale it. + expect(query).toContain(`${filterKey}:10`); + expect(serializeQueryJSONForBackend(queryJSON)).toContain('"right":"10"'); + expect(reopenedForm).toMatchObject({[`${filterKey}EqualTo`]: '10'}); + expect(buildQueryStringFromFilterFormValues(reopenedForm)).toContain(`${filterKey}:10`); + }); + + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('round-trips the selected currency for %s', (filterKey) => { + // Given a bare amount in the current query and a currency selected in its filter editor. + const currentQuery = buildSearchQueryJSON(`type:expense ${filterKey}:1199 total:1250`); + const form: Partial = {type: CONST.SEARCH.DATA_TYPES.EXPENSE, [`${filterKey}EqualTo`]: '11.99 GBP', totalEqualTo: '1250'}; + + // When the form becomes a backend query and is reopened from that query. + const query = buildFilterQueryWithSortDefaults(form, {}, currentQuery ?? {}) ?? ''; + const updatedQuery = getQueryWithUpdatedValues(query, true); + const queryJSON = buildSearchQueryJSON(updatedQuery ?? ''); + if (!queryJSON) { + throw new Error('Expected the currency-qualified query to parse'); + } + const reopenedForm = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); + + // Then the currency stays quoted, major units are not multiplied by 100, and legacy totals stay in hundredths. + expect(query).toContain(`${filterKey}:"11.99 GBP"`); + expect(serializeQueryJSONForBackend(queryJSON)).toContain('"right":"11.99 GBP"'); + expect(reopenedForm).toMatchObject({[`${filterKey}EqualTo`]: '11.99 GBP', totalEqualTo: '1250'}); + expect(buildQueryStringFromFilterFormValues(reopenedForm)).toContain(`${filterKey}:"11.99 GBP"`); + }); + + it('preserves currencies on both range bounds and on negated purchase amounts', () => { + // Given a range whose bounds have their own currencies, plus a negated purchase amount. + const form: Partial = { + type: CONST.SEARCH.DATA_TYPES.EXPENSE, + amountGreaterThan: '10.00 USD', + amountLessThan: '20.00 GBP', + purchaseAmountNot: '-3.00 EUR', + }; + + // When the query is serialized and parsed back into filter form values. + const query = buildQueryStringFromFilterFormValues(form); + const queryJSON = buildSearchQueryJSON(query); + if (!queryJSON) { + throw new Error('Expected the currency-qualified range to parse'); + } + const reopenedForm = buildFilterFormValuesFromQuery(queryJSON, {}, {}, {}, {}, {}, {}); + + // Then each operand retains its amount, currency, and operator. + expect(query).toContain('amount>"10.00 USD" amount<"20.00 GBP"'); + expect(query).toContain('-purchaseAmount:"-3.00 EUR"'); + expect(reopenedForm).toMatchObject(form); + }); + + it('converts bare user-entered amounts but leaves qualified amounts in major units', () => { + // Given a typed query mixing qualified and legacy amounts. + const query = 'amount:"11.99 GBP" purchase-amount:"-3.00 EUR" total:12.50'; + + // When the search input prepares its operands for the backend. + const updatedQuery = getQueryWithUpdatedValues(query); + + // Then only the bare amount is converted to hundredths. + expect(updatedQuery).toContain('amount:"11.99 GBP"'); + expect(updatedQuery).toContain('purchaseAmount:"-3.00 EUR"'); + expect(updatedQuery).toContain('total:1250'); + }); +}); + jest.mock('@expensify/react-native-hybrid-app', () => ({ __esModule: true, default: { diff --git a/tests/unit/Search/SearchUIUtils.test.ts b/tests/unit/Search/SearchUIUtils.test.ts index da6f979d8bb2..72b088b2054c 100644 --- a/tests/unit/Search/SearchUIUtils.test.ts +++ b/tests/unit/Search/SearchUIUtils.test.ts @@ -4,10 +4,11 @@ import type {TransactionCategoryGroupListItemType, TransactionMonthGroupListItem import type {SearchQueryJSON} from '@components/Search/types'; import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; -import {getSections, getSortedTransactionData, isTransactionCategoryGroupListItemType, isTransactionMonthGroupListItemType} from '@libs/SearchUIUtils'; +import {getSections, getSortedTransactionData, isTransactionCategoryGroupListItemType, isTransactionMonthGroupListItemType, mapFiltersFormToLabelValueList} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import type {TranslationParameters, TranslationPaths} from '@src/languages/types'; +import type {SearchAdvancedFiltersForm} from '@src/types/form'; import type SearchResults from '@src/types/onyx/SearchResults'; import {buildTransactionRow} from '../../utils/collections/searchListItems'; @@ -39,6 +40,17 @@ const buildGroupedQueryJSON = (groupBy: SearchQueryJSON['groupBy'], sortBy: Sear }; describe('SearchUIUtils', () => { + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('shows the currency in the %s filter chip', (key) => { + // Given a qualified amount in the advanced filters form. + const form: Partial = {type: CONST.SEARCH.DATA_TYPES.EXPENSE, [`${key}EqualTo`]: '12.00 USD'}; + + // When filter chips format their values with a localized hundredths formatter. + const filters = mapFiltersFormToLabelValueList(form, new Set(), undefined, translate, undefined, localeCompare, (amount) => (amount / 100).toFixed(2)); + + // Then the chip shows the comparison currency instead of NaN or a hundredfold amount. + expect(filters).toContainEqual(expect.objectContaining({key, value: 'search.filters.amount.equalTo:12.00 USD'})); + }); + it('resets grouped child queries to date-desc sorting', () => { const queryJSON = buildGroupedQueryJSON(CONST.SEARCH.GROUP_BY.CATEGORY, CONST.SEARCH.TABLE_COLUMNS.GROUP_CATEGORY); const data = createMock({}); diff --git a/tests/unit/getAmountFilterInputKeyboardTest.ts b/tests/unit/getAmountFilterInputKeyboardTest.ts new file mode 100644 index 000000000000..f723be0572d7 --- /dev/null +++ b/tests/unit/getAmountFilterInputKeyboardTest.ts @@ -0,0 +1,32 @@ +import getNativeAmountFilterInputKeyboard from '@libs/getAmountFilterInputKeyboard/index.native'; +import type getAmountFilterInputKeyboard from '@libs/getAmountFilterInputKeyboard/index.ts'; +import getAmountInputKeyboard from '@libs/getAmountInputKeyboard'; + +import CONST from '@src/CONST'; + +const getWebAmountFilterInputKeyboard = jest.requireActual<{default: typeof getAmountFilterInputKeyboard}>('@libs/getAmountFilterInputKeyboard/index.ts').default; + +jest.mock('@libs/getAmountInputKeyboard', () => jest.fn()); + +describe('getAmountFilterInputKeyboard', () => { + it('uses the default decimal input mode and a sign button on web', () => { + // Given web keyboards that do not support the native numbers-and-punctuation layout. + // When the filter chooses its amount controls. + const props = getWebAmountFilterInputKeyboard(); + + // Then NumberWithSymbolForm keeps its decimal input mode and exposes Flip for negative amounts. + expect(props).toEqual({keyboardType: undefined, shouldShowFlipButton: true}); + }); + + it.each([CONST.KEYBOARD_TYPE.DECIMAL_PAD, CONST.KEYBOARD_TYPE.NUMBERS_AND_PUNCTUATION])('keeps the native %s keyboard without adding a sign button', (keyboardType) => { + // Given the existing native keyboard selection for signed amounts. + jest.mocked(getAmountInputKeyboard).mockReturnValue({keyboardType, inputMode: undefined}); + + // When an amount filter requests its keyboard controls. + const props = getNativeAmountFilterInputKeyboard(); + + // Then native platforms retain their current keyboard and direct minus entry. + expect(getAmountInputKeyboard).toHaveBeenCalledWith(true); + expect(props).toEqual({keyboardType, inputMode: undefined, shouldShowFlipButton: false}); + }); +});