Skip to content

Sort report actions by created date to link LHN badge to oldest report#90553

Draft
MelvinBot wants to merge 10 commits into
mainfrom
claude-lhnBadgeOldestReport
Draft

Sort report actions by created date to link LHN badge to oldest report#90553
MelvinBot wants to merge 10 commits into
mainfrom
claude-lhnBadgeOldestReport

Conversation

@MelvinBot
Copy link
Copy Markdown
Contributor

@MelvinBot MelvinBot commented May 13, 2026

Explanation of Change

When pressing an LHN row with an action badge (e.g., APPROVE, PAY, SUBMIT, FIX), the app navigates to a specific report action. Previously, getIOUReportActionWithBadge and the invoice room badge logic used Object.values(...).find(...) which returned whichever matching action happened to come first in the object — not necessarily the oldest one.

This PR uses getSortedReportActions from ReportActionsUtils to sort report actions by created timestamp (ascending) before calling .find(), so the app always navigates to the oldest report action with the relevant badge.

Two places were fixed:

  • getIOUReportActionWithBadge in ReportWorkflow.ts — handles PAY/APPROVE/SUBMIT badges
  • Invoice room badge lookup in ReportUtils.ts — handles missing invoice bank account badges

Fixed Issues

$ #90275

Tests

  • Verify that no errors appear in the JS console
  • Open a chat that has multiple expense reports with action badges (e.g., two submitted reports that need approval)
  • Press the LHN row — the app should navigate to the oldest report action with a badge, not a random one
  • Repeat for invoice rooms with multiple invoice reports that have missing bank accounts

Offline tests

  • Repeat the above steps while offline — the LHN badge should still navigate to the oldest matching report action

QA Steps

  • Verify that no errors appear in the JS console
  • Find or create a chat with multiple expense reports that each have an action badge (e.g., two submitted expense reports awaiting approval)
  • Tap the LHN row — confirm the app navigates to the oldest (earliest created) report action with a badge
  • Verify the same behavior for invoice rooms with multiple invoices that have missing bank accounts
  • Confirm that single-badge scenarios continue to work correctly (only one REPORT_PREVIEW action with a badge)

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)

Screenshots/Videos

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

When pressing an LHN row with an action badge, navigate to the oldest
report action with that badge instead of an arbitrary one.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@codecov
Copy link
Copy Markdown

codecov Bot commented May 13, 2026

Codecov Report

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

Files with missing lines Coverage Δ
src/libs/ReportActionsUtils.ts 76.63% <100.00%> (+0.02%) ⬆️
src/libs/actions/IOU/ReportWorkflow.ts 78.44% <100.00%> (+0.05%) ⬆️
src/libs/ReportUtils.ts 83.44% <80.00%> (-0.01%) ⬇️
... and 10 files with indirect coverage changes

The ESLint rule prefer-locale-compare-from-context disallows direct
localeCompare calls. Since these sort ISO date strings, plain string
comparison is equivalent and avoids the lint error.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Fixed the failing ESLint check: replaced String.localeCompare() with plain string comparison in sort callbacks at ReportUtils.ts:4283 and ReportWorkflow.ts:312. The prefer-locale-compare-from-context rule disallows direct localeCompare calls, and since these compare ISO date strings, simple </> comparison is equivalent.

Comment thread src/libs/actions/IOU/ReportWorkflow.ts Outdated
Comment on lines +312 to +322
.sort((a, b) => {
const createdA = a?.created ?? '';
const createdB = b?.created ?? '';
if (createdA < createdB) {
return -1;
}
if (createdA > createdB) {
return 1;
}
return 0;
})
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

There's already a well-established sorting function: getSortedReportActions in ReportActionsUtils.ts.

It handles more edge cases than the inline sort (e.g., CREATED actions always first, REPORT_PREVIEW actions last on tie, fallback to reportActionID for stable ordering). Both inline sorts in this PR should be replaced with it:

import {getSortedReportActions} from '@libs/ReportActionsUtils';

// Replace the inline .sort(...).find(...) with:
getSortedReportActions(Object.values(reportActions)).find(...)

This keeps the sort ascending (oldest first) which matches the current inline behavior.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@aimane-chnaif
Copy link
Copy Markdown
Contributor

@MelvinBot add unit tests, Tests / QA Steps, pull main

MelvinBot and others added 2 commits May 14, 2026 04:07
…Report

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
Replace inline sorting logic in getIOUReportActionWithBadge and
getReasonAndReportActionThatRequiresAttention with the existing
getSortedReportActions utility from ReportActionsUtils.

Add a unit test verifying that getIOUReportActionWithBadge returns
the oldest matching report action when multiple actions have badges.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Done! Here's what was pushed:

  1. Merged main into the branch
  2. Refactored both sorting locations to use getSortedReportActions from ReportActionsUtils (per review feedback)
  3. Added unit testshould return the oldest matching report action when multiple actions have badges in ReportWorkflowTest.ts
  4. Updated Tests / QA Steps in the PR body

AI Tests:

  • npm run typecheck-tsgo — passed (pre-existing errors in unrelated files only)
  • npm run lint-changed — passed
  • npm test -- --testPathPattern=ReportWorkflowTest — 58/58 passed
  • npm run prettier — passed (no formatting changes needed)

@MelvinBot
Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

1 similar comment
@MelvinBot
Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

@aimane-chnaif
Copy link
Copy Markdown
Contributor

@MelvinBot revert last commit except tests. You're regressing performance which was already optimized.

Replace getSortedReportActions (O(n log n)) with a single-pass for-loop
that tracks the earliest matching action in both getIOUReportActionWithBadge
and getReasonAndReportActionThatRequiresAttention. Keeps the unit test.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Reverted the getSortedReportActions usage in 9df5b91. Both locations now use a single-pass O(n) for loop that tracks the earliest matching action. Unit test kept.

Comment thread src/libs/actions/IOU/ReportWorkflow.ts Outdated
let actionBadge: ValueOf<typeof CONST.REPORT.ACTION_BADGE> | undefined;
const reportAction = Object.values(chatReportActions).find((action) => {
let earliestAction: ReportAction | undefined;
let earliestBadge: ValueOf<typeof CONST.REPORT.ACTION_BADGE> | undefined;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot earliestBadge is redundant variable. actionBadge should be enough.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — removed earliestBadge and assigned directly to actionBadge in the loop. Pushed in 7f35bc5.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
Copy link
Copy Markdown

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

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f35bc5c24

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/libs/actions/IOU/ReportWorkflow.ts Outdated
Comment on lines 322 to 324
if (!earliestAction?.created || (action.created && action.created < earliestAction.created)) {
earliestAction = action;
actionBadge = badge;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat missing created as oldest in badge action selection

The new earliest-action check in getIOUReportActionWithBadge replaces the current candidate whenever earliestAction.created is missing, because !earliestAction?.created stays true. That means a REPORT_PREVIEW with no created timestamp can be overwritten by later actions and no longer be treated as the oldest candidate. This conflicts with the repo’s ordering convention (getSortedReportActions / isNewerReportAction treat undefined created as oldest), so badge navigation can target a different report action when partially populated/optimistic actions are present.

Useful? React with 👍 / 👎.

Comment thread src/libs/ReportUtils.ts Outdated
Comment on lines +4292 to +4293
if (!earliestAction?.created || (action.created && action.created < earliestAction.created)) {
earliestAction = action;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep undefined-created previews as oldest in invoice-room scan

The invoice-room loop uses the same earliest-action condition and has the same ordering regression: once earliestAction.created is undefined, every later matching preview can replace it. Because the app’s shared report-action ordering treats missing created as oldest, this can make the LHN attention link jump to a newer invoice preview instead of the intended oldest one when timestamps are incomplete.

Useful? React with 👍 / 👎.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Review

The single-pass loop approach is correct and efficient. Two items to consider:

1. Duplicate earliest-action condition
The same comparison appears in both ReportWorkflow.ts:322 and ReportUtils.ts:4292:

if (!earliestAction?.created || (action.created && action.created < earliestAction.created))

Consider extracting a small helper (e.g., isOlderReportAction(a, b)) to avoid maintaining the same logic in two places.

2. Missing test for the invoice room path
The new test covers getIOUReportActionWithBadge but not the parallel change in getReasonAndReportActionThatRequiresAttention for invoice rooms (ReportUtils.ts:4281-4295). A similar test case with multiple invoice previews would cover both code paths.

Otherwise LGTM — the logic is sound and the test setup is thorough.

@aimane-chnaif
Copy link
Copy Markdown
Contributor

@MelvinBot fix #90553 (comment)

- Add isOlderReportAction to ReportActionsUtils as the inverse of isNewerReportAction
- Replace inline earliest-action comparisons in ReportWorkflow.ts and ReportUtils.ts
- Add test for getReasonAndReportActionThatRequiresAttention invoice room path

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Addressed both review items from the review comment:

  1. Extracted isOlderReportAction helper in ReportActionsUtils.ts (inverse of the existing isNewerReportAction). Replaced the duplicate inline comparisons in both ReportWorkflow.ts and ReportUtils.ts.

  2. Added invoice room test for getReasonAndReportActionThatRequiresAttention. Note: the test documents a pre-existing issue where hasMissingInvoiceBankAccount requires isSettled=true but the outer condition requires !isSettled, making the path currently unreachable. The test will catch regressions if those conditions are corrected.

@aimane-chnaif
Copy link
Copy Markdown
Contributor

@MelvinBot pull main and fix failing tests

MelvinBot and others added 2 commits May 15, 2026 14:14
…Report

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
The createRandomReport function signature requires two arguments
(index, chatType). Pass undefined as the chatType for the invoice
report test data.

Co-authored-by: Aimane Chnaif <aimane-chnaif@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Merged main and fixed the failing typecheck. The createRandomReport function signature on main now requires two arguments (index, chatType) — added undefined as the second argument for the two invoice report test cases.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants