Skip to content

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

Open
emkhalid wants to merge 25 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 25 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 55.59% <100.00%> (+1.77%) ⬆️
src/hooks/useSearchShouldCalculateTotals.ts 100.00% <100.00%> (ø)
src/libs/actions/Search.ts 48.20% <100.00%> (+3.12%) ⬆️
src/components/Search/SearchBulkActionsButton.tsx 90.90% <90.47%> (+89.48%) ⬆️
...h/SearchList/ListItem/TransactionGroupListItem.tsx 76.43% <33.33%> (-0.49%) ⬇️
...s/Search/SearchPageHeader/SearchActionsBarWide.tsx 11.11% <0.00%> (-1.39%) ⬇️
src/components/Search/SearchSelectionFooter.tsx 88.23% <80.00%> (+46.56%) ⬆️
src/components/Search/SearchSelectionProvider.tsx 71.71% <84.00%> (+9.98%) ⬆️
...c/components/Search/SearchWriteActionsProvider.tsx 43.93% <36.36%> (-0.65%) ⬇️
... and 1 more
... and 10 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.

@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.

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi Thanks for clarifying that only the original issue behavior should change.

My understanding is that these changes are directly required:

  • Preserve all-matching selection after unchecking an expense.
  • Track unchecked expenses as exclusions.
  • Keep exclusions stable during reconciliation and pagination.
  • Display the authoritative matching count/total minus exclusions.
  • Pass exclusions to supported exports.
  • Keep Reports and normal page selection unchanged.

To clarify, main already sends shouldCalculateTotals: true after selecting all matching items. That existing request provides the count and total required to show the exact N selected value.

This PR also changes how that existing totals request is scheduled: it avoids recalculating totals on later pages, corrects the offset when the count is missing, queues a totals request behind an in-flight non-totals request, and prevents duplicate requests during state transitions.

Would you prefer that we retain these supporting request-flow changes, or restore the exact main scheduling behavior while keeping the exclusion fix?

@mkhutornyi

mkhutornyi commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

The flow change is fine but it should NOT introduce buggy behavior which QA thinks as deploy blocker.

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi Thanks for the detailed review! I've addressed the feedback and fixed the related bugs.

Could you please take another look when you have a chance? Thanks!

I'll also keep testing additional cases while you review to help ensure everything is safe.

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi I've tested as many scenarios as I could, and everything passed. When you have a chance, could you also help test for any regressions so we can avoid potential deploy blockers? Thanks!

@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: 6a96e370a5

ℹ️ 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/hooks/useSearchBulkActions.ts
Comment thread src/hooks/useSearchBulkActions.ts
@MelvinBot

Copy link
Copy Markdown
Contributor

Review — fix: Preserve all matching selection after deselecting an expense

Solid, well-scoped fix for #94143. The excludedTransactions model (keep all-matching active, track unchecked rows as explicit exclusions) is the right approach, the reconcile/row-selection paths are updated consistently, and the test coverage is genuinely good (provider, footer, button, row selection, in-flight dedup, CSV payload). All CI checks pass. Below are the points worth a closer look before merge — no blockers I can confirm, mostly "please verify" items.

1. Backend must honor excludedTransactionIDList (cross-repo dependency)

The exclusion only works end-to-end if the server-side ExportSearchItemsToCSV / QueueExportSearchItemsToCSV commands actually filter out excludedTransactionIDList. This PR is frontend-only — if the backend ignores the new param, an all-matching CSV export will still contain the "excluded" expenses while the UI count says otherwise. Please confirm the backend already accepts and applies this parameter (and that it's live in the same deploy). See useSearchBulkActions.ts:731 and Search.ts export.

2. Behavior change: expense all-matching label with no exclusions

Previously, for type:expense with all-matching and a known server count, the button showed "172 selected". Now SearchBulkActionsButton.tsx:145 leaves selectedAllMatchingItemsCount undefined when excludedItemsCount === 0, so it falls back to "All matching items selected". Expense-report searches still show the number, so the two types now differ. This looks intentional (asserted by the new test), but please confirm it's the desired UX — it's a visible change beyond the bug being fixed.

3. The pagination/totals reconciliation in index.tsx is the highest-risk area

src/components/Search/index.tsx:183-197 plus the two early-return guards at L419-L431 add a lot of interacting state (previousShouldCalculateTotals, searchRequestOffset, a setTimeout(() => setOffset(...), 0), and two "did we just…" heuristics). It's covered by tests and I couldn't find a concrete failure, but it's fragile and hard to reason about:

  • The setTimeout(setOffset, 0) at L195 exists only to dodge react-hooks/set-state-in-effect. Worth a one-line "why" comment beyond the eslint reference, and confirming rapid offset changes (fast scroll → select-all → scroll) can't leave offset oscillating.
  • Please make sure the empty-results / hasMoreResults: false case near the end of the list is exercised manually, since searchRequestOffset can rewind offset back to the server offset when the count is missing.

4. Footer total relies on server total sign convention

SearchSelectionFooter.tsx computes metadata.total - getTransactionTotal(excluded). The unit test uses positive values and passes, but this assumes the server total and the client-derived excluded total share the same sign/units. Worth a quick real-data sanity check (mixed positive/negative amounts, non-USD) that the displayed total actually decreases by the excluded amount.

Minor

  • The in-flight totals-request queuing in Search.ts:966-1065 only preserves one pending totals request per dedupe key — fine given the call sites, but note that a third distinct-params collision would be dropped silently.
  • Lots of excludedTransactions = getEmptyObject<SelectedTransactions>() default-param reads. These are safe because the shared frozen empty object is only read (or spread) and never mutated in place — good, just keep that invariant if this pattern spreads.

Nothing here is a hard blocker from a static read; #1 (backend contract) is the one I'd nail down before this ships, and #2 is a UX confirmation.

@mkhutornyi

mkhutornyi commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Bug: "0 selected" remaining when unselect all items one by one

Screenshot 2026-07-26 at 8 08 47 PM

And then when "Selected all" again, table header checkbox is still checked off.

Screen.Recording.2026-07-26.at.8.14.25.PM.mov

@mkhutornyi

Copy link
Copy Markdown
Contributor

The original issue isn't fixed in offline mode. And Expenses: x Total spend: x is not displayed at the footer.

Screen.Recording.2026-07-26.at.8.13.14.PM.mov

@emkhalid

Copy link
Copy Markdown
Contributor Author

Review — fix: Preserve all matching selection after deselecting an expense

Solid, well-scoped fix for #94143. The excludedTransactions model (keep all-matching active, track unchecked rows as explicit exclusions) is the right approach, the reconcile/row-selection paths are updated consistently, and the test coverage is genuinely good (provider, footer, button, row selection, in-flight dedup, CSV payload). All CI checks pass. Below are the points worth a closer look before merge — no blockers I can confirm, mostly "please verify" items.

1. Backend must honor excludedTransactionIDList (cross-repo dependency)

The exclusion only works end-to-end if the server-side ExportSearchItemsToCSV / QueueExportSearchItemsToCSV commands actually filter out excludedTransactionIDList. This PR is frontend-only — if the backend ignores the new param, an all-matching CSV export will still contain the "excluded" expenses while the UI count says otherwise. Please confirm the backend already accepts and applies this parameter (and that it's live in the same deploy). See useSearchBulkActions.ts:731 and Search.ts export.

2. Behavior change: expense all-matching label with no exclusions

Previously, for type:expense with all-matching and a known server count, the button showed "172 selected". Now SearchBulkActionsButton.tsx:145 leaves selectedAllMatchingItemsCount undefined when excludedItemsCount === 0, so it falls back to "All matching items selected". Expense-report searches still show the number, so the two types now differ. This looks intentional (asserted by the new test), but please confirm it's the desired UX — it's a visible change beyond the bug being fixed.

3. The pagination/totals reconciliation in index.tsx is the highest-risk area

src/components/Search/index.tsx:183-197 plus the two early-return guards at L419-L431 add a lot of interacting state (previousShouldCalculateTotals, searchRequestOffset, a setTimeout(() => setOffset(...), 0), and two "did we just…" heuristics). It's covered by tests and I couldn't find a concrete failure, but it's fragile and hard to reason about:

  • The setTimeout(setOffset, 0) at L195 exists only to dodge react-hooks/set-state-in-effect. Worth a one-line "why" comment beyond the eslint reference, and confirming rapid offset changes (fast scroll → select-all → scroll) can't leave offset oscillating.
  • Please make sure the empty-results / hasMoreResults: false case near the end of the list is exercised manually, since searchRequestOffset can rewind offset back to the server offset when the count is missing.

4. Footer total relies on server total sign convention

SearchSelectionFooter.tsx computes metadata.total - getTransactionTotal(excluded). The unit test uses positive values and passes, but this assumes the server total and the client-derived excluded total share the same sign/units. Worth a quick real-data sanity check (mixed positive/negative amounts, non-USD) that the displayed total actually decreases by the excluded amount.

Minor

  • The in-flight totals-request queuing in Search.ts:966-1065 only preserves one pending totals request per dedupe key — fine given the call sites, but note that a third distinct-params collision would be dropped silently.
  • Lots of excludedTransactions = getEmptyObject<SelectedTransactions>() default-param reads. These are safe because the shared frozen empty object is only read (or spread) and never mutated in place — good, just keep that invariant if this pattern spreads.

Nothing here is a hard blocker from a static read; #1 (backend contract) is the one I'd nail down before this ships, and #2 is a UX confirmation.

Thanks for the review! I verified all the points:

  • The backend correctly excludes excludedTransactionIDList from CSV exports.
  • The all-matching label is intentional when there are no exclusions.
  • Pagination, Slow 3G, end-of-list, and reconnect flows work correctly.
  • Refund and non-USD footer totals were verified with real data.

No additional issues were found.

@emkhalid

Copy link
Copy Markdown
Contributor Author

Bug: "0 selected" remaining when unselect all items one by one

Thanks for catching, done:

0-selected-fix.mov

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi Thanks for finding and reporting these!

I confirmed the offline behavior itself is expected:

  • Before any exclusion, the button shows “All matching items selected” because the server total is unavailable.
  • After excluding one expense, it shows the loaded count, such as “49 selected”.
  • The footer stays hidden offline because the complete count and total are unknown; showing a loaded-only total would be misleading.

I did find and fix a reconnect bug: the totals request was blocked because the search was reported as unfocused. Reconnecting now requests the authoritative totals and correctly updates the button and footer while preserving exclusions.

Video demos:

  • Offline selection:
offline-select-all.mp4
  • Reconnect and totals refresh:
offline-back-online-fix.mp4

@emkhalid

Copy link
Copy Markdown
Contributor Author

@mkhutornyi All done from my side and I am testing all the flows on platforms again, thanks

@mkhutornyi

Copy link
Copy Markdown
Contributor

Please fix conflict. Job 5 failing

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Overall this is a solid, well-tested change — the exclusion model (keep areAllMatchingItemsSelected on, track deselected rows in a separate excludedTransactions map, and subtract them from the server count/total) is a clean way to preserve all-matching selection. Type/lint/react-compiler/Search unit tests all pass. A few things worth a second look before merge, none of them clear blockers:

1. setOffset rewind in an effect — please confirm it can't disrupt pagination

src/components/Search/index.tsx:188-197 writes searchRequestOffset back into the component's offset state, and getSearchRequestOffsetForMissingAllMatchingCount returns Math.min(offset, serverOffset ?? offset) — i.e. it can move offset backward when the all-matching count is missing after the user has already paginated. This is the most novel/subtle piece of the PR. Can you confirm that rewinding offset while pages are already loaded only triggers the totals re-fetch and doesn't cause loaded pages to reload or the "load more" cursor to regress? A shouldPreserveAllMatchingSelection + paginate-then-select-all test that asserts the final offset would lock this in.

2. Expense button label no longer shows the count when there are no exclusions

In SearchBulkActionsButton.tsx:133-140, for isExpenseType with excludedItemsCount === 0, selectedAllMatchingItemsCount stays undefined, so the button always falls back to "All matching items selected" even when the total count is known — whereas non-expense types still show "N selected". Your test steps call this out as intended ("returns to 'All matching items selected' when no exclusions remain"), so just flagging it's a deliberate behavior divergence between expense and other types, not a regression.

3. Minor edge: clearing all-matching when hasMoreResults is unknown

shouldClearAllMatchingSelectionWhenEmpty: isOffline || searchResults?.search?.hasMoreResults === false (SearchWriteActionsProvider.tsx:405 and :473). If hasMoreResults is undefined (metadata not yet loaded) and the user is online, deselecting the last loaded row won't exit all-matching mode. Probably fine in practice, but worth confirming hasMoreResults is always populated by the time a user can toggle rows.

Other things I looked at (no action needed)
  • return inFlightRequestState.pendingTotalsRequest?.() inside .finally() (Search.ts:1130) — unconventional but correct: finally waits for a returned promise before settling and ignores its (non-rejecting) resolution value, and the recursive search() has its own .catch(handleSearchError) so it can't reject the outer chain. Fine.
  • excludedTransactions omitted from the reconcile effect deps (SearchWriteActionsProvider.tsx) — intentional and consistent with the existing selectedTransactions handling; it's read from closure and the effect re-runs on filteredData changes with a fresh closure. Comment updated correctly.
  • The default context value + all six UI test mocks + MockSearchContextProvider were all updated with excludedTransactions: {}, so no context consumers are left undefined.
  • Exclusion add/remove symmetry in applySelection, the isExcluded guards in useReconcileSelectionWithData, and the count/total subtraction in SearchSelectionFooter all reuse the same helpers as the existing client-total path, so sign/grouping conventions stay consistent.

Checks

The one red check — test (job 5) — failed on tests/actions/ReportTest.ts, which this PR doesn't touch (all Search suites pass). It looks like a pre-existing/flaky failure unrelated to these changes; a re-run should clear it.

@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: 6bf8b01c46

ℹ️ 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".

jsonQuery: exportParameters.jsonQuery,
reportIDList,
transactionIDList: selectedTransactionsKeys,
...(isExpenseType ? {excludedTransactionIDList: Object.keys(excludedTransactions)} : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Don’t send group keys as excluded transaction IDs

When all-matching selection is active in a grouped expense search and the user unchecks a collapsed group, excludedTransactions stores that group's group_... key because no child transaction IDs are loaded. Passing Object.keys(excludedTransactions) here as excludedTransactionIDList sends non-transaction IDs to the CSV export, so the exported file can still include the entire excluded group even though the UI count/footer subtracts it. Convert grouped exclusions to real transaction IDs or group filters before queuing the export.

Useful? React with 👍 / 👎.

@mkhutornyi

Copy link
Copy Markdown
Contributor

Regression Analysis from AI:

1. toggleAll header select-all leaves stale exclusions → wrong count.
SearchWriteActionsProvider.tsx:544toggleAll still passes only {data, totalSelectableItemsCount} and never clears excludedTransactions.

  • Repro (Expenses, online, >1 page): Select all matching → uncheck every loaded row (lands in selectedTransactions={}, excludedTransactions={all loaded}, areAllMatchingItemsSelected=true) → press the header checkbox to re-select.
  • Result: toggleAll takes the select-all branch, but exclusions are neither cleared (no flag) nor reset (the else if (!areAllMatchingItemsSelected) is skipped since all-matching stays true). selectedTransactions and excludedTransactions now overlap → button shows a wrong count (allMatchingItemsCount − excludedItemsCount), and reconcile re-drops the rows so the header appears unresponsive.
  • Fix direction: have toggleAll clear exclusions (or drop re-selected keys from excludedTransactions, which the row-toggle path already does but toggleAll bypasses).

2. Grouped-Expenses group header can flash unchecked under Select-all.
TransactionGroupListItem.tsx:123 — header selected-state now depends on useReconcileSelectionWithData having marked children, so newly-loaded/expanded groups render unchecked for a frame under select-all. Most likely user-visible glitch; verify on a throttled list.

3. onPress narrowing for collapsed lazy groups (behavior change — likely a fix, verify).
TransactionGroupListItem.tsx:305 — a collapsed group with a transactionsQueryJSON but zero loaded transactions no longer selects on row press (expand-only). Reads as a bugfix, but confirm no grouped view relied on tap-to-select there.

Looks like all of them are non-blockers but please double confirm

@emkhalid

Copy link
Copy Markdown
Contributor Author

Review

Overall this is a solid, well-tested change — the exclusion model (keep areAllMatchingItemsSelected on, track deselected rows in a separate excludedTransactions map, and subtract them from the server count/total) is a clean way to preserve all-matching selection. Type/lint/react-compiler/Search unit tests all pass. A few things worth a second look before merge, none of them clear blockers:

1. setOffset rewind in an effect — please confirm it can't disrupt pagination

src/components/Search/index.tsx:188-197 writes searchRequestOffset back into the component's offset state, and getSearchRequestOffsetForMissingAllMatchingCount returns Math.min(offset, serverOffset ?? offset) — i.e. it can move offset backward when the all-matching count is missing after the user has already paginated. This is the most novel/subtle piece of the PR. Can you confirm that rewinding offset while pages are already loaded only triggers the totals re-fetch and doesn't cause loaded pages to reload or the "load more" cursor to regress? A shouldPreserveAllMatchingSelection + paginate-then-select-all test that asserts the final offset would lock this in.

2. Expense button label no longer shows the count when there are no exclusions

In SearchBulkActionsButton.tsx:133-140, for isExpenseType with excludedItemsCount === 0, selectedAllMatchingItemsCount stays undefined, so the button always falls back to "All matching items selected" even when the total count is known — whereas non-expense types still show "N selected". Your test steps call this out as intended ("returns to 'All matching items selected' when no exclusions remain"), so just flagging it's a deliberate behavior divergence between expense and other types, not a regression.

3. Minor edge: clearing all-matching when hasMoreResults is unknown

shouldClearAllMatchingSelectionWhenEmpty: isOffline || searchResults?.search?.hasMoreResults === false (SearchWriteActionsProvider.tsx:405 and :473). If hasMoreResults is undefined (metadata not yet loaded) and the user is online, deselecting the last loaded row won't exit all-matching mode. Probably fine in practice, but worth confirming hasMoreResults is always populated by the time a user can toggle rows.

Other things I looked at (no action needed)

  • return inFlightRequestState.pendingTotalsRequest?.() inside .finally() (Search.ts:1130) — unconventional but correct: finally waits for a returned promise before settling and ignores its (non-rejecting) resolution value, and the recursive search() has its own .catch(handleSearchError) so it can't reject the outer chain. Fine.
  • excludedTransactions omitted from the reconcile effect deps (SearchWriteActionsProvider.tsx) — intentional and consistent with the existing selectedTransactions handling; it's read from closure and the effect re-runs on filteredData changes with a fresh closure. Comment updated correctly.
  • The default context value + all six UI test mocks + MockSearchContextProvider were all updated with excludedTransactions: {}, so no context consumers are left undefined.
  • Exclusion add/remove symmetry in applySelection, the isExcluded guards in useReconcileSelectionWithData, and the count/total subtraction in SearchSelectionFooter all reuse the same helpers as the existing client-total path, so sign/grouping conventions stay consistent.

Checks

The one red check — test (job 5) — failed on tests/actions/ReportTest.ts, which this PR doesn't touch (all Search suites pass). It looks like a pre-existing/flaky failure unrelated to these changes; a re-run should clear it.

Thanks for the review! I verified all three points:

  • Tested the pagination race twice on Slow 3G. After selecting all before offset 50 completed, the totals request ran and subsequent pages correctly requested offsets 100 and 150. No pagination regression was found.
  • “All matching items selected” with no exclusions is intentional.
  • hasMoreResults is available once interactive results are loaded, and the undefined case could not be reproduced.

No additional changes are needed.

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