Skip to content

[Due for payment 2025-11-13] [$250] Search - Some expenses are unselected after sorting #70594

Closed

Description

@lanitochka17

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.2.14-1
Reproducible in staging?: Y
Reproducible in production?: Y
If this was caught during regression testing, add the test name, ID and link from TestRail: #70211
Email or phone of affected tester (no customers): ndk.2303+new101@gmail.com
Issue reported by: Applause - Internal Team

Action Performed:

Preconditions: Account with atleast 50 expenses

  1. Open https://staging.new.expensify.com/
  2. Go to Reports tab on web -> Expenses
  3. Scroll down to loads all expenses
  4. Select all expenses
  5. Try to sort them by e.g. date

Expected Result:

Expenses are listed as order by sorting, and are still selected all

Actual Result:

Some expenses are unselected

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari
  • MacOS: Desktop
Platforms Tested: On which of our officially supported platforms was this issue tested:
  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari
  • MacOS: Desktop

Screenshots/Videos

Add any screenshot/video evidence
Bug6945196_1757953081575.Sorting_unselects_some_expenses.mp4

View all open jobs on GitHub

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~021970452751423896945
  • Upwork Job ID: 1970452751423896945
  • Last Price Increase: 2025-09-30
  • Automatic offers:
    • abzokhattab | Contributor | 109033538
Issue OwnerCurrent Issue Owner: @eVoloshchak

Activity

  1. added
    Daily
    Bug
    on Sep 15, 2025
  2. melvin-bot commented on Sep 15, 2025

    @melvin-bot

    Triggered auto assignment to @sonialiap (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  3. abzokhattab commented on Sep 15, 2025

    @abzokhattab
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Some expenses become unselected after sorting in the Reports tab when "Select All" is used.

    What is the root cause of that problem?

    • The toggleAllTransactions function uses the unsorted data array to determine which transactions to select
    • When sorting occurs, the displayed data gets reordered by getSortedSections() but the selection logic still references the original unsorted data
    • This creates a mismatch between the selection state (keyed by keyForList) and the actual displayed data order
    • The selection state is maintained correctly, but the "Select All" function operates on the wrong data source

    What changes do you think we should make in order to solve the problem?

    • Modify the toggleAllTransactions function to use the sorted data instead of the unsorted data array
    • Use getSortedSections() to get the same data that's actually being displayed to the user
    • This ensures consistency between what the user sees and what gets selected when using "Select All"

    final function:

        const toggleAllTransactions = useCallback(() => {
            const areItemsGrouped = !!groupBy;
            const totalSelected = Object.keys(selectedTransactions).length;
    
            if (totalSelected > 0) {
                clearSelectedTransactions();
                return;
            }
    
            const sortedData = getSortedSections(type, status, data, localeCompare, sortBy, sortOrder, groupBy);
    
            if (areItemsGrouped) {
                setSelectedTransactions(
                    Object.fromEntries(
                        (sortedData as TransactionGroupListItemType[]).flatMap((item) =>
                            item.transactions
                                .filter((t) => !isTransactionPendingDelete(t))
                                .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, reportActionsArray, outstandingReportsByPolicyID)),
                        ),
                    ),
                    sortedData,
                );
    
                return;
            }
    
            setSelectedTransactions(
                Object.fromEntries(
                    (sortedData as TransactionListItemType[])
                        .filter((t) => !isTransactionPendingDelete(t))
                        .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, reportActionsArray, outstandingReportsByPolicyID)),
                ),
                sortedData,
            );
        }, [clearSelectedTransactions, data, groupBy, reportActionsArray, selectedTransactions, setSelectedTransactions, outstandingReportsByPolicyID, type, status, localeCompare, sortBy, sortOrder]);

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    NA

    What alternative solutions did you explore? (Optional)

    • Or we can fix the root cause by modifying the critical useEffect that rebuilds the selection state when data changes.
    • This useEffect currently uses the unsorted data array to determine which transactions should be selected, but it should use the same sorted data that's displayed to the user.
    • By making this useEffect use getSortedSections() instead of raw data, we ensure that the selection state is always built from the same data source that users actually see
  4. nyomanjyotisa commented on Sep 16, 2025

    @nyomanjyotisa
    Member

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Search - Some expenses are unselected after sorting

    What is the root cause of that problem?

    The current hash calculation getQueryHashes includes sortBy and sortOrder parameters in the primary hash calculation

    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY}:${query.sortBy}`;
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER}:${query.sortOrder}`;

    When sorting changes, the hash changes, triggering clearTransactionsAndSetHashAndKey in the useFocusEffect which clears the selection because the new hash doesn't match the stored currentSearchHash

    useFocusEffect(clearTransactionsAndSetHashAndKey);

    What changes do you think we should make in order to solve the problem?

    We can change the hash calculation to exclude sorting parameters from the primary hash used for selection state management

    function getQueryHashes(query: SearchQueryJSON): {primaryHash: number; recentSearchHash: number; similarSearchHash: number; sortingHash: number} {
    
        ...
    
        const similarSearchHash = hashText(Array.from(filterSet).join(''), 2 ** 32);
        const recentSearchHash = hashText(orderedQuery, 2 ** 32);
    
        // Create primary hash without sorting parameters for selection state consistency
        let primaryQueryString = orderedQuery;
        if (query.policyID) {
            primaryQueryString += ` ${CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID}:${Array.isArray(query.policyID) ? query.policyID.join(',') : query.policyID} `;
        }
        const primaryHash = hashText(primaryQueryString, 2 ** 32);
    
        // Create separate sorting hash that includes sort parameters
        let sortingQueryString = primaryQueryString;
        sortingQueryString += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY}:${query.sortBy}`;
        sortingQueryString += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER}:${query.sortOrder}`;
        const sortingHash = hashText(sortingQueryString, 2 ** 32);
    
        return {primaryHash, recentSearchHash, similarSearchHash, sortingHash};
    }

    function getQueryHashes(query: SearchQueryJSON): {primaryHash: number; recentSearchHash: number; similarSearchHash: number} {
    let orderedQuery = '';
    orderedQuery += `${CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE}:${query.type}`;
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS}:${Array.isArray(query.status) ? query.status.join(',') : query.status}`;
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.GROUP_BY}:${query.groupBy}`;
    const filterSet = new Set<string>(orderedQuery);
    // Certain filters shouldn't affect whether two searchers are similar or not, since they dont
    // actually filter out results
    const similarSearchIgnoredFilters = new Set<SearchFilterKey>([CONST.SEARCH.SYNTAX_FILTER_KEYS.GROUP_CURRENCY]);
    // Certain filters' values are significant in deciding which search we are on, so we want to include
    // their value when computing the similarSearchHash
    const similarSearchValueBasedFilters = new Set<SearchFilterKey>([CONST.SEARCH.SYNTAX_FILTER_KEYS.ACTION]);
    query.flatFilters
    .map((filter) => {
    const filterKey = filter.key;
    const filters = cloneDeep(filter.filters);
    filters.sort((a, b) => customCollator.compare(a.value.toString(), b.value.toString()));
    return {filterString: buildFilterValuesString(filterKey, filters), filterKey};
    })
    .sort((a, b) => customCollator.compare(a.filterString, b.filterString))
    .forEach(({filterString, filterKey}) => {
    if (!similarSearchIgnoredFilters.has(filterKey)) {
    filterSet.add(filterKey);
    }
    if (similarSearchValueBasedFilters.has(filterKey)) {
    filterSet.add(filterString.trim());
    }
    orderedQuery += ` ${filterString}`;
    });
    const similarSearchHash = hashText(Array.from(filterSet).join(''), 2 ** 32);
    const recentSearchHash = hashText(orderedQuery, 2 ** 32);
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY}:${query.sortBy}`;
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER}:${query.sortOrder}`;
    if (query.policyID) {
    orderedQuery += ` ${CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID}:${Array.isArray(query.policyID) ? query.policyID.join(',') : query.policyID} `;
    }
    const primaryHash = hashText(orderedQuery, 2 ** 32);
    return {primaryHash, recentSearchHash, similarSearchHash};
    }

    Then update the SearchQueryJSON type to include the new sortingHash

    type SearchQueryJSON = {
        inputQuery: SearchQueryString;
        hash: number;
        /** Hash used for putting queries in recent searches list. It ignores sortOrder and sortBy, because we want to treat queries differing only in sort params as the same query */
        recentSearchHash: number;
        /** Use similarSearchHash to test if two searchers are similar i.e. have same filters but not necessary same values */
        similarSearchHash: number;
        sortingHash: number;
        flatFilters: QueryFilters;
    } & SearchQueryAST;

    type SearchQueryJSON = {
    inputQuery: SearchQueryString;
    hash: number;
    /** Hash used for putting queries in recent searches list. It ignores sortOrder and sortBy, because we want to treat queries differing only in sort params as the same query */
    recentSearchHash: number;
    /** Use similarSearchHash to test if two searchers are similar i.e. have same filters but not necessary same values */
    similarSearchHash: number;
    flatFilters: QueryFilters;
    } & SearchQueryAST;

    And add it to the result on buildSearchQueryJSON

            result.inputQuery = query;
            result.flatFilters = flatFilters;
            const {primaryHash, recentSearchHash, similarSearchHash, sortingHash} = getQueryHashes(result);
            result.hash = primaryHash;
            result.recentSearchHash = recentSearchHash;
            result.similarSearchHash = similarSearchHash;
            result.sortingHash = sortingHash;

    result.inputQuery = query;
    result.flatFilters = flatFilters;
    const {primaryHash, recentSearchHash, similarSearchHash} = getQueryHashes(result);
    result.hash = primaryHash;
    result.recentSearchHash = recentSearchHash;
    result.similarSearchHash = similarSearchHash;

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    None

    What alternative solutions did you explore? (Optional)

    None

  5. melvin-bot commented on Sep 22, 2025

    @melvin-bot

    @sonialiap Still overdue 6 days?! Let's take care of this!

  6. added
    External
    on Sep 23, 2025
  7. changed the title [-]Search - Some expenses are unselected after sorting[/-] [+][$250] Search - Some expenses are unselected after sorting[/+] on Sep 23, 2025
  8. melvin-bot commented on Sep 23, 2025

    @melvin-bot
  9. added
    Help Wanted
    on Sep 23, 2025
  10. melvin-bot commented on Sep 23, 2025

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (External)

  11. 36 remaining items

  12. melvin-bot commented on Nov 6, 2025

    @melvin-bot

    Reviewing label has been removed, please complete the "BugZero Checklist".

  13. removed
    Reviewing
    on Nov 6, 2025
  14. melvin-bot commented on Nov 6, 2025

    @melvin-bot

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.2.45-6 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2025-11-13. 🎊

    For reference, here are some details about the assignees on this issue:

  15. melvin-bot commented on Nov 6, 2025

    @melvin-bot

    @eVoloshchak / @abzokhattab @sonialiap The PR fixing this issue has been merged! The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]

  16. sonialiap commented on Nov 13, 2025

    @sonialiap
    Contributor

    Payment summary:
    @eVoloshchak $250 please request in NewDot and complete the checklist
    @abzokhattab $250 paid in upwork ✔️

  17. added
    Daily
    and removed
    Weekly
    on Nov 13, 2025
  18. sonialiap commented on Nov 24, 2025

    @sonialiap
    Contributor

    @eVoloshchak bump on completing the checklist

  19. eVoloshchak commented on Nov 24, 2025

    @eVoloshchak
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR has been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to comment: no offending PR, we ended up changing the expected behavior to "unselect all when filters are changed"

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion: regression wasn't critical

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue:https://github.com/Expensify/Expensify/issues/571717

    Regression Test Proposal

    Precondition:

    • Account with atleast 50 expenses

    Test:

    1. Go to Reports tab on web -> Expenses
    2. Scroll down to loads all expenses
    3. Select all expenses
    4. Try to sort them by e.g. date
    5. Validate that the selection is cleared and no item is selected after sorting.

    Do we agree 👍 or 👎

  20. sonialiap commented on Nov 25, 2025

    @sonialiap
    Contributor

    Thanks!

  21. garrettmknight commented on Dec 1, 2025

    @garrettmknight
    Contributor

    $250 approved for @eVoloshchak

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions