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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import usePreMountDestination from '@hooks/usePreMountDestination';
import {clearPreMountedDraftReport, clearPreMountedDraftReportMarker, preMountDraftReport} from '@libs/actions/Report/PreMountedDraftReport';
import {getReusableP2PReportID} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import {findSelfDMReportID, getParticipantsChatKey, isMoneyRequestReport} from '@libs/ReportUtils';
import {findSelfDMReportID, getParticipantsChatKey, isMoneyRequestReport, isPolicyExpenseChat} from '@libs/ReportUtils';
import {getPendingSubmitFollowUpAction} from '@libs/telemetry/submitFollowUpAction';

import getSubmitExpensePreMountDestinationRoute from '@pages/iou/request/step/confirmation/getSubmitExpensePreMountDestinationRoute';
Expand Down Expand Up @@ -83,7 +83,13 @@ function useSubmitDestinationPreMount({
const selfDMReportID = iouType === CONST.IOU.TYPE.TRACK || isSelfDMDestination ? findSelfDMReportID() : undefined;
const isMRReport = isMoneyRequestReport(report);
const shouldUsePerDiemChatReport = isPerDiemRequest && isMRReport && Navigation.getTopmostReportId() !== report?.reportID;
const routeDestinationReportID = shouldUsePerDiemChatReport ? report?.chatReportID : report?.reportID;
// Picking another workspace in the "To" picker moves the transaction to that workspace chat while the route still points
// at the previous one, so `report` resolves to undefined. Fall back to the picked workspace chat
// so the destination can still be pre-mounted instead of revealing the Inbox before navigating there.
const isUnreported = transaction?.reportID === CONST.REPORT.UNREPORTED_REPORT_ID;

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.

isUnreported computed twice

The page already computes the same value and passes it to the orchestrator.
The hook takes the page's other flags as params.

const isUnreported = transaction?.reportID === CONST.REPORT.UNREPORTED_REPORT_ID;

Add isUnreported to UseSubmitDestinationPreMountParams and pass it from the page.

const pickedParticipant = transaction?.participants?.at(0);
const pickedWorkspaceChatReportID = !isUnreported && isPolicyExpenseChat(pickedParticipant) ? pickedParticipant?.reportID : undefined;
Comment on lines +90 to +91

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.

Duplicate "first participant" variable

pickedParticipant reads transaction?.participants?.at(0), but the hook already has firstParticipant = participants.at(0) a few lines below.
participants maps transaction.participants one to one and keeps reportID and isPolicyExpenseChat, so both hold the same participant under different names.

Move firstParticipant above this block and use isPolicyExpenseChat(firstParticipant) ? firstParticipant?.reportID : undefined.

Comment on lines +86 to +91

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.

Unreported guard has no reason

The comment explains the fallback but not why unreported expenses are skipped.
Categorizing a tracked expense into a new draft workspace leaves it unreported with a workspace chat participant, so the guard reads like a bug.

Add one sentence on where an unreported expense lands and why the participant's chat is the wrong destination for it.

const routeDestinationReportID = shouldUsePerDiemChatReport ? report?.chatReportID : (report?.reportID ?? pickedWorkspaceChatReportID);
const destinationReportID = (isSelfDMDestination ? selfDMReportID : (backToReport ?? routeDestinationReportID)) ?? selfDMReportID;

// The user can swap recipients here without a remount, so `report` can still lag behind the current
Expand Down
10 changes: 8 additions & 2 deletions tests/ui/TimeExpenseConfirmationTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ jest.mock('@components/ProductTrainingContext', () => ({

jest.mock('@src/hooks/useResponsiveLayout');

jest.mock('@libs/getIsNarrowLayout', () => jest.fn(() => false));

jest.mock('@libs/Navigation/navigationRef', () => ({
__esModule: true,
default: {
Expand Down Expand Up @@ -97,14 +99,18 @@ jest.mock('@libs/Navigation/Navigation', () => {
getActiveRouteWithoutParams: jest.fn(() => ''),
isNavigationReady: jest.fn(() => Promise.resolve()),
goBack: jest.fn(),
dismissModal: jest.fn(),
dismissModal: jest.fn((options?: {afterTransition?: () => void}) => {
options?.afterTransition?.();
}),
dismissModalWithReport: jest.fn(),
getActiveRoute: jest.fn(() => ''),
getIsFullscreenPreInsertedUnderRHP: jest.fn(() => false),
getPreMountedFullscreenRouteKey: jest.fn(() => undefined),
getPreInsertedFullscreenRouteName: jest.fn(() => undefined),
clearFullscreenPreInsertedFlag: jest.fn(),
revealRouteBeforeDismissingModal: jest.fn(),
revealRouteBeforeDismissingModal: jest.fn((_route: unknown, options?: {afterTransition?: () => void}) => {
options?.afterTransition?.();
}),
isTopmostRouteModalScreen: jest.fn(() => false),
getTopmostReportId: jest.fn(() => undefined),
preInsertFullscreenUnderRHP: jest.fn(),
Expand Down
168 changes: 168 additions & 0 deletions tests/ui/components/IOURequestStepConfirmationPageTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {startSplitBill} from '@libs/actions/IOU/Split';
import getCurrentPosition from '@libs/getCurrentPosition';
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import * as IOUUtils from '@libs/IOUUtils';
import * as IsReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator';
import * as SubmitWithDismissFirst from '@libs/Navigation/helpers/submitWithDismissFirst';
import Navigation from '@libs/Navigation/Navigation';
// eslint-disable-next-line no-restricted-imports -- Namespace import is required to spy on getChatByParticipants without replacing the production module.
Expand Down Expand Up @@ -1532,6 +1533,173 @@ describe('IOURequestStepConfirmationPageTest', () => {
}
});

it('pre-mounts the picked workspace chat when the expense was moved away from the route workspace chat', async () => {
// Given a global create from the Inbox, where the route was seeded with the default workspace chat and the
// "To" picker (only editable from global create) then moved the expense to another workspace chat.
// The route still points at the default chat, so the screen can't resolve a report and has to rely on the participant.
const routeWorkspaceChatReportID = 'route-workspace-chat';
const pickedWorkspaceChatReportID = 'picked-workspace-chat';
const transactionID = 'tx-picked-workspace';
jest.mocked(getIsNarrowLayout).mockReturnValue(true);
const isReportTopmostSplitNavigatorSpy = jest.spyOn(IsReportTopmostSplitNavigator, 'default').mockReturnValue(true);

try {
await act(async () => {
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${routeWorkspaceChatReportID}`, {
reportID: routeWorkspaceChatReportID,
policyID: 'route-policy',
type: CONST.REPORT.TYPE.CHAT,
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${pickedWorkspaceChatReportID}`, {
reportID: pickedWorkspaceChatReportID,
policyID: POLICY_ID,
type: CONST.REPORT.TYPE.CHAT,
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {
transactionID,
reportID: pickedWorkspaceChatReportID,
amount: 1000,
isAmountSet: true,
currency: 'USD',
merchant: 'Test',
created: '2025-01-15',
isFromGlobalCreate: true,
iouRequestType: CONST.IOU.REQUEST_TYPE.MANUAL,
participants: [{accountID: 0, reportID: pickedWorkspaceChatReportID, policyID: POLICY_ID, isPolicyExpenseChat: true, selected: true}],
});
});

render(
<OnyxListItemProvider>
<HTMLProviderWrapper>
<CurrentUserPersonalDetailsProvider>
<LocaleContextProvider>
<IOURequestStepConfirmationWithWritableReportOrNotFound
route={{
key: 'Money_Request_Step_Confirmation',
name: 'Money_Request_Step_Confirmation',
params: {
action: CONST.IOU.ACTION.CREATE,
iouType: CONST.IOU.TYPE.SUBMIT,
transactionID,
reportID: routeWorkspaceChatReportID,
},
}}
navigation={mockNavigation}
/>
</LocaleContextProvider>
</CurrentUserPersonalDetailsProvider>
</HTMLProviderWrapper>
</OnyxListItemProvider>,
);

// When the screen renders and resolves the pre-mount destination
await waitForBatchedUpdatesWithAct();

// Then the picked workspace chat - where the expense lands - is pre-inserted, so dismissing reveals it
// directly instead of flashing the screen underneath before navigating there
await waitFor(() => expect(Navigation.preInsertFullscreenUnderRHP).toHaveBeenCalledWith(ROUTES.REPORT_WITH_ID.getRoute(pickedWorkspaceChatReportID)), {
timeout: 2000,
});
expect(Navigation.preInsertFullscreenUnderRHP).not.toHaveBeenCalledWith(expect.stringContaining(routeWorkspaceChatReportID));
} finally {
isReportTopmostSplitNavigatorSpy.mockRestore();
jest.mocked(getIsNarrowLayout).mockReturnValue(false);
}
});

it('pre-mounts the workspace chat picked on the receipt being viewed when there are multiple receipts', async () => {
// Given a global create with two receipts, where the first one is still on the default workspace chat the route
// was seeded with and the "To" picker moved only the second one to another workspace chat. The picker writes to the
// receipt being viewed, so the route's (first) transaction no longer reflects where the expenses are submitted.
Comment on lines +1613 to +1616

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.

Multi-receipt test sets up an unreachable state

The Given says the "To" picker moved only the second receipt.
The picker writes the pick to every receipt in the batch, so receipts on different workspaces can't happen in the app.

// Every receipt of a multi-scan batch is submitted to the shown receipt's recipient, so the pick applies to all
// of them, like useParticipantSubmission does.
if (shouldKeepOnSelfDM) {
for (const transactionToUpdate of transactions) {

Seed both drafts with the picked chat, or reword the Given.

const routeWorkspaceChatReportID = 'route-workspace-chat';
const pickedWorkspaceChatReportID = 'picked-workspace-chat';
const firstTransactionID = 'tx-first-receipt';
const secondTransactionID = 'tx-second-receipt';
jest.mocked(getIsNarrowLayout).mockReturnValue(true);
const isReportTopmostSplitNavigatorSpy = jest.spyOn(IsReportTopmostSplitNavigator, 'default').mockReturnValue(true);
const baseTransaction = {
amount: 1000,
isAmountSet: true,
currency: 'USD',
merchant: 'Test',
created: '2025-01-15',
isFromGlobalCreate: true,
iouRequestType: CONST.IOU.REQUEST_TYPE.MANUAL,
};

try {
await act(async () => {
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${routeWorkspaceChatReportID}`, {
reportID: routeWorkspaceChatReportID,
policyID: 'route-policy',
type: CONST.REPORT.TYPE.CHAT,
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${pickedWorkspaceChatReportID}`, {
reportID: pickedWorkspaceChatReportID,
policyID: POLICY_ID,
type: CONST.REPORT.TYPE.CHAT,
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${firstTransactionID}`, {
...baseTransaction,
transactionID: firstTransactionID,
reportID: routeWorkspaceChatReportID,
participants: [{accountID: 0, reportID: routeWorkspaceChatReportID, policyID: 'route-policy', isPolicyExpenseChat: true, selected: true}],
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${secondTransactionID}`, {
...baseTransaction,
transactionID: secondTransactionID,
reportID: pickedWorkspaceChatReportID,
participants: [{accountID: 0, reportID: pickedWorkspaceChatReportID, policyID: POLICY_ID, isPolicyExpenseChat: true, selected: true}],
});
});

render(
<OnyxListItemProvider>
<HTMLProviderWrapper>
<CurrentUserPersonalDetailsProvider>
<LocaleContextProvider>
<IOURequestStepConfirmationWithWritableReportOrNotFound
route={{
key: 'Money_Request_Step_Confirmation',
name: 'Money_Request_Step_Confirmation',
params: {
action: CONST.IOU.ACTION.CREATE,
iouType: CONST.IOU.TYPE.SUBMIT,
transactionID: firstTransactionID,
reportID: routeWorkspaceChatReportID,
},
}}
navigation={mockNavigation}
/>
</LocaleContextProvider>
</CurrentUserPersonalDetailsProvider>
</HTMLProviderWrapper>
</OnyxListItemProvider>,
);
await waitForBatchedUpdatesWithAct();
jest.mocked(Navigation.preInsertFullscreenUnderRHP).mockClear();

// When the user moves on to the second receipt, the one whose workspace was changed
const [, nextReceiptButton] = screen.getAllByRole(CONST.ROLE.BUTTON, {name: CONST.ROLE.BUTTON});
fireEvent.press(nextReceiptButton);
await waitForBatchedUpdatesWithAct();

// Then the workspace chat picked for that receipt - where the expenses land - is pre-inserted, rather than the
// first receipt's workspace chat, which would leave the user in a workspace the expenses were not submitted to
await waitFor(() => expect(Navigation.preInsertFullscreenUnderRHP).toHaveBeenCalledWith(ROUTES.REPORT_WITH_ID.getRoute(pickedWorkspaceChatReportID)), {
timeout: 2000,
});
} finally {
isReportTopmostSplitNavigatorSpy.mockRestore();
jest.mocked(getIsNarrowLayout).mockReturnValue(false);
}
});

it('skips the P2P chat lookup entirely for a self-DM destination', async () => {
// Given a self-DM destination: the sole selected participant resolves to the current user's own self-DM and
// carries accountID 0, so a P2P lookup here could only ever scan the whole report collection for a chat with
Expand Down
Loading