Skip to content

fix: Preserve all matching selection after deselecting an expense#95902

Open
emkhalid wants to merge 15 commits into
Expensify:mainfrom
emkhalid:fix/preserve-all-matching-selection
Open

fix: Preserve all matching selection after deselecting an expense#95902
emkhalid wants to merge 15 commits into
Expensify:mainfrom
emkhalid:fix/preserve-all-matching-selection

Conversation

@emkhalid

@emkhalid emkhalid commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

This PR preserves the “all matching items” selection when individual expenses are unchecked.

It:

  • Tracks unchecked expenses as explicit exclusions while keeping all-matching selection active.
  • Automatically selects newly loaded matching expenses while preserving exclusions.
  • Shows the total matching count minus excluded expenses.
  • Keeps the count and selection stable while loading additional pages or opening and closing expenses.
  • Calculates totals on demand without advancing pagination or recalculating totals for every page.
  • Passes excluded transaction IDs to supported basic/current-view CSV exports.

Fixed Issues

$ #94143
PROPOSAL: #94143 (comment)

Tests

Precondition: Use an account with more than 50 expenses.

  1. Select all matching expenses and Exclude one expense

    1. Navigate to Spend > Expenses.
    2. Open the bulk-selection menu and choose Select all.
    3. Verify the button displays “All matching items selected”.
    4. After selecting all matching expenses, uncheck one expense.
    5. Verify only that expense becomes unchecked.
    6. Verify the button displays the total matching count minus one.
    7. Verify all other matching expenses remain selected.
  2. Preserve selection during pagination

    1. Exclude one expense after selecting all matching expenses.
    2. Scroll to the bottom and load the next page.
    3. Verify newly loaded expenses are automatically checked.
    4. Verify the excluded expense remains unchecked.
    5. Verify the selected count does not increase when the next page loads.
  3. Avoid recalculating totals during pagination

    1. Select all matching expenses and wait for the total to load.
    2. Scroll to load another page.
    3. Verify the pagination Search request uses shouldCalculateTotals: false.
    4. Verify the request loads only the next page.
  4. Recheck an excluded expense

    1. Select all matching expenses.
    2. Uncheck one expense.
    3. Recheck the same expense.
    4. Verify it is selected again.
    5. Verify the button returns to “All matching items selected” when no exclusions remain.
  5. Exclude multiple expenses

    1. Select all matching expenses.
    2. Uncheck multiple expenses across loaded pages.
    3. Verify every unchecked expense remains excluded.
    4. Verify the selected count decreases once for each excluded expense.
    5. Recheck the expenses and verify the count increases correctly.
  6. Verify grouped and expense-report selection

    1. Open a grouped expense or expense-report search.
    2. Select all matching items.
    3. Exclude one selection unit.
    4. Verify the excluded row is displayed as unchecked.
    5. Verify the parent group/report is not displayed as fully selected when one of its expenses is excluded.
    6. Verify newly loaded matching rows remain selected.
  7. Verify the selection footer

    1. Select all matching expenses and wait for the count and total.
    2. Exclude one expense.
    3. Verify the footer count subtracts the excluded expense.
    4. Verify the footer total subtracts the excluded expense amount.
    5. Recheck the expense and verify its count and amount are restored.
  • Verify that no errors appear in the JS console

Offline tests

N/A

QA Steps

Same as Tests

// TODO: These must be filled out, or the issue title must include "[No QA]."

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
  1. Select all matching expenses and Exclude one expense
android-native-Select.all.matching.expenses.and.Exclude.one.expense.mov
  1. Preserve selection during pagination
android-native-Preserve.selection.during.pagination.mp4
  1. Avoid recalculating totals during pagination

Not applicable.

  1. Recheck an excluded expense
android-native-Recheck.an.excluded.expense.mov
  1. Exclude multiple expenses
android-native-Exclude.multiple.expenses.mov
  1. Verify grouped and expense-report selection
android-native-Verify.grouped.and.expense-report.selection.mp4
  1. Verify the selection footer
andoir-native-Verify.the.selection.footer.mov
Android: mWeb Chrome
  1. Select all matching expenses and Exclude one expense
android-web-Select.all.matching.expenses.and.Exclude.one.expense.mov
  1. Preserve selection during pagination
android-web-Preserve.selection.during.pagination.mp4
  1. Avoid recalculating totals during pagination

Not applicable.

  1. Recheck an excluded expense
android-web-Recheck.an.excluded.expense.mov
  1. Exclude multiple expenses
android-web-Exclude.multiple.expenses.mov
  1. Verify grouped and expense-report selection
android-web-Verify.grouped.and.expense-report.selection.mp4
  1. Verify the selection footer
andoir-web-Verify.the.selection.footer.mov
iOS: Native
  1. Select all matching expenses and Exclude one expense
ios-native-Select.all.matching.expenses.and.Exclude.one.expense.mov
  1. Preserve selection during pagination
ios-native-Preserve.selection.during.pagination.mp4
  1. Avoid recalculating totals during pagination

Not applicable.

  1. Recheck an excluded expense
ios-native-Recheck.an.excluded.expense.mov
  1. Exclude multiple expenses
ios-native-Exclude.multiple.expenses.mov
  1. Verify grouped and expense-report selection
ios-native-Verify.grouped.and.expense-report.selection.mov
  1. Verify the selection footer
ios-native-Verify.the.selection.footer.mov
iOS: mWeb Safari
  1. Select all matching expenses and Exclude one expense
ios-web-Select.all.matching.expenses.and.Exclude.one.expense.mov
  1. Preserve selection during pagination
ios-web-Preserve.selection.during.pagination.mp4
  1. Avoid recalculating totals during pagination

Not applicable.

  1. Recheck an excluded expense
ios-web-Recheck.an.excluded.expense.mov
  1. Exclude multiple expenses
ios-web-Exclude.multiple.expenses.mov
  1. Verify grouped and expense-report selection
ios-web-Verify.grouped.and.expense-report.selection.mov
  1. Verify the selection footer
ios-web-Verify.the.selection.footer.mov
MacOS: Chrome / Safari
  1. Select all matching expenses and Exclude one expense
Select.all.matching.expenses.and.Exclude.one.expense.mov
  1. Preserve selection during pagination
Preserve.selection.during.pagination.mov
  1. Avoid recalculating totals during pagination
Avoid.recalculating.totals.during.pagination.mp4
  1. Recheck an excluded expense
Recheck.an.excluded.expense.mov
  1. Exclude multiple expenses
Exclude.multiple.expenses.mov
  1. Verify grouped and expense-report selection
Verify.grouped.and.expense-report.selection.webm
  1. Verify the selection footer
Verify.the.selection.footer.mov

@codecov

codecov Bot commented Jul 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/components/Search/SearchContextDefinitions.ts 51.85% <ø> (ø)
src/hooks/useSearchBulkActions.ts 54.05% <100.00%> (+0.19%) ⬆️
src/hooks/useSearchShouldCalculateTotals.ts 100.00% <100.00%> (ø)
src/components/Search/SearchBulkActionsButton.tsx 91.66% <88.23%> (+90.21%) ⬆️
...h/SearchList/ListItem/TransactionGroupListItem.tsx 74.19% <33.33%> (-0.49%) ⬇️
...s/Search/SearchPageHeader/SearchActionsBarWide.tsx 11.11% <0.00%> (-1.39%) ⬇️
src/libs/actions/Search.ts 44.78% <70.00%> (+3.58%) ⬆️
src/components/Search/SearchSelectionFooter.tsx 88.23% <80.00%> (+46.56%) ⬆️
src/components/Search/SearchSelectionProvider.tsx 68.75% <81.81%> (+16.89%) ⬆️
...c/components/Search/SearchWriteActionsProvider.tsx 0.00% <0.00%> (ø)
... and 1 more
... and 169 files with indirect coverage changes

@emkhalid
emkhalid marked this pull request as ready for review July 12, 2026 19:55
@emkhalid
emkhalid requested review from a team as code owners July 12, 2026 19:55
@melvin-bot
melvin-bot Bot requested review from flaviadefaria and mkhutornyi July 12, 2026 19:55
@melvin-bot

melvin-bot Bot commented Jul 12, 2026

Copy link
Copy Markdown

@mkhutornyi Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed request for a team July 12, 2026 19:55

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dc68c95a59

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/components/Search/SearchSelectionProvider.tsx Outdated
@mkhutornyi

Copy link
Copy Markdown
Contributor

@codex review

@mkhutornyi mkhutornyi mentioned this pull request Jul 14, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Reviewed the exclusion-tracking approach. The core design — keeping areAllMatchingItemsSelected active and recording unchecked rows as excludedTransactions — is sound, the reconciliation in applySelection (add removed keys, drop re-added keys) reads correctly, and the lifecycle resets (clear / turn-off / re-select-all all wipe exclusions) look complete. Test coverage is good. A few things worth confirming before merge:

1. Count vs. total may disagree for partially-excluded expense reports — worth confirming
In expense-report view the excluded count collapses to unique reportIDs (SearchSelectionFooter.tsx:66, same in SearchBulkActionsButton.tsx:133), but the total subtracts every excluded transaction's amount (SearchSelectionFooter.tsx:72). If a report can ever be partially excluded (some of its transactions unchecked, not all), the count would drop by a whole report while the total only drops by those transactions. This is fine as long as unchecking in expense-report view is always report-granular — please confirm that's guaranteed.

2. Pagination offset reset is the highest-risk change — please QA carefully
index.tsx:186-193 adds a setTimeout(() => setOffset(...)) that can move offset backward (Math.min(offset, serverOffset)) when the all-matching count is missing, plus the new guard clauses around index.tsx:416. This is the most intricate part of the PR. Suggest an explicit test: load several pages, then hit Select all, and verify the list doesn't jump/scroll-reset and that no duplicate/extra Search request fires.

3. Negative-amount (refund/credit) rows — low priority
getTransactionTotal always adds Math.abs(amount), so excluding a refund still reduces the remaining total. This mirrors the pre-existing client-total convention, so it's likely intentional — just confirm the server total uses the same absolute-value convention so the subtraction at SearchSelectionFooter.tsx:72 stays correct.

4. Confirm the backend honors excludedTransactionIDList
The new param is now sent on the CSV export command. Make sure the export backend actually reads and filters on it — otherwise excluded rows will still appear in the downloaded CSV even though the UI count/total exclude them.

None of these are blockers on their own, but 1 and 2 are the ones I'd verify with a manual pass before merging.

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Code-quality pass (separate from the correctness notes above — this is about readability/maintainability, not bugs). The PR is generally clean: types are documented, the deps-omission comments were kept in sync, and the new unit tests are well-structured. A few things worth tightening:

1. Duplicated — and subtly divergent — selection-count logic (worth consolidating)
The "count selection units, expanding groups and de-duping expense-report rows" logic now exists twice with different implementations:

Two counters that are supposed to agree on the same selection can drift apart. Extracting one shared helper (e.g. in SearchUIUtils) would remove the duplication and guarantee the button and footer report the same number.

2. Pagination/totals orchestration in index.tsx is hard to follow
The new flow spreads across the render body and two effects: searchRequestOffset at index.tsx:186 plus the didJustFinishAllMatchingTotalsRequest / didEnableAllMatchingTotalsWithExistingCount guard booleans around index.tsx:416. This is a lot of stateful branching in an already-large component. Pulling it into a dedicated hook (e.g. useAllMatchingTotalsPagination) with a clear contract would make it far easier to reason about and unit-test in isolation.

3. setTimeout(() => setOffset(...), 0) needs a "why" comment
index.tsx:192 defers a state update via a zero-delay timeout. That's an unusual pattern and reads as a workaround — a one-line comment explaining what it's avoiding (render-phase set-state / effect ordering) would save the next reader a lot of guessing.

4. Redundant per-consumer default for excludedTransactions
excludedTransactions = getEmptyObject<SelectedTransactions>() is repeated in ~6 consumers (e.g. SearchBulkActionsButton.tsx:52), but the context already defaults it to {} in SearchContextDefinitions. The fallbacks are dead defensiveness — dropping them (or relying solely on the context default) removes the repetition.

5. Minor: naming drift
excludedTransactionIDs, excludedTransactionIDList, and excludedTransactionsKeys all appear for closely related things. Not worth churning on its own, but aligning them would reduce friction.

Items 1 and 2 are the ones with real maintenance value; the rest are polish.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f0b00c16ff

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/components/Search/SearchList/ListItem/TransactionGroupListItem.tsx Outdated

@mkhutornyi mkhutornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address AI review comments above

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Regression hunt on this diff. Most of the change is correctly gated behind the new all-matching/exclusion state, so ordinary selection and pagination are largely untouched. The risks below are the spots where existing behavior changes:

R1 — Group / expense-report rows now derive their checked state purely from child isSelected, dropping the previous fallback (highest risk)
ExpenseReportListItem.tsx:108 and TransactionGroupListItem.tsx:226 both dropped the || liveRowSelected fallback for non-empty rows. A parent row is now checked only when every one of its currently-loaded children has isSelected === true (isSelectAllChecked / areAllReportTransactionsSelected). Previously the row was also checked whenever the row itself was covered by select-all.

Normal per-item selection is fine — for non-empty groups/reports selection is keyed by child transaction ID, so liveRowSelected(rowKey) was already effectively dead there (see the code comment). The risk is specifically Select all matching in grouped and expense-report views: if reconcile hasn't yet marked every child isSelected (timing, or a group whose child rows aren't all loaded/reconciled), the parent row can render unchecked or indeterminate even with zero exclusions.
→ Verify: Select all in a grouped view (by category/merchant) and in expense-report view → every group/report shows fully checked immediately, not indeterminate.

R2 — useSearchShouldCalculateTotals no longer forces totals for all-matching after pagination
useSearchShouldCalculateTotals.ts:25 changed the all-matching branch from return true to return enabled. This is the intended optimization, but it's a semantics change to a shared hook: previously all-matching always requested server totals regardless of offset.
→ Verify count/total still populate correctly when the user loads several pages before hitting Select all (the case the old return true specifically protected).

R3 — Pagination offset can be pushed backward under all-matching
index.tsx:186-193 adds a setTimeout(() => setOffset(Math.min(offset, serverOffset))) when the all-matching count is missing, plus early-return guards near index.tsx:416. Gated behind all-matching, so plain pagination is unaffected, but within all-matching this can reposition the list / re-fire a request. → QA: paginate deep, then Select all, and watch for a scroll jump or duplicate Search request.

R4 — SearchActionsBarWide broadened its subscription
SearchActionsBarWide.tsx:29 swapped the narrow useSelectionCounts() read for the full useSearchSelectionContext(), so it now re-renders on any selection-context change (the rest of this module deliberately uses narrow subscriptions). Minor perf regression. useSelectionCounts is still exported — worth confirming the narrow-layout bulk bar uses the same hasSelectedTransactions gate so wide and narrow don't diverge for all-matching.

R1 is the one I'd verify first, since it touches the existing select-all display and isn't behind the exclusion flag.

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Regression scan of PR #95902. These are behaviors that worked before and could break — none are confirmed at runtime (logic-derived), so I've ranked by likelihood and flagged what to test.

1. Group/report header checkbox can show unchecked under "Select all matching" (medium)
The header selected-state no longer trusts the global all-matching flag — it now requires every child transaction's isSelected to be populated:

Previously both fell back to liveRowSelected, which is true for every row while all-matching is active. Now, immediately after tapping Select all (before useReconcileSelectionWithData populates each child's isSelected), or for a group whose children aren't loaded/reconciled, isSelectAllChecked/areAllReportTransactionsSelected is false → the header renders unchecked or indeterminate even though the row is fully covered by the selection. Test: grouped + expense-report views — tap Select all and watch for headers that flash (or stay) unchecked, and scroll new groups into view.

2. Pagination offset can be pulled backward (medium)
index.tsx:186-194 schedules setOffset(Math.min(offset, serverOffset)) whenever the all-matching count is missing. If local offset is ahead of the server's last-responded offset when Select all fires, this rewrites pagination state backward. The three guard clauses added around index.tsx:416 suggest request-loop edge cases were already hit here. Test: load several pages, then Select all (on an ad-hoc query whose count wasn't precomputed), and verify the list doesn't shrink/scroll-jump and no duplicate Search requests fire.

3. Count/total no longer refreshed while paginating under all-matching (low)
useSearchShouldCalculateTotals.ts:25 changed all-matching from always-true to return enabled, so pagination requests (offset > 0, count present) skip totals. This is the intended perf win, but the displayed count/total is now fetched once and reused — if underlying data changes mid-session it can go stale. Low impact; noting for awareness.

4. Bulk-actions bar stays visible when all loaded rows are excluded (low)
SearchActionsBarWide.tsx:29 now gates on hasSelectedTransactions, which is true whenever areAllMatchingItemsSelected is set — even if the user unchecks every currently-loaded row. The bar (and its count) will still render. Likely acceptable since "all matching" is conceptually still on, but confirm the displayed count/label reads sensibly in that state.

Item 1 is the one I'd verify first — it touches the most visible everyday flow (Select all in grouped/report views).

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi I found an additional issue while testing this PR:

  • Expenses: The selected count works correctly.
  • Reports: There are 58 report rows containing 320 expenses. After selecting all reports and unchecking one, the button shows 319 selected instead of 57 selected.

The backend returns search.count: 320 for the expense-report search, so the frontend does not know the total number of report rows before all pages are loaded.

Should we address this in the current PR? It appears the backend may need to return the total report count, possibly as a separate field.

staging.mp4

@mkhutornyi

Copy link
Copy Markdown
Contributor

The original scope is Spend > Expenses tab.
If that bug happens in production, let's fix this separately.

@emkhalid

Copy link
Copy Markdown
Contributor Author

🤖 Reviewed the exclusion-tracking approach. The core design — keeping areAllMatchingItemsSelected active and recording unchecked rows as excludedTransactions — is sound, the reconciliation in applySelection (add removed keys, drop re-added keys) reads correctly, and the lifecycle resets (clear / turn-off / re-select-all all wipe exclusions) look complete. Test coverage is good. A few things worth confirming before merge:

1. Count vs. total may disagree for partially-excluded expense reports — worth confirming In expense-report view the excluded count collapses to unique reportIDs (SearchSelectionFooter.tsx:66, same in SearchBulkActionsButton.tsx:133), but the total subtracts every excluded transaction's amount (SearchSelectionFooter.tsx:72). If a report can ever be partially excluded (some of its transactions unchecked, not all), the count would drop by a whole report while the total only drops by those transactions. This is fine as long as unchecking in expense-report view is always report-granular — please confirm that's guaranteed.

2. Pagination offset reset is the highest-risk change — please QA carefully index.tsx:186-193 adds a setTimeout(() => setOffset(...)) that can move offset backward (Math.min(offset, serverOffset)) when the all-matching count is missing, plus the new guard clauses around index.tsx:416. This is the most intricate part of the PR. Suggest an explicit test: load several pages, then hit Select all, and verify the list doesn't jump/scroll-reset and that no duplicate/extra Search request fires.

3. Negative-amount (refund/credit) rows — low priority getTransactionTotal always adds Math.abs(amount), so excluding a refund still reduces the remaining total. This mirrors the pre-existing client-total convention, so it's likely intentional — just confirm the server total uses the same absolute-value convention so the subtraction at SearchSelectionFooter.tsx:72 stays correct.

4. Confirm the backend honors excludedTransactionIDList The new param is now sent on the CSV export command. Make sure the export backend actually reads and filters on it — otherwise excluded rows will still appear in the downloaded CSV even though the UI count/total exclude them.

None of these are blockers on their own, but 1 and 2 are the ones I'd verify with a manual pass before merging.

I verified all four points and found no regression within this PR’s scope:

  1. Expense-report count/total: Report selection is all-or-nothing. Unchecking one report excluded all its transactions, reduced the report count by one, and subtracted the correct total. The separate Reports counter issue is pre-existing and out of scope.

  2. Pagination: After loading multiple pages and selecting all, only one totals request was sent. The list did not jump or lose rows, and later pagination requests used shouldCalculateTotals: false.

  3. Refunds/credits: The backend and frontend used consistent signed totals. Excluding a refund correctly increased the remaining spend total.

  4. CSV export: The frontend sent the exact excluded transaction IDs, and the generated CSV omitted those expenses while retaining the other selected expenses.

No changes are required for these points.

@emkhalid

Copy link
Copy Markdown
Contributor Author

🤖 Code-quality pass (separate from the correctness notes above — this is about readability/maintainability, not bugs). The PR is generally clean: types are documented, the deps-omission comments were kept in sync, and the new unit tests are well-structured. A few things worth tightening:

1. Duplicated — and subtly divergent — selection-count logic (worth consolidating) The "count selection units, expanding groups and de-duping expense-report rows" logic now exists twice with different implementations:

Two counters that are supposed to agree on the same selection can drift apart. Extracting one shared helper (e.g. in SearchUIUtils) would remove the duplication and guarantee the button and footer report the same number.

2. Pagination/totals orchestration in index.tsx is hard to follow The new flow spreads across the render body and two effects: searchRequestOffset at index.tsx:186 plus the didJustFinishAllMatchingTotalsRequest / didEnableAllMatchingTotalsWithExistingCount guard booleans around index.tsx:416. This is a lot of stateful branching in an already-large component. Pulling it into a dedicated hook (e.g. useAllMatchingTotalsPagination) with a clear contract would make it far easier to reason about and unit-test in isolation.

3. setTimeout(() => setOffset(...), 0) needs a "why" comment index.tsx:192 defers a state update via a zero-delay timeout. That's an unusual pattern and reads as a workaround — a one-line comment explaining what it's avoiding (render-phase set-state / effect ordering) would save the next reader a lot of guessing.

4. Redundant per-consumer default for excludedTransactions excludedTransactions = getEmptyObject<SelectedTransactions>() is repeated in ~6 consumers (e.g. SearchBulkActionsButton.tsx:52), but the context already defaults it to {} in SearchContextDefinitions. The fallbacks are dead defensiveness — dropping them (or relying solely on the context default) removes the repetition.

5. Minor: naming drift excludedTransactionIDs, excludedTransactionIDList, and excludedTransactionsKeys all appear for closely related things. Not worth churning on its own, but aligning them would reduce friction.

Items 1 and 2 are the ones with real maintenance value; the rest are polish.

Addressed the safe, in-scope cleanup:

  • Added a comment explaining why the offset update is deferred with setTimeout.

I did not change the other suggestions:

  • The button/footer count consolidation and pagination-hook extraction are broader refactors outside this issue’s scope.
  • The empty defaults are harmless defensive fallbacks.
  • The different exclusion names represent different data shapes and the API parameter name must match the backend contract.

No functionality was changed.

@emkhalid

Copy link
Copy Markdown
Contributor Author

🤖 Regression hunt on this diff. Most of the change is correctly gated behind the new all-matching/exclusion state, so ordinary selection and pagination are largely untouched. The risks below are the spots where existing behavior changes:

R1 — Group / expense-report rows now derive their checked state purely from child isSelected, dropping the previous fallback (highest risk) ExpenseReportListItem.tsx:108 and TransactionGroupListItem.tsx:226 both dropped the || liveRowSelected fallback for non-empty rows. A parent row is now checked only when every one of its currently-loaded children has isSelected === true (isSelectAllChecked / areAllReportTransactionsSelected). Previously the row was also checked whenever the row itself was covered by select-all.

Normal per-item selection is fine — for non-empty groups/reports selection is keyed by child transaction ID, so liveRowSelected(rowKey) was already effectively dead there (see the code comment). The risk is specifically Select all matching in grouped and expense-report views: if reconcile hasn't yet marked every child isSelected (timing, or a group whose child rows aren't all loaded/reconciled), the parent row can render unchecked or indeterminate even with zero exclusions. → Verify: Select all in a grouped view (by category/merchant) and in expense-report view → every group/report shows fully checked immediately, not indeterminate.

R2 — useSearchShouldCalculateTotals no longer forces totals for all-matching after pagination useSearchShouldCalculateTotals.ts:25 changed the all-matching branch from return true to return enabled. This is the intended optimization, but it's a semantics change to a shared hook: previously all-matching always requested server totals regardless of offset. → Verify count/total still populate correctly when the user loads several pages before hitting Select all (the case the old return true specifically protected).

R3 — Pagination offset can be pushed backward under all-matching index.tsx:186-193 adds a setTimeout(() => setOffset(Math.min(offset, serverOffset))) when the all-matching count is missing, plus early-return guards near index.tsx:416. Gated behind all-matching, so plain pagination is unaffected, but within all-matching this can reposition the list / re-fire a request. → QA: paginate deep, then Select all, and watch for a scroll jump or duplicate Search request.

R4 — SearchActionsBarWide broadened its subscription SearchActionsBarWide.tsx:29 swapped the narrow useSelectionCounts() read for the full useSearchSelectionContext(), so it now re-renders on any selection-context change (the rest of this module deliberately uses narrow subscriptions). Minor perf regression. useSelectionCounts is still exported — worth confirming the narrow-layout bulk bar uses the same hasSelectedTransactions gate so wide and narrow don't diverge for all-matching.

R1 is the one I'd verify first, since it touches the existing select-all display and isn't behind the exclusion flag.

Verified all four concerns:

  1. Fixed the narrow-screen unloaded-group checkbox flicker.
  2. Confirmed totals load after pagination and fixed the Slow 3G race that dropped the totals request.
  3. Confirmed pagination causes no scroll jump, missing rows, or duplicate requests.
  4. Confirmed the wide bulk-actions subscription does not introduce a meaningful regression.

No broader pagination, totals, or context refactor was made.

@emkhalid

Copy link
Copy Markdown
Contributor Author

🤖 Regression scan of PR #95902. These are behaviors that worked before and could break — none are confirmed at runtime (logic-derived), so I've ranked by likelihood and flagged what to test.

1. Group/report header checkbox can show unchecked under "Select all matching" (medium) The header selected-state no longer trusts the global all-matching flag — it now requires every child transaction's isSelected to be populated:

Previously both fell back to liveRowSelected, which is true for every row while all-matching is active. Now, immediately after tapping Select all (before useReconcileSelectionWithData populates each child's isSelected), or for a group whose children aren't loaded/reconciled, isSelectAllChecked/areAllReportTransactionsSelected is false → the header renders unchecked or indeterminate even though the row is fully covered by the selection. Test: grouped + expense-report views — tap Select all and watch for headers that flash (or stay) unchecked, and scroll new groups into view.

2. Pagination offset can be pulled backward (medium) index.tsx:186-194 schedules setOffset(Math.min(offset, serverOffset)) whenever the all-matching count is missing. If local offset is ahead of the server's last-responded offset when Select all fires, this rewrites pagination state backward. The three guard clauses added around index.tsx:416 suggest request-loop edge cases were already hit here. Test: load several pages, then Select all (on an ad-hoc query whose count wasn't precomputed), and verify the list doesn't shrink/scroll-jump and no duplicate Search requests fire.

3. Count/total no longer refreshed while paginating under all-matching (low) useSearchShouldCalculateTotals.ts:25 changed all-matching from always-true to return enabled, so pagination requests (offset > 0, count present) skip totals. This is the intended perf win, but the displayed count/total is now fetched once and reused — if underlying data changes mid-session it can go stale. Low impact; noting for awareness.

4. Bulk-actions bar stays visible when all loaded rows are excluded (low) SearchActionsBarWide.tsx:29 now gates on hasSelectedTransactions, which is true whenever areAllMatchingItemsSelected is set — even if the user unchecks every currently-loaded row. The bar (and its count) will still render. Likely acceptable since "all matching" is conceptually still on, but confirm the displayed count/label reads sensibly in that state.

Item 1 is the one I'd verify first — it touches the most visible everyday flow (Select all in grouped/report views).

Reviewed all four concerns:

  • The grouped-row flicker was valid and fixed.
  • Pagination/offset testing exposed a totals-request race, which was fixed.
  • Potentially stale totals after external data changes are outside this issue’s scope.
  • Keeping the bulk bar visible while all-matching remains active is expected behavior.

No further changes are needed.

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi thanks for the review, I addressed your comments please review again.

@mkhutornyi

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari

@mkhutornyi mkhutornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not bugs but left some questions to clarify

Comment on lines 946 to +1047
@@ -1023,6 +1044,7 @@ function search({
})
.finally(() => {
inFlightSearchRequests.delete(dedupeKey);
return inFlightRequestState.pendingTotalsRequest?.();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this change fix?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes a Slow 3G race. For example, if pagination with shouldCalculateTotals: false is still running when the user selects all, the new request with shouldCalculateTotals: true was treated as a duplicate and dropped. This queues that totals request and runs it after pagination finishes, so the correct count and footer load.

// so later pagination requests can avoid recalculating totals.
if (areAllMatchingItemsSelected) {
return true;
return enabled;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's this for?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This prevents totals from being recalculated on every page after Select all.

enabled is true when the count is missing, so selecting all still sends shouldCalculateTotals: true. Once the count is available, later pagination uses shouldCalculateTotals: false, keeping those requests lightweight.

Comment thread src/hooks/useSearchBulkActions.ts Outdated

if (areAllMatchingItemsSelected) {
if (selectedTransactionsKeys.length === 0 || !hash) {
if (!hash) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this condition removed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All-matching selection does not require loaded transaction IDs. For example, if the user excludes every loaded row, selectedTransactionsKeys is empty but off-screen matching expenses are still selected.

The export uses the search query plus excludedTransactionIDList, so only the search hash is required here.

continue;
}
if (reportKey && (reportKey in selectedTransactions || areAllMatchingItemsSelected)) {
if (reportKey && !Object.hasOwn(excludedTransactions, reportKey) && (reportKey in selectedTransactions || areAllMatchingItemsSelected)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for not using !excludedTransactions[reportKey]?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

excludedTransactions is a key-presence map, so Object.hasOwn() checks whether the report key is explicitly excluded instead of relying on the value’s truthiness. It also matches the other exclusion checks in this flow.


for (const transactionItem of transactionGroup.transactions) {
const listKey = transactionItem.keyForList ?? transactionItem.transactionID;
const isExcluded = Object.hasOwn(excludedTransactions, listKey) || Object.hasOwn(excludedTransactions, transactionItem.transactionID);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. Why Object.hasOwn used?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the same reason: exclusions are identified by key presence. The map may use either keyForList or transactionID, so Object.hasOwn() explicitly checks both possible keys and matches the other selection-map checks.

Comment on lines +45 to +50
if (isExpenseReportType) {
return new Set(
Object.values(transactions)
.map((transaction) => transaction.reportID)
.filter((reportID): reportID is string => !!reportID),
).size;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, please make sure that this PR doesn't affect production behavior on Spend > Reports tab

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed. I restored Spend > Reports to its existing main behavior and scoped the new exclusion handling to type:expense.

Reports no longer preserve all-matching mode or apply exclusion-aware counters, totals, pagination, bulk-bar, checkbox, or export behavior. The existing Reports count issue remains unchanged and will be handled separately.

Comment on lines 184 to +432
@@ -400,18 +412,36 @@ function Search({
return;
}

// Once a totals request for an already-loaded page completes, `shouldCalculateTotals` switches
// back to false. Do not immediately repeat that same page request without totals; the next real
// pagination offset change will trigger the appropriate request.
const didJustFinishAllMatchingTotalsRequest =
areAllMatchingItemsSelected &&
previousShouldCalculateTotals === true &&
!shouldCalculateTotals &&
typeof searchResults?.search?.count === 'number' &&
searchResults.search.offset === offset;
if (didJustFinishAllMatchingTotalsRequest) {
return;
}
const didEnableAllMatchingTotalsWithExistingCount =
areAllMatchingItemsSelected && previousShouldCalculateTotals === false && shouldCalculateTotals && typeof searchResults?.search?.count === 'number';
if (didEnableAllMatchingTotalsWithExistingCount) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What bug does this change fix?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This prevents duplicate Search requests introduced by the lazy totals flow in this PR:

  • When a totals response arrives, shouldCalculateTotals changes from true to false. Without the first guard, the same page is immediately requested again without totals.
  • When Select all is enabled and an authoritative count already exists, the second guard avoids requesting that same page again unnecessarily.

Both checks are scoped to the Expenses all-matching flow and prevent redundant requests caused by this fix.

@mkhutornyi

Copy link
Copy Markdown
Contributor

There's a behavorial change.

no loading and immediate "All matching items selected" in this branch:

Screen.Recording.2026-07-19.at.4.59.57.PM.mov

loading and then "x selected" in production:

Screen.Recording.2026-07-19.at.4.59.49.PM.mov

@mkhutornyi

Copy link
Copy Markdown
Contributor

Bug in offline mode:

"All matching items selected" even when there are unselected items

Screen.Recording.2026-07-19.at.5.04.03.PM.mov
Screen.Recording.2026-07-19.at.5.05.33.PM.mov

@mkhutornyi

mkhutornyi commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

@emkhalid please test & compare this branch with staging/production in both online/offline mode.
There should not be any behavioral change other than the original issue fix.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants