Skip to content
Open
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
1 change: 1 addition & 0 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16684,6 +16684,7 @@ export {
isPolicyExpenseChat,
isProcessingReport,
isOpenReport,
isOpenOrProcessingReport,
isReportEligibleForViolationFix,
getSubmitterUnfixableViolationNames,
isAwaitingFirstLevelApproval,
Expand Down
1 change: 1 addition & 0 deletions src/libs/TripReservationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ export {
getTripEReceiptIcon,
getTripReservationCode,
getReservationsFromTripReport,
getReservationsFromSpotnanaPayload,
getTripTotal,
getReservationDetailsFromSequence,
formatTransitLocationLabel,
Expand Down
54 changes: 48 additions & 6 deletions src/pages/home/ForYouSection/useReviewFlaggedExpenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Navigation from '@libs/Navigation/Navigation';
import {getSubmitterUnfixableViolationNames, isOneTransactionReport, isReportEligibleForViolationFix} from '@libs/ReportUtils';
import {getVisibleTransactionViolations} from '@libs/TransactionUtils';

import getHomeReportIndex from '@pages/home/getHomeReportIndex';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
Expand Down Expand Up @@ -91,6 +93,39 @@ function hasReviewableViolation(violations: TransactionViolations | null | undef
});
}

/** The current user's open or processing expense reports, a superset of the reports `getFlaggedExpenses` accepts. */
function pickOwnExpenseReports(allReports: OnyxCollection<Report>, currentUserAccountID: number): OnyxCollection<Report> {
const ownExpenseReports: OnyxCollection<Report> = {};
for (const key of getHomeReportIndex(allReports, currentUserAccountID).ownOpenExpenseReportKeys) {
ownExpenseReports[key] = allReports?.[key];
}
return ownExpenseReports;
}

function pickTransactionsOnReports(allTransactions: OnyxCollection<Transaction>, reports: OnyxCollection<Report>): OnyxCollection<Transaction> {
const transactions: OnyxCollection<Transaction> = {};
// Object.keys allocates one array, where Object.entries allocates one per transaction on every transaction write.
for (const key of Object.keys(allTransactions ?? {})) {
const transaction = allTransactions?.[key];
if (transaction?.reportID && reports?.[`${ONYXKEYS.COLLECTION.REPORT}${transaction.reportID}`]) {
transactions[key] = transaction;
}
}
return transactions;
}

function pickViolationsForTransactions(allTransactionViolations: OnyxCollection<TransactionViolations>, transactions: OnyxCollection<Transaction>): OnyxCollection<TransactionViolations> {
const violations: OnyxCollection<TransactionViolations> = {};
for (const transaction of Object.values(transactions ?? {})) {
const key = `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction?.transactionID}` as const;
const transactionViolations = allTransactionViolations?.[key];
if (transactionViolations) {
violations[key] = transactionViolations;
}
}
return violations;
}

// Scans the current user's still-fixable expense reports for transactions with a reviewable violation.
function getFlaggedExpenses(
allReports: OnyxCollection<Report>,
Expand Down Expand Up @@ -142,16 +177,23 @@ function getFlaggedExpenses(
* Powers the "Review X expenses" row: scans the current user's OPEN expense reports for flagged transactions
* and exposes a handler that opens the first one's transaction thread (single-expense RHP + review carousel).
*
* `useIsFocused()` gates the O(n) scan — while the screen is blurred it is skipped and the row keeps its last
* count. The Onyx subscriptions stay live (they cannot be paused) but only trigger a cheap re-render.
* The selectors narrow the collections on every write, so writes to other reports and expenses don't re-render.
* `useIsFocused()` gates only the flagged-expense scan: while the screen is blurred it is skipped and the row keeps
* its last count.
*/
function useReviewFlaggedExpenses(): ReviewFlaggedExpenses {
const isFocused = useIsFocused();
const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const [allTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION);
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [session] = useOnyx(ONYXKEYS.SESSION);
const currentUserAccountID = session?.accountID ?? CONST.DEFAULT_NUMBER_ID;
// Narrowed to what the scan can accept, so writes to other reports and expenses don't re-render Home.
const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: (reports: OnyxCollection<Report>) => pickOwnExpenseReports(reports, currentUserAccountID)});
const [allTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, {
selector: (transactions: OnyxCollection<Transaction>) => pickTransactionsOnReports(transactions, allReports),

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.

Right now the tests add the report and its expenses at the same time. Could we add one where the report shows up later and check that the count goes from 0 to 1?

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.

Added "should count a flagged expense once its report arrives after the expense and its violation": the expense and its violation are written first (count 0), then only the report lands and the count goes to 1.

});
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {
selector: (violations: OnyxCollection<TransactionViolations>) => pickViolationsForTransactions(violations, allTransactions),
});
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
// Catches a forward that lands via REPORT_ACTIONS alone, with no report write to trigger a re-render.
const [forwardedSinceLastSubmitReportIDs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS, {selector: forwardedSinceLastSubmitReportIDsSelector});

Expand Down
13 changes: 10 additions & 3 deletions src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ import type {StyleProp, ViewStyle} from 'react-native';
import React from 'react';
import {View} from 'react-native';

import type {RecentlyAddedExpense} from './useRecentlyAddedData';
import type {RecentlyAddedItem} from './useRecentlyAddedData';

import {useRecentlyAddedExpense} from './useRecentlyAddedData';

type RecentlyAddedRowProps = {
expense: RecentlyAddedExpense;
item: RecentlyAddedItem;

/** Called when the row is pressed */
onPress: () => void;
Expand All @@ -37,10 +39,15 @@ type RecentlyAddedRowProps = {
rowStyle: StyleProp<ViewStyle>;
};

function RecentlyAddedRow({expense, onPress, shouldShowSeparator, shouldShowReceiptPreview, rowStyle}: RecentlyAddedRowProps) {
function RecentlyAddedRow({item, onPress, shouldShowSeparator, shouldShowReceiptPreview, rowStyle}: RecentlyAddedRowProps) {
const styles = useThemeStyles();
const {convertToDisplayString} = useCurrencyListActions();
const {dateFnsLocale, translate} = useLocalize();
const expense = useRecentlyAddedExpense(item);

if (!expense) {
return null;
}

const formattedDate = DateUtils.formatToMonthDayWithOptionalYearInUTC(expense.created, dateFnsLocale);

Expand Down
44 changes: 35 additions & 9 deletions src/pages/home/RecentlyAddedSection/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';

import {CAROUSEL_SOURCE, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import {buildQueryStringFromFilterFormValues} from '@libs/SearchQueryUtils';
import type {TransactionThreadNavigationDescriptor} from '@libs/TransactionThreadNavigationUtils';
Expand All @@ -26,12 +27,13 @@ import {useIsFocused} from '@react-navigation/native';
import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding';
import {fullPolicySnapshotLastModifiedByPolicyIDSelector} from '@selectors/Policy';
import React from 'react';
import Onyx from 'react-native-onyx';

import type {RecentlyAddedExpense} from './useRecentlyAddedData';
import type {RecentlyAddedItem} from './useRecentlyAddedData';

import RecentlyAddedPlaceholder from './RecentlyAddedPlaceholder';
import RecentlyAddedRow from './RecentlyAddedRow';
import {useRecentlyAddedData} from './useRecentlyAddedData';
import {buildRecentlyAddedExpense, useRecentlyAddedData} from './useRecentlyAddedData';

function RecentlyAddedSection() {
const {transactions, isAwaitingFirstResult} = useRecentlyAddedData();
Expand All @@ -47,7 +49,7 @@ function RecentlyAddedSection() {
const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails();
const [personalDetails] = usePersonalDetailsByIDs([
currentUserAccountID,
...transactions.flatMap((transaction) => [transaction.reportAction?.actorAccountID, transaction.report?.ownerAccountID]),
...transactions.flatMap((transaction) => [transaction.reportAction?.actorAccountID, transaction.snapshotReport?.ownerAccountID]),
]);
const isAnonymousUser = useIsAnonymousUser();
const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
Expand All @@ -59,7 +61,29 @@ function RecentlyAddedSection() {
const hasExpenses = transactions.length > 0;
const listBottomPadding = shouldUseNarrowLayout ? styles.pb2 : styles.pb5;

const openExpense = (expense: RecentlyAddedExpense) => {
const openExpense = async (item: RecentlyAddedItem) => {
// Rows read their own live data, so the full siblings are read only now, on press.
let localTransactions;
let localReports;
try {
[localTransactions, localReports] = await Promise.all([
// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- Home is never inside a Search scope, so the rows read live data too
Onyx.multiGet(transactions.map((sibling) => `${ONYXKEYS.COLLECTION.TRANSACTION}${sibling.transactionID}` as const)),
// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- Home is never inside a Search scope, so the rows read live data too
Onyx.multiGet(transactions.map((sibling) => `${ONYXKEYS.COLLECTION.REPORT}${sibling.reportID}` as const)),
]);
} catch (error) {
Log.warn('[RecentlyAddedSection] Failed to read the expenses to open', {error});
return;
}
const resolvedSiblings = transactions
.map((sibling, index) => buildRecentlyAddedExpense(sibling, localTransactions.at(index), localReports.at(index), translate))
.filter((sibling) => !!sibling);
const expense = resolvedSiblings.find((sibling) => sibling.transactionID === item.transactionID);
if (!expense) {
return;
}

// Resolve only the tapped expense now. getReportIDToOpenForExpense may create a transaction thread, so
// resolving every sibling up front would create a thread for each multi-expense sibling on a single tap.
// Instead, seed the cheap snapshot-derived descriptors and let the carousel resolve each sibling lazily,
Expand All @@ -80,7 +104,7 @@ function RecentlyAddedSection() {
// pending and re-adds it if the delete rolls back, both from its live transaction. A descriptor would keep
// it in the arrows after the delete syncs and its live copy is gone, landing the arrow on "not here".
const siblingTransactionIDs = transactions.map((sibling) => sibling.transactionID);
const navigableSiblings = transactions.filter((sibling) => sibling.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);
const navigableSiblings = resolvedSiblings.filter((sibling) => sibling.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);
const siblingDescriptorsByTransactionID = navigableSiblings.reduce<Record<string, TransactionThreadNavigationDescriptor>>((map, sibling) => {
// eslint-disable-next-line no-param-reassign
map[sibling.transactionID] = {
Expand Down Expand Up @@ -144,11 +168,13 @@ function RecentlyAddedSection() {
containerStyles={hasExpenses || isAwaitingFirstResult ? listBottomPadding : undefined}
>
{hasExpenses ? (
transactions.map((expense, index) => (
transactions.map((item, index) => (
<RecentlyAddedRow
key={expense.transactionID}
expense={expense}
onPress={() => openExpense(expense)}
key={item.transactionID}
item={item}
onPress={() => {
openExpense(item);

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.

NAB: openExpense is async now but nothing catches a failure here. Could we add a catch inside it

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.

Added a try/catch around the sibling read in openExpense: a failed read is logged and the tap does nothing, instead of leaving a rejected promise nobody handles.

}}
shouldShowSeparator={index < transactions.length - 1}
shouldShowReceiptPreview={isFocused}
rowStyle={cardPaddingHorizontal}
Expand Down
Loading
Loading