App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Spend - Default sort is descending

Open applause-bot[bot] opened this issue 6 months ago • 190 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: 9.3.84-0 Reproducible in staging?: Yes Reproducible in production?: No If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/91710 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Windows 11/ Chrome App Component: Other

Action Performed:

  1. Open the staging.new.expensify.com website.
  2. Create new report
  3. Add two expenses to the report and force the second one of them to have a violation
  4. Go to Spend -> Reports
  5. Open the created report
  6. Change sort to Total

Expected Result:

Verify you have the default sort (Date/ASC) set. RBR pre-sort is gone.

Actual Result:

Default sort for Date is set to DESC. RBR pre-sort is still at the top

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [x] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/d6524672-c4ab-4de1-b243-41756c0000e3

View all open jobs on GitHub

Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7164951

applause-bot[bot] avatar May 28 '26 08:05 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/297f145c1eeb20e9d3e55802cae6333624c7b62935f10115ecdb0c62624c9de0

applause-bot[bot] avatar May 28 '26 08:05 applause-bot[bot]

Proposal

What is the root cause of that problem?

The sort toggle logic in SortableHeaderText.tsx:60 always defaults to DESC when clicking a column that isn't currently active:

const nextSortOrder = isActive && sortOrder === DESC ? ASC : DESC;

When isActive is false (i.e., switching to a different column), the ternary short-circuits to DESC regardless. So the flow is:

  1. Report opens with Date/ASC (correct initial state at MoneyRequestReportTransactionList.tsx:285-288)
  2. User clicks Total → isActive=false → sort becomes Total/DESC
  3. User clicks Date again → isActive=false → sort becomes Date/DESC (bug: should be ASC)

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

Modify the nextSortOrder logic in SortableHeaderText.tsx:60 so that when switching to a non-active column, the default sort order is ASC instead of DESC. The toggle behavior (clicking an already-active column flips the order) should remain unchanged.

What alternative solutions did you explore? (Optional)

An alternative would be to handle this in the onSortPress callback of MoneyRequestReportTransactionList.tsx:741 by overriding the sort order when the column changes. However, fixing it in SortableHeaderText is cleaner since it's the shared component responsible for computing the next sort order and the same issue would affect any consumer. Note that this change would also affect the Search table headers that use the same component — this is likely the correct behavior there too (defaulting to ASC when first clicking a column), but should be verified during QA.


Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

MelvinBot avatar May 28 '26 08:05 MelvinBot

🚨 Edited by proposal-police: This proposal was edited at 2026-11-20 09:30:36 UTC.

Proposal

What is the root cause of that problem?

The report transaction table declares its own default sort as Date/ASC:

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts#L103-L106

But the direction a header click produces is not decided here. It is decided by the shared SortableHeaderText, which anchors the first click of any inactive column to DESC:

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/Search/SortableHeaderText.tsx#L106-L111

SortableTableHeader forwards that order verbatim, and this table's onSortPress writes it into state without translating it to the view's own default:

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/Search/SortableTableHeader.tsx#L178

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts#L110-L115

So after Date → Amount → Date the table lands on Date/DESC, and the view's own default can no longer be reached in one click.

I measured the emitted order rather than inferring it. Rendering the real MoneyRequestReportTableHeader in Jest on top of the real useMoneyRequestReportSortedTransactions, then pressing Amount and Date, fails on current main with:

Expected: "date/asc"
Received: "date/desc"

When it became wrong

The DESC anchor is correct for the component's other consumer: Search's own default sort is Date/DESC.

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/libs/SearchParser/searchParser.peggy#L68-L73

The two defaults diverged on 2025-03-24, when this table's initial order was changed from DESC to ASC in #58903:

https://github.com/Expensify/App/blob/228e7ab3dcbf7ffaf8b68e8e6f474e239f7faa76/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L78-L82

That made the shared anchor wrong for this view immediately. The isDefaultSort gate from #86477 made it visible by tying the RBR pre-sort to Date/ASC, which is what #91710's test plan exercised. #101497 has since removed that gate, but the direction is still wrong: the table opens on Date/ASC and a click back on Date gives DESC.

Why the listed steps do not reproduce it

@rojiphil the OP's step list stops at "Change sort to Total". PR #91710's test plan has an eighth step — "Switch back to Date/ASC and verify RBR-flagged item is back on the top" — and the Applause export dropped it. Following the six listed steps, nothing is wrong.

The second reason it is easy to miss: the Date sort value is created, which is written date-only.

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/libs/actions/IOU/MoneyRequest.ts#L387

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/libs/ReportUtils.ts#L15744-L15745

Two expenses created on the same day compare equal, and Array.prototype.sort is stable, so ASC and DESC render the same rows in the same order — only the arrow flips. Expenses on different days separate cleanly.

On the RBR half of the Expected and Actual Result: since #101497 (fixing #101424) the table has no RBR-first ordering at all, and under Group by: Category the group headers stay alphabetical by design. The latter also explains QA's grouped-layout recording, where rows only move inside a group. Neither is part of this fix. What is left of this issue is the direction.

Nothing catches it: useMoneyRequestReportSortedTransactionsTest calls onSortPress with an order the test picks itself, and SortableTableHeaderTest only checks the menu headings. No test presses an inactive header and checks the order it emits.

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/tests/unit/useMoneyRequestReportSortedTransactionsTest.tsx#L149-L152

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

First, a correction to my own earlier proposal. I suggested a defaultSortOrder prop on SortableHeaderText. That is wrong: the prop is per table, not per column, so passing ASC would also flip the first click of Amount, Merchant, Description, Category and Tag in this same table. That is a behaviour change well beyond this bug.

The default belongs to the view, so the view owns the value. The translation cannot live in the view's onSortPress, though. The same handler receives the explicit Sort ascending / Sort descending choices from the column heading menu, and it cannot tell those from a plain header click:

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/Search/SortableTableHeader.tsx#L145-L160

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/Table/ColumnHeaderMenu/ColumnHeaderMenuSortItems.tsx#L54-L64

https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L468-L474

So hoist the default into one constant in the hook, and hand it to the header. The header applies it only on the plain-click path, only for the default column, and only when that column is not already active:

+const DEFAULT_SORT_CONFIG: SortConfig = {
+    sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE,
+    sortOrder: CONST.SEARCH.SORT_ORDER.ASC,
+};
-    const [sortConfig, setSortConfig] = useState<SortConfig>({
-        sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE,
-        sortOrder: CONST.SEARCH.SORT_ORDER.ASC,
-    });
+    const [sortConfig, setSortConfig] = useState<SortConfig>(DEFAULT_SORT_CONFIG);
 ...
 export default useMoneyRequestReportSortedTransactions;
+export {DEFAULT_SORT_CONFIG};

SortableTableHeader.tsx:

     sortOrder?: SortOrder;
+    defaultSort?: {sortBy: SearchSortBy; sortOrder: SortOrder};
 ...
-                            onPress={(order: SortOrder) => onSortPress(sortByColumnName, order)}
+                            onPress={(order: SortOrder) => onSortPress(sortByColumnName, !isActive && defaultSort?.sortBy === sortByColumnName ? defaultSort.sortOrder : order)}

MoneyRequestReportTableHeader.tsx:

+import {DEFAULT_SORT_CONFIG} from './useMoneyRequestReportSortedTransactions';
 ...
                 sortOrder={sortOrder}
+                defaultSort={DEFAULT_SORT_CONFIG}
                 onSortPress={onSortPress}

Only the onPress line changes behaviour. defaultSort carries the column as well as the order, so unlike the per-table prop it changes the first click of that one column only. I hoist rather than spell DATE/ASC out a second time because the bug is drift between the place that declares the default and the place that decides the first click.

Regression safety:

  • Search is untouched. SearchTableHeader passes no defaultSort, so order goes through as before. Search writes the emitted order into the URL query, so changing the shared anchor would re-rank saved and shared search links: https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/Search/index.tsx#L1411-L1422
  • The column menu is untouched: its onSort sends its explicit order straight to onSortPress, so Sort descending on Date while Amount is active still lands on Date/DESC.
  • The hook's onSortPress is unchanged, and the initial state is the same value.
  • Toggling the active Date column is unaffected: !isActive is false, so repeat clicks still flip ASC↔DESC. Switching to any non-default column still lands on DESC.
  • No offline or optimistic path is involved: sortConfig is local useState, with no API call and no failureData.
  • In the grouped layout, rows inside each group follow sortedTransactions, so they inherit the corrected order. Group headers stay alphabetical, as settled in #101424.
  • Platforms: the column header only renders on wide layouts, so on a phone there is nothing to press. On wide layouts the same shared components run on web, desktop and native tablets: https://github.com/Expensify/App/blob/80c936a367ef592136af267ca2f3435b88154c60/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L452-L453

One limitation I want to be straight about: a user who deliberately sets Date/DESC, switches to Amount and comes back to Date with a plain click gets ASC, not the DESC they last chose. The view has one default and this makes it reachable in one click; a second click still gives DESC, and the column menu gives DESC directly.

Tests, all of which I ran against current main:

  1. Steps 5 → 7 → 8: open, click Amount, click Date, expect date/asc. Fails on current main with the output above, passes with the fix.
  2. Date → Date still toggles DESC then ASC. Passes on main and with the fix.
  3. Merchant and Amount still land on DESC. Passes on main and with the fix.
  4. Click Amount, then send onSortPress('date', 'desc'), which is what the menu's Sort descending sends. Expect date/desc. Passes on main and with this fix. It fails if the translation is put in the hook's onSortPress instead (Received: "date/asc").
  5. SortableTableHeader rendered the way Search renders it, with no defaultSort: pressing an inactive Date still emits ('date', 'desc'). Passes on main and with the fix.

I did not render the whole transaction list or open the column menu in Jest. Tests 1–3 drive the real MoneyRequestReportTableHeader → SortableTableHeader → SortableHeaderText chain into the real useMoneyRequestReportSortedTransactions. Test 4 sends the order the menu item passes.

What alternative solutions did you explore? (Optional)

  • Flip the ternary to ASC. Rejected: Search's Date default is DESC, so this makes the shared header wrong for its other consumer, and Search's order is encoded in the URL.
  • A defaultSortOrder prop, my earlier proposal. Rejected above: per table rather than per column, so it changes five other columns in this table.
  • Translate the order in the hook's onSortPress. Rejected: the column menu sends explicit orders through the same handler, so an explicit Sort descending on Date would land on ASC (test 4).
  • A deterministic tie-break in the comparator. Worth doing on its own, but it only makes equal rows stable; it cannot make Date land on ASC, so it does not address the reported default sort.

yusufdeveloper2903 avatar May 28 '26 08:05 yusufdeveloper2903

Proposal

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

In the money request report view (Spend → Reports → open a report), the initial default sort is Date/ASC so that RBR-flagged transactions are surfaced at the top. After clicking the Total column header to change sort, then clicking the Date column header again, Date sorts in DESC order instead of returning to the expected Date/ASC default. This contradicts step 8 of the test plan from the linked PR #91710 ("Switch back to Date/ASC and verify RBR-flagged item is back on the top") because clicking Date no longer restores the table's documented default ordering.

What is the root cause of that problem?

The READ side — MoneyRequestReportTransactionList — initialises sortConfig with {sortBy: DATE, sortOrder: ASC} and treats that combination as the "default sort" guard that triggers the RBR pre-sort path. The WRITE side — clicks coming up from SortableHeaderText — computes the next order with logic that does not know about this table's ASC default:

https://github.com/Expensify/App/blob/139b2c8c6378e6772e6db5d298976a31b69f0c76/src/components/Search/SortableHeaderText.tsx#L60-L65

Line 60 reads const nextSortOrder = isActive && sortOrder === DESC ? ASC : DESC. When the user clicks a column that is not currently active (isActive is false because sortBy === 'total' after step 6, and Date is being re-clicked in step 7), the expression short-circuits to the falsy branch and returns DESC. The press handler in MoneyRequestReportTransactionList then writes that order straight into state without translating it to the table's per-column default:

https://github.com/Expensify/App/blob/139b2c8c6378e6772e6db5d298976a31b69f0c76/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L741-L746

The full chain is therefore: user clicks Total → SortableHeaderText emits ('total', DESC) → state becomes {sortBy: 'total', sortOrder: 'DESC'} (correct behaviour for non-default columns) → user clicks Date → SortableHeaderText sees isActive=false for Date and emits ('date', DESC) → state becomes {sortBy: 'date', sortOrder: 'DESC'}. Because isDefaultSort on line 291 only fires when sortOrder === ASC, the RBR pre-sort path in rbrTransactionIDs (lines 297-311) is also bypassed, so the RBR-flagged transaction no longer floats to the top either. The behaviour in SortableHeaderText is the right global default for the main Search screen, which uses DESC as its defaultSortOrder in SearchUIUtils (line 646), but it is wrong for this specific table whose default is Date/ASC. The mismatch was latent before PR #91710 — the new test plan added the Total → Date round-trip step, which is why staging surfaces it but production (which still ran the old test plan) does not.

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

Fix it locally inside MoneyRequestReportTransactionList's onSortPress handler so the global SortableHeaderText keeps its existing behaviour for Search (which legitimately defaults to DESC). When the user clicks a column that is not the currently active sort column (i.e. selectedSortBy !== sortBy), use the table's per-column default: ASC when selectedSortBy === CONST.SEARCH.TABLE_COLUMNS.DATE, otherwise the incoming selectedSortOrder (DESC). When the user clicks the already-active column, honour selectedSortOrder so toggling Date between ASC and DESC still works.

https://github.com/Expensify/App/blob/139b2c8c6378e6772e6db5d298976a31b69f0c76/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L741-L746

Concretely, inside the existing onSortPress callback after the isSortableColumnName guard, compute const nextOrder = selectedSortBy !== sortBy && selectedSortBy === CONST.SEARCH.TABLE_COLUMNS.DATE ? CONST.SEARCH.SORT_ORDER.ASC : selectedSortOrder and pass that as sortOrder into setSortConfig. This restores the original Date/ASC default on switch-back, which in turn re-arms isDefaultSort on line 291 and re-enables the RBR pre-sort that PR #91710 wanted to validate. The change is scoped to a single handler and a single column, does not modify any shared helper or other Search consumers, and preserves the column-toggle behaviour for repeated clicks on Date (DESC ↔ ASC) because the selectedSortBy !== sortBy check is false on a re-click of the active column.

What alternative solutions did you explore? (Optional)

Adding a per-column default-order map to SortableHeaderText (so the global component computes ASC for Date and DESC for everything else) was considered but rejected — it would change behaviour for the main Search screen and every other consumer of SortableTableHeader, where DESC is the intentional default (defaultSortOrder = DESC in SearchUIUtils.ts). Keeping the fix local to the one table that has an ASC default avoids any cross-screen regressions.

MobileMage avatar May 28 '26 08:05 MobileMage

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

melvin-bot[bot] avatar May 28 '26 08:05 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022059919919895211074

melvin-bot[bot] avatar May 28 '26 08:05 melvin-bot[bot]

⚠️ @yusufdeveloper2903 Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

github-actions[bot] avatar May 28 '26 08:05 github-actions[bot]

⚠️ @MobileMage Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar May 28 '26 08:05 github-actions[bot]

Proposal

Updated 2026-10-25: re-anchored to current main (a60491f), with a new test branch; the earlier branch predates the report-view refactor. Since #101497 (merged 2026-09-22, fixes #101424) the table no longer lifts violation (RBR) rows to the top, and group headers stay in alphabetical order by product decision, so the RBR part of the 09-05 version is dropped. The remaining defect and the fix are the ones proposed on 05-28: switching back to Date lands on DESC. Earlier updates: 09-05 re-anchor + Jest test; 09-10 split out the grouped-layout ordering (later settled in #101424).

What is the root cause of that problem?

This view declares Date/ASC as its default sort:

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts#L103-L106

The click direction, however, is computed in the shared SortableHeaderText, and for an inactive column it always comes out DESC:

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/components/Search/SortableHeaderText.tsx#L79

const nextSortOrder = isActive && sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC;

SortableTableHeader passes that value up unchanged, and the view's onSortPress stores whatever arrives:

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/components/Search/SortableTableHeader.tsx#L124

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts#L110-L115

So: Date/ASC → click Amount (the column the OP calls Total) → Amount/DESC → click Date → isActive is still false → Date/DESC. The OP's steps end on the Total click; the wrong landing shows on the next click back to Date, which is the step rojiphil's restated steps add.

DESC on first click is the right default for the Search page: its default is literally sortBy: "date", sortOrder: "desc", and Search's own onSortPress puts the clicked order into the query string:

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/libs/SearchParser/searchParser.peggy#L65-L66

https://github.com/Expensify/App/blob/a60491fded4b38f6c379d00f36b58f98ce79801c/src/components/Search/index.tsx#L1319-L1329

It is the wrong default for this view, which owns a different one.

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

In the view's onSortPress, restore ASC whenever the user switches to the Date column; toggling the already-active column is untouched. The existing setSortConfig call becomes:

setSortConfig((prevState) => {
    const isSwitchingToDate = selectedSortBy !== prevState.sortBy && selectedSortBy === CONST.SEARCH.TABLE_COLUMNS.DATE;
    return {...prevState, sortBy: selectedSortBy, sortOrder: isSwitchingToDate ? CONST.SEARCH.SORT_ORDER.ASC : selectedSortOrder};
});

Date → Amount → Date now lands on Date/ASC; Date still toggles ASC↔DESC; switching to Amount, Merchant or any other column still lands on DESC. The decision reads prevState.sortBy inside the updater, so a queued update cannot see a stale column.

Test. tests/unit/MoneyRequestReportTransactionListDefaultSortTest.tsx renders the real MoneyRequestReportTransactionList with three transactions, presses the real header cells (SortableTableHeader → SortableHeaderText, unmocked) and asserts the ordered list the component hands to its row renderer, which is mocked:

  1. Date → Amount → Date restores Date/ASC: fails on main
  2. The same round trip with a violation on one expense lands on plain Date/ASC (no RBR lift since #101497): fails on main
  3. Date → Date toggles to DESC (control)
  4. Switching to Amount, then to Merchant, lands on DESC each time (control)

On main (a60491f): 2 failed, 2 passed (the two Date-return cases land on Date/DESC). With the change: 4 passed; the neighbouring useMoneyRequestReportSortedTransactionsTest (7/7) and MoneyRequestReportTransactionsNavigationTest (6/6) still pass, and tsc -p tsconfig.jest.json is clean. Test + fix on one branch off a60491f: https://github.com/Expensify/App/compare/main...trasnake87:App:fix/91935

What alternative solutions did you explore? (Optional)

Change the shared toggle in SortableHeaderText so that switching columns lands on ASC (the first proposal on this issue). Against the same four cases on a60491f: 3 failed, 1 passed, all three at the Amount press (Amount lands smallest-first); with that one expectation relaxed, the two Date-return cases pass and the remaining failure is Merchant landing A→Z. So it fixes the Date step by making every column switch in this table land on ASC, and it would also change Search, where DESC is the declared default and a clicked order becomes part of the search URL. The override belongs with the component that declares Date/ASC, so the default and its restoration stay in one file.

trasnake87 avatar May 28 '26 08:05 trasnake87

🚨 Edited by proposal-police: This proposal was edited at 2026-09-13 17:00:55 UTC.

Proposal

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

In an opened report (Spend -> Reports -> open a report), the transaction table opens on Date/ASC, which is the view's declared default and the only state that enables the RBR violation pre-sort. Two separate behaviours have been reported against this table, and both reproduce on current main:

  1. Flat layout (OP steps and @rojiphil's restated steps): after Date -> Total -> Date, the table lands on Date/DESC instead of Date/ASC, so isDefaultSort stays false and the RBR-flagged expense no longer floats to the top.
  2. Grouped layout (@jponikarchuk's Sep 10 video, "Sort is not working in expense list in report, but is working in report List"): with Group by: Category (the default expense-report layout), pressing a column header flips the arrow but the rows do not move.

These are two different root causes producing the two reported symptoms. Fixing only one leaves the other reproducible, which is why the issue has cycled. Below I cover both.

What is the root cause of that problem?

Root cause 1 (flat layout: Date returns as DESC, RBR lost).

The view declares its default as Date/ASC and gates the RBR pre-sort on exactly that pair:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L442-L448

rbrTransactionIDs is null for any other pair, which is what turns violation-first ordering off:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L473-L490

But the direction a header click emits is decided by the shared SortableHeaderText, which anchors the first click of any inactive column to DESC:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/Search/SortableHeaderText.tsx#L79

SortableTableHeader forwards that value verbatim:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/Search/SortableTableHeader.tsx#L123

and this view's onSortPress writes it straight into state with no translation to the view's own default:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L950-L955

So Date/ASC -> click Total -> Total/DESC -> click Date -> isActive is still false -> Date/DESC. isDefaultSort is now false, rbrTransactionIDs is null, and the RBR-first ordering it gates disappears. The DESC-on-switch behaviour is correct for Search, whose declared default is DESC and whose emitted order is persisted into the search URL, so the fix has to live in this consumer, not in the shared header.

Root cause 2 (grouped layout: column sort does nothing).

The column sort does run. sortedTransactions is re-sorted on every header press:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L492-L511

The already-sorted array is then handed to groupTransactionsByCategory / groupTransactionsByTag:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L573-L577

Both helpers bucket the transactions and then unconditionally re-order the groups alphabetically before returning:

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/libs/ReportLayoutUtils.ts#L16-L25

https://github.com/Expensify/App/blob/07dca732efa6a18f69f1bdeda7bff08b87161e44/src/libs/ReportLayoutUtils.ts#L89

The user's sort therefore only reorders rows within a group, never the group order. With one expense per category (the tester's repro), every group has a single row, so the alphabetical group order never changes and the sort looks completely dead. The Search Reports list has no grouping layer, which is why sort works there and not here.

The two mechanisms are independent. Root cause 1 is about the direction the click emits; root cause 2 is about the alphabetical pass discarding the emitted order in the grouped layout.

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

Fix 1: restore the view default in this view's onSortPress. When the user switches back to the default column (Date) from a different column, use the view default order (ASC); toggling the already-active column is untouched. Doing it inside the functional updater keeps it immune to a stale sortBy closure:

onSortPress={(selectedSortBy, selectedSortOrder) => {
    if (!isSortableColumnName(selectedSortBy)) {
        return;
    }
    setHasUserSortedManually(true);
    setSortConfig((prevState) => {
        // Returning to the view's default column (Date) from another column restores the view
        // default (ASC) instead of the shared header's inactive-column DESC, so isDefaultSort
        // re-engages and the RBR pre-sort comes back.
        const isReturningToDefaultColumn = selectedSortBy === CONST.SEARCH.TABLE_COLUMNS.DATE && prevState.sortBy !== CONST.SEARCH.TABLE_COLUMNS.DATE;
        return {
            sortBy: selectedSortBy,
            sortOrder: isReturningToDefaultColumn ? CONST.SEARCH.SORT_ORDER.ASC : selectedSortOrder,
        };
    });
}}

Date -> Total -> Date now lands on Date/ASC, isDefaultSort becomes true, and the RBR pre-sort re-engages on its own. Date still toggles ASC<->DESC because prevState.sortBy !== DATE is false on a re-click. Total, Merchant, and every other column still land on DESC.

Fix 2: let the grouped layout honour an active sort. Give the grouping helpers an opt-out for the alphabetical pass (default true, so every other caller is unchanged):

function groupTransactionsByCategory(
    transactions: Transaction[],
    report: OnyxEntry<Report>,
    localeCompare: LocaleContextProps['localeCompare'],
    shouldSortGroupsAlphabetically = true,
): GroupedTransactions[] {
    // ...unchanged bucketing...
    if (!shouldSortGroupsAlphabetically) {
        // Map iteration order follows each group's first appearance in the already-sorted
        // transactions, so group order tracks the active column comparator.
        return result;
    }
    return sortGroupedTransactions(result, localeCompare);
}

(the same one-line guard in groupTransactionsByTag), and wire it from the view so the alphabetical pass only applies before the user has sorted:

const shouldSortGroupsAlphabetically = !hasUserSortedManually;
if (currentGroupBy === CONST.REPORT_LAYOUT.GROUP_BY.TAG) {
    return groupTransactionsByTag(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);
}
return groupTransactionsByCategory(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);

with a single new flag flipped by the press handler above:

const [hasUserSortedManually, setHasUserSortedManually] = useState(false);

Before any header press, groups stay alphabetical, which is today's default look, and the RBR pre-sort scope of the original PR is untouched. After a press, group order follows the active sort, so the arrow finally moves rows.

Why gate Fix 2 on hasUserSortedManually and not on isDefaultSort. isDefaultSort is true both for the pristine initial view and for an explicit user re-selection of Date/ASC. Gating the alphabetical pass on it means the instant a user deliberately sorts back to Date ascending, the groups snap back to alphabetical and the sort looks dead again, i.e. the exact reported symptom. An explicit "the user has sorted" flag separates "pristine" from "chose Date/ASC," so the grouped list keeps honouring the sort after a round-trip.

Both fixes are local: Fix 1 touches one handler; Fix 2 adds an optional, default-true parameter, so Search results, the matrix (None) layout, and every other consumer of the grouping helpers and the shared header are unaffected. sortConfig and the new flag are local useState, so no offline, optimistic, or failure path is involved.

What specific scenarios should we cover in automated tests to prevent this problem from happening again?

Flat layout (drives the real SortableTableHeader -> SortableHeaderText chain and asserts the order handed to the row renderer):

  • Date -> Total -> Date restores Date/ASC (fails on main).
  • With a violation on one expense, that expense is back at index 0 after the round-trip (fails on main).
  • Date -> Date still toggles to DESC (control).
  • Switching to Total, then Merchant, lands on DESC each time (control).

Grouped layout (ReportLayoutUtils):

  • With shouldSortGroupsAlphabetically: false, group order matches the sorted-transaction input rather than alphabetical, for both groupTransactionsByCategory and groupTransactionsByTag.
  • With the default true, groups stay alphabetical with the empty key last (existing behaviour unchanged).
  • View-level: with Group by: Category and one expense per category, pressing Total reorders the visible groups (fails on main).

What alternative solutions did you explore? (Optional)

  • Flip the ternary in SortableHeaderText to default inactive columns to ASC (MelvinBot's canonical proposal). Rejected: the same component drives Search, whose declared default is DESC and whose emitted order is written into saved-search URLs, so a global flip re-ranks Search and every other consumer.
  • Gate the grouped-layout alphabetical pass on isDefaultSort (the mechanism @neerajbachani identified for the grouped defect). It correctly locates the alphabetical pass, but as noted above isDefaultSort cannot tell the pristine view from an explicit Date/ASC re-selection, so the grouped list would still freeze when the user sorts back to Date ascending. Tracking the user action directly closes that gap.
  • Thread a defaultSortOrder prop through SortableTableHeader and SortableHeaderText. Cleaner if a second ASC-default view ever appears, but it is per-table not per-column and touches shared Search components for behaviour only this table needs today.
  • Add a deterministic tie-break to the comparator (for same-day expenses). Worth doing on its own, but it only stabilises equal rows; it changes neither the emitted sort direction nor the alphabetical group order, so it addresses neither root cause.

David-2002065 avatar May 28 '26 08:05 David-2002065

⚠️ @dilshodmackbook-sketch Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

github-actions[bot] avatar May 28 '26 08:05 github-actions[bot]

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

wildan-m avatar May 28 '26 08:05 wildan-m

⚠️ @wildan-m Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar May 28 '26 08:05 github-actions[bot]

Proposal

What is the root cause of that problem?

Two pieces of code disagree on what "the default sort" is for the money request report transaction list, and the disagreement is asymptomatic until you do exactly the round-trip in the QA repro (Date → Total → Date).

MoneyRequestReportTransactionList initializes its view-local sort as Date/ASC and gates the RBR pre-sort on exactly that pair — both the useState initial value and the isDefaultSort derivation live here:

https://github.com/Expensify/App/blob/069aa2cc6053c244cd6c485bf4c110038e94cbba/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L285-L291

…and the rbrTransactionIDs set that the comparator uses to bubble RBR-flagged transactions to the top short-circuits to null whenever isDefaultSort is false:

https://github.com/Expensify/App/blob/069aa2cc6053c244cd6c485bf4c110038e94cbba/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L297-L311

But the order the header click writes back into state is computed by the shared SortableHeaderText, which hardcodes DESC as the "first direction" for any column that isn't currently active:

https://github.com/Expensify/App/blob/069aa2cc6053c244cd6c485bf4c110038e94cbba/src/components/Search/SortableHeaderText.tsx#L60

When isActive is false (the user is switching to a different column), the ternary short-circuits to DESC no matter what — SortableHeaderText has no way to know that this particular host table has an ASC default. SortableTableHeader then forwards (columnName, DESC) to the parent's onSortPress, which writes it straight into sortConfig with no per-view translation:

https://github.com/Expensify/App/blob/069aa2cc6053c244cd6c485bf4c110038e94cbba/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L741-L746

Walking the QA repro at this SHA:

  1. Report opens → sortConfig = {DATE, ASC} → isDefaultSort=true → rbrTransactionIDs is populated → the violation transaction floats to the top. ✅
  2. Click Total → SortableHeaderText sees isActive=false for Total → emits DESC → sortConfig = {TOTAL, DESC} → isDefaultSort=false, RBR pre-sort intentionally off. ✅
  3. Click Date → SortableHeaderText sees isActive=false for Date (active column is Total) → emits DESC again → sortConfig = {DATE, DESC} → isDefaultSort is still false → rbrTransactionIDs stays null. 🐞

That single mismatch produces both reported symptoms — "Default sort for Date is set to DESC" and "RBR pre-sort is still at the top" — because the latter is gated on the former.

The DESC-on-switch behavior in SortableHeaderText is intentional and correct for the main Search screen, whose documented default order is DESC:

https://github.com/Expensify/App/blob/069aa2cc6053c244cd6c485bf4c110038e94cbba/src/libs/SearchUIUtils.ts#L646

Why this is staging-only: PR #91710 (merged 2026-05-27, shipped in 9.3.84-0) introduced the isDefaultSort-gated RBR pre-sort. Before that PR the Date column's "land on DESC after a round trip" oddity existed but had no observable side effect, so it wasn't visible to QA. The new test plan added the Total → Date round-trip step (step 8), which is why staging surfaces it now and production doesn't.

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

Fix it at the consumer layer (data/state) in MoneyRequestReportTransactionList's onSortPress, not in the shared SortableHeaderText. The view that owns the {DATE, ASC} default is the only place that has the context to enforce it.

In the onSortPress callback at MoneyRequestReportTransactionList.tsx#L741-L746, after the isSortableColumnName guard, derive the next sort order like:

If the user is switching columns (selectedSortBy !== sortBy) and the destination column is the view's default (selectedSortBy === CONST.SEARCH.TABLE_COLUMNS.DATE), force CONST.SEARCH.SORT_ORDER.ASC. Otherwise pass selectedSortOrder through unchanged.

…then setSortConfig with the corrected order. This:

  • Restores Date/ASC on the Total → Date click — isDefaultSort becomes true again, and the RBR pre-sort path at #L297-L311 re-engages on its own — both symptoms are fixed by one change.
  • Preserves the toggle on the active Date column: when selectedSortBy === sortBy (e.g., user clicks Date twice in a row), the switch condition is false and selectedSortOrder (which SortableHeaderText correctly flips between ASC/DESC for the active column) passes through unchanged.
  • Doesn't affect switching to non-default columns (Total, Merchant, etc.) — they still land on DESC, matching the existing Search-style behavior.
  • Leaves SortableHeaderText, SortableTableHeader, SearchTableHeader, and Search's defaultSortOrder = DESC untouched, so there's zero blast radius on /search.

Fix layer: consumer-side data/state. The view owns the default; the shared header is intentionally view-agnostic.

Edge cases the fix touches: none beyond the toggle case described above. Offline / optimistic / error paths don't apply — this is purely client-side useState derived from a UI click.

I'd also add a small test in the existing MoneyRequestReportTransactionList test suite that opens a report with a violation, asserts the flagged transaction is at index 0, sorts by Total, sorts by Date, and asserts index 0 again — that's the exact regression PR #91710's test plan tried to validate.

What alternative solutions did you explore? (Optional)

  • Flip the nextSortOrder ternary in SortableHeaderText.tsx#L60 to default to ASC. Rejected — the same component is rendered by SearchTableHeader on /search, where defaultSortOrder = DESC (SearchUIUtils.ts#L646) is the documented expectation (e.g., clicking Total on /search should land on "largest first"). A global flip would silently regress every Search consumer and every persisted/URL-encoded Search sort.

  • Add a defaultSortOrder prop to SortableHeaderText (default DESC so Search is unchanged) and thread it from MoneyRequestReportTableHeader → SortableTableHeader → SortableHeaderText. Structurally cleaner if a second view ever grows an ASC default, but invasive (three files, public prop addition, no current second consumer) for a one-column fix today. Worth doing as a follow-up if/when a second ASC-default view appears; not warranted now.

  • Make the Date header always reset to the view default on click instead of toggling. Rejected — it would break the standard ASC↔DESC toggle that users expect from a column header on repeated clicks.

oqildev avatar May 28 '26 09:05 oqildev

⚠️ @oqildev Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar May 28 '26 09:05 github-actions[bot]

Proposal

What is the root cause of that problem?

I reproduced the bug on the report-detail table (Spend → Reports → <report>) where the user lands on the Date column with the default sort and then clicks any other column header (e.g. Total). The Date column header's arrow indicator is the UI element under test — it is supposed to keep pointing up (ASC) when the user returns to it, since the table is mounted with sortOrder: CONST.SEARCH.SORT_ORDER.ASC at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L285-L288 .

The arrow is rendered by SortableHeaderText at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/Search/SortableHeaderText.tsx#L56-L60 . It computes nextSortOrder from a single rule:

nextSortOrder = isActive && sortOrder === DESC ? ASC : DESC

That rule has only two real branches: "currently active + DESC → toggle to ASC", and "anything else → DESC". The second branch is the bug — it fires for every press on an inactive column, regardless of which column was originally the default. So the moment the user moves the sort off Date (step 6: "Change sort to Total"), the sort state becomes TOTAL/DESC, and pressing the Date header again resolves to DATE/DESC (because isActive is false at that moment) instead of restoring the table's documented default DATE/ASC. The parent's onSortPress at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L732-L737 just trusts the selectedSortOrder it receives, so the bad direction propagates straight into setSortConfig, and the Date column header re-renders with the down arrow — matching the reporter's observation that "Default sort for Date is set to DESC".

The same SortableHeaderText rule is reached on the very first click of any column inside MoneyRequestReportTableHeader (https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx#L79-L93) because that header was added with a fixed Date/ASC initial state but no notion of a "default direction per column" — SortableHeaderText doesn't know that DATE should restart at ASC, so it falls into the catch-all DESC branch.

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

The fix belongs in the mutation layer — the onSortPress callback on the report-detail table — and not in SortableHeaderText, because the shared header component is used by many tables (Search results, workspace lists, etc.) where DESC-first on a new column is the established convention, and changing it globally would regress those surfaces.

Concretely, in MoneyRequestReportTransactionList.tsx's onSortPress at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L732-L737 I'd intercept the order that SortableHeaderText proposes and, when the press switches to a different column than the one currently active, replace it with that column's natural default direction. The table already declares the canonical default sort on mount at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L285-L288 (DATE → ASC); I'd promote that to a small lookup keyed by column (e.g. DATE → ASC, TOTAL → DESC, TAX_AMOUNT → DESC, …) and consult it whenever selectedSortBy !== sortBy. When the press is on the already-active column, the existing SortableHeaderText toggle (ASC ↔ DESC) is left untouched, so the in-column toggling behavior the rest of the app relies on is preserved.

The canonical pattern to mirror is the existing isDefaultSort constant on line 291 of the same file (https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L291) — the file already encodes the idea that "Date + ASC" is the default for this view; reusing that fact in onSortPress keeps a single source of truth instead of scattering direction defaults.

No change is needed in the render path (sortedTransactions at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L308-L319 ) or in the precomputed rbrTransactionIDs set at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L296-L307 — both consume sortBy/sortOrder correctly. Once onSortPress produces the right sortOrder, isDefaultSort becomes true again on the return-to-Date press, rbrTransactionIDs is rebuilt, and the RBR pre-sort that the PR test step 8 expects ("RBR-flagged item is back on the top") is automatically restored.

What alternative solutions did you explore? (Optional)

  1. Patch the rule directly inside SortableHeaderText (https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/Search/SortableHeaderText.tsx#L60) so the inactive-column default becomes ASC instead of DESC. This is the smallest-looking diff but it is the worst fix: SortableHeaderText is shared by all sortable tables (Search results, saved searches, workspace expense tables, etc.), and flipping the global default would regress every list whose users expect "newest / largest first" on a fresh column click — for example, the Total / Amount / Date columns on the main Search results page, which currently rely on DESC-first to surface the most relevant rows. The bug is local to the report-detail table's stated default, so the fix should be local too.

  2. Reset sortConfig back to {DATE, ASC} only when the user clicks Date specifically, leaving every other column to keep the existing DESC-first toggle. This special-cases one column instead of describing the rule. It also doesn't compose well with the new rbrTransactionIDs memo at https://github.com/Expensify/App/blob/c5a8675137c7a515164979558e3955198f3c58b5/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L296-L307 because that memo recomputes off isDefaultSort, so the right model is "every column has a natural default direction; consult it on cross-column press" — exactly what my proposed lookup does. The single-column shortcut would silently break the day another column gains a documented default (e.g. a future "Newest first" requirement on MERCHANT or SUBMITTED), and would also leave the originally reported user behavior of "the indicator on a fresh Total click is DESC" unaddressed in any consistent way.

Abdulloh0109 avatar May 28 '26 09:05 Abdulloh0109

Proposal

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

In the report expense table (Spend → Reports → open a report), clicking a column header to sort by Date or Total does not change the visible row order when Group by: Category (or Tag) is active — the default layout for expense reports. The same asc/desc controls work correctly in the Search Reports list. jponikarchuk confirmed this on staging (Sep 10 comment): sort arrows update but the list stays in alphabetical category order (Interest → Labor → Uncategorized).

What is the root cause of that problem?

Column sorting does run. MoneyRequestReportTransactionList keeps local sortConfig, builds sortedTransactions via compareValues, and updates state when a header is pressed:

https://github.com/Expensify/App/blob/7478209c405b673c3824bfdf7937601561a3f7c4/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L490-L508

That sorted array is then passed into groupTransactionsByCategory / groupTransactionsByTag. Expense reports default to grouped-by-category layout when no NVP is stored:

https://github.com/Expensify/App/blob/7478209c405b673c3824bfdf7937601561a3f7c4/src/libs/actions/ReportLayout.ts#L88-L93

After bucketing, both grouping helpers always re-sort the groups alphabetically via sortGroupedTransactions, regardless of the active column sort:

https://github.com/Expensify/App/blob/7478209c405b673c3824bfdf7937601561a3f7c4/src/libs/ReportLayoutUtils.ts#L16-L25

https://github.com/Expensify/App/blob/7478209c405b673c3824bfdf7937601561a3f7c4/src/libs/ReportLayoutUtils.ts#L78-L89

The user's sort only reorders rows within each group. With one expense per category (the tester's repro), every group has a single row — the alphabetical group order never changes, so asc/desc appears completely dead. The Search Reports page has no grouping layer, which is why sort works there.

This also explains inconsistent QA reports: sorting is visible when multiple expenses share one category (within-group reorder) or when Group by: None is selected (matrix layout skips grouping entirely).

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

Add an optional shouldSortGroupsAlphabetically flag (default true) to groupTransactionsByCategory and groupTransactionsByTag. When false, return groups in Map insertion order — which follows first appearance in the already-sorted transactions input, so group order tracks the active column comparator for every sort column.

Wire it from MoneyRequestReportTransactionList with shouldSortGroupsAlphabetically = isDefaultSort so default Date/ASC keeps today's alphabetical groups (and the RBR pre-sort scope of the original issue is untouched); any user-initiated sort skips the alphabetical pass.

App/src/libs/ReportLayoutUtils.ts

+    if (!shouldSortGroupsAlphabetically) {
+        return result;
+    }
+
     return sortGroupedTransactions(result, localeCompare);

App/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx

+        const shouldSortGroupsAlphabetically = isDefaultSort;
         if (currentGroupBy === CONST.REPORT_LAYOUT.GROUP_BY.TAG) {
-            return groupTransactionsByTag(resolvedTransactions, report, localeCompare);
+            return groupTransactionsByTag(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);
         }
-        return groupTransactionsByCategory(resolvedTransactions, report, localeCompare);
+        return groupTransactionsByCategory(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);

Default behavior is unchanged: alphabetical groups on Date/ASC. Blast radius is limited to grouped report expense lists; matrix (None) layout and the Search Reports page are unaffected.

Test branch: https://github.com/neerajbachani/App/compare/main...fix/91935-grouped-sort

What alternative solutions did you explore? (Optional)

  • Sort groups by subtotal when sorting by Total — rejected; one consistent "leading transaction" rule covers all columns without special cases.
  • Disable grouping when any non-default sort is active — rejected; users expect Group by to stay on while sorting.
  • Fix SortableHeaderText default direction (MelvinBot's original proposal) — addresses a different symptom (Date returning DESC after Total→Date round-trip on ungrouped/matrix layout), not jponikarchuk's grouped-list repro where the arrow updates but order is frozen by alphabetical groups.

What specific scenarios should we cover in automated tests to prevent this problem from happening again?

  • With shouldSortGroupsAlphabetically: false, group order matches the sorted transaction input (not alphabetical).
  • With shouldSortGroupsAlphabetically: true (default), groups stay alphabetical with empty key last — existing behavior unchanged.
  • Same assertions for both groupTransactionsByCategory and groupTransactionsByTag.

AI assistance: prepared and tested with Cursor. Implementation branch above; happy to open a PR if this scope is available.

neerajbachani avatar May 28 '26 09:05 neerajbachani

⚠️ @Abdulloh0109 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar May 28 '26 09:05 github-actions[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-09-21 06:21:37 UTC.

Proposal

What is the root cause of that problem?

There are two related sorting failures in the opened report expense table.

First, the report expense table declares its default sort as Date/ASC, and that exact state controls the default Date behavior and the RBR priority path.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L442-L448

But the shared sortable header emits DESC whenever the clicked column is not currently active.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/Search/SortableHeaderText.tsx#L75-L79

MoneyRequestReportTransactionList stores that emitted order directly.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L940-L954

So after Date/ASC -> Amount/Total -> Date, the table lands on Date/DESC instead of restoring the report table default.

Second, in the grouped layout, column sorting runs but its result is partially discarded. The table sorts sortedTransactions first.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L492-L511

Then it passes that already-sorted array to groupTransactionsByCategory / groupTransactionsByTag.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L570-L577

Both grouping helpers always sort the groups alphabetically after bucketing.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/libs/ReportLayoutUtils.ts#L16-L25

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/libs/ReportLayoutUtils.ts#L60-L119

That means the user-selected column sort only applies inside each group. With one expense per category or tag, there is nothing inside a group to reorder, so the arrows change but the visible rows stay in alphabetical group order.

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

Keep the fix local to the report expense table and grouping helpers. Do not change the shared sortable header because Search correctly uses DESC as its first inactive-column order.

In MoneyRequestReportTransactionList, define the table default once and reuse it for initial state and isDefaultSort.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L442-L448

const INITIAL_SORT_CONFIG: SortedTransactions = {
    sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE,
    sortOrder: CONST.SEARCH.SORT_ORDER.ASC,
};
const [sortConfig, setSortConfig] = useState<SortedTransactions>(INITIAL_SORT_CONFIG);
const [hasUserSortedManually, setHasUserSortedManually] = useState(false);

const {sortBy, sortOrder} = sortConfig;
const isDefaultSort = sortBy === INITIAL_SORT_CONFIG.sortBy && sortOrder === INITIAL_SORT_CONFIG.sortOrder;

Then normalize only the report table's return to the default column inside the existing onSortPress.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L940-L954

onSortPress={(selectedSortBy, selectedSortOrder) => {
    if (!isSortableColumnName(selectedSortBy)) {
        return;
    }

    setHasUserSortedManually(true);
    setSortConfig((prevState) => {
        const isReturningToDefaultColumn = selectedSortBy === INITIAL_SORT_CONFIG.sortBy && prevState.sortBy !== INITIAL_SORT_CONFIG.sortBy;

        return {
            sortBy: selectedSortBy,
            sortOrder: isReturningToDefaultColumn ? INITIAL_SORT_CONFIG.sortOrder : selectedSortOrder,
        };
    });
}}

This fixes the flat-layout bug because Amount/Total -> Date now writes Date/ASC, while repeated clicks on the active Date column still toggle normally.

For the grouped-layout bug, add an optional shouldSortGroupsAlphabetically = true parameter to both grouping helpers. Existing callers keep the current behavior by default.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/libs/ReportLayoutUtils.ts#L60-L119

function groupTransactionsByCategory(
    transactions: Transaction[],
    report: OnyxEntry<Report>,
    localeCompare: LocaleContextProps['localeCompare'],
    shouldSortGroupsAlphabetically = true,
): GroupedTransactions[] {
    // existing grouping logic

    return shouldSortGroupsAlphabetically ? sortGroupedTransactions(result, localeCompare) : result;
}

Apply the same parameter to groupTransactionsByTag.

When the report is still in its untouched initial view, keep alphabetical groups. After the user clicks a sortable column, preserve the group insertion order from resolvedTransactions, which already follows sortedTransactions.

https://github.com/Expensify/App/blob/4f5dff4dde75e862904115a203ccff0a4aa4db93/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx#L570-L577

const shouldSortGroupsAlphabetically = !hasUserSortedManually;

if (currentGroupBy === CONST.REPORT_LAYOUT.GROUP_BY.TAG) {
    return groupTransactionsByTag(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);
}
return groupTransactionsByCategory(resolvedTransactions, report, localeCompare, shouldSortGroupsAlphabetically);

This fixes the grouped tester bug because Date/Amount/etc. sorting can now control the order of the groups through the already-sorted transaction input. It is safer than using isDefaultSort for grouped ordering because a user can explicitly select Date/ASC; that should still count as a manual sort, even though the column and direction equal the initial default.

What alternative solutions did you explore? (Optional)

Alternative 1: Use isDefaultSort to decide grouped order

const shouldSortGroupsAlphabetically = isDefaultSort;

This fixes most grouped repros, but it misses the explicit manual Date/ASC case because that state is indistinguishable from the untouched initial state.

Alternative 2: Normalize sort in MoneyRequestReportTableHeader

const isSwitchingToDefaultColumn = selectedSortBy !== sortBy && selectedSortBy === defaultSortConfig.sortBy;
onSortPress(selectedSortBy, isSwitchingToDefaultColumn ? defaultSortConfig.sortOrder : selectedSortOrder);

This fixes the flat Date/ASC bug, but it adds prop plumbing through the table header even though the list already owns the default sort state.

Alternative 3: Change SortableHeaderText globally

const nextSortOrder = isActive ? toggledSortOrder : CONST.SEARCH.SORT_ORDER.ASC;

This would fix the report table's Date return, but it would change shared Search behavior and make other inactive columns start with ASC, which is outside this issue.

emkhalid avatar May 28 '26 09:05 emkhalid

⚠️ @emkhalid Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar May 28 '26 09:05 github-actions[bot]