Repository navigation
Update the to-do "Select all" count when a report leaves the list - #104015
Conversation
Live to-do searches now take reportCount from Onyx instead of the stale server snapshot, so the select-all count drops after a report leaves the bucket. The select-all menu only offers selecting every match when the row cap holds back rows, and selecting all on a live search no longer requests totals. Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
I created this PR from an upstream branch since I don't have push access to your fork. To take ownership of this branch and be able to push updates, run: Then you can close this PR and open a new one from your fork. |
|
The failing ESLint check is unrelated to this PR, so I didn't push a fix. Analysis: Both errors are in files this PR doesn't touch. They come from
Evidence: The same two errors fail ESLint on several unrelated PRs opened today, for example the Next step: [No QA] Remove useless Onyx.connect causing lint failures fixes the
|
|
🤖 Android test steps verification results: ✅ pass With 51 draft reports, "Select all" showed 51 selected. After submitting one report, "Select all" showed 50, not a stale 51. The PR's Tests section is still a TODO, so I ran the reproduction steps from [$175] Spend - Select all count is stale after submitting a report.
|
|
⏱️ Ran out of time before I could finish. This usually means the task was too complex or I got stuck exploring. Please try again with a more specific request or post in #melvinbot-ai. |
|
Please merge main |
…AllReportCount Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
Please replace your PR description with the below DescriptionExplanation of ChangeOn to-do searches like Drafts, the list is built from live Onyx data, so a report drops out of it once you submit it. The "N selected" count after "Select all" didn't follow. It read the report count the server sent when the list loaded, and submitting from a row's Submit button doesn't ask the server again, so the old number stayed. This PR changes three things on to-do searches:
Fixed Issues$ #102298 TestsBefore you start: sign in to an account on a Collect or Control workspace that has more than 50 draft reports. Test 1: "Select all" count after submitting a report (web and desktop)
Test 2: Same check while offline
On mobile: long-press a report and tap "Select", then tap "Select all" at the top of the list. The number is on the "N selected" button at the top of the screen. Tap the back arrow to leave selection mode before opening a report. Test 3: Exactly 50 drafts left Before you start: have exactly 51 draft reports, so "Select all" shows "51 selected".
Test 4: Reports page still offers selecting everything (more than 50 reports)
Offline testsSame as tests QA StepsSame as tests
PR Author Checklist
Screenshots/VideosAndroid: NativeAndroid: mWeb ChromeiOS: NativeiOS: mWeb SafariMacOS: Chrome / SafariAlso please apply this one-line comment fix. diff --git a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
--- a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
+++ b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
@@ -133 +133 @@ describe('SearchResultsProvider live to-do report count', () => {
- // Then the count the "Select all" label and the footer read drops by one, the same as the Drafts badge
+ // Then the count the "Select all" label reads drops by one, the same as the Drafts badge |
Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Please replace your PR description with the below DescriptionExplanation of ChangeOn the to-do tabs (Drafts, Needs approval, Ready to pay and Awaiting export), the rows come from data on the device, but "N selected" after "Select all" shows the report count the server sent with the first page. Submitting a report from its row removes the row right away, but nothing updates that count, so the label stays at N. The label can't just count the reports on the device. "Select all" actions send the search itself, so the server acts on every matching report, including ones this device hasn't loaded. The number has to stay the server's. This PR:
Known limit: reports that join the list after it loads, like a draft created on another device, aren't added to the count until the list reloads from the first page (for example after reopening the tab or reloading the page). Until then the count can be one low, and if one of those reports leaves again first, it can stay one low. Fixed Issues$ #102298 TestsPrerequisite: use an account with at least 55 draft reports in a workspace, each with at least one expense. For the phone test you also need a second device, or a different browser signed in to the same account. Don't use a second tab of the same browser.
Web and desktop, Needs approval (only if the account has more than 50 reports waiting for its approval)
iOS, Android and mobile web
Offline testsSame as tests QA StepsSame as tests
PR Author Checklist
Screenshots/VideosAndroid: NativeAndroid: mWeb ChromeiOS: NativeiOS: mWeb SafariMacOS: Chrome / SafariAlso please resolve and make them hidden the above codex comments I will give you the updated code on next comment. |
|
Done,
I haven't changed any code yet. Send the updated code in your next comment and I'll apply it. |
|
Please delete the outer details of the PR description |
|
Done, |
|
Please update this PR to the final code. This comment has the source changes. I'll send the test changes in the next one.
Source diffdiff --git a/src/components/Search/SearchResultsProvider.tsx b/src/components/Search/SearchResultsProvider.tsx
--- a/src/components/Search/SearchResultsProvider.tsx
+++ b/src/components/Search/SearchResultsProvider.tsx
@@ -55,3 +55,3 @@ function SearchResultsProvider({children}: SearchResultsProviderProps) {
const {footerTotal} = isBetaEnabled(CONST.BETAS.SPEND_FOOTER_SELECTORS) ? getFooterSelectionFromQuery(currentSearchQueryJSON) : {footerTotal: undefined};
- const liveTodoData = useTodoSearchResults(shouldUseLiveData ? currentSearchKey : undefined, footerTotal);
+ const liveTodoData = useTodoSearchResults(shouldUseLiveData ? currentSearchKey : undefined, footerTotal, snapshotSearchResults?.search);
@@ -67,2 +67,3 @@ function SearchResultsProvider({children}: SearchResultsProviderProps) {
currency: liveData.metadata.currency,
+ reportCount: liveData.metadata.reportCount,
};
diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx
--- a/src/components/Search/index.tsx
+++ b/src/components/Search/index.tsx
@@ -229,5 +229,2 @@ function Search({
const shouldCalculateExpenseTotals = useSearchShouldCalculateTotals(currentSearchKey, offset === 0 || isAllMatchingItemsCountMissing, isExpenseAllMatchingSelection);
- const shouldCalculateTotals = (areAllMatchingItemsSelected && !isExpenseAllMatchingSelection) || shouldCalculateExpenseTotals;
- const previousShouldCalculateTotals = usePrevious(shouldCalculateTotals);
- const searchRequestOffset = getSearchRequestOffsetForMissingAllMatchingCount(offset, searchResults?.search?.offset, isAllMatchingItemsCountMissing);
// For an expense-report "select all matching", the total the bulk-actions button waits for is the server
@@ -239,2 +236,8 @@ function Search({
isExpenseReportType && areAllMatchingItemsSelected ? typeof searchResults?.search?.reportCount !== 'number' : searchResults?.search?.count === undefined;
+ // Live to-do totals come only with page 1, unless the report count is missing. Merged onto older pages, they'd take a report that left off twice.
+ const shouldCalculateAllMatchingTotals = areAllMatchingItemsSelected && !isExpenseAllMatchingSelection && (!shouldUseLiveData || isRequiredAllMatchingTotalMissing);
+ const shouldCalculateTotals = shouldCalculateAllMatchingTotals || shouldCalculateExpenseTotals;
+ const shouldCalculateNextPageTotals = shouldCalculateTotals && !shouldUseLiveData;
+ const previousShouldCalculateTotals = usePrevious(shouldCalculateTotals);
+ const searchRequestOffset = getSearchRequestOffsetForMissingAllMatchingCount(offset, searchResults?.search?.offset, isAllMatchingItemsCountMissing);
@@ -1019,3 +1022,10 @@ function Search({
setIsLivePageAdopted(false);
- handleSearch({queryJSON, searchKey: currentSearchKey, offset: nextOffset, shouldCalculateTotals, prevReportsLength: filteredDataLength, isLoading: false});
+ handleSearch({
+ queryJSON,
+ searchKey: currentSearchKey,
+ offset: nextOffset,
+ shouldCalculateTotals: shouldCalculateNextPageTotals,
+ prevReportsLength: filteredDataLength,
+ isLoading: false,
+ });
}
@@ -1042,3 +1052,3 @@ function Search({
offset: nextOffset,
- shouldCalculateTotals,
+ shouldCalculateTotals: shouldCalculateNextPageTotals,
prevReportsLength: filteredDataLength,
@@ -1069,3 +1079,3 @@ function Search({
currentSearchKey,
- shouldCalculateTotals,
+ shouldCalculateNextPageTotals,
filteredDataLength,
diff --git a/src/hooks/useTodoSearchResults.ts b/src/hooks/useTodoSearchResults.ts
--- a/src/hooks/useTodoSearchResults.ts
+++ b/src/hooks/useTodoSearchResults.ts
@@ -27,2 +27,4 @@ type TodoMetadata = {
currency: string | undefined;
+ /** The server's report count, minus the reports that have left the list since its response */
+ reportCount?: number;
};
@@ -63,2 +65,29 @@ function computeMetadata(reports: Report[], transactionsByReportID: Record<strin
+type TodoReportCountParams = {
+ /** The server's figures for the search, from its snapshot */
+ serverSearch: SearchResults['search'] | undefined;
+
+ /** The to-do list as search data */
+ liveData: TodoSearchResultsData;
+
+ /** Whether every collection that decides which reports are to-dos has loaded */
+ isLoaded: boolean;
+};
+
+/**
+ * The report count a live to-do search shows: the server's, which also covers reports this device doesn't hold, minus
+ * the reports its responses held that have left the list since (`countedReportIDs`). To-do search responses also write
+ * their reports to Onyx, so a report that still matches is always in the list.
+ */
+function getTodoReportCount({serverSearch, liveData, isLoaded}: TodoReportCountParams): number | undefined {
+ if (serverSearch?.reportCount === undefined) {
+ return undefined;
+ }
+
+ // Until everything has loaded, reports that still match are missing from the list, so none counts as left.
+ const countedReportIDs = isLoaded ? Object.keys(serverSearch.countedReportIDs ?? {}) : [];
+ const departedReportCount = countedReportIDs.filter((reportID) => !liveData[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]).length;
+ return Math.max(serverSearch.reportCount - departedReportCount, 0);
+}
+
/**
@@ -138,2 +167,3 @@ function buildSearchResultsData(
* Builds live SearchResults-shaped data and metadata for a single to-do search (submit/approve/pay/export).
+ * Its report count is the server's from `serverSearch`, minus the reports that have left the list since.
* Returns `undefined` (and skips all classification work) when `searchKey` is not provided, so the app-wide
@@ -141,14 +171,18 @@ function buildSearchResultsData(
*/
-function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: SearchFooterTotal | undefined): {data: TodoSearchResultsData; metadata: TodoMetadata} | undefined {
- const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
- const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
- const [allReportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
+function useTodoSearchResults(
+ searchKey: SearchKey | undefined,
+ footerTotal: SearchFooterTotal | undefined,
+ serverSearch: SearchResults['search'] | undefined,
+): {data: TodoSearchResultsData; metadata: TodoMetadata} | undefined {
+ const [allReports, reportsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
+ const [allPolicies, policiesResult] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
+ const [allReportNameValuePairs, reportNameValuePairsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
const [allTransactions, transactionsMetadata] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION);
- const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
- const [allReportMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_METADATA);
- const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
- const [session] = useOnyx(ONYXKEYS.SESSION);
- const [personalDetailsList] = useAllPersonalDetailsWithoutSnapshots();
+ const [allReportActions, reportActionsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
+ const [allReportMetadata, reportMetadataResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_METADATA);
+ const [bankAccountList, bankAccountListResult] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
+ const [session, sessionResult] = useOnyx(ONYXKEYS.SESSION);
+ const [personalDetailsList, personalDetailsResult] = useAllPersonalDetailsWithoutSnapshots();
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
- const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE);
+ const [rules, rulesResult] = useOnyx(ONYXKEYS.COLLECTION.RULE);
@@ -160,2 +194,16 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
const login = personalDetailsList?.[userAccountID]?.login ?? session?.email ?? '';
+ const areTransactionsLoaded = transactionsMetadata.status === 'loaded';
+ // Every input of getTodoReportsForSearchKey must be listed here, or a report still loading counts as left.
+ const isLoaded = [
+ reportsResult,
+ policiesResult,
+ reportNameValuePairsResult,
+ transactionsMetadata,
+ reportActionsResult,
+ reportMetadataResult,
+ bankAccountListResult,
+ sessionResult,
+ personalDetailsResult,
+ rulesResult,
+ ].every((result) => result.status === 'loaded');
@@ -172,3 +220,3 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
login,
- areTransactionsLoaded: transactionsMetadata.status === 'loaded',
+ areTransactionsLoaded,
rules,
@@ -176,6 +224,7 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
- const metadata = computeMetadata(reports, transactionsByReportID, footerTotal);
const data = buildSearchResultsData(reports, transactionsByReportID, allPolicies, allReportActions, allReportNameValuePairs, personalDetailsList, allTransactionViolations);
+ const {count, total, currency} = computeMetadata(reports, transactionsByReportID, footerTotal);
+ const reportCount = getTodoReportCount({serverSearch, liveData: data, isLoaded});
- return {data, metadata};
+ return {data, metadata: {count, total, currency, reportCount}};
}
@@ -183 +232,2 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
export default useTodoSearchResults;
+export {getTodoReportCount};
diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts
--- a/src/libs/SearchUIUtils.ts
+++ b/src/libs/SearchUIUtils.ts
@@ -870,2 +870,13 @@ function isReportEntry(key: string): key is ReportKey {
+/** The IDs of the expense reports in search data */
+function getExpenseReportIDs(data: OnyxTypes.SearchResults['data']): Record<string, boolean> {
+ const reportIDs: Record<string, boolean> = {};
+ for (const key of Object.keys(data)) {
+ if (isReportEntry(key) && isExpenseReportUtil(data[key])) {
+ reportIDs[key.replace(ONYXKEYS.COLLECTION.REPORT, '')] = true;
+ }
+ }
+ return reportIDs;
+}
+
/**
@@ -7422,2 +7433,3 @@ export {
isReportEntry,
+ getExpenseReportIDs,
isTransactionEntry,
diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts
--- a/src/libs/actions/Search.ts
+++ b/src/libs/actions/Search.ts
@@ -70,3 +70,3 @@ import {savedSearchIDToSearchKey} from '@libs/SearchKeyUtils';
import {buildSearchQueryJSON, buildSearchQueryString, getFooterSelectionFromQuery, serializeQueryJSONForBackend} from '@libs/SearchQueryUtils';
-import {isTransactionGroupListItemType} from '@libs/SearchUIUtils';
+import {getExpenseReportIDs, isTransactionGroupListItemType, TODO_SEARCH_KEYS} from '@libs/SearchUIUtils';
import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils';
@@ -94,2 +94,3 @@ import type {
SaveSearch,
+ SearchResults,
SearchTagFilterItem,
@@ -125,3 +126,3 @@ import {saveLastSearchParams} from './ReportNavigation';
type OnyxSearchResponse = {
- data: [];
+ data: SearchResults['data'];
search: {
@@ -1417,3 +1418,5 @@ function search({
.then((result) => {
- const response = result?.onyxData?.[0]?.value as OnyxSearchResponse;
+ const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${queryJSON.hash}` as const;
+ // To-do responses list the other collections first and the snapshot last.
+ const response = result?.onyxData?.find((update) => update.key === snapshotKey)?.value as OnyxSearchResponse | undefined;
inFlightRequestState.didSucceed = result?.jsonCode === CONST.JSON_CODE.SUCCESS;
@@ -1434,2 +1437,9 @@ function search({
+ // Record the reports a to-do response held, apart from rows this device writes. A first-page response starts the record over.
+ if (searchKey && TODO_SEARCH_KEYS.has(searchKey) && result?.jsonCode === CONST.JSON_CODE.SUCCESS) {
+ Onyx.merge(snapshotKey, {search: {countedReportIDs: getExpenseReportIDs(response?.data ?? {})}}).catch((error: unknown) =>
+ Log.hmmm('[Search] failed to record the counted reports', {error: String(error)}),
+ );
+ }
+
if (shouldUpdateLastSearchParams) {
diff --git a/src/types/onyx/SearchResults.ts b/src/types/onyx/SearchResults.ts
--- a/src/types/onyx/SearchResults.ts
+++ b/src/types/onyx/SearchResults.ts
@@ -92,2 +92,5 @@ type SearchResultsInfo = {
+ /** Expense reports a to-do search's responses held. Those no longer in the live list come off `reportCount`. */
+ countedReportIDs?: Record<string, boolean>;
+
/** The total spend */ |
|
Here are the test changes. Please apply the diff below on top of the source changes. It changes 2 existing test files and adds 4 new ones. Test diffdiff --git a/tests/ui/SearchPageTest.tsx b/tests/ui/SearchPageTest.tsx
--- a/tests/ui/SearchPageTest.tsx
+++ b/tests/ui/SearchPageTest.tsx
@@ -113,2 +113,3 @@ type WriteActionsRender = {
applySelection: SearchSelectionActionsValue['applySelection'];
+ selectAllMatchingItems: SearchSelectionActionsValue['selectAllMatchingItems'];
};
@@ -123,4 +124,4 @@ jest.mock('@components/Search/SearchWriteActionsProvider', () => {
function MockSearchWriteActionsProvider(props: WriteActionsProviderProps) {
- const {applySelection} = useSearchSelectionActions();
- mockRenderWriteActions({filteredData: props.filteredData, applySelection});
+ const {applySelection, selectAllMatchingItems} = useSearchSelectionActions();
+ mockRenderWriteActions({filteredData: props.filteredData, applySelection, selectAllMatchingItems});
return createElement(SearchWriteActionsProvider, props);
@@ -1006,2 +1007,55 @@ describe('SearchPageNarrow', () => {
+ it('asks for its next page without totals', async () => {
+ // Given Drafts showing its first page, whose response carried the report count
+ await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10);
+ await seedTodoSnapshot(true, {reportCount: CONST.SEARCH.RESULTS_PAGE_SIZE + 10});
+ renderPage(TODO_QUERY);
+ await act(async () => {
+ jest.advanceTimersByTime(0);
+ });
+ mockSearch.mockClear();
+
+ // When the list reaches its end
+ await act(async () => {
+ listProps.onEndReached?.();
+ });
+ await act(async () => {
+ jest.advanceTimersByTime(0);
+ });
+
+ // Then the next page is asked for without totals, since totals sent with a later page would merge onto older pages
+ expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE}));
+ expect(mockSearch.mock.calls.some(([params]) => !!params?.shouldCalculateTotals)).toBe(false);
+ });
+
+ it.each([
+ ['sends no totals request once paged, since the first page already brought the report count', {reportCount: CONST.SEARCH.RESULTS_PAGE_SIZE + 10}, false],
+ ['asks for totals once paged when the report count is missing, so the bulk actions get one', {}, true],
+ ])('when every match is selected, %s', async (_description, snapshotFigures, shouldAskForTotals) => {
+ // Given Drafts paged past its first page
+ await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10);
+ await seedTodoSnapshot(true, snapshotFigures);
+ searchWritesLoadingState();
+ renderPage(TODO_QUERY);
+ await act(async () => {
+ jest.advanceTimersByTime(0);
+ });
+ await act(async () => {
+ listProps.onEndReached?.();
+ });
+ await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE, true);
+ mockSearch.mockClear();
+
+ // When every matching report is selected
+ await act(async () => {
+ lastWriteActionsRender()?.selectAllMatchingItems(true);
+ });
+ await act(async () => {
+ jest.advanceTimersByTime(0);
+ });
+
+ // Then totals are asked for only when there's no report count, since totals merged onto older pages would take a report that left off twice
+ expect(mockSearch.mock.calls.some(([params]) => !!params?.shouldCalculateTotals)).toBe(shouldAskForTotals);
+ });
+
it('shows the next rows only once the server answers their page, and ignores ends meanwhile', async () => {
diff --git a/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
--- a/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
+++ b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
@@ -24,5 +24,7 @@ jest.mock('@libs/SearchUIUtils', () => ({
+const EMPTY_TODO_METADATA = {count: 0, total: 0, currency: undefined};
+let mockTodoMetadata: Record<string, unknown> = EMPTY_TODO_METADATA;
jest.mock('@hooks/useTodoSearchResults', () => ({
__esModule: true,
- default: () => ({data: {}, metadata: {count: 0, total: 0, currency: undefined}}),
+ default: () => ({data: {}, metadata: mockTodoMetadata}),
}));
@@ -50,2 +52,3 @@ describe('SearchResultsProvider live to-do loading flag', () => {
mockIsTodoSearch = true;
+ mockTodoMetadata = EMPTY_TODO_METADATA;
});
@@ -68,2 +71,13 @@ describe('SearchResultsProvider live to-do loading flag', () => {
});
+
+ it('shows the figures the to-do list worked out, including the report count, over the snapshot', () => {
+ // Given the to-do list corrected the server's figures for reports that left it on this device
+ mockTodoMetadata = {count: 125, total: 125000, currency: 'USD', reportCount: 119};
+
+ // When the provider builds the live results over a snapshot that still holds the server's old figures
+ const {result} = renderProvider({isLoading: false, offset: 0, hash: 1, count: 126, total: 126000, currency: 'USD', reportCount: 120});
+
+ // Then the search shows the corrected figures, which "Select all" and the footer read
+ expect(result.current.currentSearchResults?.search).toMatchObject({count: 125, total: 125000, currency: 'USD', reportCount: 119});
+ });
});
diff --git a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
new file mode 100644
--- /dev/null
+++ b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
@@ -0,0 +1,280 @@
+import {act, renderHook} from '@testing-library/react-native';
+
+import {SearchResultsContext} from '@components/Search/SearchContextDefinitions';
+import SearchResultsProvider from '@components/Search/SearchResultsProvider';
+
+import {getSuggestedSearches} from '@libs/SearchSuggestionUtils';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Policy, Report, SearchResults, Transaction} from '@src/types/onyx';
+
+import React, {use} from 'react';
+import Onyx from 'react-native-onyx';
+
+import createMock from '../../utils/createMock';
+import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
+
+const CURRENT_USER_ACCOUNT_ID = 1;
+const CURRENT_USER_EMAIL = 'tester@mail.com';
+const APPROVER_ACCOUNT_ID = 2;
+const POLICY_ID = 'policy123';
+const DRAFT_REPORT_IDS = ['draft_1', 'draft_2', 'draft_3'];
+
+// The server matched more drafts than this device holds, as on an account whose to-dos aren't all loaded. Each draft
+// has one 10.00 expense.
+const SERVER_REPORT_COUNT = 120;
+const EXPENSE_AMOUNT = 1000;
+
+const suggestedSearches = getSuggestedSearches(CURRENT_USER_ACCOUNT_ID);
+const draftsQueryJSON = suggestedSearches[CONST.SEARCH.SEARCH_KEYS.SUBMIT].searchQueryJSON;
+
+const mockQueryContext = {
+ currentSearchHash: draftsQueryJSON?.hash ?? CONST.DEFAULT_NUMBER_ID,
+ currentSearchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT,
+ currentSearchQueryJSON: draftsQueryJSON,
+ suggestedSearches,
+};
+jest.mock('@components/Search/SearchContext', () => ({
+ useSearchQueryContext: () => mockQueryContext,
+}));
+
+const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${mockQueryContext.currentSearchHash}` as const;
+const firstDraftReportID = DRAFT_REPORT_IDS.at(0) ?? '';
+
+const draftReport = (reportID: string): Report =>
+ createMock<Report>({
+ reportID,
+ chatReportID: `chat_${reportID}`,
+ policyID: POLICY_ID,
+ ownerAccountID: CURRENT_USER_ACCOUNT_ID,
+ managerID: APPROVER_ACCOUNT_ID,
+ stateNum: CONST.REPORT.STATE_NUM.OPEN,
+ statusNum: CONST.REPORT.STATUS_NUM.OPEN,
+ type: CONST.REPORT.TYPE.EXPENSE,
+ currency: 'USD',
+ });
+
+const draftTransaction = (reportID: string): Transaction =>
+ createMock<Transaction>({
+ transactionID: `transaction_${reportID}`,
+ reportID,
+ amount: -1000,
+ currency: 'USD',
+ merchant: 'Merchant',
+ created: '2026-10-13',
+ reimbursable: true,
+ groupAmount: -1000,
+ groupCurrency: 'USD',
+ });
+
+// The first page the server returned when Drafts loaded: the three drafts this device holds, out of SERVER_REPORT_COUNT.
+const draftsSnapshotData = createMock<SearchResults['data']>({});
+for (const reportID of DRAFT_REPORT_IDS) {
+ Object.assign(draftsSnapshotData, {
+ [`${ONYXKEYS.COLLECTION.REPORT}${reportID}` as const]: draftReport(reportID),
+ [`${ONYXKEYS.COLLECTION.TRANSACTION}${draftTransaction(reportID).transactionID}` as const]: draftTransaction(reportID),
+ });
+}
+
+const draftsSnapshot = createMock<SearchResults>({
+ search: {
+ hash: mockQueryContext.currentSearchHash,
+ offset: 0,
+ type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT,
+ hasMoreResults: true,
+ hasResults: true,
+ isLoading: false,
+ count: SERVER_REPORT_COUNT,
+ reportCount: SERVER_REPORT_COUNT,
+ total: SERVER_REPORT_COUNT * EXPENSE_AMOUNT,
+ currency: 'USD',
+ footerTotal: CONST.SEARCH.FOOTER_TOTAL.TOTAL,
+ countedReportIDs: Object.fromEntries(DRAFT_REPORT_IDS.map((reportID) => [reportID, true])),
+ },
+ data: draftsSnapshotData,
+});
+
+function renderProvider() {
+ return renderHook(() => use(SearchResultsContext), {
+ wrapper: ({children}: {children: React.ReactNode}) => <SearchResultsProvider>{children}</SearchResultsProvider>,
+ });
+}
+
+async function seedDraftsAndSnapshot() {
+ const policy = createMock<Policy>({
+ id: POLICY_ID,
+ name: 'Test Policy',
+ role: CONST.POLICY.ROLE.ADMIN,
+ type: CONST.POLICY.TYPE.TEAM,
+ owner: CURRENT_USER_EMAIL,
+ ownerAccountID: CURRENT_USER_ACCOUNT_ID,
+ outputCurrency: 'USD',
+ approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC,
+ });
+
+ await Onyx.set(ONYXKEYS.SESSION, {email: CURRENT_USER_EMAIL, accountID: CURRENT_USER_ACCOUNT_ID});
+ await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, policy);
+ await Promise.all(DRAFT_REPORT_IDS.map((reportID) => Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, draftReport(reportID))));
+ await Promise.all(DRAFT_REPORT_IDS.map((reportID) => Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${draftTransaction(reportID).transactionID}`, draftTransaction(reportID))));
+ await Onyx.set(snapshotKey, draftsSnapshot);
+ await waitForBatchedUpdates();
+}
+
+async function renderDrafts() {
+ await seedDraftsAndSnapshot();
+ const rendered = renderProvider();
+ await act(async () => {
+ await waitForBatchedUpdates();
+ });
+ return rendered;
+}
+
+async function moveFirstDraft(stateNum: Report['stateNum'], statusNum: Report['statusNum']) {
+ await act(async () => {
+ await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${firstDraftReportID}`, {stateNum, statusNum});
+ await waitForBatchedUpdates();
+ });
+}
+
+// The last draft stands for a report from a later page, which a first-page response leaves out of its record.
+const laterPageDraftReportID = DRAFT_REPORT_IDS.at(-1) ?? '';
+const firstPageDraftReportIDs = DRAFT_REPORT_IDS.filter((reportID) => reportID !== laterPageDraftReportID);
+
+async function submitDraft(reportID: string) {
+ await act(async () => {
+ await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED});
+ await waitForBatchedUpdates();
+ });
+}
+
+/** A first-page response, which replaces the snapshot with the server's fresh count and a record of page 1 */
+async function answerFirstPage(reportCount: number) {
+ await act(async () => {
+ await Onyx.set(snapshotKey, {
+ ...draftsSnapshot,
+ search: {...draftsSnapshot.search, reportCount, countedReportIDs: Object.fromEntries(firstPageDraftReportIDs.map((reportID) => [reportID, true]))},
+ });
+ await waitForBatchedUpdates();
+ });
+}
+
+function getReportCount(result: Awaited<ReturnType<typeof renderDrafts>>['result']) {
+ return result.current.currentSearchResults?.search?.reportCount;
+}
+
+function expectFigures(result: Awaited<ReturnType<typeof renderDrafts>>['result'], reportCount: number, deviceDraftCount: number) {
+ const search = result.current.currentSearchResults?.search;
+ expect(search?.reportCount).toBe(reportCount);
+ expect(search?.count).toBe(deviceDraftCount);
+ expect(search?.total).toBe(deviceDraftCount * EXPENSE_AMOUNT);
+ expect(search?.currency).toBe('USD');
+}
+
+describe('SearchResultsProvider live to-do report count', () => {
+ beforeAll(() => {
+ // As in the app, Onyx.update copies pending markers into the snapshots that hold the updated keys.
+ Onyx.init({keys: ONYXKEYS, snapshotMergeKeys: ['pendingAction', 'pendingFields']});
+ });
+
+ beforeEach(async () => {
+ await Onyx.clear();
+ await waitForBatchedUpdates();
+ });
+
+ it("keeps the server's report count when the device holds only some of the matching reports", async () => {
+ // Given Drafts on a device that holds three of the 120 drafts the server counted
+ // When the provider builds the live results
+ const {result} = await renderDrafts();
+
+ // Then "Select all" counts every matching report, not only the three on the device
+ expect(result.current.shouldUseLiveData).toBe(true);
+ expectFigures(result, SERVER_REPORT_COUNT, DRAFT_REPORT_IDS.length);
+ });
+
+ it('lowers the report count as soon as a report leaves Drafts, without a new search', async () => {
+ // Given Drafts with the server's 120 reports
+ const {result} = await renderDrafts();
+
+ // When one draft is submitted from its row, which moves it out of Drafts on this device
+ await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+ // Then the report count drops with it, like the Drafts badge does
+ expectFigures(result, SERVER_REPORT_COUNT - 1, DRAFT_REPORT_IDS.length - 1);
+ });
+
+ it('keeps it lowered after the submit succeeds and removes the report from the snapshot', async () => {
+ // Given a draft that was submitted from its row
+ const {result} = await renderDrafts();
+ await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+ // When the submit succeeds and its success data removes the report's row from the snapshot
+ await act(async () => {
+ await Onyx.merge(snapshotKey, {data: {[`${ONYXKEYS.COLLECTION.REPORT}${firstDraftReportID}`]: null}});
+ await waitForBatchedUpdates();
+ });
+
+ // Then the report count stays lowered instead of jumping back to the server's old one
+ expectFigures(result, SERVER_REPORT_COUNT - 1, DRAFT_REPORT_IDS.length - 1);
+ });
+
+ it('puts the report back in the report count when a failed submit returns it to Drafts', async () => {
+ // Given a draft that was submitted from its row
+ const {result} = await renderDrafts();
+ await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+ // When the submit fails and its failure data returns the report to Drafts
+ await moveFirstDraft(CONST.REPORT.STATE_NUM.OPEN, CONST.REPORT.STATUS_NUM.OPEN);
+
+ // Then the report count is the server's again, without anything having to restore it
+ expectFigures(result, SERVER_REPORT_COUNT, DRAFT_REPORT_IDS.length);
+ });
+
+ it('takes nothing off for a draft created on this device and then submitted, even once its creation succeeded', async () => {
+ // Given Drafts with the server's 120 reports, and a draft created on this device, which the app writes into the snapshot with its pending markers
+ const {result} = await renderDrafts();
+ const createdReportKey = `${ONYXKEYS.COLLECTION.REPORT}created` as const;
+ const createdTransaction = {...draftTransaction('created'), pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD};
+ const createdTransactionKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${createdTransaction.transactionID}` as const;
+ const createdReport = {...draftReport('created'), pendingFields: {createReport: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}};
+ const createdSnapshotData = createMock<SearchResults['data']>({});
+ Object.assign(createdSnapshotData, {[createdReportKey]: createdReport, [createdTransactionKey]: createdTransaction});
+ await act(async () => {
+ await Onyx.set(createdReportKey, createdReport);
+ await Onyx.set(createdTransactionKey, createdTransaction);
+ await Onyx.merge(snapshotKey, {data: createdSnapshotData});
+ await waitForBatchedUpdates();
+ });
+
+ // When the creation succeeds, its success data clearing the pending markers through Onyx.update, which also clears them in the snapshot
+ await act(async () => {
+ await Onyx.update([
+ {onyxMethod: Onyx.METHOD.MERGE, key: createdReportKey, value: {pendingFields: {createReport: null}}},
+ {onyxMethod: Onyx.METHOD.MERGE, key: createdTransactionKey, value: {pendingAction: null}},
+ ]);
+ await waitForBatchedUpdates();
+ });
+
+ // And the draft is then submitted
+ await act(async () => {
+ await Onyx.merge(createdReportKey, {stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED});
+ await waitForBatchedUpdates();
+ });
+
+ // Then the server's 120 stand, since the draft isn't among the reports its responses held
+ expect(result.current.currentSearchResults?.search?.reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+
+ it("doesn't take a report off twice when a first-page response lands after it left", async () => {
+ // Given a later-page draft submitted, so the count drops to 119
+ const {result} = await renderDrafts();
+ await submitDraft(laterPageDraftReportID);
+ expect(getReportCount(result)).toBe(SERVER_REPORT_COUNT - 1);
+
+ // When a first-page response brings the server's fresh count, which no longer covers it, and a record of page 1
+ await answerFirstPage(SERVER_REPORT_COUNT - 1);
+
+ // Then the count stays at 119, since the fresh count already left it out
+ expect(getReportCount(result)).toBe(SERVER_REPORT_COUNT - 1);
+ });
+});
diff --git a/tests/unit/Search/searchCountedReportIDsTest.ts b/tests/unit/Search/searchCountedReportIDsTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/Search/searchCountedReportIDsTest.ts
@@ -0,0 +1,172 @@
+import {search} from '@libs/actions/Search';
+import {makeRequestWithSideEffects, waitForWrites} from '@libs/API';
+import {getExpenseReportIDs, getSuggestedSearches} from '@libs/SearchUIUtils';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Report, SearchResults} from '@src/types/onyx';
+
+import type {OnyxUpdate} from 'react-native-onyx';
+
+import Onyx from 'react-native-onyx';
+
+import createMock from '../../utils/createMock';
+import getOnyxValue from '../../utils/getOnyxValue';
+import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
+
+jest.mock('@libs/API', () => ({
+ makeRequestWithSideEffects: jest.fn(),
+ waitForWrites: jest.fn(),
+ write: jest.fn(),
+ read: jest.fn(),
+}));
+
+const draftsQueryJSON = getSuggestedSearches(1)[CONST.SEARCH.SEARCH_KEYS.SUBMIT].searchQueryJSON;
+if (!draftsQueryJSON) {
+ throw new Error('The Drafts query should build');
+}
+const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${draftsQueryJSON.hash}` as const;
+
+function buildSearchData(reports: Array<{reportID: string; type: string}>): SearchResults['data'] {
+ const data = createMock<SearchResults['data']>({});
+ for (const report of reports) {
+ data[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`] = createMock<Report>(report);
+ }
+ return data;
+}
+
+/**
+ * Answers the next request the way the API layer does: it applies the response's onyxData before search() sees the
+ * result. Like a real to-do response, it lists another collection first and the snapshot last.
+ */
+function answerWith(onyxMethod: typeof Onyx.METHOD.SET | typeof Onyx.METHOD.MERGE, data: SearchResults['data'], jsonCode: number = CONST.JSON_CODE.SUCCESS) {
+ const onyxData: Array<OnyxUpdate<typeof ONYXKEYS.PERSONAL_DETAILS_LIST | typeof ONYXKEYS.COLLECTION.SNAPSHOT>> = [
+ {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.PERSONAL_DETAILS_LIST, value: {}},
+ {onyxMethod, key: snapshotKey, value: {search: {reportCount: 120}, data}},
+ ];
+ jest.mocked(makeRequestWithSideEffects).mockImplementationOnce(async () => {
+ await Onyx.update(onyxData);
+ return {jsonCode, onyxData};
+ });
+}
+
+async function getCountedReportIDs() {
+ await waitForBatchedUpdates();
+ const snapshot = await getOnyxValue(snapshotKey);
+ return snapshot?.search?.countedReportIDs;
+}
+
+describe('getExpenseReportIDs', () => {
+ it('keeps only the expense reports, which are the only reports a live to-do list holds', () => {
+ // Given search data with expense, IOU, invoice and chat reports
+ const data = buildSearchData([
+ {reportID: 'expense1', type: CONST.REPORT.TYPE.EXPENSE},
+ {reportID: 'iou', type: CONST.REPORT.TYPE.IOU},
+ {reportID: 'invoice', type: CONST.REPORT.TYPE.INVOICE},
+ {reportID: 'chat', type: CONST.REPORT.TYPE.CHAT},
+ {reportID: 'expense2', type: CONST.REPORT.TYPE.EXPENSE},
+ ]);
+
+ // When their IDs are collected
+ const reportIDs = getExpenseReportIDs(data);
+
+ // Then only the expense reports are kept
+ expect(reportIDs).toEqual({expense1: true, expense2: true});
+ });
+
+ it("takes each report's ID from its key, so an entry without a reportID is still recorded", () => {
+ // Given an expense report entry whose value carries no reportID
+ const data = createMock<SearchResults['data']>({});
+ data[`${ONYXKEYS.COLLECTION.REPORT}expense1`] = createMock<Report>({type: CONST.REPORT.TYPE.EXPENSE});
+
+ // When its ID is collected
+ const reportIDs = getExpenseReportIDs(data);
+
+ // Then it is recorded under its key's ID, never as "undefined", which would count as a report that left
+ expect(reportIDs).toEqual({expense1: true});
+ });
+
+ it('returns nothing for data without reports', () => {
+ // Given search data holding no reports
+ // When the IDs are collected
+ // Then there are none
+ expect(getExpenseReportIDs(createMock<SearchResults['data']>({}))).toEqual({});
+ });
+});
+
+describe('search() records the reports a to-do search counted', () => {
+ beforeAll(() => {
+ Onyx.init({keys: ONYXKEYS});
+ });
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ jest.mocked(waitForWrites).mockResolvedValue(undefined);
+ await Onyx.clear();
+ });
+
+ it("records the expense reports a to-do search's first page held", async () => {
+ // Given Drafts answers its first page with two expense reports and a chat report
+ answerWith(
+ Onyx.METHOD.SET,
+ buildSearchData([
+ {reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE},
+ {reportID: 'B', type: CONST.REPORT.TYPE.EXPENSE},
+ {reportID: 'chat', type: CONST.REPORT.TYPE.CHAT},
+ ]),
+ );
+
+ // When the first page is searched
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+ // Then the two expense reports are recorded as the ones its count covers
+ expect(await getCountedReportIDs()).toEqual({A: true, B: true});
+ });
+
+ it("adds a later page's reports to the record", async () => {
+ // Given Drafts already recorded report A from its first page
+ answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+ // When the next page answers with report C, merged into the snapshot
+ answerWith(Onyx.METHOD.MERGE, buildSearchData([{reportID: 'C', type: CONST.REPORT.TYPE.EXPENSE}]));
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: CONST.SEARCH.RESULTS_PAGE_SIZE, shouldCalculateTotals: false, isLoading: false});
+
+ // Then both are recorded
+ expect(await getCountedReportIDs()).toEqual({A: true, C: true});
+ });
+
+ it('starts the record over with a first-page response, which replaces the snapshot', async () => {
+ // Given a record from an earlier response holding report OLD
+ await Onyx.set(snapshotKey, createMock<SearchResults>({search: {countedReportIDs: {OLD: true}}, data: {}}));
+
+ // When a new first page answers with report A
+ answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+ // Then only report A is recorded, since the old record went with the replaced snapshot
+ expect(await getCountedReportIDs()).toEqual({A: true});
+ });
+
+ it('records nothing for a search that is not a to-do', async () => {
+ // Given the same response answers a search that isn't a to-do
+ answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+
+ // When it is searched
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.EXPENSES, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+ // Then no record is kept, since only a live to-do search corrects its count
+ expect(await getCountedReportIDs()).toBeUndefined();
+ });
+
+ it('records nothing when the response failed', async () => {
+ // Given Drafts' request fails
+ answerWith(Onyx.METHOD.MERGE, {}, 500);
+
+ // When the first page is searched
+ await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+ // Then no record is kept
+ expect(await getCountedReportIDs()).toBeUndefined();
+ });
+});
diff --git a/tests/unit/hooks/getTodoReportCountTest.ts b/tests/unit/hooks/getTodoReportCountTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/hooks/getTodoReportCountTest.ts
@@ -0,0 +1,89 @@
+import {getTodoReportCount} from '@hooks/useTodoSearchResults';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Report, SearchResults} from '@src/types/onyx';
+
+import createMock from '../../utils/createMock';
+
+// The server matched 120 reports. Its responses held reports A, B and C.
+const SERVER_REPORT_COUNT = 120;
+const COUNTED_REPORT_IDS = {A: true, B: true, C: true};
+
+function buildServerSearch(search: Partial<SearchResults['search']> = {}): SearchResults['search'] {
+ return createMock<SearchResults['search']>({reportCount: SERVER_REPORT_COUNT, countedReportIDs: COUNTED_REPORT_IDS, ...search});
+}
+
+/** The to-do list on the device, holding the given reports */
+function buildLiveData(reportIDs: string[]): SearchResults['data'] {
+ const data = createMock<SearchResults['data']>({});
+ for (const reportID of reportIDs) {
+ data[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] = createMock<Report>({reportID, type: CONST.REPORT.TYPE.EXPENSE});
+ }
+ return data;
+}
+
+describe('getTodoReportCount', () => {
+ it("has no report count when the server hasn't sent one", () => {
+ // Given no server snapshot yet
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: undefined, liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+ // Then there is none to show
+ expect(reportCount).toBeUndefined();
+ });
+
+ it("keeps the server's report count while every counted report is still in the list", () => {
+ // Given the device still holds every report the server's responses held
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['A', 'B', 'C']), isLoaded: true});
+
+ // Then it is the server's, which also covers the reports this device doesn't hold
+ expect(reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+
+ it('takes a counted report that left the list off the server count', () => {
+ // Given report A left the list, so it's gone from it whatever the snapshot's rows still hold
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+ // Then one report comes off, without waiting for the next search
+ expect(reportCount).toBe(SERVER_REPORT_COUNT - 1);
+ });
+
+ it('leaves a report the server never counted out until the next response, such as a draft created on this device', () => {
+ // Given the list also holds a draft this device created, which isn't among the reports the server's responses held
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['A', 'B', 'C', 'created']), isLoaded: true});
+
+ // Then the server's count stands. The next first-page response counts the draft
+ expect(reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+
+ it("keeps the server's report count while local data is still loading", () => {
+ // Given local data hasn't finished loading, so the list is still empty
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData([]), isLoaded: false});
+
+ // Then nothing counts as having left, since reports that still match are missing until then
+ expect(reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+
+ it("keeps the server's report count when the snapshot has no record of the reports it counted", () => {
+ // Given a snapshot cached before the counted reports were recorded
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch({countedReportIDs: undefined}), liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+ // Then it is the server's until the next response records them
+ expect(reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+
+ it('never goes below zero', () => {
+ // Given a stale server count smaller than what has left
+ // When the report count is worked out
+ const reportCount = getTodoReportCount({serverSearch: buildServerSearch({reportCount: 1}), liveData: buildLiveData([]), isLoaded: true});
+
+ // Then it stops at zero
+ expect(reportCount).toBe(0);
+ });
+});
diff --git a/tests/unit/hooks/useTodoSearchResultsTest.ts b/tests/unit/hooks/useTodoSearchResultsTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/hooks/useTodoSearchResultsTest.ts
@@ -0,0 +1,66 @@
+import {renderHook} from '@testing-library/react-native';
+
+import useTodoSearchResults from '@hooks/useTodoSearchResults';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {SearchResults} from '@src/types/onyx';
+
+import createMock from '../../utils/createMock';
+
+const mockLoadingKeys = new Set<string>();
+jest.mock('react-native-onyx', () => ({
+ __esModule: true,
+ ...jest.requireActual<Record<string, unknown>>('react-native-onyx'),
+ useOnyx: (key: string) => [undefined, {status: mockLoadingKeys.has(key) ? 'loading' : 'loaded'}],
+}));
+
+jest.mock('@hooks/usePersonalDetails', () => ({
+ useAllPersonalDetailsWithoutSnapshots: () => [undefined, {status: mockLoadingKeys.has('personalDetailsList') ? 'loading' : 'loaded'}],
+}));
+
+const SERVER_REPORT_COUNT = 120;
+
+// The server counted 120 drafts, two of them on its first page. The device list built from the mocked Onyx is empty.
+const serverSearch = createMock<SearchResults['search']>({reportCount: SERVER_REPORT_COUNT, countedReportIDs: {A: true, B: true}});
+
+function renderDrafts() {
+ return renderHook(() => useTodoSearchResults(CONST.SEARCH.SEARCH_KEYS.SUBMIT, undefined, serverSearch));
+}
+
+describe('useTodoSearchResults', () => {
+ beforeEach(() => {
+ mockLoadingKeys.clear();
+ });
+
+ it('treats counted reports missing from the list as having left once everything has loaded', () => {
+ // Given every collection the to-do list reads has loaded, and the two counted reports aren't in the list
+ // When the Drafts list is built
+ const {result} = renderDrafts();
+
+ // Then both come off the server's count
+ expect(result.current?.metadata.reportCount).toBe(SERVER_REPORT_COUNT - 2);
+ });
+
+ it.each([
+ ONYXKEYS.COLLECTION.REPORT,
+ ONYXKEYS.COLLECTION.POLICY,
+ ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
+ ONYXKEYS.COLLECTION.TRANSACTION,
+ ONYXKEYS.COLLECTION.REPORT_ACTIONS,
+ ONYXKEYS.COLLECTION.REPORT_METADATA,
+ ONYXKEYS.BANK_ACCOUNT_LIST,
+ ONYXKEYS.SESSION,
+ 'personalDetailsList',
+ ONYXKEYS.COLLECTION.RULE,
+ ])("keeps the server's count while %s is still loading", (loadingKey) => {
+ // Given one of the collections that decides whether a report is a to-do is still loading from storage
+ mockLoadingKeys.add(loadingKey);
+
+ // When the Drafts list is built
+ const {result} = renderDrafts();
+
+ // Then nothing comes off, because reports that still match can be missing from the list until it loads
+ expect(result.current?.metadata.reportCount).toBe(SERVER_REPORT_COUNT);
+ });
+}); |
…AllReportCount Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
Reset every file in this PR to main, removing the live device count, the hasMoreMatchingItems prop and their tests, then apply the final source changes: record which expense reports each to-do search response held, subtract the ones that have left the live list from the server's report count, ask for totals only with the first page on to-do tabs, and read the snapshot entry from the response. Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR. Next steps: A human should review the recent commits and resolve the conflicting CI errors manually. |
|
Done,
Checks
Send the test changes when they're ready. |
…ches Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
Done, Code: The diff applied exactly as written to Description:
Checks:
|
Reviewer Checklist
Screenshots/VideosAndroid: HybridAppAndroid-Native.mp4Android: mWeb ChromeAndroid-mWeb.mp4iOS: HybridAppiOS: mWeb SafariMacOS: Chrome / SafariMac-Chrome.mp4 |
|
@MelvinBot Please merge main |
Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
|
I merged The merge brought in 6 files: deep-link handling, navigation after onboarding, the Concierge page, and their tests. None of them are files this PR changes, so I didn't re-run local checks. CI will run on the new commit. |
|
Please make the PR ready for review |
|
Done, |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c49f8ce888
ℹ️ 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".
| const clearRecord = shouldCalculateTotals ? Onyx.merge(snapshotKey, {search: {countedReportIDs: null}}) : Promise.resolve(); | ||
| clearRecord | ||
| .then(() => Onyx.merge(snapshotKey, {search: {countedReportIDs}})) |
There was a problem hiding this comment.
Retain live IDs from previously loaded pages
When selecting all after paging triggers a totals request for the current page, this clear discards countedReportIDs from every other loaded page and repopulates the record only from the response page. For example, after page 2 returns fresh totals, completing a still-visible page-1 report no longer lowers reportCount, because getTodoReportCount() cannot find that ID in the new record; the bulk-action count remains one too high until another totals refresh. Reset the departure baseline without dropping still-live counted IDs from the other hydrated pages.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pre-existing on main and documented as known limit. It will be handled on follow-up PR.
|
We did not find an internal engineer to review this PR, trying to assign a random engineer to #102298 as well as to this PR... Please reach out for help on Slack if no one gets assigned! |
JmillsExpensify
left a comment
There was a problem hiding this comment.
Makes sense to me.
|
🚧 justinpersaud has triggered a test Expensify/App build. You can view the workflow run here. |
|
🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
|
|
🚀 Deployed to staging by https://github.com/justinpersaud in version: 9.5.14-0 🚀
|
|
No help site update is needed. This PR is a bug fix that makes the "N selected" count after Select all drop when a report leaves a to-do list, which is what users already expect, and it doesn't make any existing article sentence incorrect. |
|
🚀 Deployed to production by https://github.com/grgia in version: 9.5.14-3 🚀
Bundle Size Analysis (Sentry): |





Explanation of Change
On the to-do tabs (Drafts, Needs approval, Ready to pay and Awaiting export), the rows come from data on the device, but "N selected" after "Select all" shows the report count the server sent with the first page. Submitting a report from its row removes the row right away, but nothing updates that count, so the label stays at N.
The label can't just count the reports on the device. "Select all" actions send the search itself, so the server acts on every matching report, including ones this device hasn't loaded. The number has to stay the server's.
This PR:
Known limit: reports that join the list, and reports that leave from pages loaded before the last fresh count, only show up in the count the next time the server sends one, for example when the first page reloads after bulk Submit or a report's Submit or Pay. Until then it can be one off for each such report.
Fixed Issues
$ #102298
PROPOSAL: #102298 (comment)
Tests
Prerequisite: use an account with at least 55 draft reports in a workspace, each with at least one expense. For the phone test you also need a second device, or a different browser signed in to the same account. Don't use a second tab of the same browser.
Web and desktop, Needs approval (only if the account has more than 50 reports waiting for its approval)
iOS, Android and mobile web
Offline tests
Same as tests
QA Steps
Same as tests
PR Author Checklist
### Fixed Issuessection aboveTestssectionOffline stepssectionQA stepssectiontoggleReportand notonIconClick)Avatar, I verified the components usingAvatarare working as expected)StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))npm run compress-svg)Avataris modified, I verified thatAvataris working as expected in all cases)Designlabel and/or tagged@Expensify/designso the design team can review the changes.mainbranch was merged into this PR after a review, I tested again and verified the outcome was still expected according to theTeststeps.Screenshots/Videos
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari