Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
5baad9d
fixed typescript errors and ran npm run prettier
abelhailefen Apr 11, 2026
bcc6300
refactor: update RBR logic to account for dismissed violations, repor…
abelhailefen Apr 16, 2026
16085b4
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen Apr 16, 2026
84eef2a
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen Apr 21, 2026
bd41784
fix: add accountID fallback in compareByRBR calls and expand test cov…
abelhailefen Apr 21, 2026
93f3b3a
refactor: update transactionHasRBR to include report action errors, D…
abelhailefen Apr 22, 2026
f494c87
rename variable placeholders in TransactionPreviewUtils tests for cla…
abelhailefen Apr 23, 2026
e618e2e
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen Apr 24, 2026
1949c90
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen Apr 28, 2026
977fd9a
prettier fix
abelhailefen Apr 28, 2026
eed9e5a
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 1, 2026
beefefb
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 1, 2026
90a470b
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 1, 2026
84831a4
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 3, 2026
9400b6e
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 4, 2026
5196596
Merge remote-tracking branch 'upstream/main' into fix-85553-rbr-carou…
abelhailefen May 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
import type {SortableColumnName} from '@libs/ReportUtils';
import {compareValues, getColumnsToShow, getTableMinWidth, isTransactionAmountTooLong, isTransactionTaxAmountTooLong} from '@libs/SearchUIUtils';
import {getPendingSubmitFollowUpAction} from '@libs/telemetry/submitFollowUpAction';
import {compareByRBR} from '@libs/TransactionPreviewUtils';
import {getTransactionPendingAction, isTransactionPendingDelete, shouldShowExpenseBreakdown} from '@libs/TransactionUtils';
import shouldShowTransactionYear from '@libs/TransactionUtils/shouldShowTransactionYear';
import isReportOpenInSuperWideRHP from '@navigation/helpers/isReportOpenInSuperWideRHP';
Expand Down Expand Up @@ -179,6 +180,7 @@ function MoneyRequestReportTransactionList({
const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST);
const [cardList] = useOnyx(ONYXKEYS.CARD_LIST);
const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {selector: validTransactionDraftIDsSelector});
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);

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.

❌ PERF-11

useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS) subscribes to the entire transaction violations collection without a selector. This component will re-render whenever any transaction violation changes across the entire app, not just those belonging to the transactions in this report.

Consider using a selector that filters to only the relevant transaction IDs, or compute violations per-transaction inside the useMemo using the transaction IDs already available from the transactions prop.


Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

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.

✅ This is fine, we want to rerender whenever any violation changes across the app, not just those belonging to the transactions in this report.


const shouldShowGroupedTransactions = isExpenseReport(report) && !isIOUReport(report);

Expand Down Expand Up @@ -284,12 +286,32 @@ function MoneyRequestReportTransactionList({
});

const {sortBy, sortOrder} = sortConfig;
const isDefaultSort = sortBy === CONST.SEARCH.TABLE_COLUMNS.DATE && sortOrder === CONST.SEARCH.SORT_ORDER.ASC;

// Convert reportActions array to a record keyed by reportActionID for compareByRBR
const reportActionsMap = useMemo(() => Object.fromEntries(reportActions.map((ra) => [ra.reportActionID, ra])), [reportActions]);

const sortedTransactions: TransactionWithOptionalHighlight[] = useMemo(() => {
return [...transactions].sort((a, b) =>
compareValues(getTransactionSortValue(a, sortBy, report, policy), getTransactionSortValue(b, sortBy, report, policy), sortOrder, sortBy, localeCompare, true),
);
}, [sortBy, sortOrder, transactions, localeCompare, report, policy]);
return [...transactions].sort((a, b) => {
// When on default sort (Date/ASC), prioritize RBR-flagged transactions
if (isDefaultSort && allTransactionViolations) {

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.

❌ CONSISTENCY-3

The RBR-aware sort comparator logic (violation lookup + transactionHasRBR comparison) is duplicated nearly identically in both MoneyRequestReportTransactionList.tsx and MoneyRequestReportPreviewContent.tsx.

Extract a shared compareByRBR(a, b, violations) comparator into TransactionPreviewUtils.ts next to transactionHasRBR so both call sites can reuse it.


Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

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.

This makes sense, repeated code should be extracted to a shared utility function in TransactionPreviewUtils.ts.

@ikevin127 ikevin127 Apr 9, 2026 •

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.

@abelhailefen Mind addressing this valid refactoring concern ?

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.

This is important, we should use the existing logic

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 Apply RBR sort even when violations collection is missing

The RBR prioritization is currently gated by allTransactionViolations, so if that collection is unavailable/undefined, the comparator skips transactionHasRBR() entirely and falls back to plain date sorting. In that state, transactions that should still be considered RBR via non-violation signals (hold, missing merchant/amount, receipt error) are not surfaced to the top, so the new behavior silently fails for reports without loaded violation entries.

Useful? React with 👍 / 👎.

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.

the new behavior silently fails for reports without loaded violation entries.

This is expected.

const rbrComparison = compareByRBR(
a,
b,
allTransactionViolations,
currentUserDetails?.login ?? '',
currentUserDetails?.accountID ?? CONST.DEFAULT_NUMBER_ID,
report,
policy,
reportActionsMap,
);
if (rbrComparison !== 0) {
return rbrComparison;
}
}
return compareValues(getTransactionSortValue(a, sortBy, report, policy), getTransactionSortValue(b, sortBy, report, policy), sortOrder, sortBy, localeCompare, true);
});
}, [sortBy, sortOrder, transactions, localeCompare, report, policy, isDefaultSort, allTransactionViolations, currentUserDetails?.login, currentUserDetails?.accountID, reportActionsMap]);

const resolvedTransactions = useMemo(() => resolveTransactionCardFields(sortedTransactions, cardList, translate), [sortedTransactions, cardList, translate]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {showContextMenuForReport} from '@components/ShowContextMenuContext';
import StatusBadge from '@components/StatusBadge';
import Text from '@components/Text';
import {useCurrencyListActions} from '@hooks/useCurrencyList';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
Expand Down Expand Up @@ -55,6 +56,7 @@ import shouldAdjustScroll from '@libs/shouldAdjustScroll';
import {startSpan} from '@libs/telemetry/activeSpans';
import {getPendingSubmitFollowUpAction} from '@libs/telemetry/submitFollowUpAction';
import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan';
import {compareByRBR} from '@libs/TransactionPreviewUtils';
import {hasPendingUI, isManagedCardTransaction, isPending} from '@libs/TransactionUtils';
import colors from '@styles/theme/colors';
import variables from '@styles/variables';
Expand Down Expand Up @@ -132,6 +134,7 @@ function MoneyRequestReportPreviewContent({
const shouldShowLoading =
chatReportLoadingState != null && chatReportLoadingState.hasOnceLoadedReportActions !== true && transactions.length === 0 && !chatReportMetadata?.isOptimisticReport;
// `hasOnceLoadedReportActions` becomes true before transactions populate fully,
const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
// so we defer the loading state update to ensure transactions are loaded
const shouldShowLoadingDeferred = useDeferredValue(shouldShowLoading);
const lastTransaction = transactions?.at(0);
Expand All @@ -158,6 +161,7 @@ function MoneyRequestReportPreviewContent({
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const currentUserDetails = useCurrentUserPersonalDetails();
const {translate, formatPhoneNumber} = useLocalize();
const {convertToDisplayString} = useCurrencyListActions();
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth
Expand Down Expand Up @@ -351,7 +355,15 @@ function MoneyRequestReportPreviewContent({
thumbsUpScale.set(isApprovedAnimationRunning ? withDelay(CONST.ANIMATION_THUMBS_UP_DELAY, withSpring(1, {duration: CONST.ANIMATION_THUMBS_UP_DURATION})) : 1);
}, [isApproved, isApprovedAnimationRunning, thumbsUpScale]);

const carouselTransactions = useMemo(() => (shouldShowAccessPlaceHolder ? [] : transactions.slice(0, 11)), [shouldShowAccessPlaceHolder, transactions]);
const carouselTransactions = useMemo(() => {
if (shouldShowAccessPlaceHolder) {
return [];
}
const sorted = [...transactions].sort((a, b) =>
compareByRBR(a, b, transactionViolations, currentUserDetails?.login ?? '', currentUserDetails?.accountID ?? CONST.DEFAULT_NUMBER_ID, iouReport, policy),
);
return sorted.slice(0, 11);
}, [shouldShowAccessPlaceHolder, transactions, transactionViolations, currentUserDetails?.login, currentUserDetails?.accountID, iouReport, policy]);
const prevCarouselTransactionLength = useRef(0);

useEffect(() => {
Expand Down
105 changes: 105 additions & 0 deletions src/libs/TransactionPreviewUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {OnyxEntry} from 'react-native-onyx';
import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
Expand Down Expand Up @@ -457,6 +458,108 @@ function createTransactionPreviewConditionals({
};
}

/**
* Lightweight check for whether a transaction has any RBR (Red Brick Road) indicator.
* Evaluates transaction-level signals (violations, hold, missing fields, receipt errors,
* report action errors, and DEW submit failures) with proper context for dismissed
* violations and report settlement/approval status.
*
* This logic mirrors the `shouldShowRBR` computation in `createTransactionPreviewConditionals`.
*/
function transactionHasRBR(
transaction: OnyxEntry<OnyxTypes.Transaction>,
violations: OnyxTypes.TransactionViolations,
currentUserEmail: string,
currentUserAccountID: number,
iouReport: OnyxEntry<OnyxTypes.Report>,
policy: OnyxEntry<OnyxTypes.Policy>,
reportActions?: OnyxTypes.ReportActions,
): boolean {
if (!transaction) {
return false;
}

// Check for non-dismissed violation-type or warning-type violations
if (
hasViolation(transaction, violations, currentUserEmail, currentUserAccountID, iouReport, policy, true) ||
hasWarningTypeViolation(transaction, violations, currentUserEmail, currentUserAccountID, iouReport, policy)
) {
Comment on lines +482 to +486

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 Include notice-type RBR checks in comparator

transactionHasRBR() now controls sort priority, but this branch only checks violation and warning types. In the same file, createTransactionPreviewConditionals() still treats paid-group notice violations as RBR (hasNoticeTypeViolation + paid-group check), so transactions can visibly be in an RBR state but still not be pinned by compareByRBR. This creates inconsistent behavior for paid-group reports where notice-only violations are the only red-brick signal.

Useful? React with 👍 / 👎.

return true;
}

// Check for notice-type violations (only on paid group policies)
if (hasNoticeTypeViolation(transaction, violations, currentUserEmail, currentUserAccountID, iouReport, policy, true) && isPaidGroupPolicyUtil(iouReport)) {
return true;
}

// Check for distance-request modified-amount violations (type VIOLATION or NOTICE)
if (
isDistanceRequest(transaction) &&
violations?.some(
(violation) => violation.name === CONST.VIOLATIONS.MODIFIED_AMOUNT && (violation.type === CONST.VIOLATION_TYPES.VIOLATION || violation.type === CONST.VIOLATION_TYPES.NOTICE),
)
) {
return true;
}

// Check if transaction is on hold — only counts as RBR when the report
// is not fully settled and not fully approved (matching createTransactionPreviewConditionals)
const isSettlementOrApprovalPartial = !!iouReport?.pendingFields?.partial;
const isFullySettled = isSettled(iouReport?.reportID) && !isSettlementOrApprovalPartial;
const isFullyApproved = isReportApproved({report: iouReport}) && !isSettlementOrApprovalPartial;
if (!isFullySettled && !isFullyApproved && isOnHold(transaction)) {
return true;
}

// Check if transaction has missing required fields (uses hasMissingSmartscanFields
// which guards against distance requests and receipts being scanned)
if (hasMissingSmartscanFields(transaction, iouReport)) {
return true;
}

// Check if transaction has receipt error
if (hasReceiptError(transaction)) {
return true;
}

// Check for report action errors associated with this transaction
if (hasActionWithErrorsForTransaction(iouReport?.reportID, transaction, reportActions)) {
return true;
}

// Check for DEW submit failures
if (hasDynamicExternalWorkflow(policy) && !!getMostRecentActiveDEWSubmitFailedAction(reportActions)) {
return true;
}

return false;
}

/**
* Compare two transactions by their RBR (Red Brick Road) status.
* Transactions with RBR indicators are sorted before those without.
* Returns 0 when both transactions have the same RBR status.
*/
function compareByRBR(
a: OnyxTypes.Transaction,
b: OnyxTypes.Transaction,
violations: Record<string, OnyxTypes.TransactionViolations | undefined> | undefined,
currentUserEmail: string,
currentUserAccountID: number,
iouReport: OnyxEntry<OnyxTypes.Report>,
policy: OnyxEntry<OnyxTypes.Policy>,
reportActions?: OnyxTypes.ReportActions,
): number {
const aViolations = violations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${a.transactionID}`] ?? [];
const bViolations = violations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${b.transactionID}`] ?? [];
const aHasRBR = transactionHasRBR(a, aViolations, currentUserEmail, currentUserAccountID, iouReport, policy, reportActions);
const bHasRBR = transactionHasRBR(b, bViolations, currentUserEmail, currentUserAccountID, iouReport, policy, reportActions);
if (aHasRBR === bHasRBR) {
return 0;
}
return aHasRBR ? -1 : 1;
}

export {
getReviewNavigationRoute,
getIOUPayerAndReceiver,
Expand All @@ -465,5 +568,7 @@ export {
getViolationTranslatePath,
getUniqueActionErrorsForTransaction,
formatLastFourPAN,
transactionHasRBR,
compareByRBR,
};
export type {TranslationPathOrText};
Loading
Loading