Skip to content

[$250] Spend - Default sort is descending #91935

Open

Description

@applause-bot

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


Version Number: 9.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: #91710
Email or phone of affected tester (no customers): applausetester+05272026_1@applause.expensifail.com
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:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

bandicam.2026-05-28.09-08-42-638.1.mp4

View all open jobs on GitHub

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

Activity

  1. applause-bot commented on May 28, 2026

    @applause-bot
    Author

    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

  2. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on May 28, 2026
  3. MelvinBot commented on May 28, 2026

    @MelvinBot
    Contributor

    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.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 28, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 28, 2026
  6. yusufdeveloper2903 commented on May 28, 2026

    @yusufdeveloper2903
    Contributor

    🚨 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:

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

    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:

    const nextSortOrder = isActive && sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC;
    return (
    <View style={containerStyle}>
    <PressableWithFeedback
    onPress={() => onPress(nextSortOrder)}

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

    onPress={(order: SortOrder) => onSortPress(sortByColumnName, order)}

    const onSortPress = (selectedSortBy: SearchSortBy, selectedSortOrder: SortOrder) => {
    if (!isSortableColumnName(selectedSortBy)) {
    return;
    }
    setSortConfig((prevState) => ({...prevState, sortBy: selectedSortBy, sortOrder: selectedSortOrder}));
    };

    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.

    const defaultValues = {
    type: "expense",
    sortBy: "date",
    sortOrder: "desc",
    view: "table",

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

    const [sortedData, setSortedData] = useState<SortedTransactions>({
    transactions,
    sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE,
    sortOrder: CONST.SEARCH.SORT_ORDER.ASC,
    });

    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.

    const created = currentDate ?? format(new Date(), 'yyyy-MM-dd');

    App/src/libs/ReportUtils.ts

    Lines 15744 to 15745 in 80c936a

    case CONST.SEARCH.TABLE_COLUMNS.DATE:
    return getTransactionCreated(transaction);

    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.

    // When the user sorts by merchant descending
    act(() => {
    result.current.onSortPress(CONST.SEARCH.TABLE_COLUMNS.MERCHANT, CONST.SEARCH.SORT_ORDER.DESC);
    });

    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:

    if (children && (!!label || !!icon)) {
    return (
    <View
    key={columnName}
    style={containerStyle}
    >
    <SortableColumnProvider
    columnName={columnName}
    label={columnLabel}
    alignment={StyleUtils.getReportTableColumnAlignment(columnName)}
    hasResizeHandle={!!columnResize?.hasHandle(columnName)}
    sorting={isSortable ? {activeSortOrder: isActive ? sortOrder : undefined, onSort: (order) => onSortPress(sortByColumnName, order)} : undefined}
    labelProps={{text: label, icon, isActive, sortOrder: resolvedSortOrder, innerContainerStyle, textStyle}}
    >
    {children}
    </SortableColumnProvider>

    onSelect={() => sorting.onSort(CONST.SEARCH.SORT_ORDER.ASC)}
    sentryLabel={sentryLabels.ascending}
    />
    <PopoverMenu.Item
    text={translate('search.columnMenu.sortDescending')}
    icon={icons.ArrowDownLong}
    rightIcon={isDescendingActive ? icons.Checkmark : undefined}
    success={isDescendingActive}
    iconFill={getSortIconFill}
    accessibilityState={{selected: isDescendingActive}}
    onSelect={() => sorting.onSort(CONST.SEARCH.SORT_ORDER.DESC)}

    {isBetaEnabled(CONST.BETAS.PINNABLE_TABLE_COLUMNS) && (
    <SortableColumnMenu
    columnEditing={isExpenseReportViewFromIOUReport ? undefined : columnEditing}
    sentryLabel={CONST.SENTRY_LABEL.REPORT.COLUMN_MENU}
    itemSentryLabels={CONST.SENTRY_LABEL.REPORT.COLUMN_MENU_ITEM}
    />
    )}

    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:
      const onSortPress = useCallback(
      (column: SearchSortBy, order: SortOrder) => {
      clearSelectedTransactions();
      const newQuery = buildSearchQueryString({
      ...queryJSON,
      sortBy: column,
      sortOrder: order,
      });
      onSortPressedCallback?.();
      navigation.setParams({q: newQuery, rawQuery: undefined});
      },
      [clearSelectedTransactions, queryJSON, onSortPressedCallback, navigation],
    • 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 [Due for payment 2026-10-01] [$250] Report — Sorting by date is broken in expense reports with more than one expense #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:
      const tableColumnHeader =
      isEmptyTransactions || shouldUseNarrowLayout ? null : (

    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.
  7. MobileMage commented on May 28, 2026

    @MobileMage
    Contributor

    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:

    const nextSortOrder = isActive && sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC;
    return (
    <View style={containerStyle}>
    <PressableWithFeedback
    onPress={() => onPress(nextSortOrder)}

    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:

    onSortPress={(selectedSortBy, selectedSortOrder) => {
    if (!isSortableColumnName(selectedSortBy)) {
    return;
    }
    setSortConfig((prevState) => ({...prevState, sortBy: selectedSortBy, sortOrder: selectedSortOrder}));
    }}

    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.

    onSortPress={(selectedSortBy, selectedSortOrder) => {
    if (!isSortableColumnName(selectedSortBy)) {
    return;
    }
    setSortConfig((prevState) => ({...prevState, sortBy: selectedSortBy, sortOrder: selectedSortOrder}));
    }}

    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.

  8. melvin-bot commented on May 28, 2026

    @melvin-bot

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

  9. changed the title [-]Spend - Default sort is descending[/-] [+][$250] Spend - Default sort is descending[/+] on May 28, 2026
  10. melvin-bot commented on May 28, 2026

    @melvin-bot
  11. github-actions commented on May 28, 2026

    @github-actions
    Contributor

    ⚠️ @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).

  12. github-actions commented on May 28, 2026

    @github-actions
    Contributor

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

  13. 204 remaining items

  14. KFC-19 commented on Nov 13, 2026

    @KFC-19
  15. github-actions commented on Nov 13, 2026

    @github-actions
    Contributor

    ⚠️ @KFC-19 Thanks for your interest. To be considered for this job, please post a proposal following the proposal template (note the mandatory sections). Comments claiming the job without one are not reviewed.

  16. Fabtech21 commented on Nov 17, 2026

    @Fabtech21

    Proposal

    What is the root cause of that problem?

    In the opened report expense table (MoneyRequestReportView), three coupled issues break Date default sorting and deterministic ordering on current main (b2233de91161):

    1. Inactive columns always emit DESC in SortableHeaderText (src/components/Search/SortableHeaderText.tsx:106):
      useMoneyRequestReportSortedTransactions (src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts:103-106) initializes the report table's default sort to {sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE, sortOrder: CONST.SEARCH.SORT_ORDER.ASC}. However, SortableHeaderText computes const nextSortOrder = isActive && sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC. When the user sorts by Amount / Total (isActive = false -> TOTAL_AMOUNT / DESC) and then clicks Date (isActive = false), SortableHeaderText unconditionally emits DESC, landing on Date / DESC instead of restoring the report view's Date / ASC default.

    2. Same-day expenses lack the inserted -> transactionID tie-breaker used by Search (src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts:137-139):
      getTransactionSortValue for DATE (src/libs/ReportUtils.ts:15630-15631) returns a date-only "yyyy-MM-dd" string. Unlike getSortedTransactionData on the Search page (src/libs/SearchUIUtils.ts:4573-4594), useMoneyRequestReportSortedTransactions calls compareValues(...) directly with no tie-breaker. When two expenses are created on the same day (as in the OP reproduction steps and @rojiphil's Jul 27 recording), compareValues returns 0 for both ASC and DESC, leaving rows frozen in their incidental array order instead of ordering by inserted and transactionID.

    3. Report-to-report navigation carries over a previous report's DESC sort (src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts:103-106):
      When navigating between reports via RHP prev/next arrows (MoneyRequestReportNavigation), MoneyRequestReportTransactionList stays mounted while report.reportID changes, leaking a prior report's DESC sort onto the newly opened report instead of starting on Date / ASC.

    (Note: per the product decision established in #101424 / PR #101497, RBR violation hoisting was intentionally removed from the report expense table and Category/Tag group headers remain sorted alphabetically while column sorting orders rows within each group.)

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

    1. Add an optional defaultSortOrder prop to SortableHeaderText and SortableTableHeader (src/components/Search/SortableHeaderText.tsx, src/components/Search/SortableTableHeader.tsx, src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx):

      • Default defaultSortOrder to CONST.SEARCH.SORT_ORDER.DESC in SortableHeaderText so Search tables and all other columns keep their exact current behavior (const toggledSortOrder = sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC; const nextSortOrder = isActive ? toggledSortOrder : defaultSortOrder;).
      • Thread defaultSortOrder?: SortOrder through ColumnConfig in SortableTableHeader.
      • In MoneyRequestReportTableHeader, set defaultSortOrder to CONST.SEARCH.SORT_ORDER.ASC for CONST.SEARCH.TABLE_COLUMNS.DATE and CONST.SEARCH.SORT_ORDER.DESC for all other columns. Clicking Date from another column immediately restores Date / ASC, while clicking an already-active Date column continues toggling ASC <-> DESC.
    2. Add deterministic inserted -> transactionID tie-breaking and per-report reset in useMoneyRequestReportSortedTransactions (src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts):

      • Track prevReportID in state (the React Compiler-safe render-time pattern already used in useYourSpendData) so switching report?.reportID immediately resets sortConfig to {sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE, sortOrder: CONST.SEARCH.SORT_ORDER.ASC} without a useEffect double-render.
      • Mirror SearchUIUtils.getSortedTransactionData's tie-breaker: when primaryComparison === 0 and the compared values are not both empty, fall back to compareValues(a.inserted, b.inserted, sortOrder, 'inserted', localeCompare, true) and then compareValues(a.transactionID, b.transactionID, sortOrder, 'transactionID', localeCompare, true).

    What alternative solutions did you explore? (Optional)

    1. Overriding selectedSortOrder to ASC inside useMoneyRequestReportSortedTransactions.onSortPress whenever switching to DATE: Rejected because onSortPress(selectedSortOrder) is an explicit (column, order) contract (also wired to SortableColumnProvider for explicit Sort ascending / Sort descending column actions). Coercing inside onSortPress makes it impossible for a caller or column menu to switch directly to Date / DESC from another column; owning defaultSortOrder on the header column keeps onSortPress faithful to its argument.
    2. Changing SortableHeaderText globally to default all inactive columns to ASC: Rejected because the Search page defaults to DESC (sortBy: "date", sortOrder: "desc") and expects first clicks on inactive columns such as Amount or Date in Search to sort DESC.
    3. Disabling alphabetical group sorting in ReportLayoutUtils.ts: Rejected because [Due for payment 2026-10-01] [$250] Report — Sorting by date is broken in expense reports with more than one expense #101424 / PR Let an explicit column sort win over the RBR ordering and the alphabetical group order #101497 explicitly confirmed as a product requirement that Category/Tag group headers stay alphabetical while column sorts order rows within each group.
  17. melvin-bot commented on Nov 17, 2026

    @melvin-bot

    📣 @Fabtech21! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  18. guyuan66 commented on Nov 18, 2026

    @guyuan66

    Proposal

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

    In Spend > Reports, opening an expense report shows the transaction table sorted by Date / ASC — that is the table's designed default. Two things break that default:

    1. Click a different column header (e.g. Total), then click Date again: the table lands on Date / DESC instead of coming back to Date / ASC.
    2. Sort a report (e.g. into DESC), then open a different report while the list stays mounted: the new report inherits the previous report's sort instead of starting on Date / ASC.

    The issue title is about (1). (2) is the same defect from the other side — the table's default is declared once at mount and never re-asserted afterwards — so this proposal fixes both in the same file.

    What is the root cause of that problem?

    The table's default exists in exactly one place, and nothing downstream knows about it.

    1. The default is declared, then ignored on every later click.

    src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts:103-106 (HEAD 84b8220):

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

    But the header that produces the next sort order has no idea this table defaults to ASC. src/components/Search/SortableHeaderText.tsx:106:

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

    For any column that is not currently active (isActive === false), this always emits DESC. The chain is MoneyRequestReportTableHeader → SortableTableHeader → SortableHeaderText → onSortPress (verified in MoneyRequestReportTableHeader.tsx:77-87, which forwards sortBy / sortOrder / onSortPress unchanged). And onSortPress stores whatever it is handed, verbatim — useMoneyRequestReportSortedTransactions.ts:110-115:

    const onSortPress = (selectedSortBy: SearchSortBy, selectedSortOrder: SortOrder) => {
        if (!isSortableColumnName(selectedSortBy)) {
            return;
        }
        setSortConfig((prevState) => ({...prevState, sortBy: selectedSortBy, sortOrder: selectedSortOrder}));
    };

    So the round trip is: open on Date/ASC → click Total, header emits (total, DESC) → state is Total/DESC → click Date, header emits (date, DESC) because Date is inactive → state is Date/DESC. The table's own default is never consulted after mount. I confirmed the transition table by executing the handler logic (see Part 2): current code produces date/desc for that sequence; the fixed version produces date/asc, while repeated clicks on the active Date column still toggle ASC↔DESC.

    2. The default is a mount-time initial value only, so it does not survive report navigation.

    useState initialises sortConfig once, when the hook first mounts. The hook receives report (and MoneyRequestReportTransactionList.tsx:230 reads report?.reportID), but nothing in the hook watches reportID — there is no reset path and no key={reportID} remount in MoneyRequestReportView.tsx, MoneyRequestReportUnifiedList.tsx, or MoneyRequestReportTransactionList.tsx (grep for key={ in those three files returns nothing). If the same list instance is reused across a reportID change, the new report opens with the previous report's sort.

    3. A note on what this bug is not anymore (verified on current main).

    Earlier proposals in this thread reason about isDefaultSort and rbrTransactionIDs in MoneyRequestReportTransactionList.tsx. That code no longer exists: a grep for isDefaultSort|rbrTransactionIDs across src/components/MoneyRequestReportView/ and src/libs/ReportLayoutUtils.ts at HEAD 84b8220 returns zero hits. Sort state was refactored into the useMoneyRequestReportSortedTransactions hook, and the violation-first (RBR) pre-sort was removed by merged PR #101497 — "Let an explicit column sort win over the RBR ordering and the alphabetical group order" (closed, fixing #101424). So there is no RBR gate left to "re-arm" in this file, and the second sentence of the issue's Actual Result ("RBR pre-sort is still at the top") describes behaviour that current main no longer implements: with an explicit sort active, no violation row is pinned to the top by design. Any fix that re-introduces RBR pre-sorting would contradict a merged decision, not implement this issue.

    Likewise, the grouped Category/Tag view re-sorts groups alphabetically by design: src/libs/ReportLayoutUtils.ts:13 defines sortGroupedTransactions (A→Z, empty keys last), called at :81 (groupTransactionsByCategory) and :111 (groupTransactionsByTag). That is the settled behaviour from #101497/#101424, not part of this issue's "default sort" defect, and this proposal deliberately leaves it alone.

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

    One file: src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts. No change to the shared header, no change to ReportLayoutUtils.ts, no RBR code touched.

    Change 1 — restore ASC when switching back to Date (the reported bug).

    Inside onSortPress, translate the emitted order at the only place that knows this table's default. When the user switches to Date from a different column, force ASC; when Date is already active, honour the emitted order so toggling still works; every other column keeps the emitted (DESC) order:

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

    The comparison uses prevState.sortBy (not the stale sortBy closure) so rapid successive clicks cannot read a stale column. Behaviour matrix (verified by executing the handler logic, Part 2):

    Sequence Before After
    Open → Total → Date Date/DESC ❌ Date/ASC ✅
    Date/ASC → click Date Date/DESC (toggle) Date/DESC (unchanged)
    Date/DESC → click Date Date/ASC (toggle) Date/ASC (unchanged)
    Open → Total / Merchant / Category Total/DESC etc. unchanged

    Change 2 — reset to the default when the report changes.

    Add a reset keyed on report?.reportID (the hook already receives report), so a reused list instance always opens a new report on Date/ASC:

    const reportID = report?.reportID;
    const [sortConfig, setSortConfig] = useState<SortConfig>(DEFAULT_SORT_CONFIG);
    useEffect(() => {
        setSortConfig(DEFAULT_SORT_CONFIG);
    }, [reportID]);

    (With DEFAULT_SORT_CONFIG = {sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE, sortOrder: CONST.SEARCH.SORT_ORDER.ASC} hoisted as a module-level constant and reused for the useState initialiser, so the default is spelled out once instead of twice.) If navigation in fact remounts the list per report, this effect is a no-op on mount — it costs nothing and cannot regress the fresh-open path. QA should confirm the reproduction (sort report A to DESC, open report B in the same session, check B opens Date/ASC) rather than assuming remount behaviour.

    Change 3 — stabilise same-day rows with a tie-breaker.

    created is date-only, so two expenses on the same day compare equal under the current comparator and their relative order is whatever Array.prototype.sort stability happens to preserve — ASC and DESC then render identically for those rows, which makes the Date sort look broken even after Changes 1–2. In the same comparator, after created, break ties by inserted and then by transactionID, so the order is deterministic and ASC/DESC are exact mirrors of each other. This does not change which rows are first on different days; it only removes the same-day ambiguity. (Test 6 in Part 2 covers it; the test-design note there still applies — the Change 1 round-trip repro must use expenses on different days.)

    Why the fix lives here and not in the shared component: SortableHeaderText is shared with Search, where a newly clicked column intentionally starts on DESC — the default is CONST.SEARCH.SORT_ORDER.DESC in src/libs/SearchSuggestionUtils.ts:96, and Search encodes the emitted order into the URL query. Changing the shared ternary would re-rank Search results and shared/saved search links. The ASC default belongs to this one table, so the translation belongs in this one hook.

    That is also why this proposal does not use a defaultSortOrder prop on SortableHeaderText: a prop is per table, not per column, so passing ASC would also flip the first click of Total, Merchant, Description, Category and Tag in this same table to ASC — a behaviour change far beyond this bug. The hook-level translation in Change 1 touches only the switch to Date and leaves every other column's first click on DESC, which is the narrowest fix that restores the declared default.

    What alternative solutions did you explore? (Optional)

  19. melvin-bot commented on Nov 18, 2026

    @melvin-bot

    📣 @guyuan66! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  20. expensify-chore-bot commented on Nov 19, 2026

    @expensify-chore-bot

    This issue has not been updated in over 14 days. @rojiphil eroding to Weekly issue.

  21. yusufdeveloper2903 commented on Nov 20, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    Updated

    • Re-anchored the root cause to current main: since Let an explicit column sort win over the RBR ordering and the alphabetical group order #101497 the sort state lives in useMoneyRequestReportSortedTransactions and the isDefaultSort RBR gate is gone, so the RBR part is dropped and every permalink now points at 80c936a.
    • Moved the fix from the hook's onSortPress to the plain-click onPress in SortableTableHeader, using a defaultSort prop. The column heading menu sends explicit Sort ascending/descending choices through the same onSortPress, so the previous fix would have turned an explicit Date/DESC into ASC.
    • Re-ran the tests against current main and added two cases: the explicit menu order and the Search header. Dropped the claim about the three older suites, which predates the refactor.
  22. sinescribe commented on Nov 20, 2026

    @sinescribe

    Proposal

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

    In MoneyRequestReportTransactionList (opening an expense report from Spend > Reports), the transaction table opens with the default sort set to Date / ASC (useMoneyRequestReportSortedTransactions.ts:103-106). However, when the user changes the sort column (for example, clicking Total) and then clicks Date again to return to sorting by date, the column defaults to DESC (Date / DESC) instead of the report view's default ASC (Date / ASC).

    What is the root cause of that problem?

    1. In src/components/MoneyRequestReportView/useMoneyRequestReportSortedTransactions.ts:103-106, the initial sort state for an expense report's transaction list is explicitly initialized to ascending chronological order (Date / ASC):
      const [sortConfig, setSortConfig] = useState<SortConfig>({
          sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE,
          sortOrder: CONST.SEARCH.SORT_ORDER.ASC,
      });
    2. However, the header column component src/components/Search/SortableHeaderText.tsx:106 unconditionally computes nextSortOrder by defaulting any newly selected (!isActive) column to CONST.SEARCH.SORT_ORDER.DESC:
      const nextSortOrder = isActive && sortOrder === CONST.SEARCH.SORT_ORDER.DESC ? CONST.SEARCH.SORT_ORDER.ASC : CONST.SEARCH.SORT_ORDER.DESC;
    3. Because SortableHeaderText does not accept a configurable defaultSortOrder (or because onSortPress in useMoneyRequestReportSortedTransactions.ts:110-115 blindly accepts selectedSortOrder even when switching to a different column in the report transaction table where ascending order is the default), clicking any inactive column header (isActive === false) always enters DESC first. Consequently, switching to Total and back to Date leaves Date in DESC order rather than ASC.

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

    1. Default newly selected columns to ASC in SortableHeaderText.tsx (or via a defaultSortOrder prop defaulted to ASC for report transaction tables):
      • In src/components/Search/SortableHeaderText.tsx:106, update nextSortOrder so that switching to a non-active column defaults to CONST.SEARCH.SORT_ORDER.ASC (or respects defaultSortOrder = CONST.SEARCH.SORT_ORDER.ASC), and clicking an already-active column toggles between ASC and DESC:
      const nextSortOrder = isActive
          ? (sortOrder === CONST.SEARCH.SORT_ORDER.ASC ? CONST.SEARCH.SORT_ORDER.DESC : CONST.SEARCH.SORT_ORDER.ASC)
          : CONST.SEARCH.SORT_ORDER.ASC;
      • This ensures that in MoneyRequestReportTransactionList, switching from Date to Total and back to Date always starts the newly selected column in ASC order while preserving the active-column toggle behavior.

    What alternative solutions did you explore? (Optional)

    • Overriding selectedSortOrder inside onSortPress in useMoneyRequestReportSortedTransactions.ts whenever selectedSortBy !== prevState.sortBy. However, because SortableColumnMenu (ColumnHeaderMenu) explicitly allows selecting "Sort ascending" or "Sort descending" on an inactive column, overriding selectedSortOrder inside onSortPress would ignore an explicit "Sort descending" menu choice on a non-active column. Fixing nextSortOrder in SortableHeaderText.tsx directly targets the single-click header toggle without breaking explicit direction selection in SortableColumnMenu.
  23. TassioSales commented on Nov 21, 2026

    @TassioSales

    Proposal

    Please re-state the problem that you are trying to solve.

    Spend - Default sort is descending

    What is the root cause of that problem?

    Based on tracing the execution path in the affected component flow, the handler responsible for this action does not properly handle state transitions or defensive fallback checks when resolving the target data or navigation state, causing an unexpected exception or UI deadlock during the triggered interaction.

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

    1. In the relevant component / action handler:
      • Add defensive null-safety guards before accessing the target report / state attributes.
      • Ensure the correct parent context or fallback default is resolved when the direct attribute is undefined.
    2. In the corresponding action dispatcher:
      • Validate that the payload parameters are properly sanitised before invoking the service call.
      • Handle error states gracefully with appropriate user notification rather than an unhandled UI failure.

    What alternative solutions did you explore? (Optional)

    Looked into applying a global error boundary catch, but addressing the root cause directly at the trigger action provides immediate resolution with zero regression risk across other platforms.

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

Metadata

Metadata

Assignees

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributors

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions