Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 13 additions & 3 deletions src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';

import DateUtils from '@libs/DateUtils';
import {isSettled} from '@libs/ReportUtils';
import {isFailedScanAmountPlaceholder} from '@libs/TransactionUtils';

import CONST from '@src/CONST';

Expand Down Expand Up @@ -38,15 +40,17 @@ type RecentlyAddedRowProps = {
function RecentlyAddedRow({expense, onPress, shouldShowSeparator, shouldShowReceiptPreview, rowStyle}: RecentlyAddedRowProps) {
const styles = useThemeStyles();
const {convertToDisplayString} = useCurrencyListActions();
const {dateFnsLocale} = useLocalize();
const {dateFnsLocale, translate} = useLocalize();

const formattedDate = DateUtils.formatWithUTCTimeZone(
expense.created,
DateUtils.doesDateBelongToAPastYear(expense.created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT,
dateFnsLocale,
);

const formattedAmount = convertToDisplayString(expense.amount, expense.currency);
const hasFailedScanAmountPlaceholder = isFailedScanAmountPlaceholder(expense.transaction, isSettled(expense.report));
Comment thread
x-dev90 marked this conversation as resolved.
Resolved
const shouldShowScanFailureMessage = hasFailedScanAmountPlaceholder && expense.transaction.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_FAILED;
const formattedAmount = hasFailedScanAmountPlaceholder ? '' : convertToDisplayString(expense.amount, expense.currency);

// The row always uses the stacked ("mobile") layout because it lives in the narrow right column on web/desktop
// too: a thumbnail, then the merchant + amount on the first line and the date + type underneath. This mirrors the
Expand All @@ -72,9 +76,15 @@ function RecentlyAddedRow({expense, onPress, shouldShowSeparator, shouldShowRece
<View style={[styles.flexRow, styles.alignItemsCenter, styles.justifyContentBetween, styles.gap2]}>
<Text
numberOfLines={1}
style={styles.mutedNormalTextLabel}
style={[styles.mutedNormalTextLabel, styles.flexShrink1]}
>
{formattedDate}
{shouldShowScanFailureMessage && (
<>
{` ${CONST.DOT_SEPARATOR} `}
<Text style={styles.textLabelError}>{translate('violations.shortName.smartscanFailed')}</Text>
</>
)}
</Text>
<TypeCell
transactionItem={expense.transaction}
Expand Down
13 changes: 8 additions & 5 deletions src/pages/home/RecentlyAddedSection/useRecentlyAddedData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,24 +259,27 @@ function useRecentlyAddedData(): RecentlyAddedData {
// snapshot keeps the stale, pre-edit copy. Prefer the local copy when present so the row reflects the
// edit and can render the offline pending treatment, matching how the Search transaction list behaves.
const sourceTransaction = getLocalTransaction(localTransactions, transaction.transactionID) ?? transaction;
const reportType = reportByReportID.get(transaction.reportID)?.type;
const sourceReportID = sourceTransaction.reportID ?? transaction.reportID;
const snapshotReport = reportByReportID.get(sourceReportID);
const localReport = localReports?.[`${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`];
const sourceReport = localReport ? {...snapshotReport, ...localReport} : snapshotReport;
const reportType = sourceReport?.type;
const isFromExpenseReport = reportType === CONST.REPORT.TYPE.EXPENSE;
// Self-DM and unreported (tracked) expenses support signed amounts like expense reports, so their
// sign must be preserved too. Without this, a self-DM credit/refund is collapsed to its absolute
// value and loses its negative sign.
const isFromTrackedExpense =
transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID || reportByReportID.get(transaction.reportID)?.chatType === CONST.REPORT.CHAT_TYPE.SELF_DM;
const isFromTrackedExpense = sourceReportID === CONST.REPORT.UNREPORTED_REPORT_ID || sourceReport?.chatType === CONST.REPORT.CHAT_TYPE.SELF_DM;
return {
transactionID: transaction.transactionID,
reportID: transaction.reportID,
reportID: sourceReportID,
created: getCreated(sourceTransaction),
merchant: getMerchantName(sourceTransaction, translate),
// Expense-report, self-DM, and tracked transactions are stored with an inverted sign, so the
// displayed amount must be negated for them (mirrors the Search transaction list).
amount: getAmount(sourceTransaction, isFromExpenseReport, isFromTrackedExpense),
currency: getCurrency(sourceTransaction),
reportAction: getExpenseCreationIOUActionForTransactionID(snapshotReportActions, transaction.transactionID),
report: reportByReportID.get(transaction.reportID),
report: sourceReport,
// Derive from the local copy so an offline edit (which sets `pendingFields`, not `pendingAction`)
// still surfaces the pending state, alongside offline creates (ADD) and deletes (DELETE).
pendingAction: getTransactionPendingAction(sourceTransaction),
Expand Down
101 changes: 100 additions & 1 deletion tests/ui/RecentlyAddedSectionTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import OnyxListItemProvider from '@src/components/OnyxListItemProvider';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Transaction} from '@src/types/onyx';
import type {Report, Transaction} from '@src/types/onyx';

import React from 'react';
import Onyx from 'react-native-onyx';
Expand All @@ -29,6 +29,9 @@ jest.mock('@libs/Navigation/Navigation', () => ({

jest.mock('@hooks/useResponsiveLayout', () => jest.fn());

const mockConvertToDisplayString = jest.fn((amount: number, currency: string) => `${currency} ${amount}`);
jest.mock('@hooks/useCurrencyList', () => ({useCurrencyListActions: () => ({convertToDisplayString: mockConvertToDisplayString})}));

// The component calls useIsFocused to dismiss the hovered receipt preview on blur; the test harness doesn't
// mount a NavigationContainer, so stub it to a focused state.
jest.mock('@react-navigation/native', () => {
Expand Down Expand Up @@ -115,6 +118,7 @@ type RecentlyAddedRowFixture = {
amount: number;
currency: string;
transaction: Transaction;
report?: Report;
};

function buildTransaction(transactionID: string, reportID: string): Transaction {
Expand Down Expand Up @@ -309,6 +313,101 @@ describe('RecentlyAddedSection', () => {
expect(screen.getByText('Nitro Fuel Supply Co.')).toBeOnTheScreen();
expect(screen.queryByTestId('recentlyAddedEmptyState')).not.toBeOnTheScreen();
});

it('hides a failed-scan placeholder amount and shows its failure status', async () => {
// Given a failed Scan whose zero amount is only a placeholder
const failedScanRow = {
...ROW_1,
amount: 0,
transaction: {
...ROW_1.transaction,
amount: 0,
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.SCAN_FAILED},
},
};
mockUseRecentlyAddedData.mockReturnValue({transactions: [failedScanRow], isAwaitingFirstResult: false});

// When the Recently Added row is rendered
renderRecentlyAddedSection();
await waitForBatchedUpdatesWithAct();

// Then the placeholder is not formatted as a real zero amount and its failed state is clear
expect(screen.queryByText('USD 0')).not.toBeOnTheScreen();
expect(screen.getByText(/violations\.shortName\.smartscanFailed/)).toBeOnTheScreen();
});

it('does not show a scan failure status for an offline Scan edit that has not failed', async () => {
// Given an incomplete Scan that is OPEN while its merchant edit is pending offline
const offlineScanRow = {
...ROW_1,
amount: 0,
transaction: {
...ROW_1.transaction,
amount: 0,
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.OPEN},
pendingFields: {merchant: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE},
},
};
mockUseRecentlyAddedData.mockReturnValue({transactions: [offlineScanRow], isAwaitingFirstResult: false});

// When the Recently Added row is rendered
renderRecentlyAddedSection();
await waitForBatchedUpdatesWithAct();

// Then its placeholder amount stays hidden without incorrectly claiming that scanning failed
expect(screen.queryByText('USD 0')).not.toBeOnTheScreen();
expect(screen.queryByText(/violations\.shortName\.smartscanFailed/)).not.toBeOnTheScreen();
});

it('shows a zero amount that the user explicitly confirmed', async () => {
// Given a Scan whose zero amount was explicitly confirmed by the user
const confirmedZeroRow = {
...ROW_1,
amount: 0,
transaction: {
...ROW_1.transaction,
amount: 0,
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.SCAN_FAILED},
isAmountSet: true,
},
};
mockUseRecentlyAddedData.mockReturnValue({transactions: [confirmedZeroRow], isAwaitingFirstResult: false});

// When the Recently Added row is rendered
renderRecentlyAddedSection();
await waitForBatchedUpdatesWithAct();

// Then the confirmed zero remains visible
expect(screen.getByText('USD 0')).toBeOnTheScreen();
expect(screen.queryByText(/violations\.shortName\.smartscanFailed/)).not.toBeOnTheScreen();
});

it('shows a zero amount on a settled report', async () => {
// Given a zero-value Scan on a settled report
const settledZeroRow = {
...ROW_1,
amount: 0,
report: {reportID: ROW_1.reportID, statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED} as Report,
transaction: {
...ROW_1.transaction,
amount: 0,
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.SCAN_FAILED},
},
};
mockUseRecentlyAddedData.mockReturnValue({transactions: [settledZeroRow], isAwaitingFirstResult: false});

// When the Recently Added row is rendered
renderRecentlyAddedSection();
await waitForBatchedUpdatesWithAct();

// Then the settled zero remains visible
expect(screen.getByText('USD 0')).toBeOnTheScreen();
expect(screen.queryByText(/violations\.shortName\.smartscanFailed/)).not.toBeOnTheScreen();
});
});

describe('row navigation to the expense RHP on Home', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* then shows the snapshot copy once it lands - without dropping or duplicating the row
* - keeps a deleted expense hidden after the delete succeeds but while the snapshot still lists it, and brings it
* back if the delete fails
* - prefers live report data over stale snapshot report data
*/
import {renderHook} from '@testing-library/react-native';

Expand Down Expand Up @@ -289,6 +290,59 @@ describe('useRecentlyAddedData — current-user scope', () => {
});
});

describe('useRecentlyAddedData — live report updates', () => {
it('uses the live report status when the Search snapshot is stale', () => {
// Given Home loaded an open report from Search and the live report initially matches it
setupSnapshot([makeTransaction({transactionID: 'settled', inserted: '2026-06-01 10:00:00'})], [makeReport('report_owned', ACCOUNT_ID, {statusNum: CONST.REPORT.STATUS_NUM.OPEN})]);
setupLocalReports([makeReport('report_owned', ACCOUNT_ID, {statusNum: CONST.REPORT.STATUS_NUM.OPEN})]);
const {result, rerender} = renderHook(() => useRecentlyAddedData());

// When the live report is reimbursed without refreshing the Search snapshot
setupLocalReports([makeReport('report_owned', ACCOUNT_ID, {statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED})]);
rerender({});

// Then the row receives the current settled status instead of the stale snapshot status
expect(result.current.transactions.at(0)?.report?.statusNum).toBe(CONST.REPORT.STATUS_NUM.REIMBURSED);
});

it('uses the current report after a failed scan is moved during an offline payment', () => {
// Given Search still places a failed scan on the original report while the optimistic payment has moved it to a new report
setupSnapshot(
[
makeTransaction({
transactionID: 'failedScan',
inserted: '2026-06-01 10:00:00',
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.SCAN_FAILED},
amount: 0,
}),
],
[makeReport('report_owned', ACCOUNT_ID, {type: CONST.REPORT.TYPE.EXPENSE, statusNum: CONST.REPORT.STATUS_NUM.OPEN})],
);
setupLocalTransactions([
makeTransaction({
transactionID: 'failedScan',
reportID: 'report_unpaid',
inserted: '2026-06-01 10:00:00',
iouRequestType: CONST.IOU.REQUEST_TYPE.SCAN,
receipt: {state: CONST.IOU.RECEIPT_STATE.SCAN_FAILED},
amount: 0,
}),
]);
setupLocalReports([
makeReport('report_owned', ACCOUNT_ID, {type: CONST.REPORT.TYPE.EXPENSE, statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED}),
makeReport('report_unpaid', ACCOUNT_ID, {type: CONST.REPORT.TYPE.EXPENSE, statusNum: CONST.REPORT.STATUS_NUM.OPEN}),
]);

// When Recently Added resolves the expense while the Search snapshot is stale
const {result} = renderHook(() => useRecentlyAddedData());

// Then the row stays associated with the new unpaid report instead of inheriting the settled status of the original report
expect(result.current.transactions.at(0)?.reportID).toBe('report_unpaid');
expect(result.current.transactions.at(0)?.report?.statusNum).toBe(CONST.REPORT.STATUS_NUM.OPEN);
});
});

describe('useRecentlyAddedData — unreported expenses', () => {
it('includes the current user unreported expenses even though they have no parent report', () => {
setupSnapshot(
Expand Down
Loading