Skip to content
Merged
12 changes: 10 additions & 2 deletions src/components/Search/FilterComponents/DatePresetFilterBase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ import RangeDatePicker from './RangeDatePicker';

type CustomDateModifier = Exclude<SearchDateModifier, typeof CONST.SEARCH.DATE_MODIFIERS.RANGE>;

const CUSTOM_DATE_MODIFIER_TRANSLATION_KEYS: {
[Modifier in CustomDateModifier]: Extract<SearchDateModifierLower, Lowercase<Modifier>>;
} = {
[CONST.SEARCH.DATE_MODIFIERS.ON]: 'on',
[CONST.SEARCH.DATE_MODIFIERS.BEFORE]: 'before',
[CONST.SEARCH.DATE_MODIFIERS.AFTER]: 'after',
};

/** Presets that start a new group (previous periods, then rolling ranges), so a divider is shown above them */
const PRESET_GROUP_STARTS = new Set<SearchDatePreset>([CONST.SEARCH.DATE_PRESETS.LAST_WEEK, CONST.SEARCH.DATE_PRESETS.LAST_30_DAYS]);

Expand Down Expand Up @@ -369,7 +377,7 @@ function DatePresetFilterBase({
if (!customDateValue) {
customDateDescription = undefined;
} else {
customDateDescription = `${translate(`common.${customDateModifier.toLowerCase() as SearchDateModifierLower}`)} ${customDateValue}`;
customDateDescription = `${translate(`common.${CUSTOM_DATE_MODIFIER_TRANSLATION_KEYS[customDateModifier]}`)} ${customDateValue}`;
}
const handleSingleDateSelected = (date: Date) => {
setEphemeralDateValue(format(date, CONST.DATE.FNS_FORMAT_STRING));
Expand Down Expand Up @@ -470,7 +478,7 @@ function DatePresetFilterBase({
showTooltip
item={{
keyForList: dateModifier,
text: translate(`common.${dateModifier.toLowerCase() as SearchDateModifierLower}`),
text: translate(`common.${CUSTOM_DATE_MODIFIER_TRANSLATION_KEYS[dateModifier]}`),
isSelected: selectedDateModifier === dateModifier,
}}
onSelectRow={() => selectDateModifier(dateModifier)}
Expand Down
8 changes: 3 additions & 5 deletions src/components/StatePicker/StateSelectorModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import CONST from '@src/CONST';
import {CONST as COMMON_CONST} from 'expensify-common';
import React from 'react';

type State = keyof typeof COMMON_CONST.STATES;

type StateSelectorModalProps = {
isVisible: boolean;

Expand All @@ -42,9 +40,9 @@ function StateSelectorModal({isVisible, currentState, onStateSelected, onClose,
const initialSelectedValue = useInitialSelection(currentState || undefined, {isVisible});
const initialSelectedValues = initialSelectedValue ? [initialSelectedValue] : [];

const countryStates = Object.keys(COMMON_CONST.STATES).map((state) => {
const stateName = translate(`allStates.${state as State}.stateName`);
const stateISO = translate(`allStates.${state as State}.stateISO`);
const countryStates = Object.values(COMMON_CONST.STATES).map(({stateISO: stateKey}) => {
const stateName = translate(`allStates.${stateKey}.stateName`);
const stateISO = translate(`allStates.${stateKey}.stateISO`);
return {
value: stateISO,
keyForList: stateISO,
Expand Down
101 changes: 56 additions & 45 deletions src/hooks/useAccountIndicatorChecks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ type AccountIndicatorChecksResult = {
infoStatus: IndicatorStatus | undefined;
};

/** Returns the status of the first check that matches, so the order of the checks sets their priority. */
function getFirstMatchingStatus(checks: Array<[IndicatorStatus, boolean | undefined]>): IndicatorStatus | undefined {
return checks.find(([, value]) => value)?.[0];
}

function useAccountIndicatorChecks(): AccountIndicatorChecksResult {
const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
const [fundList] = useOnyx(ONYXKEYS.FUND_LIST);
Expand Down Expand Up @@ -50,56 +55,62 @@ function useAccountIndicatorChecks(): AccountIndicatorChecksResult {
const {shouldShowAddHomeAddress} = useTimeSensitiveHomeAddress();
const {wiseMoreInfoNeededBankAccounts} = useTimeSensitiveWiseMoreInfoNeeded();

const accountChecks: Partial<Record<IndicatorStatus, boolean>> = {
[CONST.INDICATOR_STATUS.HAS_USER_WALLET_ERRORS]: Object.keys(userWallet?.errors ?? {}).length > 0,
[CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR]: hasPaymentMethodError(bankAccountList, fundList, allCards, session, policies),
[CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_ERRORS]: hasSubscriptionRedDotError(
stripeCustomerId,
retryBillingSuccessful,
billingDisputePending,
retryBillingFailed,
fundList,
billingStatus,
amountOwed,
ownerBillingGracePeriodEnd,
ownerTravelBillingGracePeriodEnd,
),
[CONST.INDICATOR_STATUS.HAS_REIMBURSEMENT_ACCOUNT_ERRORS]: Object.keys(reimbursementAccount?.errors ?? {}).length > 0,
[CONST.INDICATOR_STATUS.HAS_LOGIN_LIST_ERROR]: !!loginList && hasLoginListError(loginList),
const accountChecks: Array<[IndicatorStatus, boolean | undefined]> = [
[CONST.INDICATOR_STATUS.HAS_USER_WALLET_ERRORS, Object.keys(userWallet?.errors ?? {}).length > 0],
[CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR, hasPaymentMethodError(bankAccountList, fundList, allCards, session, policies)],
[
CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_ERRORS,
hasSubscriptionRedDotError(
stripeCustomerId,
retryBillingSuccessful,
billingDisputePending,
retryBillingFailed,
fundList,
billingStatus,
amountOwed,
ownerBillingGracePeriodEnd,
ownerTravelBillingGracePeriodEnd,
),
],
[CONST.INDICATOR_STATUS.HAS_REIMBURSEMENT_ACCOUNT_ERRORS, Object.keys(reimbursementAccount?.errors ?? {}).length > 0],
[CONST.INDICATOR_STATUS.HAS_LOGIN_LIST_ERROR, !!loginList && hasLoginListError(loginList)],
// Wallet term errors that are not caused by an IOU (we show the red brick indicator for those in the LHN instead)
[CONST.INDICATOR_STATUS.HAS_WALLET_TERMS_ERRORS]: Object.keys(walletTerms?.errors ?? {}).length > 0 && !walletTerms?.chatReportID,
[CONST.INDICATOR_STATUS.HAS_PHONE_NUMBER_ERROR]: !!privatePersonalDetails?.errorFields?.phoneNumber,
[CONST.INDICATOR_STATUS.HAS_EMPLOYEE_CARD_FEED_ERRORS]: !isPolicyAdmin ? hasCompanyCardFeedErrors : false,
[CONST.INDICATOR_STATUS.HAS_LOCKED_BANK_ACCOUNT]: Object.values(bankAccountList ?? {}).some((bankAccount) => bankAccount?.accountData?.state === CONST.BANK_ACCOUNT.STATE.LOCKED),
[CONST.INDICATOR_STATUS.HAS_DEVICE_MANAGEMENT_ERROR]: hasDeviceManagementErrorValue,
[CONST.INDICATOR_STATUS.HAS_AGENT_ERRORS]: !!hasAgentError,
};
[CONST.INDICATOR_STATUS.HAS_WALLET_TERMS_ERRORS, Object.keys(walletTerms?.errors ?? {}).length > 0 && !walletTerms?.chatReportID],
[CONST.INDICATOR_STATUS.HAS_PHONE_NUMBER_ERROR, !!privatePersonalDetails?.errorFields?.phoneNumber],
[CONST.INDICATOR_STATUS.HAS_EMPLOYEE_CARD_FEED_ERRORS, !isPolicyAdmin ? hasCompanyCardFeedErrors : false],
[CONST.INDICATOR_STATUS.HAS_LOCKED_BANK_ACCOUNT, Object.values(bankAccountList ?? {}).some((bankAccount) => bankAccount?.accountData?.state === CONST.BANK_ACCOUNT.STATE.LOCKED)],
[CONST.INDICATOR_STATUS.HAS_DEVICE_MANAGEMENT_ERROR, hasDeviceManagementErrorValue],
[CONST.INDICATOR_STATUS.HAS_AGENT_ERRORS, !!hasAgentError],
];

const infoChecks: Partial<Record<IndicatorStatus, boolean>> = {
[CONST.INDICATOR_STATUS.HAS_LOGIN_LIST_INFO]: !!loginList && hasLoginListInfo(loginList, session?.email),
[CONST.INDICATOR_STATUS.HAS_HOME_ADDRESS_INFO]: shouldShowAddHomeAddress,
[CONST.INDICATOR_STATUS.HAS_PENDING_CARD_INFO]: hasPendingExpensifyCardAction(allCards, privatePersonalDetails) || hasCardPendingDigitalWalletApproval(allCards),
[CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_INFO]: hasSubscriptionGreenDotInfo(
stripeCustomerId,
retryBillingSuccessful,
billingDisputePending,
retryBillingFailed,
fundList,
billingStatus,
amountOwed,
ownerBillingGracePeriodEnd,
ownerTravelBillingGracePeriodEnd,
),
[CONST.INDICATOR_STATUS.HAS_PARTIALLY_SETUP_BANK_ACCOUNT_INFO]: hasPartiallySetupBankAccount(bankAccountList) || hasPersonalBankAccountMissingInfo(bankAccountList),
[CONST.INDICATOR_STATUS.HAS_WISE_MORE_INFO_NEEDED_INFO]: wiseMoreInfoNeededBankAccounts.length > 0,
};
const infoChecks: Array<[IndicatorStatus, boolean]> = [
[CONST.INDICATOR_STATUS.HAS_LOGIN_LIST_INFO, !!loginList && hasLoginListInfo(loginList, session?.email)],
[CONST.INDICATOR_STATUS.HAS_HOME_ADDRESS_INFO, shouldShowAddHomeAddress],
[CONST.INDICATOR_STATUS.HAS_PENDING_CARD_INFO, hasPendingExpensifyCardAction(allCards, privatePersonalDetails) || hasCardPendingDigitalWalletApproval(allCards)],
[
CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_INFO,
hasSubscriptionGreenDotInfo(
stripeCustomerId,
retryBillingSuccessful,
billingDisputePending,
retryBillingFailed,
fundList,
billingStatus,
amountOwed,
ownerBillingGracePeriodEnd,
ownerTravelBillingGracePeriodEnd,
),
],
[CONST.INDICATOR_STATUS.HAS_PARTIALLY_SETUP_BANK_ACCOUNT_INFO, hasPartiallySetupBankAccount(bankAccountList) || hasPersonalBankAccountMissingInfo(bankAccountList)],
[CONST.INDICATOR_STATUS.HAS_WISE_MORE_INFO_NEEDED_INFO, wiseMoreInfoNeededBankAccounts.length > 0],
];

const [accountStatus] = Object.entries(accountChecks).find(([, value]) => value) ?? [];
const [infoStatus] = Object.entries(infoChecks).find(([, value]) => value) ?? [];
const accountStatus = getFirstMatchingStatus(accountChecks);
const infoStatus = getFirstMatchingStatus(infoChecks);

return {
accountStatus: accountStatus as IndicatorStatus | undefined,
infoStatus: infoStatus as IndicatorStatus | undefined,
accountStatus,
infoStatus,
};
}

Expand Down
34 changes: 34 additions & 0 deletions tests/ui/DatePresetFilterBaseCustomDateModifiersTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,38 @@ describe('DatePresetFilterBase allowedCustomDateModifiers', () => {
// Then the picker switches to On rather than reviving the Before modifier the caller ruled out
expect(onSelectDateModifier).toHaveBeenCalledWith(CONST.SEARCH.DATE_MODIFIERS.ON);
});

it('shows and selects After when it is the only allowed modifier', () => {
// Given a picker restricted to the After modifier
const onSelectDateModifier = jest.fn();
renderDatePresetFilterBase({
defaultDateValues: {...emptyDateValues, [CONST.SEARCH.DATE_MODIFIERS.AFTER]: '2026-03-04'},
allowedCustomDateModifiers: [CONST.SEARCH.DATE_MODIFIERS.AFTER],
onSelectDateModifier,
});

expect(screen.getByText(/^(After|common\.after) 2026-03-04$/)).toBeOnTheScreen();

// When the custom date option is opened
fireEvent.press(screen.getByText(CUSTOM_DATE), PRESS_EVENT);

// Then After is selected without offering the other modifier rows
expect(onSelectDateModifier).toHaveBeenCalledWith(CONST.SEARCH.DATE_MODIFIERS.AFTER);
for (const row of MODIFIER_ROWS) {
expect(screen.queryByText(row)).not.toBeOnTheScreen();
}
});

it('uses the modifier translation in the custom date description', () => {
// Given a saved custom Before date
renderDatePresetFilterBase({
defaultDateValues: {...emptyDateValues, [CONST.SEARCH.DATE_MODIFIERS.BEFORE]: '2026-03-04'},
});

// When the picker displays its collapsed custom date option
const description = screen.getByText(/^(Before|common\.before) 2026-03-04$/);

// Then its description includes the translated modifier and stored date
expect(description).toBeOnTheScreen();
});
});
49 changes: 48 additions & 1 deletion tests/ui/StateSelectorModalTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,28 @@ describe('StateSelectorModal', () => {
mockedSelectionList.mockClear();
});

it('pins the saved state to the top on reopen', () => {
it('renders every installed state with its translated name and ISO', () => {
// Given the production state list and translation-backed modal
render(
<StateSelectorModal
isVisible
currentState=""
onStateSelected={jest.fn()}
onClose={jest.fn()}
label="State"
/>,
);

// When the modal builds the unfiltered list
const options = mockedSelectionList.mock.lastCall?.[0].data;

// Then all 52 states appear in source order with translated names and codes
expect(options).toHaveLength(52);
expect(options?.map(({keyForList, text}) => ({keyForList, text}))).toEqual(Object.values(mockStates).map(({stateISO, stateName}) => ({keyForList: stateISO, text: stateName})));
});

it('pins the saved state to the top on reopen', () => {
const {rerender} = render(
<StateSelectorModal
isVisible
currentState="NY"
Expand All @@ -89,6 +109,33 @@ describe('StateSelectorModal', () => {
}),
);
expect(selectionListProps?.initiallyFocusedItemKey).toBe('NY');

// Given a newly saved selection while the modal is closed
rerender(
<StateSelectorModal
isVisible={false}
currentState="CA"
onStateSelected={jest.fn()}
onClose={jest.fn()}
label="State"
/>,
);

// When the modal reopens
rerender(
<StateSelectorModal
isVisible
currentState="CA"
onStateSelected={jest.fn()}
onClose={jest.fn()}
label="State"
/>,
);

// Then the changed selection is pinned and focused
const reopenedProps = mockedSelectionList.mock.lastCall?.[0];
expect(reopenedProps?.data.at(0)).toEqual(expect.objectContaining({keyForList: 'CA', isSelected: true}));
expect(reopenedProps?.initiallyFocusedItemKey).toBe('CA');
});

it('keeps natural filtered ordering while search is active', () => {
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/useAccountIndicatorChecksTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,48 @@ describe('useAccountIndicatorChecks', () => {
});

describe('error takes priority over info', () => {
it('returns the first truthy status in each category when multiple checks match', async () => {
// Given simultaneous wallet and bank-account errors, plus login and subscription info
await act(async () => {
await Onyx.multiSet(
createMock<OnyxMultiSetInput>({
[ONYXKEYS.USER_WALLET]: {errors: {error: 'Wallet error'}},
[ONYXKEYS.BANK_ACCOUNT_LIST]: {
// eslint-disable-next-line @typescript-eslint/naming-convention -- This fixture key is a numeric bank account ID, so it cannot follow the naming rule.
12345: {
methodID: 12345,
errors: {error: 'Bank account error'},
},
},
[ONYXKEYS.LOGINS]: {
// eslint-disable-next-line @typescript-eslint/naming-convention -- This fixture key contains an email address, so it cannot follow the naming rule.
'1_otheruser@expensify.com': {
partnerID: 1,
partnerUserID: 'different@expensify.com',
validatedDate: undefined,
},
},
[ONYXKEYS.REIMBURSEMENT_ACCOUNT]: {},
[ONYXKEYS.WALLET_TERMS]: {},
[ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: {},
[ONYXKEYS.CARD_LIST]: {},
[ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING]: 0,
[ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_SUCCESSFUL]: true,
[ONYXKEYS.SESSION]: {email: userID},
}),
);
await waitForBatchedUpdatesWithAct();
});

// When the real hook evaluates both ordered check lists
const {result} = renderHook(() => useAccountIndicatorChecks());
await waitForBatchedUpdatesWithAct();

// Then the first matching error and info status win independently
expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_USER_WALLET_ERRORS);
expect(result.current.infoStatus).toBe(CONST.INDICATOR_STATUS.HAS_LOGIN_LIST_INFO);
});

it('returns both accountStatus and infoStatus independently', async () => {
await act(async () => {
await Onyx.multiSet(
Expand Down
Loading