From e7ba77e23ee75686cf4f4195f3aae0cfda53b960 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Thu, 22 Oct 2026 16:16:28 -0600 Subject: [PATCH 1/9] Add optional currencies to amount search filters --- src/components/CurrencyPicker.tsx | 18 +++ .../AdvancedFilters/AmountFilterContent.tsx | 132 +++++++++++------- .../Search/FilterDropdowns/AmountPopup.tsx | 36 +++-- src/libs/SearchAmountFilterUtils.ts | 49 +++++++ src/libs/SearchQueryUtils.ts | 39 +++--- src/libs/SearchUIUtils.ts | 3 +- tests/unit/Search/AmountFilterContentTest.tsx | 89 ++++++++++++ .../Search/SearchAmountFilterUtilsTest.ts | 71 ++++++++++ tests/unit/Search/SearchQueryUtilsTest.ts | 59 ++++++++ tests/unit/Search/SearchUIUtils.test.ts | 14 +- 10 files changed, 431 insertions(+), 79 deletions(-) create mode 100644 src/libs/SearchAmountFilterUtils.ts create mode 100644 tests/unit/Search/AmountFilterContentTest.tsx create mode 100644 tests/unit/Search/SearchAmountFilterUtilsTest.ts diff --git a/src/components/CurrencyPicker.tsx b/src/components/CurrencyPicker.tsx index e4c33a8abedc..a43a6e917cde 100644 --- a/src/components/CurrencyPicker.tsx +++ b/src/components/CurrencyPicker.tsx @@ -51,6 +51,9 @@ type CurrencyPickerProps = { /** Should show the full page offline view (whenever the user is offline) */ shouldShowFullPageOfflineView?: boolean; + + /** Whether the picker includes an option to clear the selected currency. */ + shouldAllowEmptySelection?: boolean; }; function CurrencyPicker({ @@ -64,6 +67,7 @@ function CurrencyPicker({ excludeCurrencies, disabled = false, shouldShowFullPageOfflineView = false, + shouldAllowEmptySelection = false, onInputChange = () => {}, }: CurrencyPickerProps) { const {translate} = useLocalize(); @@ -128,6 +132,20 @@ function CurrencyPicker({ /> {!!headerContent && headerContent} + {shouldAllowEmptySelection && ( + { + onInputChange(''); + hidePickerModal(); + }} + > + + + {translate('common.none')} + + + + )} (null); useImperativeHandle(ref, () => ({ getValue: () => { const key = `${baseFilterKey}${modifier}`; - return {[key]: getBackendAmount(amount)}; + return {[key]: formatAmountFilterValue(amount, currency)}; }, })); @@ -79,17 +75,28 @@ function AmountInput({ref, baseFilterKey, modifier, value, label, autoFocus}: Am }, [didScreenTransitionEnd, autoFocus]); return ( - + <> + + {supportsAmountFilterCurrency(baseFilterKey) && ( + + )} + ); } @@ -104,8 +111,12 @@ type AmountBetweenInputProps = { function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue, autoFocus}: AmountBetweenInputProps) { const {translate} = useLocalize(); 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 [greaterThanCurrency, setGreaterThanCurrency] = useState(initialGreaterThan.currency); + const [lessThanCurrency, setLessThanCurrency] = useState(initialLessThan.currency); const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus(); const inputRef = useRef(null); @@ -113,7 +124,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), + }; }, })); @@ -129,27 +143,47 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue return ( - - + + + {supportsAmountFilterCurrency(baseFilterKey) && ( + + )} + + + + {supportsAmountFilterCurrency(baseFilterKey) && ( + + )} + ); } @@ -241,8 +275,8 @@ function AmountFilterContent({baseFilterKey, value, autoFocus, buttonSize, style ) : ( @@ -250,7 +284,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/FilterDropdowns/AmountPopup.tsx b/src/components/Search/FilterDropdowns/AmountPopup.tsx index 3527f1f904eb..7fa56e5453d4 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 CurrencyPicker from '@components/CurrencyPicker'; import MenuItem from '@components/MenuItem'; import type {SearchAmountFilterKeys, SearchAmountValues} from '@components/Search/types'; 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, supportsAmountFilterCurrency} from '@libs/SearchAmountFilterUtils'; import CONST from '@src/CONST'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; @@ -28,25 +30,29 @@ type AmountInputProps = { title: string; value: string; name: string; + shouldShowCurrencyPicker: boolean; onSave: (value: string) => void; onBackButtonPress: () => void; }; -function AmountInput({title, value, name, onSave, onBackButtonPress}: AmountInputProps) { +function AmountInput({title, value, name, shouldShowCurrencyPicker, onSave, onBackButtonPress}: AmountInputProps) { const styles = useThemeStyles(); - const [amount, setAmount] = useState(value); + const {translate} = useLocalize(); + const initialValue = getAmountFilterInputValue(value); + const [amount, setAmount] = useState(initialValue.amount); + const [currency, setCurrency] = useState(initialValue.currency); return ( onSave(amount)} + onApply={() => onSave(formatAmountFilterValue(amount, currency))} applySentryLabel={CONST.SENTRY_LABEL.SEARCH.FILTER_POPUP_APPLY_AMOUNT} onBackButtonPress={onBackButtonPress} shouldSubmitOnEnter > + {shouldShowCurrencyPicker && ( + + )} ); } @@ -74,7 +89,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 +97,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 +119,9 @@ function AmountPopup({baseFilterKey, label, value, closeOverlay, updateFilterFor return ( diff --git a/src/libs/SearchAmountFilterUtils.ts b/src/libs/SearchAmountFilterUtils.ts new file mode 100644 index 000000000000..0fd0e41d6946 --- /dev/null +++ b/src/libs/SearchAmountFilterUtils.ts @@ -0,0 +1,49 @@ +// Amount filters store bare hundredths or decimal major units followed by a comparison currency. +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; +} + +/** Separates a qualified decimal operand without changing legacy hundredths. */ +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}; +} + +/** Returns the major-unit amount and optional currency used by the editor. */ +function getAmountFilterInputValue(value?: string): AmountFilterValue { + const parsed = parseAmountFilterValue(value); + return parsed.currency ? parsed : {amount: parsed.amount ? convertToFrontendAmountAsString(Number(parsed.amount), CONST.DEFAULT_CURRENCY_DECIMALS) : ''}; +} + +/** Serializes editor values in the units expected by currency-qualified and legacy operands. */ +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(); +} + +/** Formats either operand using the caller's localized hundredths formatter. */ +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 a948d185a6f2..09f361e7cfa6 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -75,6 +75,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'; @@ -621,19 +622,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(' '); @@ -2023,23 +2024,27 @@ 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; + } + + 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 a4240970d8a6..516e8ed8fd21 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -204,6 +204,7 @@ import { isSettled, shouldReportShowSubscript, } from './ReportUtils'; +import {getAmountFilterDisplayValue} from './SearchAmountFilterUtils'; import { buildSearchQueryJSON, buildSearchQueryString, @@ -5949,7 +5950,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/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx new file mode 100644 index 000000000000..d6f096d50d31 --- /dev/null +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -0,0 +1,89 @@ +import {act, fireEvent, render, screen} from '@testing-library/react-native'; + +import CurrencyPicker from '@components/CurrencyPicker'; +import AmountFilterContent from '@components/Search/FilterComponents/AdvancedFilters/AmountFilterContent'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +jest.mock('@components/CurrencyPicker', () => jest.fn(() => null)); +jest.mock('@components/AmountWithoutCurrencyInput', () => jest.fn(() => null)); +jest.mock('@hooks/useScreenWrapperTransitionStatus', () => () => ({didScreenTransitionEnd: true})); +jest.mock('@hooks/useShouldFooterBeInsideList', () => () => false); + +describe('AmountFilterContent currency selection', () => { + 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 opened in either supported filter. + const onChange = jest.fn(); + render( + , + ); + + // When a currency is selected and the filter is confirmed. + act(() => jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].onInputChange?.('USD')); + 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('clears the currency without changing the entered amount', () => { + // Given a saved currency-qualified amount. + const onChange = jest.fn(); + render( + , + ); + + // When the picker clears its selection and the filter is confirmed. + expect(jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].shouldAllowEmptySelection).toBe(true); + act(() => jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].onInputChange?.('')); + fireEvent.press(screen.getByRole('button')); + + // Then the amount returns to the original bare hundredths format. + expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); + }); + + it('preserves the currency on each side of a between filter', () => { + // Given two bounds saved in different comparison currencies. + const onChange = jest.fn(); + render( + , + ); + + // When the range is reopened and confirmed without changes. + 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('does not offer currency selection for report totals', () => { + // Given an amount-like filter that does not support FX comparisons. + jest.mocked(CurrencyPicker).mockClear(); + + // When its existing editor is rendered. + render( + , + ); + + // Then its UI does not gain a currency picker. + expect(CurrencyPicker).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/Search/SearchAmountFilterUtilsTest.ts b/tests/unit/Search/SearchAmountFilterUtilsTest.ts new file mode 100644 index 000000000000..045190cded30 --- /dev/null +++ b/tests/unit/Search/SearchAmountFilterUtilsTest.ts @@ -0,0 +1,71 @@ +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: '', 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: '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 0c9e395e01c4..38a3fdf3387c 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -79,6 +79,65 @@ 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 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({}); From 54117c2fa617d63533168f1d45575a8721e2472c Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Fri, 23 Oct 2026 12:19:57 -0600 Subject: [PATCH 2/9] Reuse money request picker for amount filters --- src/components/CurrencyPicker.tsx | 18 ---- .../AdvancedFilters/AmountFilterContent.tsx | 98 ++++++------------- .../FilterComponents/AmountFilterInput.tsx | 97 ++++++++++++++++++ .../Search/FilterDropdowns/AmountPopup.tsx | 34 +++---- .../step/IOURequestStepCurrencyModal.tsx | 28 +++++- tests/unit/Search/AmountFilterContentTest.tsx | 83 ++++++++++++++-- 6 files changed, 241 insertions(+), 117 deletions(-) create mode 100644 src/components/Search/FilterComponents/AmountFilterInput.tsx diff --git a/src/components/CurrencyPicker.tsx b/src/components/CurrencyPicker.tsx index a43a6e917cde..e4c33a8abedc 100644 --- a/src/components/CurrencyPicker.tsx +++ b/src/components/CurrencyPicker.tsx @@ -51,9 +51,6 @@ type CurrencyPickerProps = { /** Should show the full page offline view (whenever the user is offline) */ shouldShowFullPageOfflineView?: boolean; - - /** Whether the picker includes an option to clear the selected currency. */ - shouldAllowEmptySelection?: boolean; }; function CurrencyPicker({ @@ -67,7 +64,6 @@ function CurrencyPicker({ excludeCurrencies, disabled = false, shouldShowFullPageOfflineView = false, - shouldAllowEmptySelection = false, onInputChange = () => {}, }: CurrencyPickerProps) { const {translate} = useLocalize(); @@ -132,20 +128,6 @@ function CurrencyPicker({ /> {!!headerContent && headerContent} - {shouldAllowEmptySelection && ( - { - onInputChange(''); - hidePickerModal(); - }} - > - - - {translate('common.none')} - - - - )} - - {supportsAmountFilterCurrency(baseFilterKey) && ( - - )} - + ); } @@ -143,47 +129,25 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue return ( - - - {supportsAmountFilterCurrency(baseFilterKey) && ( - - )} - - - - {supportsAmountFilterCurrency(baseFilterKey) && ( - - )} - + + ); } diff --git a/src/components/Search/FilterComponents/AmountFilterInput.tsx b/src/components/Search/FilterComponents/AmountFilterInput.tsx new file mode 100644 index 000000000000..5a715f3f1231 --- /dev/null +++ b/src/components/Search/FilterComponents/AmountFilterInput.tsx @@ -0,0 +1,97 @@ +// 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 getAmountInputKeyboard from '@libs/getAmountInputKeyboard'; +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: string; + 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} = getAmountInputKeyboard(true); + + 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 7fa56e5453d4..d9b7763adaf7 100644 --- a/src/components/Search/FilterDropdowns/AmountPopup.tsx +++ b/src/components/Search/FilterDropdowns/AmountPopup.tsx @@ -1,13 +1,12 @@ -import AmountWithoutCurrencyInput from '@components/AmountWithoutCurrencyInput'; -import CurrencyPicker from '@components/CurrencyPicker'; import MenuItem from '@components/MenuItem'; +import AmountFilterInput from '@components/Search/FilterComponents/AmountFilterInput'; import type {SearchAmountFilterKeys, SearchAmountValues} from '@components/Search/types'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import {convertToFrontendAmountAsString} from '@libs/CurrencyUtils'; -import {formatAmountFilterValue, getAmountFilterDisplayValue, getAmountFilterInputValue, supportsAmountFilterCurrency} from '@libs/SearchAmountFilterUtils'; +import {formatAmountFilterValue, getAmountFilterDisplayValue, getAmountFilterInputValue} from '@libs/SearchAmountFilterUtils'; import CONST from '@src/CONST'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; @@ -30,14 +29,13 @@ type AmountInputProps = { title: string; value: string; name: string; - shouldShowCurrencyPicker: boolean; + baseFilterKey: SearchAmountFilterKeys; onSave: (value: string) => void; onBackButtonPress: () => void; }; -function AmountInput({title, value, name, shouldShowCurrencyPicker, onSave, onBackButtonPress}: AmountInputProps) { +function AmountInput({title, value, name, baseFilterKey, onSave, onBackButtonPress}: AmountInputProps) { const styles = useThemeStyles(); - const {translate} = useLocalize(); const initialValue = getAmountFilterInputValue(value); const [amount, setAmount] = useState(initialValue.amount); const [currency, setCurrency] = useState(initialValue.currency); @@ -50,27 +48,17 @@ function AmountInput({title, value, name, shouldShowCurrencyPicker, onSave, onBa onBackButtonPress={onBackButtonPress} shouldSubmitOnEnter > - - {shouldShowCurrencyPicker && ( - - )} ); } @@ -121,7 +109,7 @@ function AmountPopup({baseFilterKey, label, value, closeOverlay, updateFilterFor title={title[selectedModifier]} value={amountValues[selectedModifier] ?? ''} name={`${baseFilterKey}${selectedModifier}`} - shouldShowCurrencyPicker={supportsAmountFilterCurrency(baseFilterKey)} + baseFilterKey={baseFilterKey} onBackButtonPress={goBack} onSave={save} /> diff --git a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx index f97ea363bdf7..004d0abb262f 100644 --- a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx +++ b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx @@ -1,6 +1,7 @@ import CurrencySelectionList from '@components/CurrencySelectionList'; import type {CurrencyListItem} from '@components/CurrencySelectionList/types'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; +import MenuItem from '@components/MenuItem'; import Modal from '@components/Modal'; import ScreenWrapper from '@components/ScreenWrapper'; @@ -25,9 +26,20 @@ type CurrencyPickerProps = { onInputChange?: (value: string, key?: string) => void; excludeCurrencies?: string[]; + + /** Whether the picker includes an option to clear the selected currency. */ + shouldAllowEmptySelection?: boolean; }; -function IOURequestStepCurrencyModal({isPickerVisible, hidePickerModal, headerText, value, excludeCurrencies, onInputChange = () => {}}: CurrencyPickerProps) { +function IOURequestStepCurrencyModal({ + isPickerVisible, + hidePickerModal, + headerText, + value, + excludeCurrencies, + shouldAllowEmptySelection = false, + onInputChange = () => {}, +}: CurrencyPickerProps) { const {translate} = useLocalize(); const [recentlyUsedCurrencies] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES); const styles = useThemeStyles(); @@ -60,6 +72,20 @@ function IOURequestStepCurrencyModal({isPickerVisible, hidePickerModal, headerTe shouldShowBackButton onBackButtonPress={hidePickerModal} /> + {shouldAllowEmptySelection && ( + { + onInputChange(''); + hidePickerModal(); + }} + > + + + {translate('common.none')} + + + + )} jest.fn(() => null)); +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); +beforeEach(() => jest.clearAllMocks()); + describe('AmountFilterContent currency selection', () => { 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 opened in either supported filter. @@ -24,8 +32,14 @@ describe('AmountFilterContent currency selection', () => { />, ); - // When a currency is selected and the filter is confirmed. - act(() => jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].onInputChange?.('USD')); + // 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', 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. @@ -44,14 +58,35 @@ describe('AmountFilterContent currency selection', () => { ); // When the picker clears its selection and the filter is confirmed. - expect(jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].shouldAllowEmptySelection).toBe(true); - act(() => jest.mocked(CurrencyPicker).mock.calls.at(-1)?.[0].onInputChange?.('')); + 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 amount returns to the original bare hundredths format. expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); }); + it('keeps the saved operand when the currency picker is dismissed', () => { + // Given an existing USD amount in the filter editor. + 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('preserves the currency on each side of a between filter', () => { // Given two bounds saved in different comparison currencies. const onChange = jest.fn(); @@ -64,6 +99,7 @@ describe('AmountFilterContent currency selection', () => { ); // 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. @@ -72,7 +108,6 @@ describe('AmountFilterContent currency selection', () => { it('does not offer currency selection for report totals', () => { // Given an amount-like filter that does not support FX comparisons. - jest.mocked(CurrencyPicker).mockClear(); // When its existing editor is rendered. render( @@ -84,6 +119,38 @@ describe('AmountFilterContent currency selection', () => { ); // Then its UI does not gain a currency picker. - expect(CurrencyPicker).not.toHaveBeenCalled(); + expect(IOURequestStepCurrencyModal).not.toHaveBeenCalled(); + expect(NumberWithSymbolForm).not.toHaveBeenCalled(); + }); +}); + +describe('AmountPopup currency selection', () => { + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('uses the money-request picker for the %s popup', (baseFilterKey) => { + // 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 equal-to editor selects USD using the shared picker 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?.('USD')); + 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 same decimal-major-unit operand as advanced filters. + expect(updateFilterForm).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: '12.00 USD', [`${baseFilterKey}GreaterThan`]: '', [`${baseFilterKey}LessThan`]: ''}); }); }); From 3cc64d841540bfe243a0d6358136eba5e52dce33 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Fri, 23 Oct 2026 13:09:11 -0600 Subject: [PATCH 3/9] Default new amount filters to policy currency --- .../AdvancedFilters/AmountFilterContent.tsx | 7 +- .../Search/FilterDropdowns/AmountPopup.tsx | 3 +- src/hooks/useAmountFilterCurrency.ts | 23 +++ tests/unit/Search/AmountFilterContentTest.tsx | 174 +++++++++++++++++- 4 files changed, 194 insertions(+), 13 deletions(-) create mode 100644 src/hooks/useAmountFilterCurrency.ts diff --git a/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx index b6e83106c990..4a6509a91c51 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx @@ -6,6 +6,7 @@ import SingleSelectListItem from '@components/SelectionList/ListItem/SingleSelec import type {ListItem} from '@components/SelectionList/types'; import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types'; +import useAmountFilterCurrency from '@hooks/useAmountFilterCurrency'; import useLocalize from '@hooks/useLocalize'; import useScreenWrapperTransitionStatus from '@hooks/useScreenWrapperTransitionStatus'; import useShouldFooterBeInsideList from '@hooks/useShouldFooterBeInsideList'; @@ -54,7 +55,7 @@ function AmountInput({ref, baseFilterKey, modifier, value, label, autoFocus}: Am const styles = useThemeStyles(); const initialValue = getAmountFilterInputValue(value); const [amount, setAmount] = useState(initialValue.amount); - const [currency, setCurrency] = useState(initialValue.currency); + const {currency, setCurrency} = useAmountFilterCurrency(baseFilterKey, value); const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus(); const inputRef = useRef(null); @@ -101,8 +102,8 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue const initialLessThan = getAmountFilterInputValue(lessThanValue); const [greaterThanAmount, setGreaterThanAmount] = useState(initialGreaterThan.amount); const [lessThanAmount, setLessThanAmount] = useState(initialLessThan.amount); - const [greaterThanCurrency, setGreaterThanCurrency] = useState(initialGreaterThan.currency); - const [lessThanCurrency, setLessThanCurrency] = useState(initialLessThan.currency); + const {currency: greaterThanCurrency, setCurrency: setGreaterThanCurrency} = useAmountFilterCurrency(baseFilterKey, greaterThanValue); + const {currency: lessThanCurrency, setCurrency: setLessThanCurrency} = useAmountFilterCurrency(baseFilterKey, lessThanValue); const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus(); const inputRef = useRef(null); diff --git a/src/components/Search/FilterDropdowns/AmountPopup.tsx b/src/components/Search/FilterDropdowns/AmountPopup.tsx index d9b7763adaf7..8e7abb2f67ab 100644 --- a/src/components/Search/FilterDropdowns/AmountPopup.tsx +++ b/src/components/Search/FilterDropdowns/AmountPopup.tsx @@ -2,6 +2,7 @@ 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'; @@ -38,7 +39,7 @@ function AmountInput({title, value, name, baseFilterKey, onSave, onBackButtonPre const styles = useThemeStyles(); const initialValue = getAmountFilterInputValue(value); const [amount, setAmount] = useState(initialValue.amount); - const [currency, setCurrency] = useState(initialValue.currency); + const {currency, setCurrency} = useAmountFilterCurrency(baseFilterKey, value); return ( (); + 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/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx index 870f2ecfa7c8..a4f13f124387 100644 --- a/tests/unit/Search/AmountFilterContentTest.tsx +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -1,28 +1,39 @@ -import {act, fireEvent, render, screen} from '@testing-library/react-native'; +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 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)); -beforeEach(() => jest.clearAllMocks()); +beforeEach(() => { + jest.clearAllMocks(); + jest.mocked(useDefaultExpensePolicy).mockReturnValue(undefined); +}); describe('AmountFilterContent currency selection', () => { 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 opened in either supported filter. + // 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', shouldShowCurrencyButton: true, allowNegativeInput: true}); + 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(() => { @@ -46,8 +57,59 @@ describe('AmountFilterContent currency selection', () => { 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('clears the currency without changing the entered amount', () => { - // Given a saved currency-qualified amount. + // Given a saved currency-qualified amount and a GBP workspace default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); const onChange = jest.fn(); render( { }); it('keeps the saved operand when the currency picker is dismissed', () => { - // Given an existing USD amount in the filter editor. + // Given an existing USD amount and a different workspace default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'GBP'})); const onChange = jest.fn(); render( { 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 bounds saved in different comparison currencies. + // Given two saved currencies that differ from the policy default. + jest.mocked(useDefaultExpensePolicy).mockReturnValue(createMock({outputCurrency: 'EUR'})); const onChange = jest.fn(); render( { }); it('does not offer currency selection for report totals', () => { - // Given an amount-like filter that does not support FX comparisons. + // 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([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('uses the money-request picker for the %s popup', (baseFilterKey) => { // Given a quick filter popup holding a bare amount. const updateFilterForm = jest.fn(); @@ -154,3 +278,35 @@ describe('AmountPopup currency selection', () => { expect(updateFilterForm).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: '12.00 USD', [`${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 None 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'); + }); +}); From 3eb09a786489b796ad32c086176316c64bdf2024 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Mon, 26 Oct 2026 13:07:08 -0600 Subject: [PATCH 4/9] Show Any currency in amount search filters --- .../FilterComponents/AmountFilterInput.tsx | 4 +- src/languages/de.ts | 1 + src/languages/el.ts | 1 + src/languages/en.ts | 1 + src/languages/es.ts | 1 + src/languages/fr.ts | 1 + src/languages/it.ts | 1 + src/languages/ja.ts | 1 + src/languages/nl.ts | 1 + src/languages/pl.ts | 1 + src/languages/pt-BR.ts | 1 + src/languages/zh-hans.ts | 1 + .../step/IOURequestStepCurrencyModal.tsx | 2 +- tests/ui/IOURequestStepCurrencyModalTest.tsx | 53 ++++++++++++++++++ tests/unit/Search/AmountFilterContentTest.tsx | 56 +++++++++++++++---- .../Search/SearchAmountFilterUtilsTest.ts | 2 + tests/unit/Search/SearchQueryUtilsTest.ts | 19 +++++++ 17 files changed, 132 insertions(+), 15 deletions(-) create mode 100644 tests/ui/IOURequestStepCurrencyModalTest.tsx diff --git a/src/components/Search/FilterComponents/AmountFilterInput.tsx b/src/components/Search/FilterComponents/AmountFilterInput.tsx index 5a715f3f1231..313a775e47c5 100644 --- a/src/components/Search/FilterComponents/AmountFilterInput.tsx +++ b/src/components/Search/FilterComponents/AmountFilterInput.tsx @@ -75,8 +75,8 @@ function AmountFilterInput({ref, baseFilterKey, amount, currency, label, name, a allowNegativeInput keyboardType={keyboardType} shouldShowCurrencyButton - currencyButtonLabel={currency || translate('common.none')} - currencyButtonAccessibilityLabel={[label, translate('common.selectCurrency'), currency || translate('common.none')].join(', ')} + currencyButtonLabel={currency || translate('common.anyCurrency')} + currencyButtonAccessibilityLabel={[label, translate('common.selectCurrency'), currency || translate('common.anyCurrency')].join(', ')} onCurrencyButtonPress={() => setIsCurrencyPickerVisible(true)} shouldShowBigNumberPad={false} shouldUseBorderlessButtons diff --git a/src/languages/de.ts b/src/languages/de.ts index e20973762420..46e18caaaabf 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Wird noch festgelegt', selectCurrency: 'Wähle eine Währung', + 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 db4339ca360a..e327c57ac696 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -335,6 +335,7 @@ const translations: TranslationDeepObject = { pm: 'μ.μ.', tbd: 'Θα καθοριστεί', selectCurrency: 'Επιλέξτε νόμισμα', + anyCurrency: 'Οποιοδήποτε νόμισμα', selectSymbolOrCurrency: 'Επιλέξτε ένα σύμβολο ή νόμισμα', card: 'Κάρτα', mcc: 'MCC', diff --git a/src/languages/en.ts b/src/languages/en.ts index 092989ece971..65a78756b387 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -412,6 +412,7 @@ 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', + 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 da7bfb5a7ea6..6d532997e94f 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -324,6 +324,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Por determinar', selectCurrency: 'Selecciona una moneda', + 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 0b2681f3d3ad..5a77a9c6695d 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'À déterminer', selectCurrency: 'Sélectionner une devise', + 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 794a3567154d..e1f6b15f89d4 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Da definire', selectCurrency: 'Seleziona una valuta', + 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 ce0377972968..571cd7642ca8 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: '午後', tbd: '未定', selectCurrency: '通貨を選択', + anyCurrency: 'すべての通貨', selectSymbolOrCurrency: '記号または通貨を選択', card: 'カード', mcc: 'MCC', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index afabae980554..bdd5eff7ecad 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Nader te bepalen', selectCurrency: 'Selecteer een valuta', + 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 2c829ff16a00..eccb759bfb3d 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -336,6 +336,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Do ustalenia', selectCurrency: 'Wybierz walutę', + 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 61089c6fae54..34268cffff98 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'A definir', selectCurrency: 'Selecione uma moeda', + 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 4f8f4379ce45..032efaf73c66 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: '下午', tbd: '待定', selectCurrency: '选择货币', + anyCurrency: '任意货币', selectSymbolOrCurrency: '选择符号或货币', card: '卡片', mcc: 'MCC', diff --git a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx index 004d0abb262f..9c82792e51df 100644 --- a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx +++ b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx @@ -81,7 +81,7 @@ function IOURequestStepCurrencyModal({ > - {translate('common.none')} + {translate('common.anyCurrency')} diff --git a/tests/ui/IOURequestStepCurrencyModalTest.tsx b/tests/ui/IOURequestStepCurrencyModalTest.tsx new file mode 100644 index 000000000000..5a9137c25785 --- /dev/null +++ b/tests/ui/IOURequestStepCurrencyModalTest.tsx @@ -0,0 +1,53 @@ +import {fireEvent, render, screen} from '@testing-library/react-native'; + +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'})); + +describe('IOURequestStepCurrencyModal', () => { + 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. + fireEvent.press(screen.getByText('common.anyCurrency'), {nativeEvent: {}}); + + // 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(screen.queryByText('common.anyCurrency')).toBeNull(); + }); +}); diff --git a/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx index a4f13f124387..f68b1ff767ea 100644 --- a/tests/unit/Search/AmountFilterContentTest.tsx +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -24,6 +24,7 @@ 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(); @@ -107,25 +108,31 @@ describe('AmountFilterContent currency selection', () => { expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); }); - it('clears the currency without changing the entered amount', () => { + it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('selects Any currency without changing the %s amount', (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 the picker clears its selection and the filter is confirmed. + // 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 amount returns to the original bare hundredths format. - expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); + // Then the selection is labeled clearly and the amount returns to bare hundredths. + expect(jest.mocked(NumberWithSymbolForm).mock.calls.at(-1)?.[0]).toMatchObject({ + value: '0.10', + currency: '', + currencyButtonLabel: 'common.anyCurrency', + }); + 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', () => { @@ -197,6 +204,26 @@ describe('AmountFilterContent currency selection', () => { 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'})); @@ -249,7 +276,12 @@ describe('AmountPopup currency selection', () => { expect(updateFilterForm).toHaveBeenCalledWith({purchaseAmountEqualTo: '11.99 GBP', purchaseAmountGreaterThan: '', purchaseAmountLessThan: ''}); }); - it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('uses the money-request picker for the %s popup', (baseFilterKey) => { + 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( @@ -266,16 +298,16 @@ describe('AmountPopup currency selection', () => { throw new Error('Expected amount comparison options'); } - // When the equal-to editor selects USD using the shared picker and both popup steps are applied. + // 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?.('USD')); + 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 same decimal-major-unit operand as advanced filters. - expect(updateFilterForm).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: '12.00 USD', [`${baseFilterKey}GreaterThan`]: '', [`${baseFilterKey}LessThan`]: ''}); + // Then quick filters preserve the qualified or legacy format used by advanced filters. + expect(updateFilterForm).toHaveBeenCalledWith({[`${baseFilterKey}EqualTo`]: expected, [`${baseFilterKey}GreaterThan`]: '', [`${baseFilterKey}LessThan`]: ''}); }); }); @@ -297,7 +329,7 @@ describe('Amount filter currency defaults', () => { rerender(undefined); expect(result.current.currency).toBe('GBP'); - // When None is chosen, then later policy updates do not re-enable FX. + // 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); diff --git a/tests/unit/Search/SearchAmountFilterUtilsTest.ts b/tests/unit/Search/SearchAmountFilterUtilsTest.ts index 045190cded30..b0b404eb019e 100644 --- a/tests/unit/Search/SearchAmountFilterUtilsTest.ts +++ b/tests/unit/Search/SearchAmountFilterUtilsTest.ts @@ -10,6 +10,7 @@ describe('SearchAmountFilterUtils', () => { {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. @@ -22,6 +23,7 @@ describe('SearchAmountFilterUtils', () => { 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'}, diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index e7c1bbd01a28..b87bd71de359 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -80,6 +80,25 @@ 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`); From 9a82c3091eec7f044ab7b547bc0c79f3378f2f7f Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Tue, 27 Oct 2026 10:21:11 -0600 Subject: [PATCH 5/9] Shorten any-currency amount filter labels --- .../Search/FilterComponents/AmountFilterInput.tsx | 2 +- src/languages/de.ts | 1 + src/languages/el.ts | 1 + src/languages/en.ts | 1 + src/languages/es.ts | 1 + src/languages/fr.ts | 1 + src/languages/it.ts | 1 + src/languages/ja.ts | 1 + src/languages/nl.ts | 1 + src/languages/pl.ts | 1 + src/languages/pt-BR.ts | 1 + src/languages/zh-hans.ts | 1 + tests/unit/Search/AmountFilterContentTest.tsx | 9 +++++---- 13 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/components/Search/FilterComponents/AmountFilterInput.tsx b/src/components/Search/FilterComponents/AmountFilterInput.tsx index 313a775e47c5..a6a1b2b1acde 100644 --- a/src/components/Search/FilterComponents/AmountFilterInput.tsx +++ b/src/components/Search/FilterComponents/AmountFilterInput.tsx @@ -75,7 +75,7 @@ function AmountFilterInput({ref, baseFilterKey, amount, currency, label, name, a allowNegativeInput keyboardType={keyboardType} shouldShowCurrencyButton - currencyButtonLabel={currency || translate('common.anyCurrency')} + currencyButtonLabel={currency || translate('common.any')} currencyButtonAccessibilityLabel={[label, translate('common.selectCurrency'), currency || translate('common.anyCurrency')].join(', ')} onCurrencyButtonPress={() => setIsCurrencyPickerVisible(true)} shouldShowBigNumberPad={false} diff --git a/src/languages/de.ts b/src/languages/de.ts index aef6365531a7..86e7339114b2 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -330,6 +330,7 @@ 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', diff --git a/src/languages/el.ts b/src/languages/el.ts index 20698fc952a4..2c156ba5beb0 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -335,6 +335,7 @@ const translations: TranslationDeepObject = { pm: 'μ.μ.', tbd: 'Θα καθοριστεί', selectCurrency: 'Επιλέξτε νόμισμα', + any: 'Οποιοδήποτε', anyCurrency: 'Οποιοδήποτε νόμισμα', selectSymbolOrCurrency: 'Επιλέξτε ένα σύμβολο ή νόμισμα', card: 'Κάρτα', diff --git a/src/languages/en.ts b/src/languages/en.ts index 65dc94368249..1b119db90fde 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -412,6 +412,7 @@ 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', diff --git a/src/languages/es.ts b/src/languages/es.ts index 0a1c559d2f11..6290e52c7441 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -324,6 +324,7 @@ 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', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index af8aac39d775..bf8b6fa46c39 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -330,6 +330,7 @@ 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', diff --git a/src/languages/it.ts b/src/languages/it.ts index 3dc8fafb7b51..e2b2588d0dba 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -330,6 +330,7 @@ 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', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 3aed2074a79c..f914e53bce3b 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: '午後', tbd: '未定', selectCurrency: '通貨を選択', + any: 'すべて', anyCurrency: 'すべての通貨', selectSymbolOrCurrency: '記号または通貨を選択', card: 'カード', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 4dd2065a4916..589e916d4eca 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -330,6 +330,7 @@ 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', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 26607156986e..ec72d16f4509 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -336,6 +336,7 @@ const translations: TranslationDeepObject = { pm: 'PM', tbd: 'Do ustalenia', selectCurrency: 'Wybierz walutę', + any: 'Dowolna', anyCurrency: 'Dowolna waluta', selectSymbolOrCurrency: 'Wybierz symbol lub walutę', card: 'Karta', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index ceb971aacfad..2a782880729a 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -330,6 +330,7 @@ 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', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index b7accb243b47..188a72d08542 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -330,6 +330,7 @@ const translations: TranslationDeepObject = { pm: '下午', tbd: '待定', selectCurrency: '选择货币', + any: '任意', anyCurrency: '任意货币', selectSymbolOrCurrency: '选择符号或货币', card: '卡片', diff --git a/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx index f68b1ff767ea..ed09db1443f2 100644 --- a/tests/unit/Search/AmountFilterContentTest.tsx +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -108,7 +108,7 @@ describe('AmountFilterContent currency selection', () => { expect(onChange).toHaveBeenCalledWith({amountEqualTo: '1200', amountGreaterThan: undefined, amountLessThan: undefined}); }); - it.each([CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT])('selects Any currency without changing the %s amount', (baseFilterKey) => { + 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(); @@ -125,11 +125,11 @@ describe('AmountFilterContent currency selection', () => { act(() => jest.mocked(IOURequestStepCurrencyModal).mock.calls.at(-1)?.[0].onInputChange?.('')); fireEvent.press(screen.getByRole('button')); - // Then the selection is labeled clearly and the amount returns to bare hundredths. + // 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.anyCurrency', + 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}); @@ -306,7 +306,8 @@ describe('AmountPopup currency selection', () => { act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); act(() => jest.mocked(BasePopup).mock.calls.at(-1)?.[0].onApply()); - // Then quick filters preserve the qualified or legacy format used by advanced filters. + // 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`]: ''}); }); }); From c0901f62e4b24f6513e0c2b4c1470e4b3d3f9c50 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Tue, 27 Oct 2026 10:43:05 -0600 Subject: [PATCH 6/9] Place Any currency under All in currency picker --- .../CurrencySelectionList/index.tsx | 17 +++++- src/components/CurrencySelectionList/types.ts | 3 + .../step/IOURequestStepCurrencyModal.tsx | 16 +----- tests/ui/CurrencySelectionListTest.tsx | 55 ++++++++++++++++++- tests/ui/IOURequestStepCurrencyModalTest.tsx | 11 +++- 5 files changed, 81 insertions(+), 21 deletions(-) diff --git a/src/components/CurrencySelectionList/index.tsx b/src/components/CurrencySelectionList/index.tsx index 96ebc9264c16..1fc6481359f4 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,6 +25,7 @@ function CurrencySelectionList({ selectedCurrencies = getEmptyArray(), recentlyUsedCurrencies, excludedCurrencies = [], + shouldAllowEmptySelection = false, ...restProps }: CurrencySelectionListProps) { const {currencyList} = useCurrencyListState(); @@ -67,6 +70,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 +109,7 @@ function CurrencySelectionList({ } } else if (!isEmpty) { sections.push({ + title: shouldAllowEmptySelection ? translate('common.all') : undefined, data: shouldDisplayInitiallyPinnedOptionsOnTop ? unpinnedOptions : filteredCurrencies, sectionIndex: 3, }); @@ -116,7 +131,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 - {shouldAllowEmptySelection && ( - { - onInputChange(''); - hidePickerModal(); - }} - > - - - {translate('common.anyCurrency')} - - - - )} diff --git a/tests/ui/CurrencySelectionListTest.tsx b/tests/ui/CurrencySelectionListTest.tsx index afa2c02940b6..03eff28f764b 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,56 @@ describe('CurrencySelectionList', () => { mockedSelectionList.mockClear(); }); + it.each([ + {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: ['EUR']}, + {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: []}, + {initiallySelectedCurrencyCode: '', recentlyUsedCurrencies: ['EUR']}, + {initiallySelectedCurrencyCode: '', 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('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 index 5a9137c25785..9c0e248d63fd 100644 --- a/tests/ui/IOURequestStepCurrencyModalTest.tsx +++ b/tests/ui/IOURequestStepCurrencyModalTest.tsx @@ -1,4 +1,6 @@ -import {fireEvent, render, screen} from '@testing-library/react-native'; +import {act, render, screen} from '@testing-library/react-native'; + +import CurrencySelectionList from '@components/CurrencySelectionList'; import IOURequestStepCurrencyModal from '@pages/iou/request/step/IOURequestStepCurrencyModal'; @@ -27,7 +29,10 @@ describe('IOURequestStepCurrencyModal', () => { ); // When Any currency is selected instead of a currency code. - fireEvent.press(screen.getByText('common.anyCurrency'), {nativeEvent: {}}); + const listProps = jest.mocked(CurrencySelectionList).mock.calls.at(-1)?.[0]; + expect(listProps?.shouldAllowEmptySelection).toBe(true); + expect(screen.queryByText('common.anyCurrency')).toBeNull(); + act(() => listProps?.onSelect({currencyCode: '', currencyName: 'Any currency', keyForList: 'any-currency'})); // Then the caller receives the empty selection used by legacy operands. expect(onInputChange).toHaveBeenCalledWith(''); @@ -48,6 +53,6 @@ describe('IOURequestStepCurrencyModal', () => { ); // Then money requests cannot select the search-only Any currency option. - expect(screen.queryByText('common.anyCurrency')).toBeNull(); + expect(jest.mocked(CurrencySelectionList).mock.calls.at(-1)?.[0].shouldAllowEmptySelection).toBe(false); }); }); From 6ce26e3b713d683fe38e9ed792e0a3e68e0a5193 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Tue, 27 Oct 2026 11:51:45 -0600 Subject: [PATCH 7/9] Clarify amount filter currency handling comments --- src/hooks/useAmountFilterCurrency.ts | 2 +- src/libs/SearchQueryUtils.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hooks/useAmountFilterCurrency.ts b/src/hooks/useAmountFilterCurrency.ts index fa1894108e78..a3f9073b4662 100644 --- a/src/hooks/useAmountFilterCurrency.ts +++ b/src/hooks/useAmountFilterCurrency.ts @@ -12,7 +12,7 @@ import useDefaultExpensePolicy from './useDefaultExpensePolicy'; function useAmountFilterCurrency(baseFilterKey: SearchAmountFilterKeys, value?: string) { const defaultPolicy = useDefaultExpensePolicy(); - // Empty string preserves a currency-less choice; undefined follows the saved operand or policy default. + // 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; diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 09f361e7cfa6..923c9ae22f1d 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -2030,6 +2030,8 @@ function buildFilterFormValuesFromQuery( 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); }; From 5a4e86a48e95d65c894089251477e7a84117f954 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Fri, 30 Oct 2026 13:58:05 -0600 Subject: [PATCH 8/9] Address amount filter review feedback --- .../CurrencySelectionList/index.tsx | 4 ++- .../AdvancedFilters/AmountFilterContent.tsx | 4 ++- .../FilterComponents/AmountFilterInput.tsx | 11 +++++-- src/libs/SearchAmountFilterUtils.ts | 11 ++++--- .../index.native.ts | 7 ++++ .../getAmountFilterInputKeyboard/index.ts | 6 ++++ .../step/IOURequestStepCurrencyModal.tsx | 4 +-- tests/ui/CurrencySelectionListTest.tsx | 17 ++++++++-- tests/ui/IOURequestStepCurrencyModalTest.tsx | 28 ++++++++++++++++ tests/unit/Search/AmountFilterContentTest.tsx | 21 ++++++++++++ .../unit/getAmountFilterInputKeyboardTest.ts | 32 +++++++++++++++++++ 11 files changed, 130 insertions(+), 15 deletions(-) create mode 100644 src/libs/getAmountFilterInputKeyboard/index.native.ts create mode 100644 src/libs/getAmountFilterInputKeyboard/index.ts create mode 100644 tests/unit/getAmountFilterInputKeyboardTest.ts diff --git a/src/components/CurrencySelectionList/index.tsx b/src/components/CurrencySelectionList/index.tsx index 1fc6481359f4..c7f72d66707c 100644 --- a/src/components/CurrencySelectionList/index.tsx +++ b/src/components/CurrencySelectionList/index.tsx @@ -31,7 +31,9 @@ function CurrencySelectionList({ 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); diff --git a/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx index 4a6509a91c51..dfa7898f5505 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/AmountFilterContent.tsx @@ -8,6 +8,7 @@ import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types'; import useAmountFilterCurrency from '@hooks/useAmountFilterCurrency'; import useLocalize from '@hooks/useLocalize'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useScreenWrapperTransitionStatus from '@hooks/useScreenWrapperTransitionStatus'; import useShouldFooterBeInsideList from '@hooks/useShouldFooterBeInsideList'; import useStyleUtils from '@hooks/useStyleUtils'; @@ -97,6 +98,7 @@ type AmountBetweenInputProps = { function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue, autoFocus}: AmountBetweenInputProps) { const {translate} = useLocalize(); + const {shouldUseNarrowLayout} = useResponsiveLayout(); const styles = useThemeStyles(); const initialGreaterThan = getAmountFilterInputValue(greaterThanValue); const initialLessThan = getAmountFilterInputValue(lessThanValue); @@ -129,7 +131,7 @@ function AmountBetweenInput({ref, baseFilterKey, greaterThanValue, lessThanValue const lessThanLabel = translate('search.filters.amount.lessThan'); return ( - + ; 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; @@ -57,7 +61,7 @@ function AmountFilterInput({ref, baseFilterKey, amount, currency, label, name, a } const hideCurrencyPicker = () => setIsCurrencyPickerVisible(false); - const {keyboardType} = getAmountInputKeyboard(true); + const {keyboardType, shouldShowFlipButton} = getAmountFilterInputKeyboard(); return ( @@ -74,9 +78,10 @@ function AmountFilterInput({ref, baseFilterKey, amount, currency, label, name, a onInputChange={onAmountChange} allowNegativeInput keyboardType={keyboardType} + shouldShowFlipButton={shouldShowFlipButton} shouldShowCurrencyButton currencyButtonLabel={currency || translate('common.any')} - currencyButtonAccessibilityLabel={[label, translate('common.selectCurrency'), currency || translate('common.anyCurrency')].join(', ')} + currencyButtonAccessibilityLabel={[label.trim(), translate('common.selectCurrency'), currency || translate('common.anyCurrency')].join(', ')} onCurrencyButtonPress={() => setIsCurrencyPickerVisible(true)} shouldShowBigNumberPad={false} shouldUseBorderlessButtons diff --git a/src/libs/SearchAmountFilterUtils.ts b/src/libs/SearchAmountFilterUtils.ts index 0fd0e41d6946..8e08f4d84121 100644 --- a/src/libs/SearchAmountFilterUtils.ts +++ b/src/libs/SearchAmountFilterUtils.ts @@ -1,4 +1,5 @@ -// Amount filters store bare hundredths or decimal major units followed by a comparison currency. +// 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'; @@ -13,19 +14,19 @@ function supportsAmountFilterCurrency(filterKey: string): boolean { return filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT || filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.PURCHASE_AMOUNT; } -/** Separates a qualified decimal operand without changing legacy hundredths. */ +/** 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}; } -/** Returns the major-unit amount and optional currency used by the editor. */ +/** 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) : ''}; } -/** Serializes editor values in the units expected by currency-qualified and legacy operands. */ +/** 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 ''; @@ -35,7 +36,7 @@ function formatAmountFilterValue(amount: string, currency?: string): string { return currency ? `${convertToFrontendAmountAsString(backendAmount, CONST.DEFAULT_CURRENCY_DECIMALS)} ${currency}` : backendAmount.toString(); } -/** Formats either operand using the caller's localized hundredths formatter. */ +/** 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 ''; 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 1a1fcece602a..e75c28e5da22 100644 --- a/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx +++ b/src/pages/iou/request/step/IOURequestStepCurrencyModal.tsx @@ -8,8 +8,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'; @@ -55,7 +53,7 @@ function IOURequestStepCurrencyModal({ onClose={hidePickerModal} onModalHide={hidePickerModal} shouldEnableNewFocusManagement - onBackdropPress={Navigation.dismissModal} + onBackdropPress={hidePickerModal} shouldUseModalPaddingStyle={false} shouldHandleNavigationBack enableEdgeToEdgeBottomSafeAreaPadding diff --git a/tests/ui/CurrencySelectionListTest.tsx b/tests/ui/CurrencySelectionListTest.tsx index 03eff28f764b..b2e68d1df2eb 100644 --- a/tests/ui/CurrencySelectionListTest.tsx +++ b/tests/ui/CurrencySelectionListTest.tsx @@ -76,8 +76,6 @@ describe('CurrencySelectionList', () => { it.each([ {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: ['EUR']}, {initiallySelectedCurrencyCode: 'USD', recentlyUsedCurrencies: []}, - {initiallySelectedCurrencyCode: '', recentlyUsedCurrencies: ['EUR']}, - {initiallySelectedCurrencyCode: '', 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}); @@ -96,6 +94,21 @@ describe('CurrencySelectionList', () => { } }); + 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}); diff --git a/tests/ui/IOURequestStepCurrencyModalTest.tsx b/tests/ui/IOURequestStepCurrencyModalTest.tsx index 9c0e248d63fd..91eb10500caa 100644 --- a/tests/ui/IOURequestStepCurrencyModalTest.tsx +++ b/tests/ui/IOURequestStepCurrencyModalTest.tsx @@ -1,6 +1,9 @@ import {act, render, screen} 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'; @@ -11,8 +14,33 @@ jest.mock('@components/Modal', () => jest.fn(({children}: {children: React.React 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])('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(); diff --git a/tests/unit/Search/AmountFilterContentTest.tsx b/tests/unit/Search/AmountFilterContentTest.tsx index ed09db1443f2..23f6857f8e11 100644 --- a/tests/unit/Search/AmountFilterContentTest.tsx +++ b/tests/unit/Search/AmountFilterContentTest.tsx @@ -2,6 +2,7 @@ import {act, fireEvent, render, renderHook, screen} from '@testing-library/react 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'; @@ -32,6 +33,26 @@ beforeEach(() => { }); 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'})); 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}); + }); +}); From f3a8380706d89fb0f510d7e2c737cdb89914ab64 Mon Sep 17 00:00:00 2001 From: Carlos Martins Date: Mon, 2 Nov 2026 14:25:32 -0600 Subject: [PATCH 9/9] Remove vacuous currency picker assertion --- tests/ui/IOURequestStepCurrencyModalTest.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/ui/IOURequestStepCurrencyModalTest.tsx b/tests/ui/IOURequestStepCurrencyModalTest.tsx index c8b680dc5ece..1ef6b6417a11 100644 --- a/tests/ui/IOURequestStepCurrencyModalTest.tsx +++ b/tests/ui/IOURequestStepCurrencyModalTest.tsx @@ -1,4 +1,4 @@ -import {act, render, screen} from '@testing-library/react-native'; +import {act, render} from '@testing-library/react-native'; import CurrencySelectionList from '@components/CurrencySelectionList'; import Modal from '@components/Modal'; @@ -83,7 +83,6 @@ describe('IOURequestStepCurrencyModal', () => { // 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); - expect(screen.queryByText('common.anyCurrency')).toBeNull(); act(() => listProps?.onSelect({currencyCode: '', currencyName: 'Any currency', keyForList: 'any-currency'})); // Then the caller receives the empty selection used by legacy operands.