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
@@ -0,0 +1,143 @@
import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails';

import useDefaultExpensePolicy from '@hooks/useDefaultExpensePolicy';
import useOnyx from '@hooks/useOnyx';
import usePersonalPolicy from '@hooks/usePersonalPolicy';
import useSelfDMReport from '@hooks/useSelfDMReport';

import {navigateToConfirmationPage, navigateToParticipantPage} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getPolicyExpenseChat, isSelfDM} from '@libs/ReportUtils';
import shouldUseDefaultExpensePolicy from '@libs/shouldUseDefaultExpensePolicy';
import {endSpan} from '@libs/telemetry/activeSpans';

import startScanProcessSpan from '@pages/iou/request/step/IOURequestStepScan/utils/startScanProcessSpan';

import {setMoneyRequestParticipants, setMoneyRequestParticipantsFromReport} from '@userActions/IOU/MoneyRequest';
import {setTransactionReport} from '@userActions/Transaction';

import CONST from '@src/CONST';
import type {IOUType} from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type Transaction from '@src/types/onyx/Transaction';

import type {RefObject} from 'react';
import type {OnyxEntry} from 'react-native-onyx';

/**
* Owns the post-capture-only Onyx reads used by navigateGlobalCreate.
*
* The Provider's root element type stays the same across renders, so the
* camera isn't torn down when subscriptions become ready. useNavigateGlobalCreate()
* returns a stable callable.
*/
import React, {createContext, useCallback, useContext, useEffect, useRef, useState} from 'react';

type NavigateGlobalCreateFn = (transactionIDs: string[], isMultiScanEnabled: boolean) => void;

type ProviderProps = WithCurrentUserPersonalDetailsProps & {
iouType: IOUType;
reportID: string;
transactionID: string;
transaction: OnyxEntry<Transaction>;
backToReport: string | undefined;
children: React.ReactNode;
};

type SubscriberProps = Omit<ProviderProps, 'children'> & {
fnRef: RefObject<NavigateGlobalCreateFn>;
};

const NO_OP: NavigateGlobalCreateFn = () => {};
const NavigateGlobalCreateContext = createContext<NavigateGlobalCreateFn>(NO_OP);

function useNavigateGlobalCreate(): NavigateGlobalCreateFn {
return useContext(NavigateGlobalCreateContext);
}

function NavigateGlobalCreateProvider({children, ...rest}: ProviderProps) {
const fnRef = useRef<NavigateGlobalCreateFn>(NO_OP);
const [isReady, setIsReady] = useState(false);

// Stable dispatch — context value identity never changes, so consumers
// don't re-render on Onyx ticks. Late-binds to fnRef.current at call time.
const dispatch = useCallback((transactionIDs: string[], isMultiScanEnabled: boolean) => {
fnRef.current(transactionIDs, isMultiScanEnabled);
}, []);

useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- intentional one-tick defer to keep heavy Onyx subscriptions off the camera-mount critical path
setIsReady(true);

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: does it make sense to add a small render test here? The tricky part is the isReady flip + fnRef publish, and it could regress silently later. Something that checks the camera subtree stays mounted across the flip, and that navigateGlobalCreate still works once the subscriber is ready. Not blocking.

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.

sure, it makes sense, I added tests

}, []);

return (
<NavigateGlobalCreateContext.Provider value={dispatch}>
{isReady && (
<NavigateGlobalCreateSubscriber
fnRef={fnRef}
{...rest}
/>
)}
{children}
</NavigateGlobalCreateContext.Provider>
);
}

function NavigateGlobalCreateSubscriber({fnRef, iouType, reportID, transactionID, transaction, backToReport, currentUserPersonalDetails}: SubscriberProps) {
const defaultExpensePolicy = useDefaultExpensePolicy();
const personalPolicy = usePersonalPolicy();
const selfDMReport = useSelfDMReport();
const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED);
const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END);
const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END);

const navigateGlobalCreate: NavigateGlobalCreateFn = (transactionIDs, isMultiScanEnabled) => {
startScanProcessSpan(isMultiScanEnabled);
if (shouldUseDefaultExpensePolicy(iouType, defaultExpensePolicy, amountOwed, userBillingGracePeriodEnds, ownerBillingGracePeriodEnd, currentUserPersonalDetails.accountID)) {
const shouldAutoReport = !!defaultExpensePolicy?.autoReporting || !!personalPolicy?.autoReporting;
const targetReport = shouldAutoReport ? getPolicyExpenseChat(currentUserPersonalDetails.accountID, defaultExpensePolicy?.id) : selfDMReport;
const transactionReportID = isSelfDM(targetReport) ? CONST.REPORT.UNREPORTED_REPORT_ID : targetReport?.reportID;
const iouTypeTrackOrSubmit = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID ? CONST.IOU.TYPE.TRACK : CONST.IOU.TYPE.SUBMIT;

// If the user previously selected different participants in confirmation, preserve that choice
if (transaction?.participants && transaction.participants.at(0)?.reportID !== targetReport?.reportID) {
const isTrackExpense = transaction.participants.at(0)?.reportID === selfDMReport?.reportID;

const setParticipantsPromises = transactionIDs.map((tid) => setMoneyRequestParticipants(tid, transaction.participants));
Promise.all(setParticipantsPromises).then(() => {
if (isTrackExpense) {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, CONST.IOU.TYPE.TRACK, transactionID, selfDMReport?.reportID));
} else {
navigateToConfirmationPage(iouType, transactionID, reportID, backToReport, iouType === CONST.IOU.TYPE.CREATE, transaction.reportID);
}
});
return;
}

const setParticipantsPromises = transactionIDs.map((tid) => {
setTransactionReport(tid, {reportID: transactionReportID}, true);
return setMoneyRequestParticipantsFromReport(tid, targetReport, currentUserPersonalDetails.accountID);
});
Promise.all(setParticipantsPromises).then(() => {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, iouTypeTrackOrSubmit, transactionID, targetReport?.reportID));
});
} else {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
navigateToParticipantPage(iouType, transactionID, reportID);
}
};

useEffect(() => {
// eslint-disable-next-line no-param-reassign -- publish navigate fn through ref so the context value identity stays stable across Onyx ticks
fnRef.current = navigateGlobalCreate;
});

return null;
}

NavigateGlobalCreateProvider.displayName = 'NavigateGlobalCreateProvider';

export {NavigateGlobalCreateProvider, useNavigateGlobalCreate};
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,18 @@ import {useFullScreenLoaderActions} from '@components/FullScreenLoaderContext';
import withCurrentUserPersonalDetails from '@components/withCurrentUserPersonalDetails';
import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails';

import useDefaultExpensePolicy from '@hooks/useDefaultExpensePolicy';
import useFilesValidation from '@hooks/useFilesValidation';
import {precacheReceiptImage} from '@hooks/useLocalReceiptThumbnail';
import useOnyx from '@hooks/useOnyx';
import useOptimisticDraftTransactions from '@hooks/useOptimisticDraftTransactions';
import usePersonalPolicy from '@hooks/usePersonalPolicy';
import useSelfDMReport from '@hooks/useSelfDMReport';

import {navigateToConfirmationPage, navigateToParticipantPage} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getPolicyExpenseChat, isSelfDM} from '@libs/ReportUtils';
import shouldUseDefaultExpensePolicy from '@libs/shouldUseDefaultExpensePolicy';
import {endSpan} from '@libs/telemetry/activeSpans';

import type {ReceiptFile} from '@pages/iou/request/step/IOURequestStepScan/types';
import buildReceiptFiles from '@pages/iou/request/step/IOURequestStepScan/utils/buildReceiptFiles';
import getFileSource from '@pages/iou/request/step/IOURequestStepScan/utils/getFileSource';
import startScanProcessSpan from '@pages/iou/request/step/IOURequestStepScan/utils/startScanProcessSpan';
import useScanFileReadabilityCheck from '@pages/iou/request/step/IOURequestStepScan/utils/useScanFileReadabilityCheck';

import {setMoneyRequestParticipants, setMoneyRequestParticipantsFromReport} from '@userActions/IOU/MoneyRequest';
import {setTransactionReport} from '@userActions/Transaction';

import CONST from '@src/CONST';
import type {IOUType} from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import {validTransactionDraftIDsSelector} from '@src/selectors/TransactionDraft';
import type Transaction from '@src/types/onyx/Transaction';
import type {FileObject} from '@src/types/utils/Attachment';
Expand All @@ -39,6 +24,7 @@ import React from 'react';

import Camera from './Camera';
import {useMultiScanActions, useMultiScanState} from './MultiScanContext';
import {NavigateGlobalCreateProvider, useNavigateGlobalCreate} from './NavigateGlobalCreateContext';

type ScanGlobalCreateProps = WithCurrentUserPersonalDetailsProps & {
iouType: IOUType;
Expand All @@ -51,61 +37,36 @@ type ScanGlobalCreateProps = WithCurrentUserPersonalDetailsProps & {
/**
* ScanGlobalCreate — initiated from the FAB (+) button (no specific report).
* Uses default expense policy to auto-select workspace, or navigates to participant picker.
*
* Wrapper renders NavigateGlobalCreateProvider so post-capture Onyx reads stay
* off the camera-mount critical path. See NavigateGlobalCreateContext.tsx.
*/
function ScanGlobalCreate({iouType, reportID, transactionID, transaction, backToReport, currentUserPersonalDetails}: ScanGlobalCreateProps) {
const defaultExpensePolicy = useDefaultExpensePolicy();
const personalPolicy = usePersonalPolicy();
const selfDMReport = useSelfDMReport();
const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {selector: validTransactionDraftIDsSelector});
const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED);
const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END);
const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END);
function ScanGlobalCreate({iouType, backToReport, ...innerProps}: ScanGlobalCreateProps) {
return (
<NavigateGlobalCreateProvider
iouType={iouType}
backToReport={backToReport}
{...innerProps}
>
<ScanGlobalCreateInner {...innerProps} />
</NavigateGlobalCreateProvider>
);
}

type ScanGlobalCreateInnerProps = Omit<ScanGlobalCreateProps, 'iouType' | 'backToReport'>;

function ScanGlobalCreateInner({reportID, transactionID, transaction, currentUserPersonalDetails}: ScanGlobalCreateInnerProps) {
const navigateGlobalCreate = useNavigateGlobalCreate();
const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {
selector: validTransactionDraftIDsSelector,
});
const {isMultiScanEnabled} = useMultiScanState();
const {disableMultiScan} = useMultiScanActions();
const {setIsLoaderVisible} = useFullScreenLoaderActions();

const [transactions] = useOptimisticDraftTransactions(transaction);

useScanFileReadabilityCheck(transactions, draftTransactionIDs ?? [], disableMultiScan);

const navigateGlobalCreate = (transactionIDs: string[]) => {
startScanProcessSpan(isMultiScanEnabled);
if (shouldUseDefaultExpensePolicy(iouType, defaultExpensePolicy, amountOwed, userBillingGracePeriodEnds, ownerBillingGracePeriodEnd, currentUserPersonalDetails.accountID)) {
const shouldAutoReport = !!defaultExpensePolicy?.autoReporting || !!personalPolicy?.autoReporting;
const targetReport = shouldAutoReport ? getPolicyExpenseChat(currentUserPersonalDetails.accountID, defaultExpensePolicy?.id) : selfDMReport;
const transactionReportID = isSelfDM(targetReport) ? CONST.REPORT.UNREPORTED_REPORT_ID : targetReport?.reportID;
const iouTypeTrackOrSubmit = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID ? CONST.IOU.TYPE.TRACK : CONST.IOU.TYPE.SUBMIT;

// If the user previously selected different participants in confirmation, preserve that choice
if (transaction?.participants && transaction.participants.at(0)?.reportID !== targetReport?.reportID) {
const isTrackExpense = transaction.participants.at(0)?.reportID === selfDMReport?.reportID;

const setParticipantsPromises = transactionIDs.map((tid) => setMoneyRequestParticipants(tid, transaction.participants));
Promise.all(setParticipantsPromises).then(() => {
if (isTrackExpense) {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, CONST.IOU.TYPE.TRACK, transactionID, selfDMReport?.reportID));
} else {
navigateToConfirmationPage(iouType, transactionID, reportID, backToReport, iouType === CONST.IOU.TYPE.CREATE, transaction.reportID);
}
});
return;
}

const setParticipantsPromises = transactionIDs.map((tid) => {
setTransactionReport(tid, {reportID: transactionReportID}, true);
return setMoneyRequestParticipantsFromReport(tid, targetReport, currentUserPersonalDetails.accountID);
});
Promise.all(setParticipantsPromises).then(() => {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CONFIRMATION.getRoute(CONST.IOU.ACTION.CREATE, iouTypeTrackOrSubmit, transactionID, targetReport?.reportID));
});
} else {
endSpan(CONST.TELEMETRY.SPAN_SCAN_PROCESS_AND_NAVIGATE);
navigateToParticipantPage(iouType, transactionID, reportID);
}
};

const processReceipts = (files: FileObject[]) => {
const receiptFiles = buildReceiptFiles({
files,
Expand All @@ -128,15 +89,18 @@ function ScanGlobalCreate({iouType, reportID, transactionID, transaction, backTo
return;
}

navigateGlobalCreate(receiptFiles.map((rf: ReceiptFile) => rf.transactionID));
navigateGlobalCreate(
receiptFiles.map((rf: ReceiptFile) => rf.transactionID),
isMultiScanEnabled,
);
};

const submitMultiScan = () => {
const ids = transactions.map((t) => t.transactionID).filter((id): id is string => !!id);
if (ids.length === 0) {
return;
}
navigateGlobalCreate(ids);
navigateGlobalCreate(ids, isMultiScanEnabled);
};

const {validateFiles, PDFValidationComponent, ErrorModal} = useFilesValidation((files: FileObject[]) => {
Expand Down
63 changes: 63 additions & 0 deletions tests/unit/NavigateGlobalCreateProviderTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/no-unsafe-type-assertion -- baseProps is a minimal test fixture; casting via `as unknown` keeps the test focused on mount-stability instead of dragging in every field of WithCurrentUserPersonalDetailsProps */
import {render} from '@testing-library/react-native';

import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails';

import {NavigateGlobalCreateProvider} from '@pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext';

import CONST from '@src/CONST';

import React, {useEffect} from 'react';

import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

// Stub the heavy hooks the Subscriber pulls in — this test only cares about
// mount stability of the children subtree across the isReady transition.
jest.mock('@hooks/useDefaultExpensePolicy', () => ({__esModule: true, default: () => undefined}));
jest.mock('@hooks/usePersonalPolicy', () => ({__esModule: true, default: () => undefined}));
jest.mock('@hooks/useSelfDMReport', () => ({__esModule: true, default: () => undefined}));
jest.mock('@hooks/useOnyx', () => ({__esModule: true, default: () => [undefined]}));

const baseProps = {
iouType: CONST.IOU.TYPE.CREATE,
reportID: '1',
transactionID: 't1',
transaction: undefined,
backToReport: undefined,
currentUserPersonalDetails: {accountID: 1, login: 'a@b.com'},
} as unknown as WithCurrentUserPersonalDetailsProps & {
iouType: typeof CONST.IOU.TYPE.CREATE;
reportID: string;
transactionID: string;
transaction: undefined;
backToReport: undefined;
};

describe('NavigateGlobalCreateProvider', () => {
it('does not remount children across the isReady transition', async () => {
const onMount = jest.fn();

function Child() {
useEffect(() => {
onMount();
}, []);
return null;
}

render(
<NavigateGlobalCreateProvider {...baseProps}>
<Child />
</NavigateGlobalCreateProvider>,
);

// Wait for the Provider's one-tick useEffect (setIsReady) + the
// Subscriber to mount and its own useEffect (fnRef publish) to fire.
await waitForBatchedUpdates();
await waitForBatchedUpdates();

// If the Provider's root element type ever changes across the isReady
// flip, React would tear down and rebuild the children subtree — the
// Camera would remount, and onMount would fire a second time.
expect(onMount).toHaveBeenCalledTimes(1);
});
});
Loading